msan_interceptors.cc revision 3f4beff5efdd0d30844ca8b270876f7d59a608e7
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(double, strtod_l, const char *nptr, char **endptr,
333            void *loc) {  // NOLINT
334  ENSURE_MSAN_INITED();
335  double res = REAL(strtod_l)(nptr, endptr, loc);  // NOLINT
336  if (!__msan_has_dynamic_component()) {
337    __msan_unpoison(endptr, sizeof(*endptr));
338  }
339  return res;
340}
341
342INTERCEPTOR(double, __strtod_l, const char *nptr, char **endptr,
343            void *loc) {  // NOLINT
344  ENSURE_MSAN_INITED();
345  double res = REAL(__strtod_l)(nptr, endptr, loc);  // NOLINT
346  if (!__msan_has_dynamic_component()) {
347    __msan_unpoison(endptr, sizeof(*endptr));
348  }
349  return res;
350}
351
352INTERCEPTOR(float, strtof, const char *nptr, char **endptr) {  // NOLINT
353  ENSURE_MSAN_INITED();
354  float res = REAL(strtof)(nptr, endptr);  // NOLINT
355  if (!__msan_has_dynamic_component()) {
356    __msan_unpoison(endptr, sizeof(*endptr));
357  }
358  return res;
359}
360
361INTERCEPTOR(float, strtof_l, const char *nptr, char **endptr,
362            void *loc) {  // NOLINT
363  ENSURE_MSAN_INITED();
364  float res = REAL(strtof_l)(nptr, endptr, loc);  // NOLINT
365  if (!__msan_has_dynamic_component()) {
366    __msan_unpoison(endptr, sizeof(*endptr));
367  }
368  return res;
369}
370
371INTERCEPTOR(float, __strtof_l, const char *nptr, char **endptr,
372            void *loc) {  // NOLINT
373  ENSURE_MSAN_INITED();
374  float res = REAL(__strtof_l)(nptr, endptr, loc);  // NOLINT
375  if (!__msan_has_dynamic_component()) {
376    __msan_unpoison(endptr, sizeof(*endptr));
377  }
378  return res;
379}
380
381INTERCEPTOR(long double, strtold, const char *nptr, char **endptr) {  // NOLINT
382  ENSURE_MSAN_INITED();
383  long double res = REAL(strtold)(nptr, endptr);  // NOLINT
384  if (!__msan_has_dynamic_component()) {
385    __msan_unpoison(endptr, sizeof(*endptr));
386  }
387  return res;
388}
389
390INTERCEPTOR(long double, strtold_l, const char *nptr, char **endptr,
391            void *loc) {  // NOLINT
392  ENSURE_MSAN_INITED();
393  long double res = REAL(strtold_l)(nptr, endptr, loc);  // NOLINT
394  if (!__msan_has_dynamic_component()) {
395    __msan_unpoison(endptr, sizeof(*endptr));
396  }
397  return res;
398}
399
400INTERCEPTOR(long double, __strtold_l, const char *nptr, char **endptr,
401            void *loc) {  // NOLINT
402  ENSURE_MSAN_INITED();
403  long double res = REAL(__strtold_l)(nptr, endptr, loc);  // NOLINT
404  if (!__msan_has_dynamic_component()) {
405    __msan_unpoison(endptr, sizeof(*endptr));
406  }
407  return res;
408}
409
410INTERCEPTOR(int, vasprintf, char **strp, const char *format, va_list ap) {
411  ENSURE_MSAN_INITED();
412  int res = REAL(vasprintf)(strp, format, ap);
413  if (res >= 0 && !__msan_has_dynamic_component()) {
414    __msan_unpoison(strp, sizeof(*strp));
415    __msan_unpoison(*strp, res + 1);
416  }
417  return res;
418}
419
420INTERCEPTOR(int, asprintf, char **strp, const char *format, ...) {  // NOLINT
421  ENSURE_MSAN_INITED();
422  va_list ap;
423  va_start(ap, format);
424  int res = vasprintf(strp, format, ap);  // NOLINT
425  va_end(ap);
426  return res;
427}
428
429INTERCEPTOR(int, vsnprintf, char *str, uptr size,
430            const char *format, va_list ap) {
431  ENSURE_MSAN_INITED();
432  int res = REAL(vsnprintf)(str, size, format, ap);
433  if (res >= 0 && !__msan_has_dynamic_component()) {
434    __msan_unpoison(str, res + 1);
435  }
436  return res;
437}
438
439INTERCEPTOR(int, vsprintf, char *str, const char *format, va_list ap) {
440  ENSURE_MSAN_INITED();
441  int res = REAL(vsprintf)(str, format, ap);
442  if (res >= 0 && !__msan_has_dynamic_component()) {
443    __msan_unpoison(str, res + 1);
444  }
445  return res;
446}
447
448INTERCEPTOR(int, vswprintf, void *str, uptr size, void *format, va_list ap) {
449  ENSURE_MSAN_INITED();
450  int res = REAL(vswprintf)(str, size, format, ap);
451  if (res >= 0 && !__msan_has_dynamic_component()) {
452    __msan_unpoison(str, 4 * (res + 1));
453  }
454  return res;
455}
456
457INTERCEPTOR(int, sprintf, char *str, const char *format, ...) {  // NOLINT
458  ENSURE_MSAN_INITED();
459  va_list ap;
460  va_start(ap, format);
461  int res = vsprintf(str, format, ap);  // NOLINT
462  va_end(ap);
463  return res;
464}
465
466INTERCEPTOR(int, snprintf, char *str, uptr size, const char *format, ...) {
467  ENSURE_MSAN_INITED();
468  va_list ap;
469  va_start(ap, format);
470  int res = vsnprintf(str, size, format, ap);
471  va_end(ap);
472  return res;
473}
474
475INTERCEPTOR(int, swprintf, void *str, uptr size, void *format, ...) {
476  ENSURE_MSAN_INITED();
477  va_list ap;
478  va_start(ap, format);
479  int res = vswprintf(str, size, format, ap);
480  va_end(ap);
481  return res;
482}
483
484// SIZE_T strftime(char *s, SIZE_T max, const char *format,const struct tm *tm);
485INTERCEPTOR(SIZE_T, strftime, char *s, SIZE_T max, const char *format,
486            void *tm) {
487  ENSURE_MSAN_INITED();
488  SIZE_T res = REAL(strftime)(s, max, format, tm);
489  if (res) __msan_unpoison(s, res + 1);
490  return res;
491}
492
493INTERCEPTOR(int, mbtowc, wchar_t *dest, const char *src, SIZE_T n) {
494  ENSURE_MSAN_INITED();
495  int res = REAL(mbtowc)(dest, src, n);
496  if (res != -1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
497  return res;
498}
499
500INTERCEPTOR(int, mbrtowc, wchar_t *dest, const char *src, SIZE_T n, void *ps) {
501  ENSURE_MSAN_INITED();
502  SIZE_T res = REAL(mbrtowc)(dest, src, n, ps);
503  if (res != (SIZE_T)-1 && dest) __msan_unpoison(dest, sizeof(wchar_t));
504  return res;
505}
506
507INTERCEPTOR(SIZE_T, wcslen, const wchar_t *s) {
508  ENSURE_MSAN_INITED();
509  SIZE_T res = REAL(wcslen)(s);
510  CHECK_UNPOISONED(s, sizeof(wchar_t) * (res + 1));
511  return res;
512}
513
514// wchar_t *wcschr(const wchar_t *wcs, wchar_t wc);
515INTERCEPTOR(wchar_t *, wcschr, void *s, wchar_t wc, void *ps) {
516  ENSURE_MSAN_INITED();
517  wchar_t *res = REAL(wcschr)(s, wc, ps);
518  return res;
519}
520
521// wchar_t *wcscpy(wchar_t *dest, const wchar_t *src);
522INTERCEPTOR(wchar_t *, wcscpy, wchar_t *dest, const wchar_t *src) {
523  ENSURE_MSAN_INITED();
524  wchar_t *res = REAL(wcscpy)(dest, src);
525  __msan_copy_poison(dest, src, sizeof(wchar_t) * (REAL(wcslen)(src) + 1));
526  return res;
527}
528
529// wchar_t *wmemcpy(wchar_t *dest, const wchar_t *src, SIZE_T n);
530INTERCEPTOR(wchar_t *, wmemcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
531  ENSURE_MSAN_INITED();
532  wchar_t *res = REAL(wmemcpy)(dest, src, n);
533  __msan_copy_poison(dest, src, n * sizeof(wchar_t));
534  return res;
535}
536
537INTERCEPTOR(wchar_t *, wmempcpy, wchar_t *dest, const wchar_t *src, SIZE_T n) {
538  ENSURE_MSAN_INITED();
539  wchar_t *res = REAL(wmempcpy)(dest, src, n);
540  __msan_copy_poison(dest, src, n * sizeof(wchar_t));
541  return res;
542}
543
544INTERCEPTOR(wchar_t *, wmemset, wchar_t *s, wchar_t c, SIZE_T n) {
545  CHECK(MEM_IS_APP(s));
546  ENSURE_MSAN_INITED();
547  wchar_t *res = (wchar_t *)fast_memset(s, c, n * sizeof(wchar_t));
548  __msan_unpoison(s, n * sizeof(wchar_t));
549  return res;
550}
551
552INTERCEPTOR(wchar_t *, wmemmove, wchar_t *dest, const wchar_t *src, SIZE_T n) {
553  ENSURE_MSAN_INITED();
554  wchar_t *res = REAL(wmemmove)(dest, src, n);
555  __msan_move_poison(dest, src, n * sizeof(wchar_t));
556  return res;
557}
558
559INTERCEPTOR(int, wcscmp, const wchar_t *s1, const wchar_t *s2) {
560  ENSURE_MSAN_INITED();
561  int res = REAL(wcscmp)(s1, s2);
562  return res;
563}
564
565INTERCEPTOR(double, wcstod, const wchar_t *nptr, wchar_t **endptr) {
566  ENSURE_MSAN_INITED();
567  double res = REAL(wcstod)(nptr, endptr);
568  __msan_unpoison(endptr, sizeof(*endptr));
569  return res;
570}
571
572// #define UNSUPPORTED(name) \
573//   INTERCEPTOR(void, name, void) {                     \
574//     Printf("MSAN: Unsupported %s\n", __FUNCTION__);   \
575//     Die();                                            \
576//   }
577
578// FIXME: intercept the following functions:
579// Note, they only matter when running without a dynamic tool.
580// UNSUPPORTED(wcscoll_l)
581// UNSUPPORTED(wcsnrtombs)
582// UNSUPPORTED(wcstol)
583// UNSUPPORTED(wcstoll)
584// UNSUPPORTED(wcstold)
585// UNSUPPORTED(wcstoul)
586// UNSUPPORTED(wcstoull)
587// UNSUPPORTED(wcsxfrm_l)
588// UNSUPPORTED(wcsdup)
589// UNSUPPORTED(wcsftime)
590// UNSUPPORTED(wcsstr)
591// UNSUPPORTED(wcsrchr)
592// UNSUPPORTED(wctob)
593
594INTERCEPTOR(int, gettimeofday, void *tv, void *tz) {
595  ENSURE_MSAN_INITED();
596  int res = REAL(gettimeofday)(tv, tz);
597  if (tv)
598    __msan_unpoison(tv, 16);
599  if (tz)
600    __msan_unpoison(tz, 8);
601  return res;
602}
603
604INTERCEPTOR(char *, fcvt, double x, int a, int *b, int *c) {
605  ENSURE_MSAN_INITED();
606  char *res = REAL(fcvt)(x, a, b, c);
607  if (!__msan_has_dynamic_component()) {
608    __msan_unpoison(b, sizeof(*b));
609    __msan_unpoison(c, sizeof(*c));
610  }
611  return res;
612}
613
614INTERCEPTOR(char *, getenv, char *name) {
615  ENSURE_MSAN_INITED();
616  char *res = REAL(getenv)(name);
617  if (!__msan_has_dynamic_component()) {
618    if (res)
619      __msan_unpoison(res, REAL(strlen)(res) + 1);
620  }
621  return res;
622}
623
624extern char **environ;
625
626static void UnpoisonEnviron() {
627  char **envp = environ;
628  for (; *envp; ++envp) {
629    __msan_unpoison(envp, sizeof(*envp));
630    __msan_unpoison(*envp, REAL(strlen)(*envp) + 1);
631  }
632  // Trailing NULL pointer.
633  __msan_unpoison(envp, sizeof(*envp));
634}
635
636INTERCEPTOR(int, setenv, const char *name, const char *value, int overwrite) {
637  ENSURE_MSAN_INITED();
638  int res = REAL(setenv)(name, value, overwrite);
639  if (!res) UnpoisonEnviron();
640  return res;
641}
642
643INTERCEPTOR(int, putenv, char *string) {
644  ENSURE_MSAN_INITED();
645  int res = REAL(putenv)(string);
646  if (!res) UnpoisonEnviron();
647  return res;
648}
649
650INTERCEPTOR(int, __fxstat, int magic, int fd, void *buf) {
651  ENSURE_MSAN_INITED();
652  int res = REAL(__fxstat)(magic, fd, buf);
653  if (!res)
654    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
655  return res;
656}
657
658INTERCEPTOR(int, __fxstat64, int magic, int fd, void *buf) {
659  ENSURE_MSAN_INITED();
660  int res = REAL(__fxstat64)(magic, fd, buf);
661  if (!res)
662    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
663  return res;
664}
665
666INTERCEPTOR(int, __fxstatat, int magic, int fd, char *pathname, void *buf,
667            int flags) {
668  ENSURE_MSAN_INITED();
669  int res = REAL(__fxstatat)(magic, fd, pathname, buf, flags);
670  if (!res) __msan_unpoison(buf, __sanitizer::struct_stat_sz);
671  return res;
672}
673
674INTERCEPTOR(int, __fxstatat64, int magic, int fd, char *pathname, void *buf,
675            int flags) {
676  ENSURE_MSAN_INITED();
677  int res = REAL(__fxstatat64)(magic, fd, pathname, buf, flags);
678  if (!res) __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
679  return res;
680}
681
682INTERCEPTOR(int, __xstat, int magic, char *path, void *buf) {
683  ENSURE_MSAN_INITED();
684  int res = REAL(__xstat)(magic, path, buf);
685  if (!res)
686    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
687  return res;
688}
689
690INTERCEPTOR(int, __xstat64, int magic, char *path, void *buf) {
691  ENSURE_MSAN_INITED();
692  int res = REAL(__xstat64)(magic, path, buf);
693  if (!res)
694    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
695  return res;
696}
697
698INTERCEPTOR(int, __lxstat, int magic, char *path, void *buf) {
699  ENSURE_MSAN_INITED();
700  int res = REAL(__lxstat)(magic, path, buf);
701  if (!res)
702    __msan_unpoison(buf, __sanitizer::struct_stat_sz);
703  return res;
704}
705
706INTERCEPTOR(int, __lxstat64, int magic, char *path, void *buf) {
707  ENSURE_MSAN_INITED();
708  int res = REAL(__lxstat64)(magic, path, buf);
709  if (!res)
710    __msan_unpoison(buf, __sanitizer::struct_stat64_sz);
711  return res;
712}
713
714INTERCEPTOR(int, pipe, int pipefd[2]) {
715  if (msan_init_is_running)
716    return REAL(pipe)(pipefd);
717  ENSURE_MSAN_INITED();
718  int res = REAL(pipe)(pipefd);
719  if (!res)
720    __msan_unpoison(pipefd, sizeof(int[2]));
721  return res;
722}
723
724INTERCEPTOR(int, pipe2, int pipefd[2], int flags) {
725  ENSURE_MSAN_INITED();
726  int res = REAL(pipe2)(pipefd, flags);
727  if (!res)
728    __msan_unpoison(pipefd, sizeof(int[2]));
729  return res;
730}
731
732INTERCEPTOR(int, socketpair, int domain, int type, int protocol, int sv[2]) {
733  ENSURE_MSAN_INITED();
734  int res = REAL(socketpair)(domain, type, protocol, sv);
735  if (!res)
736    __msan_unpoison(sv, sizeof(int[2]));
737  return res;
738}
739
740INTERCEPTOR(char *, fgets, char *s, int size, void *stream) {
741  ENSURE_MSAN_INITED();
742  char *res = REAL(fgets)(s, size, stream);
743  if (res)
744    __msan_unpoison(s, REAL(strlen)(s) + 1);
745  return res;
746}
747
748INTERCEPTOR(char *, fgets_unlocked, char *s, int size, void *stream) {
749  ENSURE_MSAN_INITED();
750  char *res = REAL(fgets_unlocked)(s, size, stream);
751  if (res)
752    __msan_unpoison(s, REAL(strlen)(s) + 1);
753  return res;
754}
755
756INTERCEPTOR(int, getrlimit, int resource, void *rlim) {
757  if (msan_init_is_running)
758    return REAL(getrlimit)(resource, rlim);
759  ENSURE_MSAN_INITED();
760  int res = REAL(getrlimit)(resource, rlim);
761  if (!res)
762    __msan_unpoison(rlim, __sanitizer::struct_rlimit_sz);
763  return res;
764}
765
766INTERCEPTOR(int, getrlimit64, int resource, void *rlim) {
767  if (msan_init_is_running)
768    return REAL(getrlimit64)(resource, rlim);
769  ENSURE_MSAN_INITED();
770  int res = REAL(getrlimit64)(resource, rlim);
771  if (!res)
772    __msan_unpoison(rlim, __sanitizer::struct_rlimit64_sz);
773  return res;
774}
775
776INTERCEPTOR(int, statfs, const char *s, void *buf) {
777  ENSURE_MSAN_INITED();
778  int res = REAL(statfs)(s, buf);
779  if (!res)
780    __msan_unpoison(buf, __sanitizer::struct_statfs_sz);
781  return res;
782}
783
784INTERCEPTOR(int, fstatfs, int fd, void *buf) {
785  ENSURE_MSAN_INITED();
786  int res = REAL(fstatfs)(fd, buf);
787  if (!res)
788    __msan_unpoison(buf, __sanitizer::struct_statfs_sz);
789  return res;
790}
791
792INTERCEPTOR(int, statfs64, const char *s, void *buf) {
793  ENSURE_MSAN_INITED();
794  int res = REAL(statfs64)(s, buf);
795  if (!res)
796    __msan_unpoison(buf, __sanitizer::struct_statfs64_sz);
797  return res;
798}
799
800INTERCEPTOR(int, fstatfs64, int fd, void *buf) {
801  ENSURE_MSAN_INITED();
802  int res = REAL(fstatfs64)(fd, buf);
803  if (!res)
804    __msan_unpoison(buf, __sanitizer::struct_statfs64_sz);
805  return res;
806}
807
808INTERCEPTOR(int, uname, void *utsname) {
809  ENSURE_MSAN_INITED();
810  int res = REAL(uname)(utsname);
811  if (!res) {
812    __msan_unpoison(utsname, __sanitizer::struct_utsname_sz);
813  }
814  return res;
815}
816
817INTERCEPTOR(int, gethostname, char *name, SIZE_T len) {
818  ENSURE_MSAN_INITED();
819  int res = REAL(gethostname)(name, len);
820  if (!res) {
821    SIZE_T real_len = REAL(strnlen)(name, len);
822    if (real_len < len)
823      ++real_len;
824    __msan_unpoison(name, real_len);
825  }
826  return res;
827}
828
829INTERCEPTOR(int, epoll_wait, int epfd, void *events, int maxevents,
830    int timeout) {
831  ENSURE_MSAN_INITED();
832  int res = REAL(epoll_wait)(epfd, events, maxevents, timeout);
833  if (res > 0) {
834    __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
835  }
836  return res;
837}
838
839INTERCEPTOR(int, epoll_pwait, int epfd, void *events, int maxevents,
840    int timeout, void *sigmask) {
841  ENSURE_MSAN_INITED();
842  int res = REAL(epoll_pwait)(epfd, events, maxevents, timeout, sigmask);
843  if (res > 0) {
844    __msan_unpoison(events, __sanitizer::struct_epoll_event_sz * res);
845  }
846  return res;
847}
848
849INTERCEPTOR(SSIZE_T, recv, int fd, void *buf, SIZE_T len, int flags) {
850  ENSURE_MSAN_INITED();
851  SSIZE_T res = REAL(recv)(fd, buf, len, flags);
852  if (res > 0)
853    __msan_unpoison(buf, res);
854  return res;
855}
856
857INTERCEPTOR(SSIZE_T, recvfrom, int fd, void *buf, SIZE_T len, int flags,
858            void *srcaddr, int *addrlen) {
859  ENSURE_MSAN_INITED();
860  SIZE_T srcaddr_sz;
861  if (srcaddr) srcaddr_sz = *addrlen;
862  SSIZE_T res = REAL(recvfrom)(fd, buf, len, flags, srcaddr, addrlen);
863  if (res > 0) {
864    __msan_unpoison(buf, res);
865    if (srcaddr) {
866      SIZE_T sz = *addrlen;
867      __msan_unpoison(srcaddr, (sz < srcaddr_sz) ? sz : srcaddr_sz);
868    }
869  }
870  return res;
871}
872
873INTERCEPTOR(void *, calloc, SIZE_T nmemb, SIZE_T size) {
874  if (CallocShouldReturnNullDueToOverflow(size, nmemb))
875    return AllocatorReturnNull();
876  GET_MALLOC_STACK_TRACE;
877  if (!msan_inited) {
878    // Hack: dlsym calls calloc before REAL(calloc) is retrieved from dlsym.
879    const SIZE_T kCallocPoolSize = 1024;
880    static uptr calloc_memory_for_dlsym[kCallocPoolSize];
881    static SIZE_T allocated;
882    SIZE_T size_in_words = ((nmemb * size) + kWordSize - 1) / kWordSize;
883    void *mem = (void*)&calloc_memory_for_dlsym[allocated];
884    allocated += size_in_words;
885    CHECK(allocated < kCallocPoolSize);
886    return mem;
887  }
888  return MsanReallocate(&stack, 0, nmemb * size, sizeof(u64), true);
889}
890
891INTERCEPTOR(void *, realloc, void *ptr, SIZE_T size) {
892  GET_MALLOC_STACK_TRACE;
893  return MsanReallocate(&stack, ptr, size, sizeof(u64), false);
894}
895
896INTERCEPTOR(void *, malloc, SIZE_T size) {
897  GET_MALLOC_STACK_TRACE;
898  return MsanReallocate(&stack, 0, size, sizeof(u64), false);
899}
900
901void __msan_allocated_memory(const void* data, uptr size) {
902  GET_MALLOC_STACK_TRACE;
903  if (flags()->poison_in_malloc)
904    __msan_poison(data, size);
905  if (__msan_get_track_origins()) {
906    u32 stack_id = StackDepotPut(stack.trace, stack.size);
907    CHECK(stack_id);
908    CHECK_EQ((stack_id >> 31), 0);  // Higher bit is occupied by stack origins.
909    __msan_set_origin(data, size, stack_id);
910  }
911}
912
913INTERCEPTOR(void *, mmap, void *addr, SIZE_T length, int prot, int flags,
914            int fd, OFF_T offset) {
915  ENSURE_MSAN_INITED();
916  void *res = REAL(mmap)(addr, length, prot, flags, fd, offset);
917  if (res != (void*)-1)
918    __msan_unpoison(res, RoundUpTo(length, GetPageSize()));
919  return res;
920}
921
922INTERCEPTOR(void *, mmap64, void *addr, SIZE_T length, int prot, int flags,
923            int fd, OFF64_T offset) {
924  ENSURE_MSAN_INITED();
925  void *res = REAL(mmap64)(addr, length, prot, flags, fd, offset);
926  if (res != (void*)-1)
927    __msan_unpoison(res, RoundUpTo(length, GetPageSize()));
928  return res;
929}
930
931struct dlinfo {
932  char *dli_fname;
933  void *dli_fbase;
934  char *dli_sname;
935  void *dli_saddr;
936};
937
938INTERCEPTOR(int, dladdr, void *addr, dlinfo *info) {
939  ENSURE_MSAN_INITED();
940  int res = REAL(dladdr)(addr, info);
941  if (res != 0) {
942    __msan_unpoison(info, sizeof(*info));
943    if (info->dli_fname)
944      __msan_unpoison(info->dli_fname, REAL(strlen)(info->dli_fname) + 1);
945    if (info->dli_sname)
946      __msan_unpoison(info->dli_sname, REAL(strlen)(info->dli_sname) + 1);
947  }
948  return res;
949}
950
951// dlopen() ultimately calls mmap() down inside the loader, which generally
952// doesn't participate in dynamic symbol resolution.  Therefore we won't
953// intercept its calls to mmap, and we have to hook it here.  The loader
954// initializes the module before returning, so without the dynamic component, we
955// won't be able to clear the shadow before the initializers.  Fixing this would
956// require putting our own initializer first to clear the shadow.
957INTERCEPTOR(void *, dlopen, const char *filename, int flag) {
958  ENSURE_MSAN_INITED();
959  EnterLoader();
960  link_map *map = (link_map *)REAL(dlopen)(filename, flag);
961  ExitLoader();
962  if (!__msan_has_dynamic_component() && map) {
963    // If msandr didn't clear the shadow before the initializers ran, we do it
964    // ourselves afterwards.
965    ForEachMappedRegion(map, __msan_unpoison);
966  }
967  return (void *)map;
968}
969
970typedef int (*dl_iterate_phdr_cb)(__sanitizer_dl_phdr_info *info, SIZE_T size,
971                                  void *data);
972struct dl_iterate_phdr_data {
973  dl_iterate_phdr_cb callback;
974  void *data;
975};
976
977static int msan_dl_iterate_phdr_cb(__sanitizer_dl_phdr_info *info, SIZE_T size,
978                                   void *data) {
979  if (info) {
980    __msan_unpoison(info, size);
981    if (info->dlpi_name)
982      __msan_unpoison(info->dlpi_name, REAL(strlen)(info->dlpi_name) + 1);
983  }
984  dl_iterate_phdr_data *cbdata = (dl_iterate_phdr_data *)data;
985  UnpoisonParam(3);
986  return cbdata->callback(info, size, cbdata->data);
987}
988
989INTERCEPTOR(int, dl_iterate_phdr, dl_iterate_phdr_cb callback, void *data) {
990  ENSURE_MSAN_INITED();
991  EnterLoader();
992  dl_iterate_phdr_data cbdata;
993  cbdata.callback = callback;
994  cbdata.data = data;
995  int res = REAL(dl_iterate_phdr)(msan_dl_iterate_phdr_cb, (void *)&cbdata);
996  ExitLoader();
997  return res;
998}
999
1000INTERCEPTOR(int, getrusage, int who, void *usage) {
1001  ENSURE_MSAN_INITED();
1002  int res = REAL(getrusage)(who, usage);
1003  if (res == 0) {
1004    __msan_unpoison(usage, __sanitizer::struct_rusage_sz);
1005  }
1006  return res;
1007}
1008
1009// sigactions_mu guarantees atomicity of sigaction() and signal() calls.
1010// Access to sigactions[] is gone with relaxed atomics to avoid data race with
1011// the signal handler.
1012const int kMaxSignals = 1024;
1013static atomic_uintptr_t sigactions[kMaxSignals];
1014static StaticSpinMutex sigactions_mu;
1015
1016static void SignalHandler(int signo) {
1017  ScopedThreadLocalStateBackup stlsb;
1018  UnpoisonParam(1);
1019
1020  typedef void (*signal_cb)(int x);
1021  signal_cb cb =
1022      (signal_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
1023  cb(signo);
1024}
1025
1026static void SignalAction(int signo, void *si, void *uc) {
1027  ScopedThreadLocalStateBackup stlsb;
1028  UnpoisonParam(3);
1029  __msan_unpoison(si, sizeof(__sanitizer_sigaction));
1030  __msan_unpoison(uc, __sanitizer::ucontext_t_sz);
1031
1032  typedef void (*sigaction_cb)(int, void *, void *);
1033  sigaction_cb cb =
1034      (sigaction_cb)atomic_load(&sigactions[signo], memory_order_relaxed);
1035  cb(signo, si, uc);
1036}
1037
1038INTERCEPTOR(int, sigaction, int signo, const __sanitizer_sigaction *act,
1039            __sanitizer_sigaction *oldact) {
1040  ENSURE_MSAN_INITED();
1041  // FIXME: check that *act is unpoisoned.
1042  // That requires intercepting all of sigemptyset, sigfillset, etc.
1043  int res;
1044  if (flags()->wrap_signals) {
1045    SpinMutexLock lock(&sigactions_mu);
1046    CHECK_LT(signo, kMaxSignals);
1047    uptr old_cb = atomic_load(&sigactions[signo], memory_order_relaxed);
1048    __sanitizer_sigaction new_act;
1049    __sanitizer_sigaction *pnew_act = act ? &new_act : 0;
1050    if (act) {
1051      internal_memcpy(pnew_act, act, sizeof(__sanitizer_sigaction));
1052      uptr cb = (uptr)pnew_act->sa_sigaction;
1053      uptr new_cb = (pnew_act->sa_flags & __sanitizer::sa_siginfo)
1054                        ? (uptr)SignalAction
1055                        : (uptr)SignalHandler;
1056      if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1057        atomic_store(&sigactions[signo], cb, memory_order_relaxed);
1058        pnew_act->sa_sigaction = (void (*)(int, void *, void *))new_cb;
1059      }
1060    }
1061    res = REAL(sigaction)(signo, pnew_act, oldact);
1062    if (res == 0 && oldact) {
1063      uptr cb = (uptr)oldact->sa_sigaction;
1064      if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1065        oldact->sa_sigaction = (void (*)(int, void *, void *))old_cb;
1066      }
1067    }
1068  } else {
1069    res = REAL(sigaction)(signo, act, oldact);
1070  }
1071
1072  if (res == 0 && oldact) {
1073    __msan_unpoison(oldact, sizeof(__sanitizer_sigaction));
1074  }
1075  return res;
1076}
1077
1078INTERCEPTOR(int, signal, int signo, uptr cb) {
1079  ENSURE_MSAN_INITED();
1080  if (flags()->wrap_signals) {
1081    CHECK_LT(signo, kMaxSignals);
1082    SpinMutexLock lock(&sigactions_mu);
1083    if (cb != __sanitizer::sig_ign && cb != __sanitizer::sig_dfl) {
1084      atomic_store(&sigactions[signo], cb, memory_order_relaxed);
1085      cb = (uptr) SignalHandler;
1086    }
1087    return REAL(signal)(signo, cb);
1088  } else {
1089    return REAL(signal)(signo, cb);
1090  }
1091}
1092
1093extern "C" int pthread_attr_init(void *attr);
1094extern "C" int pthread_attr_destroy(void *attr);
1095extern "C" int pthread_attr_setstacksize(void *attr, uptr stacksize);
1096extern "C" int pthread_attr_getstack(void *attr, uptr *stack, uptr *stacksize);
1097
1098INTERCEPTOR(int, pthread_create, void *th, void *attr, void *(*callback)(void*),
1099            void * param) {
1100  ENSURE_MSAN_INITED(); // for GetTlsSize()
1101  __sanitizer_pthread_attr_t myattr;
1102  if (attr == 0) {
1103    pthread_attr_init(&myattr);
1104    attr = &myattr;
1105  }
1106
1107  AdjustStackSizeLinux(attr, flags()->verbosity);
1108
1109  int res = REAL(pthread_create)(th, attr, callback, param);
1110  if (attr == &myattr)
1111    pthread_attr_destroy(&myattr);
1112  if (!res) {
1113    __msan_unpoison(th, __sanitizer::pthread_t_sz);
1114  }
1115  return res;
1116}
1117
1118INTERCEPTOR(int, pthread_key_create, __sanitizer_pthread_key_t *key,
1119            void (*dtor)(void *value)) {
1120  ENSURE_MSAN_INITED();
1121  int res = REAL(pthread_key_create)(key, dtor);
1122  if (!res && key)
1123    __msan_unpoison(key, sizeof(*key));
1124  return res;
1125}
1126
1127INTERCEPTOR(int, pthread_join, void *th, void **retval) {
1128  ENSURE_MSAN_INITED();
1129  int res = REAL(pthread_join)(th, retval);
1130  if (!res && retval)
1131    __msan_unpoison(retval, sizeof(*retval));
1132  return res;
1133}
1134
1135extern char *tzname[2];
1136
1137INTERCEPTOR(void, tzset) {
1138  ENSURE_MSAN_INITED();
1139  REAL(tzset)();
1140  if (tzname[0])
1141    __msan_unpoison(tzname[0], REAL(strlen)(tzname[0]) + 1);
1142  if (tzname[1])
1143    __msan_unpoison(tzname[1], REAL(strlen)(tzname[1]) + 1);
1144  return;
1145}
1146
1147struct MSanAtExitRecord {
1148  void (*func)(void *arg);
1149  void *arg;
1150};
1151
1152void MSanAtExitWrapper(void *arg) {
1153  UnpoisonParam(1);
1154  MSanAtExitRecord *r = (MSanAtExitRecord *)arg;
1155  r->func(r->arg);
1156  InternalFree(r);
1157}
1158
1159// Unpoison argument shadow for C++ module destructors.
1160INTERCEPTOR(int, __cxa_atexit, void (*func)(void *), void *arg,
1161            void *dso_handle) {
1162  if (msan_init_is_running) return REAL(__cxa_atexit)(func, arg, dso_handle);
1163  ENSURE_MSAN_INITED();
1164  MSanAtExitRecord *r =
1165      (MSanAtExitRecord *)InternalAlloc(sizeof(MSanAtExitRecord));
1166  r->func = func;
1167  r->arg = arg;
1168  return REAL(__cxa_atexit)(MSanAtExitWrapper, r, dso_handle);
1169}
1170
1171struct MSanInterceptorContext {
1172  bool in_interceptor_scope;
1173};
1174
1175namespace __msan {
1176
1177int OnExit() {
1178  // FIXME: ask frontend whether we need to return failure.
1179  return 0;
1180}
1181
1182}  // namespace __msan
1183
1184// A version of CHECK_UNPOISED using a saved scope value. Used in common
1185// interceptors.
1186#define CHECK_UNPOISONED_CTX(ctx, x, n)                         \
1187  do {                                                          \
1188    if (!((MSanInterceptorContext *)ctx)->in_interceptor_scope) \
1189      CHECK_UNPOISONED_0(x, n);                                 \
1190  } while (0)
1191
1192#define COMMON_INTERCEPTOR_UNPOISON_PARAM(ctx, count)  \
1193  UnpoisonParam(count)
1194#define COMMON_INTERCEPTOR_WRITE_RANGE(ctx, ptr, size) \
1195  __msan_unpoison(ptr, size)
1196#define COMMON_INTERCEPTOR_READ_RANGE(ctx, ptr, size) \
1197  CHECK_UNPOISONED_CTX(ctx, ptr, size)
1198#define COMMON_INTERCEPTOR_INITIALIZE_RANGE(ctx, ptr, size) \
1199  __msan_unpoison(ptr, size)
1200#define COMMON_INTERCEPTOR_ENTER(ctx, func, ...)              \
1201  if (msan_init_is_running) return REAL(func)(__VA_ARGS__);   \
1202  MSanInterceptorContext msan_ctx = {IsInInterceptorScope()}; \
1203  ctx = (void *)&msan_ctx;                                    \
1204  (void)ctx;                                                  \
1205  InterceptorScope interceptor_scope;                         \
1206  ENSURE_MSAN_INITED();
1207#define COMMON_INTERCEPTOR_FD_ACQUIRE(ctx, fd) \
1208  do {                                         \
1209  } while (false)
1210#define COMMON_INTERCEPTOR_FD_RELEASE(ctx, fd) \
1211  do {                                         \
1212  } while (false)
1213#define COMMON_INTERCEPTOR_FD_SOCKET_ACCEPT(ctx, fd, newfd) \
1214  do {                                                      \
1215  } while (false)
1216#define COMMON_INTERCEPTOR_SET_THREAD_NAME(ctx, name) \
1217  do {                                                \
1218  } while (false)  // FIXME
1219#define COMMON_INTERCEPTOR_BLOCK_REAL(name) REAL(name)
1220#define COMMON_INTERCEPTOR_ON_EXIT(ctx) OnExit()
1221#include "sanitizer_common/sanitizer_common_interceptors.inc"
1222
1223#define COMMON_SYSCALL_PRE_READ_RANGE(p, s) CHECK_UNPOISONED(p, s)
1224#define COMMON_SYSCALL_PRE_WRITE_RANGE(p, s) \
1225  do {                                       \
1226  } while (false)
1227#define COMMON_SYSCALL_POST_READ_RANGE(p, s) \
1228  do {                                       \
1229  } while (false)
1230#define COMMON_SYSCALL_POST_WRITE_RANGE(p, s) __msan_unpoison(p, s)
1231#include "sanitizer_common/sanitizer_common_syscalls.inc"
1232
1233// static
1234void *fast_memset(void *ptr, int c, SIZE_T n) {
1235  // hack until we have a really fast internal_memset
1236  if (sizeof(uptr) == 8 &&
1237      (n % 8) == 0 &&
1238      ((uptr)ptr % 8) == 0 &&
1239      (c == 0 || c == -1)) {
1240    // Printf("memset %p %zd %x\n", ptr, n, c);
1241    uptr to_store = c ? -1L : 0L;
1242    uptr *p = (uptr*)ptr;
1243    for (SIZE_T i = 0; i < n / 8; i++)
1244      p[i] = to_store;
1245    return ptr;
1246  }
1247  return internal_memset(ptr, c, n);
1248}
1249
1250// static
1251void *fast_memcpy(void *dst, const void *src, SIZE_T n) {
1252  // Same hack as in fast_memset above.
1253  if (sizeof(uptr) == 8 &&
1254      (n % 8) == 0 &&
1255      ((uptr)dst % 8) == 0 &&
1256      ((uptr)src % 8) == 0) {
1257    uptr *d = (uptr*)dst;
1258    uptr *s = (uptr*)src;
1259    for (SIZE_T i = 0; i < n / 8; i++)
1260      d[i] = s[i];
1261    return dst;
1262  }
1263  return internal_memcpy(dst, src, n);
1264}
1265
1266// These interface functions reside here so that they can use
1267// fast_memset, etc.
1268void __msan_unpoison(const void *a, uptr size) {
1269  if (!MEM_IS_APP(a)) return;
1270  fast_memset((void*)MEM_TO_SHADOW((uptr)a), 0, size);
1271}
1272
1273void __msan_poison(const void *a, uptr size) {
1274  if (!MEM_IS_APP(a)) return;
1275  fast_memset((void*)MEM_TO_SHADOW((uptr)a),
1276              __msan::flags()->poison_heap_with_zeroes ? 0 : -1, size);
1277}
1278
1279void __msan_poison_stack(void *a, uptr size) {
1280  if (!MEM_IS_APP(a)) return;
1281  fast_memset((void*)MEM_TO_SHADOW((uptr)a),
1282              __msan::flags()->poison_stack_with_zeroes ? 0 : -1, size);
1283}
1284
1285void __msan_clear_and_unpoison(void *a, uptr size) {
1286  fast_memset(a, 0, size);
1287  fast_memset((void*)MEM_TO_SHADOW((uptr)a), 0, size);
1288}
1289
1290void __msan_copy_origin(void *dst, const void *src, uptr size) {
1291  if (!__msan_get_track_origins()) return;
1292  if (!MEM_IS_APP(dst) || !MEM_IS_APP(src)) return;
1293  uptr d = MEM_TO_ORIGIN(dst);
1294  uptr s = MEM_TO_ORIGIN(src);
1295  uptr beg = d & ~3UL;  // align down.
1296  uptr end = (d + size + 3) & ~3UL;  // align up.
1297  s = s & ~3UL;  // align down.
1298  fast_memcpy((void*)beg, (void*)s, end - beg);
1299}
1300
1301void __msan_copy_poison(void *dst, const void *src, uptr size) {
1302  if (!MEM_IS_APP(dst)) return;
1303  if (!MEM_IS_APP(src)) return;
1304  fast_memcpy((void*)MEM_TO_SHADOW((uptr)dst),
1305              (void*)MEM_TO_SHADOW((uptr)src), size);
1306  __msan_copy_origin(dst, src, size);
1307}
1308
1309void __msan_move_poison(void *dst, const void *src, uptr size) {
1310  if (!MEM_IS_APP(dst)) return;
1311  if (!MEM_IS_APP(src)) return;
1312  internal_memmove((void*)MEM_TO_SHADOW((uptr)dst),
1313         (void*)MEM_TO_SHADOW((uptr)src), size);
1314  __msan_copy_origin(dst, src, size);
1315}
1316
1317void *__msan_memcpy(void *dest, const void *src, SIZE_T n) {
1318  ENSURE_MSAN_INITED();
1319  void *res = fast_memcpy(dest, src, n);
1320  __msan_copy_poison(dest, src, n);
1321  return res;
1322}
1323
1324void *__msan_memset(void *s, int c, SIZE_T n) {
1325  ENSURE_MSAN_INITED();
1326  void *res = fast_memset(s, c, n);
1327  __msan_unpoison(s, n);
1328  return res;
1329}
1330
1331void *__msan_memmove(void *dest, const void *src, SIZE_T n) {
1332  ENSURE_MSAN_INITED();
1333  void *res = REAL(memmove)(dest, src, n);
1334  __msan_move_poison(dest, src, n);
1335  return res;
1336}
1337
1338namespace __msan {
1339void InitializeInterceptors() {
1340  static int inited = 0;
1341  CHECK_EQ(inited, 0);
1342  SANITIZER_COMMON_INTERCEPTORS_INIT;
1343
1344  INTERCEPT_FUNCTION(mmap);
1345  INTERCEPT_FUNCTION(mmap64);
1346  INTERCEPT_FUNCTION(posix_memalign);
1347  INTERCEPT_FUNCTION(memalign);
1348  INTERCEPT_FUNCTION(valloc);
1349  INTERCEPT_FUNCTION(pvalloc);
1350  INTERCEPT_FUNCTION(malloc);
1351  INTERCEPT_FUNCTION(calloc);
1352  INTERCEPT_FUNCTION(realloc);
1353  INTERCEPT_FUNCTION(free);
1354  INTERCEPT_FUNCTION(fread);
1355  INTERCEPT_FUNCTION(fread_unlocked);
1356  INTERCEPT_FUNCTION(readlink);
1357  INTERCEPT_FUNCTION(memcpy);
1358  INTERCEPT_FUNCTION(mempcpy);
1359  INTERCEPT_FUNCTION(memset);
1360  INTERCEPT_FUNCTION(memmove);
1361  INTERCEPT_FUNCTION(bcopy);
1362  INTERCEPT_FUNCTION(wmemset);
1363  INTERCEPT_FUNCTION(wmemcpy);
1364  INTERCEPT_FUNCTION(wmempcpy);
1365  INTERCEPT_FUNCTION(wmemmove);
1366  INTERCEPT_FUNCTION(strcpy);  // NOLINT
1367  INTERCEPT_FUNCTION(stpcpy);  // NOLINT
1368  INTERCEPT_FUNCTION(strdup);
1369  INTERCEPT_FUNCTION(__strdup);
1370  INTERCEPT_FUNCTION(strndup);
1371  INTERCEPT_FUNCTION(__strndup);
1372  INTERCEPT_FUNCTION(strncpy);  // NOLINT
1373  INTERCEPT_FUNCTION(strlen);
1374  INTERCEPT_FUNCTION(strnlen);
1375  INTERCEPT_FUNCTION(gcvt);
1376  INTERCEPT_FUNCTION(strcat);  // NOLINT
1377  INTERCEPT_FUNCTION(strncat);  // NOLINT
1378  INTERCEPT_FUNCTION(strtol);
1379  INTERCEPT_FUNCTION(strtoll);
1380  INTERCEPT_FUNCTION(strtoul);
1381  INTERCEPT_FUNCTION(strtoull);
1382  INTERCEPT_FUNCTION(strtod);
1383  INTERCEPT_FUNCTION(strtod_l);
1384  INTERCEPT_FUNCTION(__strtod_l);
1385  INTERCEPT_FUNCTION(strtof);
1386  INTERCEPT_FUNCTION(strtof_l);
1387  INTERCEPT_FUNCTION(__strtof_l);
1388  INTERCEPT_FUNCTION(strtold);
1389  INTERCEPT_FUNCTION(strtold_l);
1390  INTERCEPT_FUNCTION(__strtold_l);
1391  INTERCEPT_FUNCTION(vasprintf);
1392  INTERCEPT_FUNCTION(asprintf);
1393  INTERCEPT_FUNCTION(vsprintf);
1394  INTERCEPT_FUNCTION(vsnprintf);
1395  INTERCEPT_FUNCTION(vswprintf);
1396  INTERCEPT_FUNCTION(sprintf);  // NOLINT
1397  INTERCEPT_FUNCTION(snprintf);
1398  INTERCEPT_FUNCTION(swprintf);
1399  INTERCEPT_FUNCTION(strftime);
1400  INTERCEPT_FUNCTION(mbtowc);
1401  INTERCEPT_FUNCTION(mbrtowc);
1402  INTERCEPT_FUNCTION(wcslen);
1403  INTERCEPT_FUNCTION(wcschr);
1404  INTERCEPT_FUNCTION(wcscpy);
1405  INTERCEPT_FUNCTION(wcscmp);
1406  INTERCEPT_FUNCTION(wcstod);
1407  INTERCEPT_FUNCTION(getenv);
1408  INTERCEPT_FUNCTION(setenv);
1409  INTERCEPT_FUNCTION(putenv);
1410  INTERCEPT_FUNCTION(gettimeofday);
1411  INTERCEPT_FUNCTION(fcvt);
1412  INTERCEPT_FUNCTION(__fxstat);
1413  INTERCEPT_FUNCTION(__fxstatat);
1414  INTERCEPT_FUNCTION(__xstat);
1415  INTERCEPT_FUNCTION(__lxstat);
1416  INTERCEPT_FUNCTION(__fxstat64);
1417  INTERCEPT_FUNCTION(__fxstatat64);
1418  INTERCEPT_FUNCTION(__xstat64);
1419  INTERCEPT_FUNCTION(__lxstat64);
1420  INTERCEPT_FUNCTION(pipe);
1421  INTERCEPT_FUNCTION(pipe2);
1422  INTERCEPT_FUNCTION(socketpair);
1423  INTERCEPT_FUNCTION(fgets);
1424  INTERCEPT_FUNCTION(fgets_unlocked);
1425  INTERCEPT_FUNCTION(getrlimit);
1426  INTERCEPT_FUNCTION(getrlimit64);
1427  INTERCEPT_FUNCTION(statfs);
1428  INTERCEPT_FUNCTION(fstatfs);
1429  INTERCEPT_FUNCTION(statfs64);
1430  INTERCEPT_FUNCTION(fstatfs64);
1431  INTERCEPT_FUNCTION(uname);
1432  INTERCEPT_FUNCTION(gethostname);
1433  INTERCEPT_FUNCTION(epoll_wait);
1434  INTERCEPT_FUNCTION(epoll_pwait);
1435  INTERCEPT_FUNCTION(recv);
1436  INTERCEPT_FUNCTION(recvfrom);
1437  INTERCEPT_FUNCTION(dladdr);
1438  INTERCEPT_FUNCTION(dlopen);
1439  INTERCEPT_FUNCTION(dl_iterate_phdr);
1440  INTERCEPT_FUNCTION(getrusage);
1441  INTERCEPT_FUNCTION(sigaction);
1442  INTERCEPT_FUNCTION(signal);
1443  INTERCEPT_FUNCTION(pthread_create);
1444  INTERCEPT_FUNCTION(pthread_key_create);
1445  INTERCEPT_FUNCTION(pthread_join);
1446  INTERCEPT_FUNCTION(tzset);
1447  INTERCEPT_FUNCTION(__cxa_atexit);
1448  inited = 1;
1449}
1450}  // namespace __msan
1451