msan_interceptors.cc revision cfc29de659f3abbb9273fb0fb1c9a3cd5400c81b
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 "sanitizer_common/sanitizer_platform_limits_posix.h"
21#include "sanitizer_common/sanitizer_allocator.h"
22#include "sanitizer_common/sanitizer_allocator_internal.h"
23#include "sanitizer_common/sanitizer_atomic.h"
24#include "sanitizer_common/sanitizer_common.h"
25#include "sanitizer_common/sanitizer_stackdepot.h"
26#include "sanitizer_common/sanitizer_libc.h"
27#include "sanitizer_common/sanitizer_linux.h"
28
29#include <stdarg.h>
30// ACHTUNG! No other system header includes in this file.
31// Ideally, we should get rid of stdarg.h as well.
32
33using namespace __msan;
34
35using __sanitizer::memory_order;
36using __sanitizer::atomic_load;
37using __sanitizer::atomic_store;
38using __sanitizer::atomic_uintptr_t;
39
40// True if this is a nested interceptor.
41static THREADLOCAL int in_interceptor_scope;
42
43struct InterceptorScope {
44  InterceptorScope() { ++in_interceptor_scope; }
45  ~InterceptorScope() { --in_interceptor_scope; }
46};
47
48bool IsInInterceptorScope() {
49  return in_interceptor_scope;
50}
51
52#define ENSURE_MSAN_INITED() do { \
53  CHECK(!msan_init_is_running); \
54  if (!msan_inited) { \
55    __msan_init(); \
56  } \
57} while (0)
58
59// Check that [x, x+n) range is unpoisoned.
60#define CHECK_UNPOISONED_0(x, n)                                             \
61  do {                                                                       \
62    sptr offset = __msan_test_shadow(x, n);                                  \
63    if (__msan::IsInSymbolizer()) break;                                     \
64    if (offset >= 0 && __msan::flags()->report_umrs) {                       \
65      GET_CALLER_PC_BP_SP;                                                   \
66      (void) sp;                                                             \
67      Printf("UMR in %s at offset %d inside [%p, +%d) \n", __FUNCTION__,     \
68             offset, x, n);                                                  \
69      __msan::PrintWarningWithOrigin(pc, bp,                                 \
70                                     __msan_get_origin((char *)x + offset)); \
71      if (__msan::flags()->halt_on_error) {                                  \
72        Printf("Exiting\n");                                                 \
73        Die();                                                               \
74      }                                                                      \
75    }                                                                        \
76  } while (0)
77
78// Check that [x, x+n) range is unpoisoned unless we are in a nested
79// interceptor.
80#define CHECK_UNPOISONED(x, n)                             \
81  do {                                                     \
82    if (!IsInInterceptorScope()) CHECK_UNPOISONED_0(x, n); \
83  } while (0);
84
85static void *fast_memset(void *ptr, int c, SIZE_T n);
86static void *fast_memcpy(void *dst, const void *src, SIZE_T n);
87
88INTERCEPTOR(SIZE_T, fread, void *ptr, SIZE_T size, SIZE_T nmemb, void *file) {
89  ENSURE_MSAN_INITED();
90  SIZE_T res = REAL(fread)(ptr, size, nmemb, file);
91  if (res > 0)
92    __msan_unpoison(ptr, res *size);
93  return res;
94}
95
96INTERCEPTOR(SIZE_T, fread_unlocked, void *ptr, SIZE_T size, SIZE_T nmemb,
97            void *file) {
98  ENSURE_MSAN_INITED();
99  SIZE_T res = REAL(fread_unlocked)(ptr, size, nmemb, file);
100  if (res > 0)
101    __msan_unpoison(ptr, res *size);
102  return res;
103}
104
105INTERCEPTOR(SSIZE_T, readlink, const char *path, char *buf, SIZE_T bufsiz) {
106  ENSURE_MSAN_INITED();
107  SSIZE_T res = REAL(readlink)(path, buf, bufsiz);
108  if (res > 0)
109    __msan_unpoison(buf, res);
110  return res;
111}
112
113INTERCEPTOR(void *, memcpy, void *dest, const void *src, SIZE_T n) {
114  return __msan_memcpy(dest, src, n);
115}
116
117INTERCEPTOR(void *, mempcpy, void *dest, const void *src, SIZE_T n) {
118  return (char *)__msan_memcpy(dest, src, n) + n;
119}
120
121INTERCEPTOR(void *, memmove, void *dest, const void *src, SIZE_T n) {
122  return __msan_memmove(dest, src, n);
123}
124
125INTERCEPTOR(void *, memset, void *s, int c, SIZE_T n) {
126  return __msan_memset(s, c, n);
127}
128
129INTERCEPTOR(void *, bcopy, const void *src, void *dest, SIZE_T n) {
130  return __msan_memmove(dest, src, n);
131}
132
133INTERCEPTOR(int, posix_memalign, void **memptr, SIZE_T alignment, SIZE_T size) {
134  GET_MALLOC_STACK_TRACE;
135  CHECK_EQ(alignment & (alignment - 1), 0);
136  CHECK_NE(memptr, 0);
137  *memptr = MsanReallocate(&stack, 0, size, alignment, false);
138  CHECK_NE(*memptr, 0);
139  __msan_unpoison(memptr, sizeof(*memptr));
140  return 0;
141}
142
143INTERCEPTOR(void *, memalign, SIZE_T boundary, SIZE_T size) {
144  GET_MALLOC_STACK_TRACE;
145  CHECK_EQ(boundary & (boundary - 1), 0);
146  void *ptr = MsanReallocate(&stack, 0, size, boundary, false);
147  return ptr;
148}
149
150INTERCEPTOR(void *, valloc, SIZE_T size) {
151  GET_MALLOC_STACK_TRACE;
152  void *ptr = MsanReallocate(&stack, 0, size, GetPageSizeCached(), false);
153  return ptr;
154}
155
156INTERCEPTOR(void *, pvalloc, SIZE_T size) {
157  GET_MALLOC_STACK_TRACE;
158  uptr PageSize = GetPageSizeCached();
159  size = RoundUpTo(size, PageSize);
160  if (size == 0) {
161    // pvalloc(0) should allocate one page.
162    size = PageSize;
163  }
164  void *ptr = MsanReallocate(&stack, 0, size, PageSize, false);
165  return ptr;
166}
167
168INTERCEPTOR(void, free, void *ptr) {
169  GET_MALLOC_STACK_TRACE;
170  if (ptr == 0) return;
171  MsanDeallocate(&stack, ptr);
172}
173
174INTERCEPTOR(SIZE_T, strlen, const char *s) {
175  ENSURE_MSAN_INITED();
176  SIZE_T res = REAL(strlen)(s);
177  CHECK_UNPOISONED(s, res + 1);
178  return res;
179}
180
181INTERCEPTOR(SIZE_T, strnlen, const char *s, SIZE_T n) {
182  ENSURE_MSAN_INITED();
183  SIZE_T res = REAL(strnlen)(s, n);
184  SIZE_T scan_size = (res == n) ? res : res + 1;
185  CHECK_UNPOISONED(s, scan_size);
186  return res;
187}
188
189// FIXME: Add stricter shadow checks in str* interceptors (ex.: strcpy should
190// check the shadow of the terminating \0 byte).
191
192INTERCEPTOR(char *, strcpy, char *dest, const char *src) {  // NOLINT
193  ENSURE_MSAN_INITED();
194  SIZE_T n = REAL(strlen)(src);
195  char *res = REAL(strcpy)(dest, src);  // NOLINT
196  __msan_copy_poison(dest, src, n + 1);
197  return res;
198}
199
200INTERCEPTOR(char *, strncpy, char *dest, const char *src, SIZE_T n) {  // NOLINT
201  ENSURE_MSAN_INITED();
202  SIZE_T copy_size = REAL(strnlen)(src, n);
203  if (copy_size < n)
204    copy_size++;  // trailing \0
205  char *res = REAL(strncpy)(dest, src, n);  // NOLINT
206  __msan_copy_poison(dest, src, copy_size);
207  return res;
208}
209
210INTERCEPTOR(char *, stpcpy, char *dest, const char *src) {  // NOLINT
211  ENSURE_MSAN_INITED();
212  SIZE_T n = REAL(strlen)(src);
213  char *res = REAL(stpcpy)(dest, src);  // NOLINT
214  __msan_copy_poison(dest, src, n + 1);
215  return res;
216}
217
218INTERCEPTOR(char *, strdup, char *src) {
219  ENSURE_MSAN_INITED();
220  SIZE_T n = REAL(strlen)(src);
221  char *res = REAL(strdup)(src);
222  __msan_copy_poison(res, src, n + 1);
223  return res;
224}
225
226INTERCEPTOR(char *, __strdup, char *src) {
227  ENSURE_MSAN_INITED();
228  SIZE_T n = REAL(strlen)(src);
229  char *res = REAL(__strdup)(src);
230  __msan_copy_poison(res, src, n + 1);
231  return res;
232}
233
234INTERCEPTOR(char *, strndup, char *src, SIZE_T n) {
235  ENSURE_MSAN_INITED();
236  SIZE_T copy_size = REAL(strnlen)(src, n);
237  char *res = REAL(strndup)(src, n);
238  __msan_copy_poison(res, src, copy_size);
239  __msan_unpoison(res + copy_size, 1); // \0
240  return res;
241}
242
243INTERCEPTOR(char *, __strndup, char *src, SIZE_T n) {
244  ENSURE_MSAN_INITED();
245  SIZE_T copy_size = REAL(strnlen)(src, n);
246  char *res = REAL(__strndup)(src, n);
247  __msan_copy_poison(res, src, copy_size);
248  __msan_unpoison(res + copy_size, 1); // \0
249  return res;
250}
251
252INTERCEPTOR(char *, gcvt, double number, SIZE_T ndigit, char *buf) {
253  ENSURE_MSAN_INITED();
254  char *res = REAL(gcvt)(number, ndigit, buf);
255  // DynamoRio tool will take care of unpoisoning gcvt result for us.
256  if (!__msan_has_dynamic_component()) {
257    SIZE_T n = REAL(strlen)(buf);
258    __msan_unpoison(buf, n + 1);
259  }
260  return res;
261}
262
263INTERCEPTOR(char *, strcat, char *dest, const char *src) {  // NOLINT
264  ENSURE_MSAN_INITED();
265  SIZE_T src_size = REAL(strlen)(src);
266  SIZE_T dest_size = REAL(strlen)(dest);
267  char *res = REAL(strcat)(dest, src);  // NOLINT
268  __msan_copy_poison(dest + dest_size, src, src_size + 1);
269  return res;
270}
271
272INTERCEPTOR(char *, strncat, char *dest, const char *src, SIZE_T n) {  // NOLINT
273  ENSURE_MSAN_INITED();
274  SIZE_T dest_size = REAL(strlen)(dest);
275  SIZE_T copy_size = REAL(strlen)(src);
276  if (copy_size < n)
277    copy_size++;  // trailing \0
278  char *res = REAL(strncat)(dest, src, n);  // NOLINT
279  __msan_copy_poison(dest + dest_size, src, copy_size);
280  return res;
281}
282
283INTERCEPTOR(long, strtol, const char *nptr, char **endptr,  // NOLINT
284            int base) {
285  ENSURE_MSAN_INITED();
286  long res = REAL(strtol)(nptr, endptr, base);  // NOLINT
287  if (!__msan_has_dynamic_component()) {
288    __msan_unpoison(endptr, sizeof(*endptr));
289  }
290  return res;
291}
292
293INTERCEPTOR(long long, strtoll, const char *nptr, char **endptr,  // NOLINT
294            int base) {
295  ENSURE_MSAN_INITED();
296  long res = REAL(strtoll)(nptr, endptr, base);  //NOLINT
297  if (!__msan_has_dynamic_component()) {
298    __msan_unpoison(endptr, sizeof(*endptr));
299  }
300  return res;
301}
302
303INTERCEPTOR(unsigned long, strtoul, const char *nptr, char **endptr,  // NOLINT
304            int base) {
305  ENSURE_MSAN_INITED();
306  unsigned long res = REAL(strtoul)(nptr, endptr, base);  // NOLINT
307  if (!__msan_has_dynamic_component()) {
308    __msan_unpoison(endptr, sizeof(*endptr));
309  }
310  return res;
311}
312
313INTERCEPTOR(unsigned long long, strtoull, const char *nptr,  // NOLINT
314            char **endptr, int base) {
315  ENSURE_MSAN_INITED();
316  unsigned long res = REAL(strtoull)(nptr, endptr, base);  // NOLINT
317  if (!__msan_has_dynamic_component()) {
318    __msan_unpoison(endptr, sizeof(*endptr));
319  }
320  return res;
321}
322
323INTERCEPTOR(double, strtod, const char *nptr, char **endptr) {  // NOLINT
324  ENSURE_MSAN_INITED();
325  double res = REAL(strtod)(nptr, endptr);  // NOLINT
326  if (!__msan_has_dynamic_component()) {
327    __msan_unpoison(endptr, sizeof(*endptr));
328  }
329  return res;
330}
331
332INTERCEPTOR(float, strtof, const char *nptr, char **endptr) {  // NOLINT
333  ENSURE_MSAN_INITED();
334  float res = REAL(strtof)(nptr, endptr);  // NOLINT
335  if (!__msan_has_dynamic_component()) {
336    __msan_unpoison(endptr, sizeof(*endptr));
337  }
338  return res;
339}
340
341INTERCEPTOR(long double, strtold, const char *nptr, char **endptr) {  // NOLINT
342  ENSURE_MSAN_INITED();
343  long double res = REAL(strtold)(nptr, endptr);  // NOLINT
344  if (!__msan_has_dynamic_component()) {
345    __msan_unpoison(endptr, sizeof(*endptr));
346  }
347  return res;
348}
349
350INTERCEPTOR(int, vasprintf, char **strp, const char *format, va_list ap) {
351  ENSURE_MSAN_INITED();
352  int res = REAL(vasprintf)(strp, format, ap);
353  if (res >= 0 && !__msan_has_dynamic_component()) {
354    __msan_unpoison(strp, sizeof(*strp));
355    __msan_unpoison(*strp, res + 1);
356  }
357  return res;
358}
359
360INTERCEPTOR(int, asprintf, char **strp, const char *format, ...) {  // NOLINT
361  ENSURE_MSAN_INITED();
362  va_list ap;
363  va_start(ap, format);
364  int res = vasprintf(strp, format, ap);  // NOLINT
365  va_end(ap);
366  return res;
367}
368
369INTERCEPTOR(int, vsnprintf, char *str, uptr size,
370            const char *format, va_list ap) {
371  ENSURE_MSAN_INITED();
372  int res = REAL(vsnprintf)(str, size, format, ap);
373  if (res >= 0 && !__msan_has_dynamic_component()) {
374    __msan_unpoison(str, res + 1);
375  }
376  return res;
377}
378
379INTERCEPTOR(int, vsprintf, char *str, const char *format, va_list ap) {
380  ENSURE_MSAN_INITED();
381  int res = REAL(vsprintf)(str, format, ap);
382  if (res >= 0 && !__msan_has_dynamic_component()) {
383    __msan_unpoison(str, res + 1);
384  }
385  return res;
386}
387
388INTERCEPTOR(int, vswprintf, void *str, uptr size, void *format, va_list ap) {
389  ENSURE_MSAN_INITED();
390  int res = REAL(vswprintf)(str, size, format, ap);
391  if (res >= 0 && !__msan_has_dynamic_component()) {
392    __msan_unpoison(str, 4 * (res + 1));
393  }
394  return res;
395}
396
397INTERCEPTOR(int, sprintf, char *str, const char *format, ...) {  // NOLINT
398  ENSURE_MSAN_INITED();
399  va_list ap;
400  va_start(ap, format);
401  int res = vsprintf(str, format, ap);  // NOLINT
402  va_end(ap);
403  return res;
404}
405
406INTERCEPTOR(int, snprintf, char *str, uptr size, const char *format, ...) {
407  ENSURE_MSAN_INITED();
408  va_list ap;
409  va_start(ap, format);
410  int res = vsnprintf(str, size, format, ap);
411  va_end(ap);
412  return res;
413}
414
415INTERCEPTOR(int, swprintf, void *str, uptr size, void *format, ...) {
416  ENSURE_MSAN_INITED();
417  va_list ap;
418  va_start(ap, format);
419  int res = vswprintf(str, size, format, ap);
420  va_end(ap);
421  return res;
422}
423
424// SIZE_T strftime(char *s, SIZE_T max, const char *format,const struct tm *tm);
425INTERCEPTOR(SIZE_T, strftime, char *s, SIZE_T max, const char *format,
426            void *tm) {
427  ENSURE_MSAN_INITED();
428  SIZE_T res = REAL(strftime)(s, max, format, tm);
429  if (res) __msan_unpoison(s, res + 1);
430  return res;
431}
432
433INTERCEPTOR(int, mbtowc, wchar_t *dest, const char *src, SIZE_T n) {
434  ENSURE_MSAN_INITED();
435  int res = REAL(mbtowc)(dest, src, n);
436  if (res != -1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
437  return res;
438}
439
440INTERCEPTOR(int, mbrtowc, wchar_t *dest, const char *src, SIZE_T n, void *ps) {
441  ENSURE_MSAN_INITED();
442  SIZE_T res = REAL(mbrtowc)(dest, src, n, ps);
443  if (res != (SIZE_T)-1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
444  return res;
445}
446
447INTERCEPTOR(SIZE_T, wcslen, const wchar_t *s) {
448  ENSURE_MSAN_INITED();
449  SIZE_T res = REAL(wcslen)(s);
450  CHECK_UNPOISONED(s, sizeof(wchar_t) * (res + 1));
451  return res;
452}
453
454// wchar_t *wcschr(const wchar_t *wcs, wchar_t wc);
455INTERCEPTOR(wchar_t *, wcschr, void *s, wchar_t wc, void *ps) {
456  ENSURE_MSAN_INITED();
457  wchar_t *res = REAL(wcschr)(s, wc, ps);
458  return res;
459}
460
461// wchar_t *wcscpy(wchar_t *dest, const wchar_t *src);
462INTERCEPTOR(wchar_t *, wcscpy, wchar_t *dest, const wchar_t *src) {
463  ENSURE_MSAN_INITED();
464  wchar_t *res = REAL(wcscpy)(dest, src);
465  __msan_copy_poison(dest, src, sizeof(wchar_t) * (REAL(wcslen)(src) + 1));
466  return res;
467}
468
469// wchar_t *wmemcpy(wchar_t *dest, const wchar_t *src, SIZE_T n);
470INTERCEPTOR(wchar_t *, wmemcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
471  ENSURE_MSAN_INITED();
472  wchar_t *res = REAL(wmemcpy)(dest, src, n);
473  __msan_copy_poison(dest, src, n * sizeof(wchar_t));
474  return res;
475}
476
477INTERCEPTOR(wchar_t *, wmempcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
478  ENSURE_MSAN_INITED();
479  wchar_t *res = REAL(wmempcpy)(dest, src, n);
480  __msan_copy_poison(dest, src, n * sizeof(wchar_t));
481  return res;
482}
483
484INTERCEPTOR(wchar_t *, wmemset, wchar_t *s, wchar_t c, SIZE_T n) {
485  CHECK(MEM_IS_APP(s));
486  ENSURE_MSAN_INITED();
487  wchar_t *res = (wchar_t *)fast_memset(s, c, n * sizeof(wchar_t));
488  __msan_unpoison(s, n * sizeof(wchar_t));
489  return res;
490}
491
492INTERCEPTOR(wchar_t *, wmemmove, wchar_t *dest, const wchar_t *src, SIZE_T n) {
493  ENSURE_MSAN_INITED();
494  wchar_t *res = REAL(wmemmove)(dest, src, n);
495  __msan_move_poison(dest, src, n * sizeof(wchar_t));
496  return res;
497}
498
499INTERCEPTOR(int, wcscmp, const wchar_t *s1, const wchar_t *s2) {
500  ENSURE_MSAN_INITED();
501  int res = REAL(wcscmp)(s1, s2);
502  return res;
503}
504
505INTERCEPTOR(double, wcstod, const wchar_t *nptr, wchar_t **endptr) {
506  ENSURE_MSAN_INITED();
507  double res = REAL(wcstod)(nptr, endptr);
508  __msan_unpoison(endptr, sizeof(*endptr));
509  return res;
510}
511
512// #define UNSUPPORTED(name) \
513//   INTERCEPTOR(void, name, void) {                     \
514//     Printf("MSAN: Unsupported %s\n", __FUNCTION__);   \
515//     Die();                                            \
516//   }
517
518// FIXME: intercept the following functions:
519// Note, they only matter when running without a dynamic tool.
520// UNSUPPORTED(wcscoll_l)
521// UNSUPPORTED(wcsnrtombs)
522// UNSUPPORTED(wcstol)
523// UNSUPPORTED(wcstoll)
524// UNSUPPORTED(wcstold)
525// UNSUPPORTED(wcstoul)
526// UNSUPPORTED(wcstoull)
527// UNSUPPORTED(wcsxfrm_l)
528// UNSUPPORTED(wcsdup)
529// UNSUPPORTED(wcsftime)
530// UNSUPPORTED(wcsstr)
531// UNSUPPORTED(wcsrchr)
532// UNSUPPORTED(wctob)
533
534INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
535  ENSURE_MSAN_INITED();
536  int res = REAL(gettimeofday)(tv, tz);
537  if (tv)
538    __msan_unpoison(tv, 16);
539  if (tz)
540    __msan_unpoison(tz, 8);
541  return res;
542}
543
544INTERCEPTOR(char *, fcvt, double x, int a, int *b, int *c) {
545  ENSURE_MSAN_INITED();
546  char *res = REAL(fcvt)(x, a, b, c);
547  if (!__msan_has_dynamic_component()) {
548    __msan_unpoison(b, sizeof(*b));
549    __msan_unpoison(c, sizeof(*c));
550  }
551  return res;
552}
553
554INTERCEPTOR(char *, getenv, char *name) {
555  ENSURE_MSAN_INITED();
556  char *res = REAL(getenv)(name);
557  if (!__msan_has_dynamic_component()) {
558    if (res)
559      __msan_unpoison(res, REAL(strlen)(res) + 1);
560  }
561  return res;
562}
563
564extern char **environ;
565
566static void UnpoisonEnviron() {
567  char **envp = environ;
568  for (; *envp; ++envp) {
569    __msan_unpoison(envp, sizeof(*envp));
570    __msan_unpoison(*envp, REAL(strlen)(*envp) + 1);
571  }
572  // Trailing NULL pointer.
573  __msan_unpoison(envp, sizeof(*envp));
574}
575
576INTERCEPTOR(int, setenv, const char *name, const char *value, int overwrite) {
577  ENSURE_MSAN_INITED();
578  int res = REAL(setenv)(name, value, overwrite);
579  if (!res) UnpoisonEnviron();
580  return res;
581}
582
583INTERCEPTOR(int, putenv, char *string) {
584  ENSURE_MSAN_INITED();
585  int res = REAL(putenv)(string);
586  if (!res) UnpoisonEnviron();
587  return res;
588}
589
590INTERCEPTOR(int, __fxstat, int magic, int fd, void *buf) {
591  ENSURE_MSAN_INITED();
592  int res = REAL(__fxstat)(magic, fd, buf);
593  if (!res)
594    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
595  return res;
596}
597
598INTERCEPTOR(int, __fxstat64, int magic, int fd, void *buf) {
599  ENSURE_MSAN_INITED();
600  int res = REAL(__fxstat64)(magic, fd, buf);
601  if (!res)
602    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
603  return res;
604}
605
606INTERCEPTOR(int, __fxstatat, int magic, int fd, char *pathname, void *buf,
607            int flags) {
608  ENSURE_MSAN_INITED();
609  int res = REAL(__fxstatat)(magic, fd, pathname, buf, flags);
610  if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz);
611  return res;
612}
613
614INTERCEPTOR(int, __fxstatat64, int magic, int fd, char *pathname, void *buf,
615            int flags) {
616  ENSURE_MSAN_INITED();
617  int res = REAL(__fxstatat64)(magic, fd, pathname, buf, flags);
618  if (!res) __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
619  return res;
620}
621
622INTERCEPTOR(int, __xstat, int magic, char *path, void *buf) {
623  ENSURE_MSAN_INITED();
624  int res = REAL(__xstat)(magic, path, buf);
625  if (!res)
626    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
627  return res;
628}
629
630INTERCEPTOR(int, __xstat64, int magic, char *path, void *buf) {
631  ENSURE_MSAN_INITED();
632  int res = REAL(__xstat64)(magic, path, buf);
633  if (!res)
634    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
635  return res;
636}
637
638INTERCEPTOR(int, __lxstat, int magic, char *path, void *buf) {
639  ENSURE_MSAN_INITED();
640  int res = REAL(__lxstat)(magic, path, buf);
641  if (!res)
642    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
643  return res;
644}
645
646INTERCEPTOR(int, __lxstat64, int magic, char *path, void *buf) {
647  ENSURE_MSAN_INITED();
648  int res = REAL(__lxstat64)(magic, path, buf);
649  if (!res)
650    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
651  return res;
652}
653
654INTERCEPTOR(int, pipe, int pipefd[2]) {
655  if (msan_init_is_running)
656    return REAL(pipe)(pipefd);
657  ENSURE_MSAN_INITED();
658  int res = REAL(pipe)(pipefd);
659  if (!res)
660    __msan_unpoison(pipefd, sizeof(int[2]));
661  return res;
662}
663
664INTERCEPTOR(int, pipe2, int pipefd[2], int flags) {
665  ENSURE_MSAN_INITED();
666  int res = REAL(pipe2)(pipefd, flags);
667  if (!res)
668    __msan_unpoison(pipefd, sizeof(int[2]));
669  return res;
670}
671
672INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int sv[2]) {
673  ENSURE_MSAN_INITED();
674  int res = REAL(socketpair)(domain, type, protocol, sv);
675  if (!res)
676    __msan_unpoison(sv, sizeof(int[2]));
677  return res;
678}
679
680INTERCEPTOR(char *, fgets, char *s, int size, void *stream) {
681  ENSURE_MSAN_INITED();
682  char *res = REAL(fgets)(s, size, stream);
683  if (res)
684    __msan_unpoison(s, REAL(strlen)(s) + 1);
685  return res;
686}
687
688INTERCEPTOR(char *, fgets_unlocked, char *s, int size, void *stream) {
689  ENSURE_MSAN_INITED();
690  char *res = REAL(fgets_unlocked)(s, size, stream);
691  if (res)
692    __msan_unpoison(s, REAL(strlen)(s) + 1);
693  return res;
694}
695
696INTERCEPTOR(int, getrlimit, int resource, void *rlim) {
697  if (msan_init_is_running)
698    return REAL(getrlimit)(resource, rlim);
699  ENSURE_MSAN_INITED();
700  int res = REAL(getrlimit)(resource, rlim);
701  if (!res)
702    __msan_unpoison(rlim, __sanitizer::struct_rlimit_sz);
703  return res;
704}
705
706INTERCEPTOR(int, getrlimit64, int resource, void *rlim) {
707  if (msan_init_is_running)
708    return REAL(getrlimit64)(resource, rlim);
709  ENSURE_MSAN_INITED();
710  int res = REAL(getrlimit64)(resource, rlim);
711  if (!res)
712    __msan_unpoison(rlim, __sanitizer::struct_rlimit64_sz);
713  return res;
714}
715
716INTERCEPTOR(int, statfs, const char *s, void *buf) {
717  ENSURE_MSAN_INITED();
718  int res = REAL(statfs)(s, buf);
719  if (!res)
720    __msan_unpoison(buf, __sanitizer::struct_statfs_sz);
721  return res;
722}
723
724INTERCEPTOR(int, fstatfs, int fd, void *buf) {
725  ENSURE_MSAN_INITED();
726  int res = REAL(fstatfs)(fd, buf);
727  if (!res)
728    __msan_unpoison(buf, __sanitizer::struct_statfs_sz);
729  return res;
730}
731
732INTERCEPTOR(int, statfs64, const char *s, void *buf) {
733  ENSURE_MSAN_INITED();
734  int res = REAL(statfs64)(s, buf);
735  if (!res)
736    __msan_unpoison(buf, __sanitizer::struct_statfs64_sz);
737  return res;
738}
739
740INTERCEPTOR(int, fstatfs64, int fd, void *buf) {
741  ENSURE_MSAN_INITED();
742  int res = REAL(fstatfs64)(fd, buf);
743  if (!res)
744    __msan_unpoison(buf, __sanitizer::struct_statfs64_sz);
745  return res;
746}
747
748INTERCEPTOR(int, uname, void *utsname) {
749  ENSURE_MSAN_INITED();
750  int res = REAL(uname)(utsname);
751  if (!res) {
752    __msan_unpoison(utsname, __sanitizer::struct_utsname_sz);
753  }
754  return res;
755}
756
757INTERCEPTOR(int, gethostname, char *name, SIZE_T len) {
758  ENSURE_MSAN_INITED();
759  int res = REAL(gethostname)(name, len);
760  if (!res) {
761    SIZE_T real_len = REAL(strnlen)(name, len);
762    if (real_len < len)
763      ++real_len;
764    __msan_unpoison(name, real_len);
765  }
766  return res;
767}
768
769INTERCEPTOR(int, epoll_wait, int epfd, void *events, int maxevents,
770    int timeout) {
771  ENSURE_MSAN_INITED();
772  int res = REAL(epoll_wait)(epfd, events, maxevents, timeout);
773  if (res > 0) {
774    __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
775  }
776  return res;
777}
778
779INTERCEPTOR(int, epoll_pwait, int epfd, void *events, int maxevents,
780    int timeout, void *sigmask) {
781  ENSURE_MSAN_INITED();
782  int res = REAL(epoll_pwait)(epfd, events, maxevents, timeout, sigmask);
783  if (res > 0) {
784    __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
785  }
786  return res;
787}
788
789INTERCEPTOR(SSIZE_T, recv, int fd, void *buf, SIZE_T len, int flags) {
790  ENSURE_MSAN_INITED();
791  SSIZE_T res = REAL(recv)(fd, buf, len, flags);
792  if (res > 0)
793    __msan_unpoison(buf, res);
794  return res;
795}
796
797INTERCEPTOR(SSIZE_T, recvfrom, int fd, void *buf, SIZE_T len, int flags,
798            void *srcaddr, int *addrlen) {
799  ENSURE_MSAN_INITED();
800  SIZE_T srcaddr_sz;
801  if (srcaddr) srcaddr_sz = *addrlen;
802  SSIZE_T res = REAL(recvfrom)(fd, buf, len, flags, srcaddr, addrlen);
803  if (res > 0) {
804    __msan_unpoison(buf, res);
805    if (srcaddr) {
806      SIZE_T sz = *addrlen;
807      __msan_unpoison(srcaddr, (sz < srcaddr_sz) ? sz : srcaddr_sz);
808    }
809  }
810  return res;
811}
812
813INTERCEPTOR(void *, calloc, SIZE_T nmemb, SIZE_T size) {
814  if (CallocShouldReturnNullDueToOverflow(size, nmemb))
815    return AllocatorReturnNull();
816  GET_MALLOC_STACK_TRACE;
817  if (!msan_inited) {
818    // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym.
819    const SIZE_T kCallocPoolSize = 1024;
820    static uptr calloc_memory_for_dlsym[kCallocPoolSize];
821    static SIZE_T allocated;
822    SIZE_T size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize;
823    void *mem = (void*)&calloc_memory_for_dlsym[allocated];
824    allocated += size_in_words;
825    CHECK(allocated < kCallocPoolSize);
826    return mem;
827  }
828  return MsanReallocate(&stack, 0, nmemb * size, sizeof(u64), true);
829}
830
831INTERCEPTOR(void *, realloc, void *ptr, SIZE_T size) {
832  GET_MALLOC_STACK_TRACE;
833  return MsanReallocate(&stack, ptr, size, sizeof(u64), false);
834}
835
836INTERCEPTOR(void *, malloc, SIZE_T size) {
837  GET_MALLOC_STACK_TRACE;
838  return MsanReallocate(&stack, 0, size, sizeof(u64), false);
839}
840
841void __msan_allocated_memory(const void* data, uptr size) {
842  GET_MALLOC_STACK_TRACE;
843  if (flags()->poison_in_malloc)
844    __msan_poison(data, size);
845  if (__msan_get_track_origins()) {
846    u32 stack_id = StackDepotPut(stack.trace, stack.size);
847    CHECK(stack_id);
848    CHECK_EQ((stack_id >> 31), 0);  // Higher bit is occupied by stack origins.
849    __msan_set_origin(data, size, stack_id);
850  }
851}
852
853INTERCEPTOR(void *, mmap, void *addr, SIZE_T length, int prot, int flags,
854            int fd, OFF_T offset) {
855  ENSURE_MSAN_INITED();
856  void *res = REAL(mmap)(addr, length, prot, flags, fd, offset);
857  if (res != (void*)-1)
858    __msan_unpoison(res, RoundUpTo(length, GetPageSize()));
859  return res;
860}
861
862INTERCEPTOR(void *, mmap64, void *addr, SIZE_T length, int prot, int flags,
863            int fd, OFF64_T offset) {
864  ENSURE_MSAN_INITED();
865  void *res = REAL(mmap64)(addr, length, prot, flags, fd, offset);
866  if (res != (void*)-1)
867    __msan_unpoison(res, RoundUpTo(length, GetPageSize()));
868  return res;
869}
870
871struct dlinfo {
872  char *dli_fname;
873  void *dli_fbase;
874  char *dli_sname;
875  void *dli_saddr;
876};
877
878INTERCEPTOR(int, dladdr, void *addr, dlinfo *info) {
879  ENSURE_MSAN_INITED();
880  int res = REAL(dladdr)(addr, info);
881  if (res != 0) {
882    __msan_unpoison(info, sizeof(*info));
883    if (info->dli_fname)
884      __msan_unpoison(info->dli_fname, REAL(strlen)(info->dli_fname) + 1);
885    if (info->dli_sname)
886      __msan_unpoison(info->dli_sname, REAL(strlen)(info->dli_sname) + 1);
887  }
888  return res;
889}
890
891// dlopen() ultimately calls mmap() down inside the loader, which generally
892// doesn't participate in dynamic symbol resolution.  Therefore we won't
893// intercept its calls to mmap, and we have to hook it here.  The loader
894// initializes the module before returning, so without the dynamic component, we
895// won't be able to clear the shadow before the initializers.  Fixing this would
896// require putting our own initializer first to clear the shadow.
897INTERCEPTOR(void *, dlopen, const char *filename, int flag) {
898  ENSURE_MSAN_INITED();
899  EnterLoader();
900  link_map *map = (link_map *)REAL(dlopen)(filename, flag);
901  ExitLoader();
902  if (!__msan_has_dynamic_component() && map) {
903    // If msandr didn't clear the shadow before the initializers ran, we do it
904    // ourselves afterwards.
905    ForEachMappedRegion(map, __msan_unpoison);
906  }
907  return (void *)map;
908}
909
910typedef int (*dl_iterate_phdr_cb)(__sanitizer_dl_phdr_info *info, SIZE_T size,
911                                  void *data);
912struct dl_iterate_phdr_data {
913  dl_iterate_phdr_cb callback;
914  void *data;
915};
916
917static int msan_dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
918                                   void *data) {
919  if (info) {
920    __msan_unpoison(info, size);
921    if (info->dlpi_name)
922      __msan_unpoison(info->dlpi_name, REAL(strlen)(info->dlpi_name) + 1);
923  }
924  dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
925  UnpoisonParam(3);
926  return cbdata->callback(info, size, cbdata->data);
927}
928
929INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb callback, void *data) {
930  ENSURE_MSAN_INITED();
931  EnterLoader();
932  dl_iterate_phdr_data cbdata;
933  cbdata.callback = callback;
934  cbdata.data = data;
935  int res = REAL(dl_iterate_phdr)(msan_dl_iterate_phdr_cb, (void *)&cbdata);
936  ExitLoader();
937  return res;
938}
939
940INTERCEPTOR(int, getrusage, int who, void *usage) {
941  ENSURE_MSAN_INITED();
942  int res = REAL(getrusage)(who, usage);
943  if (res == 0) {
944    __msan_unpoison(usage, __sanitizer::struct_rusage_sz);
945  }
946  return res;
947}
948
949// sigactions_mu guarantees atomicity of sigaction() and signal() calls.
950// Access to sigactions[] is gone with relaxed atomics to avoid data race with
951// the signal handler.
952const int kMaxSignals = 1024;
953static atomic_uintptr_t sigactions[kMaxSignals];
954static StaticSpinMutex sigactions_mu;
955
956static void SignalHandler(int signo) {
957  ScopedThreadLocalStateBackup stlsb;
958  UnpoisonParam(1);
959
960  typedef void (*signal_cb)(int x);
961  signal_cb cb =
962      (signal_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
963  cb(signo);
964}
965
966static void SignalAction(int signo, void *si, void *uc) {
967  ScopedThreadLocalStateBackup stlsb;
968  UnpoisonParam(3);
969  __msan_unpoison(si, sizeof(__sanitizer_sigaction));
970  __msan_unpoison(uc, __sanitizer::ucontext_t_sz);
971
972  typedef void (*sigaction_cb)(int, void *, void *);
973  sigaction_cb cb =
974      (sigaction_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
975  cb(signo, si, uc);
976}
977
978INTERCEPTOR(int, sigaction, int signo, const __sanitizer_sigaction *act,
979            __sanitizer_sigaction *oldact) {
980  ENSURE_MSAN_INITED();
981  // FIXME: check that *act is unpoisoned.
982  // That requires intercepting all of sigemptyset, sigfillset, etc.
983  int res;
984  if (flags()->wrap_signals) {
985    SpinMutexLock lock(&sigactions_mu);
986    CHECK_LT(signo, kMaxSignals);
987    uptr old_cb = atomic_load(&sigactions[signo], memory_order_relaxed);
988    __sanitizer_sigaction new_act;
989    __sanitizer_sigaction *pnew_act = act ? &new_act : 0;
990    if (act) {
991      internal_memcpy(pnew_act, act, sizeof(__sanitizer_sigaction));
992      uptr cb = (uptr)pnew_act->sa_sigaction;
993      uptr new_cb = (pnew_act->sa_flags & __sanitizer::sa_siginfo)
994                        ? (uptr)SignalAction
995                        : (uptr)SignalHandler;
996      if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
997        atomic_store(&sigactions[signo], cb, memory_order_relaxed);
998        pnew_act->sa_sigaction = (void (*)(int, void *, void *))new_cb;
999      }
1000    }
1001    res = REAL(sigaction)(signo, pnew_act, oldact);
1002    if (res == 0 && oldact) {
1003      uptr cb = (uptr)oldact->sa_sigaction;
1004      if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1005        oldact->sa_sigaction = (void (*)(int, void *, void *))old_cb;
1006      }
1007    }
1008  } else {
1009    res = REAL(sigaction)(signo, act, oldact);
1010  }
1011
1012  if (res == 0 && oldact) {
1013    __msan_unpoison(oldact, sizeof(__sanitizer_sigaction));
1014  }
1015  return res;
1016}
1017
1018INTERCEPTOR(int, signal, int signo, uptr cb) {
1019  ENSURE_MSAN_INITED();
1020  if (flags()->wrap_signals) {
1021    CHECK_LT(signo, kMaxSignals);
1022    SpinMutexLock lock(&sigactions_mu);
1023    if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1024      atomic_store(&sigactions[signo], cb, memory_order_relaxed);
1025      cb = (uptr) SignalHandler;
1026    }
1027    return REAL(signal)(signo, cb);
1028  } else {
1029    return REAL(signal)(signo, cb);
1030  }
1031}
1032
1033extern "C" int pthread_attr_init(void *attr);
1034extern "C" int pthread_attr_destroy(void *attr);
1035extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
1036extern "C" int pthread_attr_getstack(void *attr, uptr *stack, uptr *stacksize);
1037
1038INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void*),
1039            void * param) {
1040  ENSURE_MSAN_INITED(); // for GetTlsSize()
1041  __sanitizer_pthread_attr_t myattr;
1042  if (attr == 0) {
1043    pthread_attr_init(&myattr);
1044    attr = &myattr;
1045  }
1046
1047  AdjustStackSizeLinux(attr, flags()->verbosity);
1048
1049  int res = REAL(pthread_create)(th, attr, callback, param);
1050  if (attr == &myattr)
1051    pthread_attr_destroy(&myattr);
1052  if (!res) {
1053    __msan_unpoison(th, __sanitizer::pthread_t_sz);
1054  }
1055  return res;
1056}
1057
1058INTERCEPTOR(int, pthread_key_create, __sanitizer_pthread_key_t *key,
1059            void (*dtor)(void *value)) {
1060  ENSURE_MSAN_INITED();
1061  int res = REAL(pthread_key_create)(key, dtor);
1062  if (!res && key)
1063    __msan_unpoison(key, sizeof(*key));
1064  return res;
1065}
1066
1067INTERCEPTOR(int, pthread_join, void *th, void **retval) {
1068  ENSURE_MSAN_INITED();
1069  int res = REAL(pthread_join)(th, retval);
1070  if (!res && retval)
1071    __msan_unpoison(retval, sizeof(*retval));
1072  return res;
1073}
1074
1075extern char *tzname[2];
1076
1077INTERCEPTOR(void, tzset) {
1078  ENSURE_MSAN_INITED();
1079  REAL(tzset)();
1080  if (tzname[0])
1081    __msan_unpoison(tzname[0], REAL(strlen)(tzname[0]) + 1);
1082  if (tzname[1])
1083    __msan_unpoison(tzname[1], REAL(strlen)(tzname[1]) + 1);
1084  return;
1085}
1086
1087struct MSanAtExitRecord {
1088  void (*func)(void *arg);
1089  void *arg;
1090};
1091
1092void MSanAtExitWrapper(void *arg) {
1093  UnpoisonParam(1);
1094  MSanAtExitRecord *r = (MSanAtExitRecord *)arg;
1095  r->func(r->arg);
1096  InternalFree(r);
1097}
1098
1099// Unpoison argument shadow for C++ module destructors.
1100INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg,
1101            void *dso_handle) {
1102  if (msan_init_is_running) return REAL(__cxa_atexit)(func, arg, dso_handle);
1103  ENSURE_MSAN_INITED();
1104  MSanAtExitRecord *r =
1105      (MSanAtExitRecord *)InternalAlloc(sizeof(MSanAtExitRecord));
1106  r->func = func;
1107  r->arg = arg;
1108  return REAL(__cxa_atexit)(MSanAtExitWrapper, r, dso_handle);
1109}
1110
1111struct MSanInterceptorContext {
1112  bool in_interceptor_scope;
1113};
1114
1115// A version of CHECK_UNPOISED using a saved scope value. Used in common
1116// interceptors.
1117#define CHECK_UNPOISONED_CTX(ctx, x, n)                         \
1118  do {                                                          \
1119    if (!((MSanInterceptorContext *)ctx)->in_interceptor_scope) \
1120      CHECK_UNPOISONED_0(x, n);                                 \
1121  } while (0)
1122
1123#define COMMON_INTERCEPTOR_UNPOISON_PARAM(ctx, count)  \
1124  UnpoisonParam(count)
1125#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
1126  __msan_unpoison(ptr, size)
1127#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
1128  CHECK_UNPOISONED_CTX(ctx, ptr, size)
1129#define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)              \
1130  if (msan_init_is_running) return REAL(func)(__VA_ARGS__);   \
1131  MSanInterceptorContext msan_ctx = {IsInInterceptorScope()}; \
1132  ctx = (void *)&msan_ctx;                                    \
1133  InterceptorScope interceptor_scope;                         \
1134  ENSURE_MSAN_INITED();
1135#define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
1136  do {                                         \
1137  } while (false)
1138#define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
1139  do {                                         \
1140  } while (false)
1141#define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
1142  do {                                                      \
1143  } while (false)
1144#define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
1145  do {                                                \
1146  } while (false)  // FIXME
1147#define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
1148#include "sanitizer_common/sanitizer_common_interceptors.inc"
1149
1150#define COMMON_SYSCALL_PRE_READ_RANGE(p, s) CHECK_UNPOISONED(p, s)
1151#define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
1152  do {                                       \
1153  } while (false)
1154#define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
1155  do {                                       \
1156  } while (false)
1157#define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) __msan_unpoison(p, s)
1158#include "sanitizer_common/sanitizer_common_syscalls.inc"
1159
1160// static
1161void *fast_memset(void *ptr, int c, SIZE_T n) {
1162  // hack until we have a really fast internal_memset
1163  if (sizeof(uptr) == 8 &&
1164      (n % 8) == 0 &&
1165      ((uptr)ptr % 8) == 0 &&
1166      (c == 0 || c == -1)) {
1167    // Printf("memset %p %zd %x\n", ptr, n, c);
1168    uptr to_store = c ? -1L : 0L;
1169    uptr *p = (uptr*)ptr;
1170    for (SIZE_T i = 0; i < n / 8; i++)
1171      p[i] = to_store;
1172    return ptr;
1173  }
1174  return internal_memset(ptr, c, n);
1175}
1176
1177// static
1178void *fast_memcpy(void *dst, const void *src, SIZE_T n) {
1179  // Same hack as in fast_memset above.
1180  if (sizeof(uptr) == 8 &&
1181      (n % 8) == 0 &&
1182      ((uptr)dst % 8) == 0 &&
1183      ((uptr)src % 8) == 0) {
1184    uptr *d = (uptr*)dst;
1185    uptr *s = (uptr*)src;
1186    for (SIZE_T i = 0; i < n / 8; i++)
1187      d[i] = s[i];
1188    return dst;
1189  }
1190  return internal_memcpy(dst, src, n);
1191}
1192
1193// These interface functions reside here so that they can use
1194// fast_memset, etc.
1195void __msan_unpoison(const void *a, uptr size) {
1196  if (!MEM_IS_APP(a)) return;
1197  fast_memset((void*)MEM_TO_SHADOW((uptr)a), 0, size);
1198}
1199
1200void __msan_poison(const void *a, uptr size) {
1201  if (!MEM_IS_APP(a)) return;
1202  fast_memset((void*)MEM_TO_SHADOW((uptr)a),
1203              __msan::flags()->poison_heap_with_zeroes ? 0 : -1, size);
1204}
1205
1206void __msan_poison_stack(void *a, uptr size) {
1207  if (!MEM_IS_APP(a)) return;
1208  fast_memset((void*)MEM_TO_SHADOW((uptr)a),
1209              __msan::flags()->poison_stack_with_zeroes ? 0 : -1, size);
1210}
1211
1212void __msan_clear_and_unpoison(void *a, uptr size) {
1213  fast_memset(a, 0, size);
1214  fast_memset((void*)MEM_TO_SHADOW((uptr)a), 0, size);
1215}
1216
1217void __msan_copy_origin(void *dst, const void *src, uptr size) {
1218  if (!__msan_get_track_origins()) return;
1219  if (!MEM_IS_APP(dst) || !MEM_IS_APP(src)) return;
1220  uptr d = MEM_TO_ORIGIN(dst);
1221  uptr s = MEM_TO_ORIGIN(src);
1222  uptr beg = d & ~3UL;  // align down.
1223  uptr end = (d + size + 3) & ~3UL;  // align up.
1224  s = s & ~3UL;  // align down.
1225  fast_memcpy((void*)beg, (void*)s, end - beg);
1226}
1227
1228void __msan_copy_poison(void *dst, const void *src, uptr size) {
1229  if (!MEM_IS_APP(dst)) return;
1230  if (!MEM_IS_APP(src)) return;
1231  fast_memcpy((void*)MEM_TO_SHADOW((uptr)dst),
1232              (void*)MEM_TO_SHADOW((uptr)src), size);
1233  __msan_copy_origin(dst, src, size);
1234}
1235
1236void __msan_move_poison(void *dst, const void *src, uptr size) {
1237  if (!MEM_IS_APP(dst)) return;
1238  if (!MEM_IS_APP(src)) return;
1239  internal_memmove((void*)MEM_TO_SHADOW((uptr)dst),
1240         (void*)MEM_TO_SHADOW((uptr)src), size);
1241  __msan_copy_origin(dst, src, size);
1242}
1243
1244void *__msan_memcpy(void *dest, const void *src, SIZE_T n) {
1245  ENSURE_MSAN_INITED();
1246  void *res = fast_memcpy(dest, src, n);
1247  __msan_copy_poison(dest, src, n);
1248  return res;
1249}
1250
1251void *__msan_memset(void *s, int c, SIZE_T n) {
1252  ENSURE_MSAN_INITED();
1253  void *res = fast_memset(s, c, n);
1254  __msan_unpoison(s, n);
1255  return res;
1256}
1257
1258void *__msan_memmove(void *dest, const void *src, SIZE_T n) {
1259  ENSURE_MSAN_INITED();
1260  void *res = REAL(memmove)(dest, src, n);
1261  __msan_move_poison(dest, src, n);
1262  return res;
1263}
1264
1265namespace __msan {
1266void InitializeInterceptors() {
1267  static int inited = 0;
1268  CHECK_EQ(inited, 0);
1269  SANITIZER_COMMON_INTERCEPTORS_INIT;
1270
1271  INTERCEPT_FUNCTION(mmap);
1272  INTERCEPT_FUNCTION(mmap64);
1273  INTERCEPT_FUNCTION(posix_memalign);
1274  INTERCEPT_FUNCTION(memalign);
1275  INTERCEPT_FUNCTION(valloc);
1276  INTERCEPT_FUNCTION(pvalloc);
1277  INTERCEPT_FUNCTION(malloc);
1278  INTERCEPT_FUNCTION(calloc);
1279  INTERCEPT_FUNCTION(realloc);
1280  INTERCEPT_FUNCTION(free);
1281  INTERCEPT_FUNCTION(fread);
1282  INTERCEPT_FUNCTION(fread_unlocked);
1283  INTERCEPT_FUNCTION(readlink);
1284  INTERCEPT_FUNCTION(memcpy);
1285  INTERCEPT_FUNCTION(mempcpy);
1286  INTERCEPT_FUNCTION(memset);
1287  INTERCEPT_FUNCTION(memmove);
1288  INTERCEPT_FUNCTION(bcopy);
1289  INTERCEPT_FUNCTION(wmemset);
1290  INTERCEPT_FUNCTION(wmemcpy);
1291  INTERCEPT_FUNCTION(wmempcpy);
1292  INTERCEPT_FUNCTION(wmemmove);
1293  INTERCEPT_FUNCTION(strcpy);  // NOLINT
1294  INTERCEPT_FUNCTION(stpcpy);  // NOLINT
1295  INTERCEPT_FUNCTION(strdup);
1296  INTERCEPT_FUNCTION(__strdup);
1297  INTERCEPT_FUNCTION(strndup);
1298  INTERCEPT_FUNCTION(__strndup);
1299  INTERCEPT_FUNCTION(strncpy);  // NOLINT
1300  INTERCEPT_FUNCTION(strlen);
1301  INTERCEPT_FUNCTION(strnlen);
1302  INTERCEPT_FUNCTION(gcvt);
1303  INTERCEPT_FUNCTION(strcat);  // NOLINT
1304  INTERCEPT_FUNCTION(strncat);  // NOLINT
1305  INTERCEPT_FUNCTION(strtol);
1306  INTERCEPT_FUNCTION(strtoll);
1307  INTERCEPT_FUNCTION(strtoul);
1308  INTERCEPT_FUNCTION(strtoull);
1309  INTERCEPT_FUNCTION(strtod);
1310  INTERCEPT_FUNCTION(strtof);
1311  INTERCEPT_FUNCTION(strtold);
1312  INTERCEPT_FUNCTION(vasprintf);
1313  INTERCEPT_FUNCTION(asprintf);
1314  INTERCEPT_FUNCTION(vsprintf);
1315  INTERCEPT_FUNCTION(vsnprintf);
1316  INTERCEPT_FUNCTION(vswprintf);
1317  INTERCEPT_FUNCTION(sprintf);  // NOLINT
1318  INTERCEPT_FUNCTION(snprintf);
1319  INTERCEPT_FUNCTION(swprintf);
1320  INTERCEPT_FUNCTION(strftime);
1321  INTERCEPT_FUNCTION(mbtowc);
1322  INTERCEPT_FUNCTION(mbrtowc);
1323  INTERCEPT_FUNCTION(wcslen);
1324  INTERCEPT_FUNCTION(wcschr);
1325  INTERCEPT_FUNCTION(wcscpy);
1326  INTERCEPT_FUNCTION(wcscmp);
1327  INTERCEPT_FUNCTION(wcstod);
1328  INTERCEPT_FUNCTION(getenv);
1329  INTERCEPT_FUNCTION(setenv);
1330  INTERCEPT_FUNCTION(putenv);
1331  INTERCEPT_FUNCTION(gettimeofday);
1332  INTERCEPT_FUNCTION(fcvt);
1333  INTERCEPT_FUNCTION(__fxstat);
1334  INTERCEPT_FUNCTION(__fxstatat);
1335  INTERCEPT_FUNCTION(__xstat);
1336  INTERCEPT_FUNCTION(__lxstat);
1337  INTERCEPT_FUNCTION(__fxstat64);
1338  INTERCEPT_FUNCTION(__fxstatat64);
1339  INTERCEPT_FUNCTION(__xstat64);
1340  INTERCEPT_FUNCTION(__lxstat64);
1341  INTERCEPT_FUNCTION(pipe);
1342  INTERCEPT_FUNCTION(pipe2);
1343  INTERCEPT_FUNCTION(socketpair);
1344  INTERCEPT_FUNCTION(fgets);
1345  INTERCEPT_FUNCTION(fgets_unlocked);
1346  INTERCEPT_FUNCTION(getrlimit);
1347  INTERCEPT_FUNCTION(getrlimit64);
1348  INTERCEPT_FUNCTION(statfs);
1349  INTERCEPT_FUNCTION(fstatfs);
1350  INTERCEPT_FUNCTION(statfs64);
1351  INTERCEPT_FUNCTION(fstatfs64);
1352  INTERCEPT_FUNCTION(uname);
1353  INTERCEPT_FUNCTION(gethostname);
1354  INTERCEPT_FUNCTION(epoll_wait);
1355  INTERCEPT_FUNCTION(epoll_pwait);
1356  INTERCEPT_FUNCTION(recv);
1357  INTERCEPT_FUNCTION(recvfrom);
1358  INTERCEPT_FUNCTION(dladdr);
1359  INTERCEPT_FUNCTION(dlopen);
1360  INTERCEPT_FUNCTION(dl_iterate_phdr);
1361  INTERCEPT_FUNCTION(getrusage);
1362  INTERCEPT_FUNCTION(sigaction);
1363  INTERCEPT_FUNCTION(signal);
1364  INTERCEPT_FUNCTION(pthread_create);
1365  INTERCEPT_FUNCTION(pthread_key_create);
1366  INTERCEPT_FUNCTION(pthread_join);
1367  INTERCEPT_FUNCTION(tzset);
1368  INTERCEPT_FUNCTION(__cxa_atexit);
1369  inited = 1;
1370}
1371}  // namespace __msan
1372