1//===-- msan_test.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// MemorySanitizer unit tests.
13//===----------------------------------------------------------------------===//
14
15#ifndef MSAN_EXTERNAL_TEST_CONFIG
16#include "msan_test_config.h"
17#endif // MSAN_EXTERNAL_TEST_CONFIG
18
19#include "sanitizer/msan_interface.h"
20#include "msandr_test_so.h"
21
22#include <inttypes.h>
23#include <stdlib.h>
24#include <stdarg.h>
25#include <stdio.h>
26#include <assert.h>
27#include <wchar.h>
28#include <math.h>
29
30#include <arpa/inet.h>
31#include <dlfcn.h>
32#include <grp.h>
33#include <unistd.h>
34#include <link.h>
35#include <limits.h>
36#include <sys/time.h>
37#include <sys/types.h>
38#include <sys/stat.h>
39#include <fcntl.h>
40#include <sys/resource.h>
41#include <sys/ioctl.h>
42#include <sys/sysinfo.h>
43#include <sys/utsname.h>
44#include <sys/mman.h>
45#include <sys/vfs.h>
46#include <dirent.h>
47#include <pwd.h>
48#include <sys/socket.h>
49#include <netdb.h>
50
51#if defined(__i386__) || defined(__x86_64__)
52# include <emmintrin.h>
53# define MSAN_HAS_M128 1
54#else
55# define MSAN_HAS_M128 0
56#endif
57
58typedef unsigned char      U1;
59typedef unsigned short     U2;  // NOLINT
60typedef unsigned int       U4;
61typedef unsigned long long U8;  // NOLINT
62typedef   signed char      S1;
63typedef   signed short     S2;  // NOLINT
64typedef   signed int       S4;
65typedef   signed long long S8;  // NOLINT
66#define NOINLINE      __attribute__((noinline))
67#define INLINE      __attribute__((always_inline))
68
69static bool TrackingOrigins() {
70  S8 x;
71  __msan_set_origin(&x, sizeof(x), 0x1234);
72  U4 origin = __msan_get_origin(&x);
73  __msan_set_origin(&x, sizeof(x), 0);
74  return origin == 0x1234;
75}
76
77#define EXPECT_UMR(action) \
78    do {                        \
79      __msan_set_expect_umr(1); \
80      action;                   \
81      __msan_set_expect_umr(0); \
82    } while (0)
83
84#define EXPECT_UMR_O(action, origin) \
85    do {                                            \
86      __msan_set_expect_umr(1);                     \
87      action;                                       \
88      __msan_set_expect_umr(0);                     \
89      if (TrackingOrigins())                        \
90        EXPECT_EQ(origin, __msan_get_umr_origin()); \
91    } while (0)
92
93#define EXPECT_UMR_S(action, stack_origin) \
94    do {                                            \
95      __msan_set_expect_umr(1);                     \
96      action;                                       \
97      __msan_set_expect_umr(0);                     \
98      U4 id = __msan_get_umr_origin();             \
99      const char *str = __msan_get_origin_descr_if_stack(id); \
100      if (!str || strcmp(str, stack_origin)) {      \
101        fprintf(stderr, "EXPECT_POISONED_S: id=%u %s, %s", \
102                id, stack_origin, str);  \
103        EXPECT_EQ(1, 0);                            \
104      }                                             \
105    } while (0)
106
107#define EXPECT_POISONED(x) ExpectPoisoned(x)
108
109template<typename T>
110void ExpectPoisoned(const T& t) {
111  EXPECT_NE(-1, __msan_test_shadow((void*)&t, sizeof(t)));
112}
113
114#define EXPECT_POISONED_O(x, origin) \
115  ExpectPoisonedWithOrigin(x, origin)
116
117template<typename T>
118void ExpectPoisonedWithOrigin(const T& t, unsigned origin) {
119  EXPECT_NE(-1, __msan_test_shadow((void*)&t, sizeof(t)));
120  if (TrackingOrigins())
121    EXPECT_EQ(origin, __msan_get_origin((void*)&t));
122}
123
124#define EXPECT_POISONED_S(x, stack_origin) \
125  ExpectPoisonedWithStackOrigin(x, stack_origin)
126
127template<typename T>
128void ExpectPoisonedWithStackOrigin(const T& t, const char *stack_origin) {
129  EXPECT_NE(-1, __msan_test_shadow((void*)&t, sizeof(t)));
130  U4 id = __msan_get_origin((void*)&t);
131  const char *str = __msan_get_origin_descr_if_stack(id);
132  if (!str || strcmp(str, stack_origin)) {
133    fprintf(stderr, "EXPECT_POISONED_S: id=%u %s, %s",
134        id, stack_origin, str);
135    EXPECT_EQ(1, 0);
136  }
137}
138
139#define EXPECT_NOT_POISONED(x) ExpectNotPoisoned(x)
140
141template<typename T>
142void ExpectNotPoisoned(const T& t) {
143  EXPECT_EQ(-1, __msan_test_shadow((void*)&t, sizeof(t)));
144}
145
146static U8 poisoned_array[100];
147template<class T>
148T *GetPoisoned(int i = 0, T val = 0) {
149  T *res = (T*)&poisoned_array[i];
150  *res = val;
151  __msan_poison(&poisoned_array[i], sizeof(T));
152  return res;
153}
154
155template<class T>
156T *GetPoisonedO(int i, U4 origin, T val = 0) {
157  T *res = (T*)&poisoned_array[i];
158  *res = val;
159  __msan_poison(&poisoned_array[i], sizeof(T));
160  __msan_set_origin(&poisoned_array[i], sizeof(T), origin);
161  return res;
162}
163
164// This function returns its parameter but in such a way that compiler
165// can not prove it.
166template<class T>
167NOINLINE
168static T Ident(T t) {
169  volatile T ret = t;
170  return ret;
171}
172
173template<class T> NOINLINE T ReturnPoisoned() { return *GetPoisoned<T>(); }
174
175static volatile int g_one = 1;
176static volatile int g_zero = 0;
177static volatile int g_0 = 0;
178static volatile int g_1 = 1;
179
180S4 a_s4[100];
181S8 a_s8[100];
182
183// Check that malloc poisons memory.
184// A lot of tests below depend on this.
185TEST(MemorySanitizerSanity, PoisonInMalloc) {
186  int *x = (int*)malloc(sizeof(int));
187  EXPECT_POISONED(*x);
188  free(x);
189}
190
191TEST(MemorySanitizer, NegativeTest1) {
192  S4 *x = GetPoisoned<S4>();
193  if (g_one)
194    *x = 0;
195  EXPECT_NOT_POISONED(*x);
196}
197
198TEST(MemorySanitizer, PositiveTest1) {
199  // Load to store.
200  EXPECT_POISONED(*GetPoisoned<S1>());
201  EXPECT_POISONED(*GetPoisoned<S2>());
202  EXPECT_POISONED(*GetPoisoned<S4>());
203  EXPECT_POISONED(*GetPoisoned<S8>());
204
205  // S->S conversions.
206  EXPECT_POISONED(*GetPoisoned<S1>());
207  EXPECT_POISONED(*GetPoisoned<S1>());
208  EXPECT_POISONED(*GetPoisoned<S1>());
209
210  EXPECT_POISONED(*GetPoisoned<S2>());
211  EXPECT_POISONED(*GetPoisoned<S2>());
212  EXPECT_POISONED(*GetPoisoned<S2>());
213
214  EXPECT_POISONED(*GetPoisoned<S4>());
215  EXPECT_POISONED(*GetPoisoned<S4>());
216  EXPECT_POISONED(*GetPoisoned<S4>());
217
218  EXPECT_POISONED(*GetPoisoned<S8>());
219  EXPECT_POISONED(*GetPoisoned<S8>());
220  EXPECT_POISONED(*GetPoisoned<S8>());
221
222  // ZExt
223  EXPECT_POISONED(*GetPoisoned<U1>());
224  EXPECT_POISONED(*GetPoisoned<U1>());
225  EXPECT_POISONED(*GetPoisoned<U1>());
226  EXPECT_POISONED(*GetPoisoned<U2>());
227  EXPECT_POISONED(*GetPoisoned<U2>());
228  EXPECT_POISONED(*GetPoisoned<U4>());
229
230  // Unary ops.
231  EXPECT_POISONED(- *GetPoisoned<S4>());
232
233  EXPECT_UMR(a_s4[g_zero] = 100 / *GetPoisoned<S4>(0, 1));
234
235
236  a_s4[g_zero] = 1 - *GetPoisoned<S4>();
237  a_s4[g_zero] = 1 + *GetPoisoned<S4>();
238}
239
240TEST(MemorySanitizer, Phi1) {
241  S4 c;
242  if (g_one) {
243    c = *GetPoisoned<S4>();
244  } else {
245    break_optimization(0);
246    c = 0;
247  }
248  EXPECT_POISONED(c);
249}
250
251TEST(MemorySanitizer, Phi2) {
252  S4 i = *GetPoisoned<S4>();
253  S4 n = g_one;
254  EXPECT_UMR(for (; i < g_one; i++););
255  EXPECT_POISONED(i);
256}
257
258NOINLINE void Arg1ExpectUMR(S4 a1) { EXPECT_POISONED(a1); }
259NOINLINE void Arg2ExpectUMR(S4 a1, S4 a2) { EXPECT_POISONED(a2); }
260NOINLINE void Arg3ExpectUMR(S1 a1, S4 a2, S8 a3) { EXPECT_POISONED(a3); }
261
262TEST(MemorySanitizer, ArgTest) {
263  Arg1ExpectUMR(*GetPoisoned<S4>());
264  Arg2ExpectUMR(0, *GetPoisoned<S4>());
265  Arg3ExpectUMR(0, 1, *GetPoisoned<S8>());
266}
267
268
269TEST(MemorySanitizer, CallAndRet) {
270  if (!__msan_has_dynamic_component()) return;
271  ReturnPoisoned<S1>();
272  ReturnPoisoned<S2>();
273  ReturnPoisoned<S4>();
274  ReturnPoisoned<S8>();
275
276  EXPECT_POISONED(ReturnPoisoned<S1>());
277  EXPECT_POISONED(ReturnPoisoned<S2>());
278  EXPECT_POISONED(ReturnPoisoned<S4>());
279  EXPECT_POISONED(ReturnPoisoned<S8>());
280}
281
282// malloc() in the following test may be optimized to produce a compile-time
283// undef value. Check that we trap on the volatile assignment anyway.
284TEST(MemorySanitizer, DISABLED_MallocNoIdent) {
285  S4 *x = (int*)malloc(sizeof(S4));
286  EXPECT_POISONED(*x);
287  free(x);
288}
289
290TEST(MemorySanitizer, Malloc) {
291  S4 *x = (int*)Ident(malloc(sizeof(S4)));
292  EXPECT_POISONED(*x);
293  free(x);
294}
295
296TEST(MemorySanitizer, Realloc) {
297  S4 *x = (int*)Ident(realloc(0, sizeof(S4)));
298  EXPECT_POISONED(x[0]);
299  x[0] = 1;
300  x = (int*)Ident(realloc(x, 2 * sizeof(S4)));
301  EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
302  EXPECT_POISONED(x[1]);
303  x = (int*)Ident(realloc(x, 3 * sizeof(S4)));
304  EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
305  EXPECT_POISONED(x[2]);
306  EXPECT_POISONED(x[1]);
307  x[2] = 1;  // Init this here. Check that after realloc it is poisoned again.
308  x = (int*)Ident(realloc(x, 2 * sizeof(S4)));
309  EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
310  EXPECT_POISONED(x[1]);
311  x = (int*)Ident(realloc(x, 3 * sizeof(S4)));
312  EXPECT_POISONED(x[1]);
313  EXPECT_POISONED(x[2]);
314  free(x);
315}
316
317TEST(MemorySanitizer, Calloc) {
318  S4 *x = (int*)Ident(calloc(1, sizeof(S4)));
319  EXPECT_NOT_POISONED(*x);  // Should not be poisoned.
320  // EXPECT_EQ(0, *x);
321  free(x);
322}
323
324TEST(MemorySanitizer, AndOr) {
325  U4 *p = GetPoisoned<U4>();
326  // We poison two bytes in the midle of a 4-byte word to make the test
327  // correct regardless of endianness.
328  ((U1*)p)[1] = 0;
329  ((U1*)p)[2] = 0xff;
330  EXPECT_NOT_POISONED(*p & 0x00ffff00);
331  EXPECT_NOT_POISONED(*p & 0x00ff0000);
332  EXPECT_NOT_POISONED(*p & 0x0000ff00);
333  EXPECT_POISONED(*p & 0xff000000);
334  EXPECT_POISONED(*p & 0x000000ff);
335  EXPECT_POISONED(*p & 0x0000ffff);
336  EXPECT_POISONED(*p & 0xffff0000);
337
338  EXPECT_NOT_POISONED(*p | 0xff0000ff);
339  EXPECT_NOT_POISONED(*p | 0xff00ffff);
340  EXPECT_NOT_POISONED(*p | 0xffff00ff);
341  EXPECT_POISONED(*p | 0xff000000);
342  EXPECT_POISONED(*p | 0x000000ff);
343  EXPECT_POISONED(*p | 0x0000ffff);
344  EXPECT_POISONED(*p | 0xffff0000);
345
346  EXPECT_POISONED(*GetPoisoned<bool>() & *GetPoisoned<bool>());
347}
348
349template<class T>
350static bool applyNot(T value, T shadow) {
351  __msan_partial_poison(&value, &shadow, sizeof(T));
352  return !value;
353}
354
355TEST(MemorySanitizer, Not) {
356  EXPECT_NOT_POISONED(applyNot<U4>(0x0, 0x0));
357  EXPECT_NOT_POISONED(applyNot<U4>(0xFFFFFFFF, 0x0));
358  EXPECT_POISONED(applyNot<U4>(0xFFFFFFFF, 0xFFFFFFFF));
359  EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x0FFFFFFF));
360  EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x00FFFFFF));
361  EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x0000FFFF));
362  EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x00000000));
363  EXPECT_POISONED(applyNot<U4>(0xFF000000, 0xFF000000));
364  EXPECT_NOT_POISONED(applyNot<U4>(0xFF800000, 0xFF000000));
365  EXPECT_POISONED(applyNot<U4>(0x00008000, 0x00008000));
366
367  EXPECT_NOT_POISONED(applyNot<U1>(0x0, 0x0));
368  EXPECT_NOT_POISONED(applyNot<U1>(0xFF, 0xFE));
369  EXPECT_NOT_POISONED(applyNot<U1>(0xFF, 0x0));
370  EXPECT_POISONED(applyNot<U1>(0xFF, 0xFF));
371
372  EXPECT_POISONED(applyNot<void*>((void*)0xFFFFFF, (void*)(-1)));
373  EXPECT_NOT_POISONED(applyNot<void*>((void*)0xFFFFFF, (void*)(-2)));
374}
375
376TEST(MemorySanitizer, Shift) {
377  U4 *up = GetPoisoned<U4>();
378  ((U1*)up)[0] = 0;
379  ((U1*)up)[3] = 0xff;
380  EXPECT_NOT_POISONED(*up >> 30);
381  EXPECT_NOT_POISONED(*up >> 24);
382  EXPECT_POISONED(*up >> 23);
383  EXPECT_POISONED(*up >> 10);
384
385  EXPECT_NOT_POISONED(*up << 30);
386  EXPECT_NOT_POISONED(*up << 24);
387  EXPECT_POISONED(*up << 23);
388  EXPECT_POISONED(*up << 10);
389
390  S4 *sp = (S4*)up;
391  EXPECT_NOT_POISONED(*sp >> 30);
392  EXPECT_NOT_POISONED(*sp >> 24);
393  EXPECT_POISONED(*sp >> 23);
394  EXPECT_POISONED(*sp >> 10);
395
396  sp = GetPoisoned<S4>();
397  ((S1*)sp)[1] = 0;
398  ((S1*)sp)[2] = 0;
399  EXPECT_POISONED(*sp >> 31);
400
401  EXPECT_POISONED(100 >> *GetPoisoned<S4>());
402  EXPECT_POISONED(100U >> *GetPoisoned<S4>());
403}
404
405NOINLINE static int GetPoisonedZero() {
406  int *zero = new int;
407  *zero = 0;
408  __msan_poison(zero, sizeof(*zero));
409  int res = *zero;
410  delete zero;
411  return res;
412}
413
414TEST(MemorySanitizer, LoadFromDirtyAddress) {
415  int *a = new int;
416  *a = 0;
417  EXPECT_UMR(break_optimization((void*)(U8)a[GetPoisonedZero()]));
418  delete a;
419}
420
421TEST(MemorySanitizer, StoreToDirtyAddress) {
422  int *a = new int;
423  EXPECT_UMR(a[GetPoisonedZero()] = 0);
424  break_optimization(a);
425  delete a;
426}
427
428
429NOINLINE void StackTestFunc() {
430  S4 p4;
431  S4 ok4 = 1;
432  S2 p2;
433  S2 ok2 = 1;
434  S1 p1;
435  S1 ok1 = 1;
436  break_optimization(&p4);
437  break_optimization(&ok4);
438  break_optimization(&p2);
439  break_optimization(&ok2);
440  break_optimization(&p1);
441  break_optimization(&ok1);
442
443  EXPECT_POISONED(p4);
444  EXPECT_POISONED(p2);
445  EXPECT_POISONED(p1);
446  EXPECT_NOT_POISONED(ok1);
447  EXPECT_NOT_POISONED(ok2);
448  EXPECT_NOT_POISONED(ok4);
449}
450
451TEST(MemorySanitizer, StackTest) {
452  StackTestFunc();
453}
454
455NOINLINE void StackStressFunc() {
456  int foo[10000];
457  break_optimization(foo);
458}
459
460TEST(MemorySanitizer, DISABLED_StackStressTest) {
461  for (int i = 0; i < 1000000; i++)
462    StackStressFunc();
463}
464
465template<class T>
466void TestFloatingPoint() {
467  static volatile T v;
468  static T g[100];
469  break_optimization(&g);
470  T *x = GetPoisoned<T>();
471  T *y = GetPoisoned<T>(1);
472  EXPECT_POISONED(*x);
473  EXPECT_POISONED((long long)*x);
474  EXPECT_POISONED((int)*x);
475  g[0] = *x;
476  g[1] = *x + *y;
477  g[2] = *x - *y;
478  g[3] = *x * *y;
479}
480
481TEST(MemorySanitizer, FloatingPointTest) {
482  TestFloatingPoint<float>();
483  TestFloatingPoint<double>();
484}
485
486TEST(MemorySanitizer, DynMem) {
487  S4 x = 0;
488  S4 *y = GetPoisoned<S4>();
489  memcpy(y, &x, g_one * sizeof(S4));
490  EXPECT_NOT_POISONED(*y);
491}
492
493static char *DynRetTestStr;
494
495TEST(MemorySanitizer, DynRet) {
496  if (!__msan_has_dynamic_component()) return;
497  ReturnPoisoned<S8>();
498  EXPECT_NOT_POISONED(clearenv());
499}
500
501
502TEST(MemorySanitizer, DynRet1) {
503  if (!__msan_has_dynamic_component()) return;
504  ReturnPoisoned<S8>();
505}
506
507struct LargeStruct {
508  S4 x[10];
509};
510
511NOINLINE
512LargeStruct LargeRetTest() {
513  LargeStruct res;
514  res.x[0] = *GetPoisoned<S4>();
515  res.x[1] = *GetPoisoned<S4>();
516  res.x[2] = *GetPoisoned<S4>();
517  res.x[3] = *GetPoisoned<S4>();
518  res.x[4] = *GetPoisoned<S4>();
519  res.x[5] = *GetPoisoned<S4>();
520  res.x[6] = *GetPoisoned<S4>();
521  res.x[7] = *GetPoisoned<S4>();
522  res.x[8] = *GetPoisoned<S4>();
523  res.x[9] = *GetPoisoned<S4>();
524  return res;
525}
526
527TEST(MemorySanitizer, strcmp) {
528  char s1[10];
529  char s2[10];
530  strncpy(s1, "foo", 10);
531  s2[0] = 'f';
532  s2[1] = 'n';
533  EXPECT_GT(strcmp(s1, s2), 0);
534  s2[1] = 'o';
535  int res;
536  EXPECT_UMR(res = strcmp(s1, s2));
537  EXPECT_NOT_POISONED(res);
538  EXPECT_EQ(strncmp(s1, s2, 1), 0);
539}
540
541TEST(MemorySanitizer, LargeRet) {
542  LargeStruct a = LargeRetTest();
543  EXPECT_POISONED(a.x[0]);
544  EXPECT_POISONED(a.x[9]);
545}
546
547TEST(MemorySanitizer, fread) {
548  char *x = new char[32];
549  FILE *f = fopen("/proc/self/stat", "r");
550  assert(f);
551  fread(x, 1, 32, f);
552  EXPECT_NOT_POISONED(x[0]);
553  EXPECT_NOT_POISONED(x[16]);
554  EXPECT_NOT_POISONED(x[31]);
555  fclose(f);
556  delete x;
557}
558
559TEST(MemorySanitizer, read) {
560  char *x = new char[32];
561  int fd = open("/proc/self/stat", O_RDONLY);
562  assert(fd > 0);
563  int sz = read(fd, x, 32);
564  assert(sz == 32);
565  EXPECT_NOT_POISONED(x[0]);
566  EXPECT_NOT_POISONED(x[16]);
567  EXPECT_NOT_POISONED(x[31]);
568  close(fd);
569  delete x;
570}
571
572TEST(MemorySanitizer, pread) {
573  char *x = new char[32];
574  int fd = open("/proc/self/stat", O_RDONLY);
575  assert(fd > 0);
576  int sz = pread(fd, x, 32, 0);
577  assert(sz == 32);
578  EXPECT_NOT_POISONED(x[0]);
579  EXPECT_NOT_POISONED(x[16]);
580  EXPECT_NOT_POISONED(x[31]);
581  close(fd);
582  delete x;
583}
584
585TEST(MemorySanitizer, readv) {
586  char buf[2011];
587  struct iovec iov[2];
588  iov[0].iov_base = buf + 1;
589  iov[0].iov_len = 5;
590  iov[1].iov_base = buf + 10;
591  iov[1].iov_len = 2000;
592  int fd = open("/proc/self/stat", O_RDONLY);
593  assert(fd > 0);
594  int sz = readv(fd, iov, 2);
595  ASSERT_LT(sz, 5 + 2000);
596  ASSERT_GT(sz, iov[0].iov_len);
597  EXPECT_POISONED(buf[0]);
598  EXPECT_NOT_POISONED(buf[1]);
599  EXPECT_NOT_POISONED(buf[5]);
600  EXPECT_POISONED(buf[6]);
601  EXPECT_POISONED(buf[9]);
602  EXPECT_NOT_POISONED(buf[10]);
603  EXPECT_NOT_POISONED(buf[10 + (sz - 1) - 5]);
604  EXPECT_POISONED(buf[11 + (sz - 1) - 5]);
605  close(fd);
606}
607
608TEST(MemorySanitizer, preadv) {
609  char buf[2011];
610  struct iovec iov[2];
611  iov[0].iov_base = buf + 1;
612  iov[0].iov_len = 5;
613  iov[1].iov_base = buf + 10;
614  iov[1].iov_len = 2000;
615  int fd = open("/proc/self/stat", O_RDONLY);
616  assert(fd > 0);
617  int sz = preadv(fd, iov, 2, 3);
618  ASSERT_LT(sz, 5 + 2000);
619  ASSERT_GT(sz, iov[0].iov_len);
620  EXPECT_POISONED(buf[0]);
621  EXPECT_NOT_POISONED(buf[1]);
622  EXPECT_NOT_POISONED(buf[5]);
623  EXPECT_POISONED(buf[6]);
624  EXPECT_POISONED(buf[9]);
625  EXPECT_NOT_POISONED(buf[10]);
626  EXPECT_NOT_POISONED(buf[10 + (sz - 1) - 5]);
627  EXPECT_POISONED(buf[11 + (sz - 1) - 5]);
628  close(fd);
629}
630
631// FIXME: fails now.
632TEST(MemorySanitizer, DISABLED_ioctl) {
633  struct winsize ws;
634  EXPECT_EQ(ioctl(2, TIOCGWINSZ, &ws), 0);
635  EXPECT_NOT_POISONED(ws.ws_col);
636}
637
638TEST(MemorySanitizer, readlink) {
639  char *x = new char[1000];
640  readlink("/proc/self/exe", x, 1000);
641  EXPECT_NOT_POISONED(x[0]);
642  delete [] x;
643}
644
645
646TEST(MemorySanitizer, stat) {
647  struct stat* st = new struct stat;
648  int res = stat("/proc/self/stat", st);
649  assert(!res);
650  EXPECT_NOT_POISONED(st->st_dev);
651  EXPECT_NOT_POISONED(st->st_mode);
652  EXPECT_NOT_POISONED(st->st_size);
653}
654
655TEST(MemorySanitizer, statfs) {
656  struct statfs* st = new struct statfs;
657  int res = statfs("/", st);
658  assert(!res);
659  EXPECT_NOT_POISONED(st->f_type);
660  EXPECT_NOT_POISONED(st->f_bfree);
661  EXPECT_NOT_POISONED(st->f_namelen);
662}
663
664TEST(MemorySanitizer, pipe) {
665  int* pipefd = new int[2];
666  int res = pipe(pipefd);
667  assert(!res);
668  EXPECT_NOT_POISONED(pipefd[0]);
669  EXPECT_NOT_POISONED(pipefd[1]);
670  close(pipefd[0]);
671  close(pipefd[1]);
672}
673
674TEST(MemorySanitizer, pipe2) {
675  int* pipefd = new int[2];
676  int res = pipe2(pipefd, O_NONBLOCK);
677  assert(!res);
678  EXPECT_NOT_POISONED(pipefd[0]);
679  EXPECT_NOT_POISONED(pipefd[1]);
680  close(pipefd[0]);
681  close(pipefd[1]);
682}
683
684TEST(MemorySanitizer, socketpair) {
685  int sv[2];
686  int res = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
687  assert(!res);
688  EXPECT_NOT_POISONED(sv[0]);
689  EXPECT_NOT_POISONED(sv[1]);
690  close(sv[0]);
691  close(sv[1]);
692}
693
694TEST(MemorySanitizer, bind_getsockname) {
695  int sock = socket(AF_UNIX, SOCK_STREAM, 0);
696
697  struct sockaddr_in sai;
698  memset(&sai, 0, sizeof(sai));
699  sai.sin_family = AF_UNIX;
700  int res = bind(sock, (struct sockaddr *)&sai, sizeof(sai));
701
702  assert(!res);
703  char buf[200];
704  socklen_t addrlen;
705  EXPECT_UMR(getsockname(sock, (struct sockaddr *)&buf, &addrlen));
706
707  addrlen = sizeof(buf);
708  res = getsockname(sock, (struct sockaddr *)&buf, &addrlen);
709  EXPECT_NOT_POISONED(addrlen);
710  EXPECT_NOT_POISONED(buf[0]);
711  EXPECT_NOT_POISONED(buf[addrlen - 1]);
712  EXPECT_POISONED(buf[addrlen]);
713  close(sock);
714}
715
716TEST(MemorySanitizer, accept) {
717  int listen_socket = socket(AF_INET, SOCK_STREAM, 0);
718  ASSERT_LT(0, listen_socket);
719
720  struct sockaddr_in sai;
721  sai.sin_family = AF_INET;
722  sai.sin_port = 0;
723  sai.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
724  int res = bind(listen_socket, (struct sockaddr *)&sai, sizeof(sai));
725  ASSERT_EQ(0, res);
726
727  res = listen(listen_socket, 1);
728  ASSERT_EQ(0, res);
729
730  socklen_t sz = sizeof(sai);
731  res = getsockname(listen_socket, (struct sockaddr *)&sai, &sz);
732  ASSERT_EQ(0, res);
733  ASSERT_EQ(sizeof(sai), sz);
734
735  int connect_socket = socket(AF_INET, SOCK_STREAM, 0);
736  ASSERT_LT(0, connect_socket);
737  res = fcntl(connect_socket, F_SETFL, O_NONBLOCK);
738  ASSERT_EQ(0, res);
739  res = connect(connect_socket, (struct sockaddr *)&sai, sizeof(sai));
740  ASSERT_EQ(-1, res);
741  ASSERT_EQ(EINPROGRESS, errno);
742
743  __msan_poison(&sai, sizeof(sai));
744  int new_sock = accept(listen_socket, (struct sockaddr *)&sai, &sz);
745  ASSERT_LT(0, new_sock);
746  ASSERT_EQ(sizeof(sai), sz);
747  EXPECT_NOT_POISONED(sai);
748
749  __msan_poison(&sai, sizeof(sai));
750  res = getpeername(new_sock, (struct sockaddr *)&sai, &sz);
751  ASSERT_EQ(0, res);
752  ASSERT_EQ(sizeof(sai), sz);
753  EXPECT_NOT_POISONED(sai);
754
755  close(new_sock);
756  close(connect_socket);
757  close(listen_socket);
758}
759
760TEST(MemorySanitizer, getaddrinfo) {
761  struct addrinfo *ai;
762  struct addrinfo hints;
763  memset(&hints, 0, sizeof(hints));
764  hints.ai_family = AF_INET;
765  int res = getaddrinfo("localhost", NULL, &hints, &ai);
766  ASSERT_EQ(0, res);
767  EXPECT_NOT_POISONED(*ai);
768  ASSERT_EQ(sizeof(sockaddr_in), ai->ai_addrlen);
769  EXPECT_NOT_POISONED(*(sockaddr_in*)ai->ai_addr);
770}
771
772TEST(MemorySanitizer, getnameinfo) {
773  struct sockaddr_in sai;
774  sai.sin_family = AF_INET;
775  sai.sin_port = 80;
776  sai.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
777  char host[500];
778  char serv[500];
779  int res = getnameinfo((struct sockaddr *)&sai, sizeof(sai), host,
780                        sizeof(host), serv, sizeof(serv), 0);
781  ASSERT_EQ(0, res);
782  EXPECT_NOT_POISONED(host[0]);
783  EXPECT_POISONED(host[sizeof(host) - 1]);
784
785  ASSERT_NE(0, strlen(host));
786  EXPECT_NOT_POISONED(serv[0]);
787  EXPECT_POISONED(serv[sizeof(serv) - 1]);
788  ASSERT_NE(0, strlen(serv));
789}
790
791#define EXPECT_HOSTENT_NOT_POISONED(he)        \
792  do {                                         \
793    EXPECT_NOT_POISONED(*(he));                \
794    ASSERT_NE((void *) 0, (he)->h_name);       \
795    ASSERT_NE((void *) 0, (he)->h_aliases);    \
796    ASSERT_NE((void *) 0, (he)->h_addr_list);  \
797    EXPECT_NOT_POISONED(strlen((he)->h_name)); \
798    char **p = (he)->h_aliases;                \
799    while (*p) {                               \
800      EXPECT_NOT_POISONED(strlen(*p));         \
801      ++p;                                     \
802    }                                          \
803    char **q = (he)->h_addr_list;              \
804    while (*q) {                               \
805      EXPECT_NOT_POISONED(*q[0]);              \
806      ++q;                                     \
807    }                                          \
808    EXPECT_NOT_POISONED(*q);                   \
809  } while (0)
810
811TEST(MemorySanitizer, gethostent) {
812  struct hostent *he = gethostent();
813  ASSERT_NE((void *)NULL, he);
814  EXPECT_HOSTENT_NOT_POISONED(he);
815}
816
817#ifndef MSAN_TEST_DISABLE_GETHOSTBYNAME
818
819TEST(MemorySanitizer, gethostbyname) {
820  struct hostent *he = gethostbyname("localhost");
821  ASSERT_NE((void *)NULL, he);
822  EXPECT_HOSTENT_NOT_POISONED(he);
823}
824
825#endif // MSAN_TEST_DISABLE_GETHOSTBYNAME
826
827TEST(MemorySanitizer, gethostbyname2) {
828  struct hostent *he = gethostbyname2("localhost", AF_INET);
829  ASSERT_NE((void *)NULL, he);
830  EXPECT_HOSTENT_NOT_POISONED(he);
831}
832
833TEST(MemorySanitizer, gethostbyaddr) {
834  in_addr_t addr = inet_addr("127.0.0.1");
835  EXPECT_NOT_POISONED(addr);
836  struct hostent *he = gethostbyaddr(&addr, sizeof(addr), AF_INET);
837  ASSERT_NE((void *)NULL, he);
838  EXPECT_HOSTENT_NOT_POISONED(he);
839}
840
841TEST(MemorySanitizer, gethostent_r) {
842  char buf[2000];
843  struct hostent he;
844  struct hostent *result;
845  int err;
846  int res = gethostent_r(&he, buf, sizeof(buf), &result, &err);
847  ASSERT_EQ(0, res);
848  EXPECT_NOT_POISONED(result);
849  ASSERT_NE((void *)NULL, result);
850  EXPECT_HOSTENT_NOT_POISONED(result);
851  EXPECT_NOT_POISONED(err);
852}
853
854TEST(MemorySanitizer, gethostbyname_r) {
855  char buf[2000];
856  struct hostent he;
857  struct hostent *result;
858  int err;
859  int res = gethostbyname_r("localhost", &he, buf, sizeof(buf), &result, &err);
860  ASSERT_EQ(0, res);
861  EXPECT_NOT_POISONED(result);
862  ASSERT_NE((void *)NULL, result);
863  EXPECT_HOSTENT_NOT_POISONED(result);
864  EXPECT_NOT_POISONED(err);
865}
866
867TEST(MemorySanitizer, gethostbyname2_r) {
868  char buf[2000];
869  struct hostent he;
870  struct hostent *result;
871  int err;
872  int res = gethostbyname2_r("localhost", AF_INET, &he, buf, sizeof(buf),
873                             &result, &err);
874  ASSERT_EQ(0, res);
875  EXPECT_NOT_POISONED(result);
876  ASSERT_NE((void *)NULL, result);
877  EXPECT_HOSTENT_NOT_POISONED(result);
878  EXPECT_NOT_POISONED(err);
879}
880
881TEST(MemorySanitizer, gethostbyaddr_r) {
882  char buf[2000];
883  struct hostent he;
884  struct hostent *result;
885  int err;
886  in_addr_t addr = inet_addr("127.0.0.1");
887  EXPECT_NOT_POISONED(addr);
888  int res = gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &he, buf, sizeof(buf),
889                            &result, &err);
890  ASSERT_EQ(0, res);
891  EXPECT_NOT_POISONED(result);
892  ASSERT_NE((void *)NULL, result);
893  EXPECT_HOSTENT_NOT_POISONED(result);
894  EXPECT_NOT_POISONED(err);
895}
896
897TEST(MemorySanitizer, getsockopt) {
898  int sock = socket(AF_UNIX, SOCK_STREAM, 0);
899  struct linger l[2];
900  socklen_t sz = sizeof(l[0]);
901  int res = getsockopt(sock, SOL_SOCKET, SO_LINGER, &l[0], &sz);
902  ASSERT_EQ(0, res);
903  ASSERT_EQ(sizeof(l[0]), sz);
904  EXPECT_NOT_POISONED(l[0]);
905  EXPECT_POISONED(*(char *)(l + 1));
906}
907
908TEST(MemorySanitizer, getcwd) {
909  char path[PATH_MAX + 1];
910  char* res = getcwd(path, sizeof(path));
911  assert(res);
912  EXPECT_NOT_POISONED(path[0]);
913}
914
915TEST(MemorySanitizer, getcwd_gnu) {
916  char* res = getcwd(NULL, 0);
917  assert(res);
918  EXPECT_NOT_POISONED(res[0]);
919  free(res);
920}
921
922TEST(MemorySanitizer, get_current_dir_name) {
923  char* res = get_current_dir_name();
924  assert(res);
925  EXPECT_NOT_POISONED(res[0]);
926  free(res);
927}
928
929TEST(MemorySanitizer, confstr) {
930  char buf[3];
931  size_t res = confstr(_CS_PATH, buf, sizeof(buf));
932  ASSERT_GT(res, sizeof(buf));
933  EXPECT_NOT_POISONED(buf[0]);
934  EXPECT_NOT_POISONED(buf[sizeof(buf) - 1]);
935
936  char buf2[1000];
937  res = confstr(_CS_PATH, buf2, sizeof(buf2));
938  ASSERT_LT(res, sizeof(buf2));
939  EXPECT_NOT_POISONED(buf2[0]);
940  EXPECT_NOT_POISONED(buf2[res - 1]);
941  EXPECT_POISONED(buf2[res]);
942  ASSERT_EQ(res, strlen(buf2) + 1);
943}
944
945TEST(MemorySanitizer, readdir) {
946  DIR *dir = opendir(".");
947  struct dirent *d = readdir(dir);
948  assert(d);
949  EXPECT_NOT_POISONED(d->d_name[0]);
950  closedir(dir);
951}
952
953TEST(MemorySanitizer, readdir_r) {
954  DIR *dir = opendir(".");
955  struct dirent d;
956  struct dirent *pd;
957  int res = readdir_r(dir, &d, &pd);
958  assert(!res);
959  EXPECT_NOT_POISONED(pd);
960  EXPECT_NOT_POISONED(d.d_name[0]);
961  closedir(dir);
962}
963
964TEST(MemorySanitizer, realpath) {
965  const char* relpath = ".";
966  char path[PATH_MAX + 1];
967  char* res = realpath(relpath, path);
968  assert(res);
969  EXPECT_NOT_POISONED(path[0]);
970}
971
972TEST(MemorySanitizer, realpath_null) {
973  const char* relpath = ".";
974  char* res = realpath(relpath, NULL);
975  printf("%d, %s\n", errno, strerror(errno));
976  assert(res);
977  EXPECT_NOT_POISONED(res[0]);
978  free(res);
979}
980
981TEST(MemorySanitizer, canonicalize_file_name) {
982  const char* relpath = ".";
983  char* res = canonicalize_file_name(relpath);
984  assert(res);
985  EXPECT_NOT_POISONED(res[0]);
986  free(res);
987}
988
989extern char **environ;
990
991TEST(MemorySanitizer, setenv) {
992  setenv("AAA", "BBB", 1);
993  for (char **envp = environ; *envp; ++envp) {
994    EXPECT_NOT_POISONED(*envp);
995    EXPECT_NOT_POISONED(*envp[0]);
996  }
997}
998
999TEST(MemorySanitizer, putenv) {
1000  char s[] = "AAA=BBB";
1001  putenv(s);
1002  for (char **envp = environ; *envp; ++envp) {
1003    EXPECT_NOT_POISONED(*envp);
1004    EXPECT_NOT_POISONED(*envp[0]);
1005  }
1006}
1007
1008TEST(MemorySanitizer, memcpy) {
1009  char* x = new char[2];
1010  char* y = new char[2];
1011  x[0] = 1;
1012  x[1] = *GetPoisoned<char>();
1013  memcpy(y, x, 2);
1014  EXPECT_NOT_POISONED(y[0]);
1015  EXPECT_POISONED(y[1]);
1016}
1017
1018TEST(MemorySanitizer, memmove) {
1019  char* x = new char[2];
1020  char* y = new char[2];
1021  x[0] = 1;
1022  x[1] = *GetPoisoned<char>();
1023  memmove(y, x, 2);
1024  EXPECT_NOT_POISONED(y[0]);
1025  EXPECT_POISONED(y[1]);
1026}
1027
1028TEST(MemorySanitizer, bcopy) {
1029  char* x = new char[2];
1030  char* y = new char[2];
1031  x[0] = 1;
1032  x[1] = *GetPoisoned<char>();
1033  bcopy(x, y, 2);
1034  EXPECT_NOT_POISONED(y[0]);
1035  EXPECT_POISONED(y[1]);
1036}
1037
1038TEST(MemorySanitizer, strdup) {
1039  char buf[4] = "abc";
1040  __msan_poison(buf + 2, sizeof(*buf));
1041  char *x = strdup(buf);
1042  EXPECT_NOT_POISONED(x[0]);
1043  EXPECT_NOT_POISONED(x[1]);
1044  EXPECT_POISONED(x[2]);
1045  EXPECT_NOT_POISONED(x[3]);
1046  free(x);
1047}
1048
1049TEST(MemorySanitizer, strndup) {
1050  char buf[4] = "abc";
1051  __msan_poison(buf + 2, sizeof(*buf));
1052  char *x = strndup(buf, 3);
1053  EXPECT_NOT_POISONED(x[0]);
1054  EXPECT_NOT_POISONED(x[1]);
1055  EXPECT_POISONED(x[2]);
1056  EXPECT_NOT_POISONED(x[3]);
1057  free(x);
1058}
1059
1060TEST(MemorySanitizer, strndup_short) {
1061  char buf[4] = "abc";
1062  __msan_poison(buf + 1, sizeof(*buf));
1063  __msan_poison(buf + 2, sizeof(*buf));
1064  char *x = strndup(buf, 2);
1065  EXPECT_NOT_POISONED(x[0]);
1066  EXPECT_POISONED(x[1]);
1067  EXPECT_NOT_POISONED(x[2]);
1068  free(x);
1069}
1070
1071
1072template<class T, int size>
1073void TestOverlapMemmove() {
1074  T *x = new T[size];
1075  assert(size >= 3);
1076  x[2] = 0;
1077  memmove(x, x + 1, (size - 1) * sizeof(T));
1078  EXPECT_NOT_POISONED(x[1]);
1079  if (!__msan_has_dynamic_component()) {
1080    // FIXME: under DR we will lose this information
1081    // because accesses in memmove will unpoisin the shadow.
1082    // We need to use our own memove implementation instead of libc's.
1083    EXPECT_POISONED(x[0]);
1084    EXPECT_POISONED(x[2]);
1085  }
1086  delete [] x;
1087}
1088
1089TEST(MemorySanitizer, overlap_memmove) {
1090  TestOverlapMemmove<U1, 10>();
1091  TestOverlapMemmove<U1, 1000>();
1092  TestOverlapMemmove<U8, 4>();
1093  TestOverlapMemmove<U8, 1000>();
1094}
1095
1096TEST(MemorySanitizer, strcpy) {  // NOLINT
1097  char* x = new char[3];
1098  char* y = new char[3];
1099  x[0] = 'a';
1100  x[1] = *GetPoisoned<char>(1, 1);
1101  x[2] = 0;
1102  strcpy(y, x);  // NOLINT
1103  EXPECT_NOT_POISONED(y[0]);
1104  EXPECT_POISONED(y[1]);
1105  EXPECT_NOT_POISONED(y[2]);
1106}
1107
1108TEST(MemorySanitizer, strncpy) {  // NOLINT
1109  char* x = new char[3];
1110  char* y = new char[3];
1111  x[0] = 'a';
1112  x[1] = *GetPoisoned<char>(1, 1);
1113  x[2] = 0;
1114  strncpy(y, x, 2);  // NOLINT
1115  EXPECT_NOT_POISONED(y[0]);
1116  EXPECT_POISONED(y[1]);
1117  EXPECT_POISONED(y[2]);
1118}
1119
1120TEST(MemorySanitizer, stpcpy) {  // NOLINT
1121  char* x = new char[3];
1122  char* y = new char[3];
1123  x[0] = 'a';
1124  x[1] = *GetPoisoned<char>(1, 1);
1125  x[2] = 0;
1126  char *res = stpcpy(y, x);  // NOLINT
1127  ASSERT_EQ(res, y + 2);
1128  EXPECT_NOT_POISONED(y[0]);
1129  EXPECT_POISONED(y[1]);
1130  EXPECT_NOT_POISONED(y[2]);
1131}
1132
1133TEST(MemorySanitizer, strtol) {
1134  char *e;
1135  assert(1 == strtol("1", &e, 10));
1136  EXPECT_NOT_POISONED((S8) e);
1137}
1138
1139TEST(MemorySanitizer, strtoll) {
1140  char *e;
1141  assert(1 == strtoll("1", &e, 10));
1142  EXPECT_NOT_POISONED((S8) e);
1143}
1144
1145TEST(MemorySanitizer, strtoul) {
1146  char *e;
1147  assert(1 == strtoul("1", &e, 10));
1148  EXPECT_NOT_POISONED((S8) e);
1149}
1150
1151TEST(MemorySanitizer, strtoull) {
1152  char *e;
1153  assert(1 == strtoull("1", &e, 10));
1154  EXPECT_NOT_POISONED((S8) e);
1155}
1156
1157TEST(MemorySanitizer, strtoimax) {
1158  char *e;
1159  assert(1 == strtoimax("1", &e, 10));
1160  EXPECT_NOT_POISONED((S8) e);
1161}
1162
1163TEST(MemorySanitizer, strtoumax) {
1164  char *e;
1165  assert(1 == strtoumax("1", &e, 10));
1166  EXPECT_NOT_POISONED((S8) e);
1167}
1168
1169TEST(MemorySanitizer, strtod) {
1170  char *e;
1171  assert(0 != strtod("1.5", &e));
1172  EXPECT_NOT_POISONED((S8) e);
1173}
1174
1175TEST(MemorySanitizer, strtof) {
1176  char *e;
1177  assert(0 != strtof("1.5", &e));
1178  EXPECT_NOT_POISONED((S8) e);
1179}
1180
1181TEST(MemorySanitizer, strtold) {
1182  char *e;
1183  assert(0 != strtold("1.5", &e));
1184  EXPECT_NOT_POISONED((S8) e);
1185}
1186
1187TEST(MemorySanitizer, modf) {
1188  double x, y;
1189  x = modf(2.1, &y);
1190  EXPECT_NOT_POISONED(y);
1191}
1192
1193TEST(MemorySanitizer, modff) {
1194  float x, y;
1195  x = modff(2.1, &y);
1196  EXPECT_NOT_POISONED(y);
1197}
1198
1199TEST(MemorySanitizer, modfl) {
1200  long double x, y;
1201  x = modfl(2.1, &y);
1202  EXPECT_NOT_POISONED(y);
1203}
1204
1205TEST(MemorySanitizer, sprintf) {  // NOLINT
1206  char buff[10];
1207  break_optimization(buff);
1208  EXPECT_POISONED(buff[0]);
1209  int res = sprintf(buff, "%d", 1234567);  // NOLINT
1210  assert(res == 7);
1211  assert(buff[0] == '1');
1212  assert(buff[1] == '2');
1213  assert(buff[2] == '3');
1214  assert(buff[6] == '7');
1215  assert(buff[7] == 0);
1216  EXPECT_POISONED(buff[8]);
1217}
1218
1219TEST(MemorySanitizer, snprintf) {
1220  char buff[10];
1221  break_optimization(buff);
1222  EXPECT_POISONED(buff[0]);
1223  int res = snprintf(buff, sizeof(buff), "%d", 1234567);
1224  assert(res == 7);
1225  assert(buff[0] == '1');
1226  assert(buff[1] == '2');
1227  assert(buff[2] == '3');
1228  assert(buff[6] == '7');
1229  assert(buff[7] == 0);
1230  EXPECT_POISONED(buff[8]);
1231}
1232
1233TEST(MemorySanitizer, swprintf) {
1234  wchar_t buff[10];
1235  assert(sizeof(wchar_t) == 4);
1236  break_optimization(buff);
1237  EXPECT_POISONED(buff[0]);
1238  int res = swprintf(buff, 9, L"%d", 1234567);
1239  assert(res == 7);
1240  assert(buff[0] == '1');
1241  assert(buff[1] == '2');
1242  assert(buff[2] == '3');
1243  assert(buff[6] == '7');
1244  assert(buff[7] == 0);
1245  EXPECT_POISONED(buff[8]);
1246}
1247
1248TEST(MemorySanitizer, asprintf) {  // NOLINT
1249  char *pbuf;
1250  EXPECT_POISONED(pbuf);
1251  int res = asprintf(&pbuf, "%d", 1234567);  // NOLINT
1252  assert(res == 7);
1253  EXPECT_NOT_POISONED(pbuf);
1254  assert(pbuf[0] == '1');
1255  assert(pbuf[1] == '2');
1256  assert(pbuf[2] == '3');
1257  assert(pbuf[6] == '7');
1258  assert(pbuf[7] == 0);
1259  free(pbuf);
1260}
1261
1262TEST(MemorySanitizer, mbstowcs) {
1263  const char *x = "abc";
1264  wchar_t buff[10];
1265  int res = mbstowcs(buff, x, 2);
1266  EXPECT_EQ(2, res);
1267  EXPECT_EQ(L'a', buff[0]);
1268  EXPECT_EQ(L'b', buff[1]);
1269  EXPECT_POISONED(buff[2]);
1270  res = mbstowcs(buff, x, 10);
1271  EXPECT_EQ(3, res);
1272  EXPECT_NOT_POISONED(buff[3]);
1273}
1274
1275TEST(MemorySanitizer, wcstombs) {
1276  const wchar_t *x = L"abc";
1277  char buff[10];
1278  int res = wcstombs(buff, x, 4);
1279  EXPECT_EQ(res, 3);
1280  EXPECT_EQ(buff[0], 'a');
1281  EXPECT_EQ(buff[1], 'b');
1282  EXPECT_EQ(buff[2], 'c');
1283}
1284
1285TEST(MemorySanitizer, wcsrtombs) {
1286  const wchar_t *x = L"abc";
1287  const wchar_t *p = x;
1288  char buff[10];
1289  mbstate_t mbs;
1290  memset(&mbs, 0, sizeof(mbs));
1291  int res = wcsrtombs(buff, &p, 4, &mbs);
1292  EXPECT_EQ(res, 3);
1293  EXPECT_EQ(buff[0], 'a');
1294  EXPECT_EQ(buff[1], 'b');
1295  EXPECT_EQ(buff[2], 'c');
1296  EXPECT_EQ(buff[3], '\0');
1297  EXPECT_POISONED(buff[4]);
1298}
1299
1300TEST(MemorySanitizer, wcsnrtombs) {
1301  const wchar_t *x = L"abc";
1302  const wchar_t *p = x;
1303  char buff[10];
1304  mbstate_t mbs;
1305  memset(&mbs, 0, sizeof(mbs));
1306  int res = wcsnrtombs(buff, &p, 2, 4, &mbs);
1307  EXPECT_EQ(res, 2);
1308  EXPECT_EQ(buff[0], 'a');
1309  EXPECT_EQ(buff[1], 'b');
1310  EXPECT_POISONED(buff[2]);
1311}
1312
1313TEST(MemorySanitizer, mbtowc) {
1314  const char *x = "abc";
1315  wchar_t wx;
1316  int res = mbtowc(&wx, x, 3);
1317  EXPECT_GT(res, 0);
1318  EXPECT_NOT_POISONED(wx);
1319}
1320
1321TEST(MemorySanitizer, mbrtowc) {
1322  const char *x = "abc";
1323  wchar_t wx;
1324  mbstate_t mbs;
1325  memset(&mbs, 0, sizeof(mbs));
1326  int res = mbrtowc(&wx, x, 3, &mbs);
1327  EXPECT_GT(res, 0);
1328  EXPECT_NOT_POISONED(wx);
1329}
1330
1331TEST(MemorySanitizer, gettimeofday) {
1332  struct timeval tv;
1333  struct timezone tz;
1334  break_optimization(&tv);
1335  break_optimization(&tz);
1336  assert(sizeof(tv) == 16);
1337  assert(sizeof(tz) == 8);
1338  EXPECT_POISONED(tv.tv_sec);
1339  EXPECT_POISONED(tv.tv_usec);
1340  EXPECT_POISONED(tz.tz_minuteswest);
1341  EXPECT_POISONED(tz.tz_dsttime);
1342  assert(0 == gettimeofday(&tv, &tz));
1343  EXPECT_NOT_POISONED(tv.tv_sec);
1344  EXPECT_NOT_POISONED(tv.tv_usec);
1345  EXPECT_NOT_POISONED(tz.tz_minuteswest);
1346  EXPECT_NOT_POISONED(tz.tz_dsttime);
1347}
1348
1349TEST(MemorySanitizer, clock_gettime) {
1350  struct timespec tp;
1351  EXPECT_POISONED(tp.tv_sec);
1352  EXPECT_POISONED(tp.tv_nsec);
1353  assert(0 == clock_gettime(CLOCK_REALTIME, &tp));
1354  EXPECT_NOT_POISONED(tp.tv_sec);
1355  EXPECT_NOT_POISONED(tp.tv_nsec);
1356}
1357
1358TEST(MemorySanitizer, clock_getres) {
1359  struct timespec tp;
1360  EXPECT_POISONED(tp.tv_sec);
1361  EXPECT_POISONED(tp.tv_nsec);
1362  assert(0 == clock_getres(CLOCK_REALTIME, 0));
1363  EXPECT_POISONED(tp.tv_sec);
1364  EXPECT_POISONED(tp.tv_nsec);
1365  assert(0 == clock_getres(CLOCK_REALTIME, &tp));
1366  EXPECT_NOT_POISONED(tp.tv_sec);
1367  EXPECT_NOT_POISONED(tp.tv_nsec);
1368}
1369
1370TEST(MemorySanitizer, getitimer) {
1371  struct itimerval it1, it2;
1372  int res;
1373  EXPECT_POISONED(it1.it_interval.tv_sec);
1374  EXPECT_POISONED(it1.it_interval.tv_usec);
1375  EXPECT_POISONED(it1.it_value.tv_sec);
1376  EXPECT_POISONED(it1.it_value.tv_usec);
1377  res = getitimer(ITIMER_VIRTUAL, &it1);
1378  assert(!res);
1379  EXPECT_NOT_POISONED(it1.it_interval.tv_sec);
1380  EXPECT_NOT_POISONED(it1.it_interval.tv_usec);
1381  EXPECT_NOT_POISONED(it1.it_value.tv_sec);
1382  EXPECT_NOT_POISONED(it1.it_value.tv_usec);
1383
1384  it1.it_interval.tv_sec = it1.it_value.tv_sec = 10000;
1385  it1.it_interval.tv_usec = it1.it_value.tv_usec = 0;
1386
1387  res = setitimer(ITIMER_VIRTUAL, &it1, &it2);
1388  assert(!res);
1389  EXPECT_NOT_POISONED(it2.it_interval.tv_sec);
1390  EXPECT_NOT_POISONED(it2.it_interval.tv_usec);
1391  EXPECT_NOT_POISONED(it2.it_value.tv_sec);
1392  EXPECT_NOT_POISONED(it2.it_value.tv_usec);
1393
1394  // Check that old_value can be 0, and disable the timer.
1395  memset(&it1, 0, sizeof(it1));
1396  res = setitimer(ITIMER_VIRTUAL, &it1, 0);
1397  assert(!res);
1398}
1399
1400TEST(MemorySanitizer, setitimer_null) {
1401  setitimer(ITIMER_VIRTUAL, 0, 0);
1402  // Not testing the return value, since it the behaviour seems to differ
1403  // between libc implementations and POSIX.
1404  // Should never crash, though.
1405}
1406
1407TEST(MemorySanitizer, time) {
1408  time_t t;
1409  EXPECT_POISONED(t);
1410  time_t t2 = time(&t);
1411  assert(t2 != (time_t)-1);
1412  EXPECT_NOT_POISONED(t);
1413}
1414
1415TEST(MemorySanitizer, localtime) {
1416  time_t t = 123;
1417  struct tm *time = localtime(&t);
1418  assert(time != 0);
1419  EXPECT_NOT_POISONED(time->tm_sec);
1420  EXPECT_NOT_POISONED(time->tm_hour);
1421  EXPECT_NOT_POISONED(time->tm_year);
1422  EXPECT_NOT_POISONED(time->tm_isdst);
1423}
1424
1425TEST(MemorySanitizer, localtime_r) {
1426  time_t t = 123;
1427  struct tm time;
1428  struct tm *res = localtime_r(&t, &time);
1429  assert(res != 0);
1430  EXPECT_NOT_POISONED(time.tm_sec);
1431  EXPECT_NOT_POISONED(time.tm_hour);
1432  EXPECT_NOT_POISONED(time.tm_year);
1433  EXPECT_NOT_POISONED(time.tm_isdst);
1434}
1435
1436TEST(MemorySanitizer, mmap) {
1437  const int size = 4096;
1438  void *p1, *p2;
1439  p1 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1440  __msan_poison(p1, size);
1441  munmap(p1, size);
1442  for (int i = 0; i < 1000; i++) {
1443    p2 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
1444    if (p2 == p1)
1445      break;
1446    else
1447      munmap(p2, size);
1448  }
1449  if (p1 == p2) {
1450    EXPECT_NOT_POISONED(*(char*)p2);
1451    munmap(p2, size);
1452  }
1453}
1454
1455// FIXME: enable and add ecvt.
1456// FIXME: check why msandr does nt handle fcvt.
1457TEST(MemorySanitizer, fcvt) {
1458  int a, b;
1459  break_optimization(&a);
1460  break_optimization(&b);
1461  EXPECT_POISONED(a);
1462  EXPECT_POISONED(b);
1463  char *str = fcvt(12345.6789, 10, &a, &b);
1464  EXPECT_NOT_POISONED(a);
1465  EXPECT_NOT_POISONED(b);
1466}
1467
1468TEST(MemorySanitizer, frexp) {
1469  int x;
1470  x = *GetPoisoned<int>();
1471  double r = frexp(1.1, &x);
1472  EXPECT_NOT_POISONED(r);
1473  EXPECT_NOT_POISONED(x);
1474
1475  x = *GetPoisoned<int>();
1476  float rf = frexpf(1.1, &x);
1477  EXPECT_NOT_POISONED(rf);
1478  EXPECT_NOT_POISONED(x);
1479
1480  x = *GetPoisoned<int>();
1481  double rl = frexpl(1.1, &x);
1482  EXPECT_NOT_POISONED(rl);
1483  EXPECT_NOT_POISONED(x);
1484}
1485
1486namespace {
1487
1488static int cnt;
1489
1490void SigactionHandler(int signo, siginfo_t* si, void* uc) {
1491  assert(signo == SIGPROF);
1492  assert(si);
1493  EXPECT_NOT_POISONED(si->si_errno);
1494  EXPECT_NOT_POISONED(si->si_pid);
1495#if __linux__
1496# if defined(__x86_64__)
1497  EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_RIP]);
1498# elif defined(__i386__)
1499  EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_EIP]);
1500# endif
1501#endif
1502  ++cnt;
1503}
1504
1505TEST(MemorySanitizer, sigaction) {
1506  struct sigaction act = {};
1507  struct sigaction oldact = {};
1508  struct sigaction origact = {};
1509
1510  sigaction(SIGPROF, 0, &origact);
1511
1512  act.sa_flags |= SA_SIGINFO;
1513  act.sa_sigaction = &SigactionHandler;
1514  sigaction(SIGPROF, &act, 0);
1515
1516  kill(getpid(), SIGPROF);
1517
1518  act.sa_flags &= ~SA_SIGINFO;
1519  act.sa_handler = SIG_DFL;
1520  sigaction(SIGPROF, &act, 0);
1521
1522  act.sa_flags &= ~SA_SIGINFO;
1523  act.sa_handler = SIG_IGN;
1524  sigaction(SIGPROF, &act, &oldact);
1525  EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
1526  EXPECT_EQ(SIG_DFL, oldact.sa_handler);
1527  kill(getpid(), SIGPROF);
1528
1529  act.sa_flags |= SA_SIGINFO;
1530  act.sa_sigaction = &SigactionHandler;
1531  sigaction(SIGPROF, &act, &oldact);
1532  EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
1533  EXPECT_EQ(SIG_IGN, oldact.sa_handler);
1534  kill(getpid(), SIGPROF);
1535
1536  act.sa_flags &= ~SA_SIGINFO;
1537  act.sa_handler = SIG_DFL;
1538  sigaction(SIGPROF, &act, &oldact);
1539  EXPECT_TRUE(oldact.sa_flags & SA_SIGINFO);
1540  EXPECT_EQ(&SigactionHandler, oldact.sa_sigaction);
1541  EXPECT_EQ(2, cnt);
1542
1543  sigaction(SIGPROF, &origact, 0);
1544}
1545
1546} // namespace
1547
1548struct StructWithDtor {
1549  ~StructWithDtor();
1550};
1551
1552NOINLINE StructWithDtor::~StructWithDtor() {
1553  break_optimization(0);
1554}
1555
1556TEST(MemorySanitizer, Invoke) {
1557  StructWithDtor s;  // Will cause the calls to become invokes.
1558  EXPECT_NOT_POISONED(0);
1559  EXPECT_POISONED(*GetPoisoned<int>());
1560  EXPECT_NOT_POISONED(0);
1561  EXPECT_POISONED(*GetPoisoned<int>());
1562  EXPECT_POISONED(ReturnPoisoned<S4>());
1563}
1564
1565TEST(MemorySanitizer, ptrtoint) {
1566  // Test that shadow is propagated through pointer-to-integer conversion.
1567  void* p = (void*)0xABCD;
1568  __msan_poison(((char*)&p) + 1, sizeof(p));
1569  EXPECT_NOT_POISONED((((uintptr_t)p) & 0xFF) == 0);
1570
1571  void* q = (void*)0xABCD;
1572  __msan_poison(&q, sizeof(q) - 1);
1573  EXPECT_POISONED((((uintptr_t)q) & 0xFF) == 0);
1574}
1575
1576static void vaargsfn2(int guard, ...) {
1577  va_list vl;
1578  va_start(vl, guard);
1579  EXPECT_NOT_POISONED(va_arg(vl, int));
1580  EXPECT_NOT_POISONED(va_arg(vl, int));
1581  EXPECT_NOT_POISONED(va_arg(vl, int));
1582  EXPECT_POISONED(va_arg(vl, double));
1583  va_end(vl);
1584}
1585
1586static void vaargsfn(int guard, ...) {
1587  va_list vl;
1588  va_start(vl, guard);
1589  EXPECT_NOT_POISONED(va_arg(vl, int));
1590  EXPECT_POISONED(va_arg(vl, int));
1591  // The following call will overwrite __msan_param_tls.
1592  // Checks after it test that arg shadow was somehow saved across the call.
1593  vaargsfn2(1, 2, 3, 4, *GetPoisoned<double>());
1594  EXPECT_NOT_POISONED(va_arg(vl, int));
1595  EXPECT_POISONED(va_arg(vl, int));
1596  va_end(vl);
1597}
1598
1599TEST(MemorySanitizer, VAArgTest) {
1600  int* x = GetPoisoned<int>();
1601  int* y = GetPoisoned<int>(4);
1602  vaargsfn(1, 13, *x, 42, *y);
1603}
1604
1605static void vaargsfn_many(int guard, ...) {
1606  va_list vl;
1607  va_start(vl, guard);
1608  EXPECT_NOT_POISONED(va_arg(vl, int));
1609  EXPECT_POISONED(va_arg(vl, int));
1610  EXPECT_NOT_POISONED(va_arg(vl, int));
1611  EXPECT_NOT_POISONED(va_arg(vl, int));
1612  EXPECT_NOT_POISONED(va_arg(vl, int));
1613  EXPECT_NOT_POISONED(va_arg(vl, int));
1614  EXPECT_NOT_POISONED(va_arg(vl, int));
1615  EXPECT_NOT_POISONED(va_arg(vl, int));
1616  EXPECT_NOT_POISONED(va_arg(vl, int));
1617  EXPECT_POISONED(va_arg(vl, int));
1618  va_end(vl);
1619}
1620
1621TEST(MemorySanitizer, VAArgManyTest) {
1622  int* x = GetPoisoned<int>();
1623  int* y = GetPoisoned<int>(4);
1624  vaargsfn_many(1, 2, *x, 3, 4, 5, 6, 7, 8, 9, *y);
1625}
1626
1627static void vaargsfn_pass2(va_list vl) {
1628  EXPECT_NOT_POISONED(va_arg(vl, int));
1629  EXPECT_NOT_POISONED(va_arg(vl, int));
1630  EXPECT_POISONED(va_arg(vl, int));
1631}
1632
1633static void vaargsfn_pass(int guard, ...) {
1634  va_list vl;
1635  va_start(vl, guard);
1636  EXPECT_POISONED(va_arg(vl, int));
1637  vaargsfn_pass2(vl);
1638  va_end(vl);
1639}
1640
1641TEST(MemorySanitizer, VAArgPass) {
1642  int* x = GetPoisoned<int>();
1643  int* y = GetPoisoned<int>(4);
1644  vaargsfn_pass(1, *x, 2, 3, *y);
1645}
1646
1647static void vaargsfn_copy2(va_list vl) {
1648  EXPECT_NOT_POISONED(va_arg(vl, int));
1649  EXPECT_POISONED(va_arg(vl, int));
1650}
1651
1652static void vaargsfn_copy(int guard, ...) {
1653  va_list vl;
1654  va_start(vl, guard);
1655  EXPECT_NOT_POISONED(va_arg(vl, int));
1656  EXPECT_POISONED(va_arg(vl, int));
1657  va_list vl2;
1658  va_copy(vl2, vl);
1659  vaargsfn_copy2(vl2);
1660  EXPECT_NOT_POISONED(va_arg(vl, int));
1661  EXPECT_POISONED(va_arg(vl, int));
1662  va_end(vl);
1663}
1664
1665TEST(MemorySanitizer, VAArgCopy) {
1666  int* x = GetPoisoned<int>();
1667  int* y = GetPoisoned<int>(4);
1668  vaargsfn_copy(1, 2, *x, 3, *y);
1669}
1670
1671static void vaargsfn_ptr(int guard, ...) {
1672  va_list vl;
1673  va_start(vl, guard);
1674  EXPECT_NOT_POISONED(va_arg(vl, int*));
1675  EXPECT_POISONED(va_arg(vl, int*));
1676  EXPECT_NOT_POISONED(va_arg(vl, int*));
1677  EXPECT_POISONED(va_arg(vl, double*));
1678  va_end(vl);
1679}
1680
1681TEST(MemorySanitizer, VAArgPtr) {
1682  int** x = GetPoisoned<int*>();
1683  double** y = GetPoisoned<double*>(8);
1684  int z;
1685  vaargsfn_ptr(1, &z, *x, &z, *y);
1686}
1687
1688static void vaargsfn_overflow(int guard, ...) {
1689  va_list vl;
1690  va_start(vl, guard);
1691  EXPECT_NOT_POISONED(va_arg(vl, int));
1692  EXPECT_NOT_POISONED(va_arg(vl, int));
1693  EXPECT_POISONED(va_arg(vl, int));
1694  EXPECT_NOT_POISONED(va_arg(vl, int));
1695  EXPECT_NOT_POISONED(va_arg(vl, int));
1696  EXPECT_NOT_POISONED(va_arg(vl, int));
1697
1698  EXPECT_NOT_POISONED(va_arg(vl, double));
1699  EXPECT_NOT_POISONED(va_arg(vl, double));
1700  EXPECT_NOT_POISONED(va_arg(vl, double));
1701  EXPECT_POISONED(va_arg(vl, double));
1702  EXPECT_NOT_POISONED(va_arg(vl, double));
1703  EXPECT_POISONED(va_arg(vl, int*));
1704  EXPECT_NOT_POISONED(va_arg(vl, double));
1705  EXPECT_NOT_POISONED(va_arg(vl, double));
1706
1707  EXPECT_POISONED(va_arg(vl, int));
1708  EXPECT_POISONED(va_arg(vl, double));
1709  EXPECT_POISONED(va_arg(vl, int*));
1710
1711  EXPECT_NOT_POISONED(va_arg(vl, int));
1712  EXPECT_NOT_POISONED(va_arg(vl, double));
1713  EXPECT_NOT_POISONED(va_arg(vl, int*));
1714
1715  EXPECT_POISONED(va_arg(vl, int));
1716  EXPECT_POISONED(va_arg(vl, double));
1717  EXPECT_POISONED(va_arg(vl, int*));
1718
1719  va_end(vl);
1720}
1721
1722TEST(MemorySanitizer, VAArgOverflow) {
1723  int* x = GetPoisoned<int>();
1724  double* y = GetPoisoned<double>(8);
1725  int** p = GetPoisoned<int*>(16);
1726  int z;
1727  vaargsfn_overflow(1,
1728      1, 2, *x, 4, 5, 6,
1729      1.1, 2.2, 3.3, *y, 5.5, *p, 7.7, 8.8,
1730      // the following args will overflow for sure
1731      *x, *y, *p,
1732      7, 9.9, &z,
1733      *x, *y, *p);
1734}
1735
1736static void vaargsfn_tlsoverwrite2(int guard, ...) {
1737  va_list vl;
1738  va_start(vl, guard);
1739  EXPECT_NOT_POISONED(va_arg(vl, int));
1740  va_end(vl);
1741}
1742
1743static void vaargsfn_tlsoverwrite(int guard, ...) {
1744  // This call will overwrite TLS contents unless it's backed up somewhere.
1745  vaargsfn_tlsoverwrite2(2, 42);
1746  va_list vl;
1747  va_start(vl, guard);
1748  EXPECT_POISONED(va_arg(vl, int));
1749  va_end(vl);
1750}
1751
1752TEST(MemorySanitizer, VAArgTLSOverwrite) {
1753  int* x = GetPoisoned<int>();
1754  vaargsfn_tlsoverwrite(1, *x);
1755}
1756
1757struct StructByVal {
1758  int a, b, c, d, e, f;
1759};
1760
1761NOINLINE void StructByValTestFunc(struct StructByVal s) {
1762  EXPECT_NOT_POISONED(s.a);
1763  EXPECT_POISONED(s.b);
1764  EXPECT_NOT_POISONED(s.c);
1765  EXPECT_POISONED(s.d);
1766  EXPECT_NOT_POISONED(s.e);
1767  EXPECT_POISONED(s.f);
1768}
1769
1770NOINLINE void StructByValTestFunc1(struct StructByVal s) {
1771  StructByValTestFunc(s);
1772}
1773
1774NOINLINE void StructByValTestFunc2(int z, struct StructByVal s) {
1775  StructByValTestFunc(s);
1776}
1777
1778TEST(MemorySanitizer, StructByVal) {
1779  // Large aggregates are passed as "byval" pointer argument in LLVM.
1780  struct StructByVal s;
1781  s.a = 1;
1782  s.b = *GetPoisoned<int>();
1783  s.c = 2;
1784  s.d = *GetPoisoned<int>();
1785  s.e = 3;
1786  s.f = *GetPoisoned<int>();
1787  StructByValTestFunc(s);
1788  StructByValTestFunc1(s);
1789  StructByValTestFunc2(0, s);
1790}
1791
1792
1793#if MSAN_HAS_M128
1794NOINLINE __m128i m128Eq(__m128i *a, __m128i *b) { return _mm_cmpeq_epi16(*a, *b); }
1795NOINLINE __m128i m128Lt(__m128i *a, __m128i *b) { return _mm_cmplt_epi16(*a, *b); }
1796TEST(MemorySanitizer, m128) {
1797  __m128i a = _mm_set1_epi16(0x1234);
1798  __m128i b = _mm_set1_epi16(0x7890);
1799  EXPECT_NOT_POISONED(m128Eq(&a, &b));
1800  EXPECT_NOT_POISONED(m128Lt(&a, &b));
1801}
1802// FIXME: add more tests for __m128i.
1803#endif  // MSAN_HAS_M128
1804
1805// We should not complain when copying this poisoned hole.
1806struct StructWithHole {
1807  U4  a;
1808  // 4-byte hole.
1809  U8  b;
1810};
1811
1812NOINLINE StructWithHole ReturnStructWithHole() {
1813  StructWithHole res;
1814  __msan_poison(&res, sizeof(res));
1815  res.a = 1;
1816  res.b = 2;
1817  return res;
1818}
1819
1820TEST(MemorySanitizer, StructWithHole) {
1821  StructWithHole a = ReturnStructWithHole();
1822  break_optimization(&a);
1823}
1824
1825template <class T>
1826NOINLINE T ReturnStruct() {
1827  T res;
1828  __msan_poison(&res, sizeof(res));
1829  res.a = 1;
1830  return res;
1831}
1832
1833template <class T>
1834NOINLINE void TestReturnStruct() {
1835  T s1 = ReturnStruct<T>();
1836  EXPECT_NOT_POISONED(s1.a);
1837  EXPECT_POISONED(s1.b);
1838}
1839
1840struct SSS1 {
1841  int a, b, c;
1842};
1843struct SSS2 {
1844  int b, a, c;
1845};
1846struct SSS3 {
1847  int b, c, a;
1848};
1849struct SSS4 {
1850  int c, b, a;
1851};
1852
1853struct SSS5 {
1854  int a;
1855  float b;
1856};
1857struct SSS6 {
1858  int a;
1859  double b;
1860};
1861struct SSS7 {
1862  S8 b;
1863  int a;
1864};
1865struct SSS8 {
1866  S2 b;
1867  S8 a;
1868};
1869
1870TEST(MemorySanitizer, IntStruct3) {
1871  TestReturnStruct<SSS1>();
1872  TestReturnStruct<SSS2>();
1873  TestReturnStruct<SSS3>();
1874  TestReturnStruct<SSS4>();
1875  TestReturnStruct<SSS5>();
1876  TestReturnStruct<SSS6>();
1877  TestReturnStruct<SSS7>();
1878  TestReturnStruct<SSS8>();
1879}
1880
1881struct LongStruct {
1882  U1 a1, b1;
1883  U2 a2, b2;
1884  U4 a4, b4;
1885  U8 a8, b8;
1886};
1887
1888NOINLINE LongStruct ReturnLongStruct1() {
1889  LongStruct res;
1890  __msan_poison(&res, sizeof(res));
1891  res.a1 = res.a2 = res.a4 = res.a8 = 111;
1892  // leaves b1, .., b8 poisoned.
1893  return res;
1894}
1895
1896NOINLINE LongStruct ReturnLongStruct2() {
1897  LongStruct res;
1898  __msan_poison(&res, sizeof(res));
1899  res.b1 = res.b2 = res.b4 = res.b8 = 111;
1900  // leaves a1, .., a8 poisoned.
1901  return res;
1902}
1903
1904TEST(MemorySanitizer, LongStruct) {
1905  LongStruct s1 = ReturnLongStruct1();
1906  __msan_print_shadow(&s1, sizeof(s1));
1907  EXPECT_NOT_POISONED(s1.a1);
1908  EXPECT_NOT_POISONED(s1.a2);
1909  EXPECT_NOT_POISONED(s1.a4);
1910  EXPECT_NOT_POISONED(s1.a8);
1911
1912  EXPECT_POISONED(s1.b1);
1913  EXPECT_POISONED(s1.b2);
1914  EXPECT_POISONED(s1.b4);
1915  EXPECT_POISONED(s1.b8);
1916
1917  LongStruct s2 = ReturnLongStruct2();
1918  __msan_print_shadow(&s2, sizeof(s2));
1919  EXPECT_NOT_POISONED(s2.b1);
1920  EXPECT_NOT_POISONED(s2.b2);
1921  EXPECT_NOT_POISONED(s2.b4);
1922  EXPECT_NOT_POISONED(s2.b8);
1923
1924  EXPECT_POISONED(s2.a1);
1925  EXPECT_POISONED(s2.a2);
1926  EXPECT_POISONED(s2.a4);
1927  EXPECT_POISONED(s2.a8);
1928}
1929
1930TEST(MemorySanitizer, getrlimit) {
1931  struct rlimit limit;
1932  __msan_poison(&limit, sizeof(limit));
1933  int result = getrlimit(RLIMIT_DATA, &limit);
1934  assert(result == 0);
1935  EXPECT_NOT_POISONED(limit.rlim_cur);
1936  EXPECT_NOT_POISONED(limit.rlim_max);
1937}
1938
1939TEST(MemorySanitizer, getrusage) {
1940  struct rusage usage;
1941  __msan_poison(&usage, sizeof(usage));
1942  int result = getrusage(RUSAGE_SELF, &usage);
1943  assert(result == 0);
1944  EXPECT_NOT_POISONED(usage.ru_utime.tv_sec);
1945  EXPECT_NOT_POISONED(usage.ru_utime.tv_usec);
1946  EXPECT_NOT_POISONED(usage.ru_stime.tv_sec);
1947  EXPECT_NOT_POISONED(usage.ru_stime.tv_usec);
1948  EXPECT_NOT_POISONED(usage.ru_maxrss);
1949  EXPECT_NOT_POISONED(usage.ru_minflt);
1950  EXPECT_NOT_POISONED(usage.ru_majflt);
1951  EXPECT_NOT_POISONED(usage.ru_inblock);
1952  EXPECT_NOT_POISONED(usage.ru_oublock);
1953  EXPECT_NOT_POISONED(usage.ru_nvcsw);
1954  EXPECT_NOT_POISONED(usage.ru_nivcsw);
1955}
1956
1957#ifdef __GLIBC__
1958extern char *program_invocation_name;
1959#else  // __GLIBC__
1960# error "TODO: port this"
1961#endif
1962
1963static void dladdr_testfn() {}
1964
1965TEST(MemorySanitizer, dladdr) {
1966  Dl_info info;
1967  __msan_poison(&info, sizeof(info));
1968  int result = dladdr((const void*)dladdr_testfn, &info);
1969  assert(result != 0);
1970  EXPECT_NOT_POISONED((unsigned long)info.dli_fname);
1971  if (info.dli_fname)
1972    EXPECT_NOT_POISONED(strlen(info.dli_fname));
1973  EXPECT_NOT_POISONED((unsigned long)info.dli_fbase);
1974  EXPECT_NOT_POISONED((unsigned long)info.dli_sname);
1975  if (info.dli_sname)
1976    EXPECT_NOT_POISONED(strlen(info.dli_sname));
1977  EXPECT_NOT_POISONED((unsigned long)info.dli_saddr);
1978}
1979
1980#ifndef MSAN_TEST_DISABLE_DLOPEN
1981
1982static int dl_phdr_callback(struct dl_phdr_info *info, size_t size, void *data) {
1983  (*(int *)data)++;
1984  EXPECT_NOT_POISONED(info->dlpi_addr);
1985  EXPECT_NOT_POISONED(strlen(info->dlpi_name));
1986  EXPECT_NOT_POISONED(info->dlpi_phnum);
1987  for (int i = 0; i < info->dlpi_phnum; ++i)
1988    EXPECT_NOT_POISONED(info->dlpi_phdr[i]);
1989  return 0;
1990}
1991
1992// Compute the path to our loadable DSO.  We assume it's in the same
1993// directory.  Only use string routines that we intercept so far to do this.
1994static int PathToLoadable(char *buf, size_t sz) {
1995  const char *basename = "libmsan_loadable.x86_64.so";
1996  char *argv0 = program_invocation_name;
1997  char *last_slash = strrchr(argv0, '/');
1998  assert(last_slash);
1999  int res =
2000      snprintf(buf, sz, "%.*s/%s", int(last_slash - argv0), argv0, basename);
2001  return res < sz ? 0 : res;
2002}
2003
2004TEST(MemorySanitizer, dl_iterate_phdr) {
2005  char path[4096];
2006  int res = PathToLoadable(path, sizeof(path));
2007  assert(!res);
2008
2009  // Having at least one dlopen'ed library in the process makes this more
2010  // entertaining.
2011  void *lib = dlopen(path, RTLD_LAZY);
2012  ASSERT_NE((void*)0, lib);
2013
2014  int count = 0;
2015  int result = dl_iterate_phdr(dl_phdr_callback, &count);
2016  assert(count > 0);
2017
2018  dlclose(lib);
2019}
2020
2021
2022TEST(MemorySanitizer, dlopen) {
2023  char path[4096];
2024  int res = PathToLoadable(path, sizeof(path));
2025  assert(!res);
2026
2027  // We need to clear shadow for globals when doing dlopen.  In order to test
2028  // this, we have to poison the shadow for the DSO before we load it.  In
2029  // general this is difficult, but the loader tends to reload things in the
2030  // same place, so we open, close, and then reopen.  The global should always
2031  // start out clean after dlopen.
2032  for (int i = 0; i < 2; i++) {
2033    void *lib = dlopen(path, RTLD_LAZY);
2034    if (lib == NULL) {
2035      printf("dlerror: %s\n", dlerror());
2036      assert(lib != NULL);
2037    }
2038    void **(*get_dso_global)() = (void **(*)())dlsym(lib, "get_dso_global");
2039    assert(get_dso_global);
2040    void **dso_global = get_dso_global();
2041    EXPECT_NOT_POISONED(*dso_global);
2042    __msan_poison(dso_global, sizeof(*dso_global));
2043    EXPECT_POISONED(*dso_global);
2044    dlclose(lib);
2045  }
2046}
2047
2048// Regression test for a crash in dlopen() interceptor.
2049TEST(MemorySanitizer, dlopenFailed) {
2050  const char *path = "/libmsan_loadable_does_not_exist.x86_64.so";
2051  void *lib = dlopen(path, RTLD_LAZY);
2052  ASSERT_EQ(0, lib);
2053}
2054
2055#endif // MSAN_TEST_DISABLE_DLOPEN
2056
2057TEST(MemorySanitizer, sched_getaffinity) {
2058  cpu_set_t mask;
2059  int res = sched_getaffinity(getpid(), sizeof(mask), &mask);
2060  ASSERT_EQ(0, res);
2061  EXPECT_NOT_POISONED(mask);
2062}
2063
2064TEST(MemorySanitizer, scanf) {
2065  const char *input = "42 hello";
2066  int* d = new int;
2067  char* s = new char[7];
2068  int res = sscanf(input, "%d %5s", d, s);
2069  printf("res %d\n", res);
2070  assert(res == 2);
2071  EXPECT_NOT_POISONED(*d);
2072  EXPECT_NOT_POISONED(s[0]);
2073  EXPECT_NOT_POISONED(s[1]);
2074  EXPECT_NOT_POISONED(s[2]);
2075  EXPECT_NOT_POISONED(s[3]);
2076  EXPECT_NOT_POISONED(s[4]);
2077  EXPECT_NOT_POISONED(s[5]);
2078  EXPECT_POISONED(s[6]);
2079  delete s;
2080  delete d;
2081}
2082
2083static void *SimpleThread_threadfn(void* data) {
2084  return new int;
2085}
2086
2087TEST(MemorySanitizer, SimpleThread) {
2088  pthread_t t;
2089  void *p;
2090  int res = pthread_create(&t, NULL, SimpleThread_threadfn, NULL);
2091  assert(!res);
2092  EXPECT_NOT_POISONED(t);
2093  res = pthread_join(t, &p);
2094  assert(!res);
2095  EXPECT_NOT_POISONED(p);
2096  delete (int*)p;
2097}
2098
2099static void *SmallStackThread_threadfn(void* data) {
2100  return 0;
2101}
2102
2103TEST(MemorySanitizer, SmallStackThread) {
2104  pthread_attr_t attr;
2105  pthread_t t;
2106  void *p;
2107  int res;
2108  res = pthread_attr_init(&attr);
2109  ASSERT_EQ(0, res);
2110  res = pthread_attr_setstacksize(&attr, 64 * 1024);
2111  ASSERT_EQ(0, res);
2112  res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
2113  ASSERT_EQ(0, res);
2114  res = pthread_join(t, &p);
2115  ASSERT_EQ(0, res);
2116  res = pthread_attr_destroy(&attr);
2117  ASSERT_EQ(0, res);
2118}
2119
2120TEST(MemorySanitizer, PreAllocatedStackThread) {
2121  pthread_attr_t attr;
2122  pthread_t t;
2123  int res;
2124  res = pthread_attr_init(&attr);
2125  ASSERT_EQ(0, res);
2126  void *stack;
2127  const size_t kStackSize = 64 * 1024;
2128  res = posix_memalign(&stack, 4096, kStackSize);
2129  ASSERT_EQ(0, res);
2130  res = pthread_attr_setstack(&attr, stack, kStackSize);
2131  ASSERT_EQ(0, res);
2132  // A small self-allocated stack can not be extended by the tool.
2133  // In this case pthread_create is expected to fail.
2134  res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
2135  EXPECT_NE(0, res);
2136  res = pthread_attr_destroy(&attr);
2137  ASSERT_EQ(0, res);
2138}
2139
2140TEST(MemorySanitizer, pthread_getschedparam) {
2141  int policy;
2142  struct sched_param param;
2143  int res = pthread_getschedparam(pthread_self(), &policy, &param);
2144  ASSERT_EQ(0, res);
2145  EXPECT_NOT_POISONED(policy);
2146  EXPECT_NOT_POISONED(param.sched_priority);
2147}
2148
2149TEST(MemorySanitizer, pthread_key_create) {
2150  pthread_key_t key;
2151  int res = pthread_key_create(&key, NULL);
2152  assert(!res);
2153  EXPECT_NOT_POISONED(key);
2154  res = pthread_key_delete(key);
2155  assert(!res);
2156}
2157
2158TEST(MemorySanitizer, posix_memalign) {
2159  void *p;
2160  EXPECT_POISONED(p);
2161  int res = posix_memalign(&p, 4096, 13);
2162  ASSERT_EQ(0, res);
2163  EXPECT_NOT_POISONED(p);
2164  free(p);
2165}
2166
2167TEST(MemorySanitizer, inet_pton) {
2168  const char *s = "1:0:0:0:0:0:0:8";
2169  unsigned char buf[sizeof(struct in6_addr)];
2170  int res = inet_pton(AF_INET6, s, buf);
2171  ASSERT_EQ(1, res);
2172  EXPECT_NOT_POISONED(buf[0]);
2173  EXPECT_NOT_POISONED(buf[sizeof(struct in6_addr) - 1]);
2174
2175  char s_out[INET6_ADDRSTRLEN];
2176  EXPECT_POISONED(s_out[3]);
2177  const char *q = inet_ntop(AF_INET6, buf, s_out, INET6_ADDRSTRLEN);
2178  ASSERT_NE((void*)0, q);
2179  EXPECT_NOT_POISONED(s_out[3]);
2180}
2181
2182TEST(MemorySanitizer, inet_aton) {
2183  const char *s = "127.0.0.1";
2184  struct in_addr in[2];
2185  int res = inet_aton(s, in);
2186  ASSERT_NE(0, res);
2187  EXPECT_NOT_POISONED(in[0]);
2188  EXPECT_POISONED(*(char *)(in + 1));
2189}
2190
2191TEST(MemorySanitizer, uname) {
2192  struct utsname u;
2193  int res = uname(&u);
2194  assert(!res);
2195  EXPECT_NOT_POISONED(strlen(u.sysname));
2196  EXPECT_NOT_POISONED(strlen(u.nodename));
2197  EXPECT_NOT_POISONED(strlen(u.release));
2198  EXPECT_NOT_POISONED(strlen(u.version));
2199  EXPECT_NOT_POISONED(strlen(u.machine));
2200}
2201
2202TEST(MemorySanitizer, gethostname) {
2203  char buf[100];
2204  int res = gethostname(buf, 100);
2205  assert(!res);
2206  EXPECT_NOT_POISONED(strlen(buf));
2207}
2208
2209TEST(MemorySanitizer, sysinfo) {
2210  struct sysinfo info;
2211  int res = sysinfo(&info);
2212  assert(!res);
2213  EXPECT_NOT_POISONED(info);
2214}
2215
2216TEST(MemorySanitizer, getpwuid) {
2217  struct passwd *p = getpwuid(0); // root
2218  assert(p);
2219  EXPECT_NOT_POISONED(p->pw_name);
2220  assert(p->pw_name);
2221  EXPECT_NOT_POISONED(p->pw_name[0]);
2222  EXPECT_NOT_POISONED(p->pw_uid);
2223  assert(p->pw_uid == 0);
2224}
2225
2226TEST(MemorySanitizer, getpwnam_r) {
2227  struct passwd pwd;
2228  struct passwd *pwdres;
2229  char buf[10000];
2230  int res = getpwnam_r("root", &pwd, buf, sizeof(buf), &pwdres);
2231  assert(!res);
2232  EXPECT_NOT_POISONED(pwd.pw_name);
2233  assert(pwd.pw_name);
2234  EXPECT_NOT_POISONED(pwd.pw_name[0]);
2235  EXPECT_NOT_POISONED(pwd.pw_uid);
2236  assert(pwd.pw_uid == 0);
2237}
2238
2239TEST(MemorySanitizer, getpwnam_r_positive) {
2240  struct passwd pwd;
2241  struct passwd *pwdres;
2242  char s[5];
2243  strncpy(s, "abcd", 5);
2244  __msan_poison(s, 5);
2245  char buf[10000];
2246  int res;
2247  EXPECT_UMR(res = getpwnam_r(s, &pwd, buf, sizeof(buf), &pwdres));
2248}
2249
2250TEST(MemorySanitizer, getgrnam_r) {
2251  struct group grp;
2252  struct group *grpres;
2253  char buf[10000];
2254  int res = getgrnam_r("root", &grp, buf, sizeof(buf), &grpres);
2255  assert(!res);
2256  EXPECT_NOT_POISONED(grp.gr_name);
2257  assert(grp.gr_name);
2258  EXPECT_NOT_POISONED(grp.gr_name[0]);
2259  EXPECT_NOT_POISONED(grp.gr_gid);
2260}
2261
2262template<class T>
2263static bool applySlt(T value, T shadow) {
2264  __msan_partial_poison(&value, &shadow, sizeof(T));
2265  volatile bool zzz = true;
2266  // This "|| zzz" trick somehow makes LLVM emit "icmp slt" instead of
2267  // a shift-and-trunc to get at the highest bit.
2268  volatile bool v = value < 0 || zzz;
2269  return v;
2270}
2271
2272TEST(MemorySanitizer, SignedCompareWithZero) {
2273  EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xF));
2274  EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFF));
2275  EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFFFFFF));
2276  EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0x7FFFFFF));
2277  EXPECT_UMR(applySlt<S4>(0xF, 0x80FFFFFF));
2278  EXPECT_UMR(applySlt<S4>(0xF, 0xFFFFFFFF));
2279}
2280
2281template <class T, class S>
2282static T poisoned(T Va, S Sa) {
2283  char SIZE_CHECK1[(ssize_t)sizeof(T) - (ssize_t)sizeof(S)];
2284  char SIZE_CHECK2[(ssize_t)sizeof(S) - (ssize_t)sizeof(T)];
2285  T a;
2286  a = Va;
2287  __msan_partial_poison(&a, &Sa, sizeof(T));
2288  return a;
2289}
2290
2291TEST(MemorySanitizer, ICmpRelational) {
2292  EXPECT_NOT_POISONED(poisoned(0, 0) < poisoned(0, 0));
2293  EXPECT_NOT_POISONED(poisoned(0U, 0) < poisoned(0U, 0));
2294  EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) < poisoned(0LL, 0LLU));
2295  EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) < poisoned(0LLU, 0LLU));
2296  EXPECT_POISONED(poisoned(0xFF, 0xFF) < poisoned(0xFF, 0xFF));
2297  EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) <
2298                  poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
2299  EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) <
2300                  poisoned(-1, 0xFFFFFFFFU));
2301
2302  EXPECT_NOT_POISONED(poisoned(0, 0) <= poisoned(0, 0));
2303  EXPECT_NOT_POISONED(poisoned(0U, 0) <= poisoned(0U, 0));
2304  EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) <= poisoned(0LL, 0LLU));
2305  EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) <= poisoned(0LLU, 0LLU));
2306  EXPECT_POISONED(poisoned(0xFF, 0xFF) <= poisoned(0xFF, 0xFF));
2307  EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) <=
2308                  poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
2309  EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) <=
2310                  poisoned(-1, 0xFFFFFFFFU));
2311
2312  EXPECT_NOT_POISONED(poisoned(0, 0) > poisoned(0, 0));
2313  EXPECT_NOT_POISONED(poisoned(0U, 0) > poisoned(0U, 0));
2314  EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) > poisoned(0LL, 0LLU));
2315  EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) > poisoned(0LLU, 0LLU));
2316  EXPECT_POISONED(poisoned(0xFF, 0xFF) > poisoned(0xFF, 0xFF));
2317  EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >
2318                  poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
2319  EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >
2320                  poisoned(-1, 0xFFFFFFFFU));
2321
2322  EXPECT_NOT_POISONED(poisoned(0, 0) >= poisoned(0, 0));
2323  EXPECT_NOT_POISONED(poisoned(0U, 0) >= poisoned(0U, 0));
2324  EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) >= poisoned(0LL, 0LLU));
2325  EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) >= poisoned(0LLU, 0LLU));
2326  EXPECT_POISONED(poisoned(0xFF, 0xFF) >= poisoned(0xFF, 0xFF));
2327  EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >=
2328                  poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
2329  EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >=
2330                  poisoned(-1, 0xFFFFFFFFU));
2331
2332  EXPECT_POISONED(poisoned(6, 0xF) > poisoned(7, 0));
2333  EXPECT_POISONED(poisoned(0xF, 0xF) > poisoned(7, 0));
2334
2335  EXPECT_NOT_POISONED(poisoned(-1, 0x80000000U) >= poisoned(-1, 0U));
2336}
2337
2338#if MSAN_HAS_M128
2339TEST(MemorySanitizer, ICmpVectorRelational) {
2340  EXPECT_NOT_POISONED(
2341      _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0)),
2342                   poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0))));
2343  EXPECT_NOT_POISONED(
2344      _mm_cmplt_epi16(poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0)),
2345                   poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0))));
2346  EXPECT_POISONED(
2347      _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF)),
2348                   poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF))));
2349  EXPECT_POISONED(_mm_cmpgt_epi16(poisoned(_mm_set1_epi16(6), _mm_set1_epi16(0xF)),
2350                               poisoned(_mm_set1_epi16(7), _mm_set1_epi16(0))));
2351}
2352#endif
2353
2354// Volatile bitfield store is implemented as load-mask-store
2355// Test that we don't warn on the store of (uninitialized) padding.
2356struct VolatileBitfieldStruct {
2357  volatile unsigned x : 1;
2358  unsigned y : 1;
2359};
2360
2361TEST(MemorySanitizer, VolatileBitfield) {
2362  VolatileBitfieldStruct *S = new VolatileBitfieldStruct;
2363  S->x = 1;
2364  EXPECT_NOT_POISONED((unsigned)S->x);
2365  EXPECT_POISONED((unsigned)S->y);
2366}
2367
2368TEST(MemorySanitizer, UnalignedLoad) {
2369  char x[32];
2370  memset(x + 8, 0, 16);
2371  EXPECT_POISONED(__sanitizer_unaligned_load16(x+6));
2372  EXPECT_POISONED(__sanitizer_unaligned_load16(x+7));
2373  EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x+8));
2374  EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x+9));
2375  EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x+22));
2376  EXPECT_POISONED(__sanitizer_unaligned_load16(x+23));
2377  EXPECT_POISONED(__sanitizer_unaligned_load16(x+24));
2378
2379  EXPECT_POISONED(__sanitizer_unaligned_load32(x+4));
2380  EXPECT_POISONED(__sanitizer_unaligned_load32(x+7));
2381  EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x+8));
2382  EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x+9));
2383  EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x+20));
2384  EXPECT_POISONED(__sanitizer_unaligned_load32(x+21));
2385  EXPECT_POISONED(__sanitizer_unaligned_load32(x+24));
2386
2387  EXPECT_POISONED(__sanitizer_unaligned_load64(x));
2388  EXPECT_POISONED(__sanitizer_unaligned_load64(x+1));
2389  EXPECT_POISONED(__sanitizer_unaligned_load64(x+7));
2390  EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x+8));
2391  EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x+9));
2392  EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x+16));
2393  EXPECT_POISONED(__sanitizer_unaligned_load64(x+17));
2394  EXPECT_POISONED(__sanitizer_unaligned_load64(x+21));
2395  EXPECT_POISONED(__sanitizer_unaligned_load64(x+24));
2396}
2397
2398TEST(MemorySanitizer, UnalignedStore16) {
2399  char x[5];
2400  U2 y = 0;
2401  __msan_poison(&y, 1);
2402  __sanitizer_unaligned_store16(x + 1, y);
2403  EXPECT_POISONED(x[0]);
2404  EXPECT_POISONED(x[1]);
2405  EXPECT_NOT_POISONED(x[2]);
2406  EXPECT_POISONED(x[3]);
2407  EXPECT_POISONED(x[4]);
2408}
2409
2410TEST(MemorySanitizer, UnalignedStore32) {
2411  char x[8];
2412  U4 y4 = 0;
2413  __msan_poison(&y4, 2);
2414  __sanitizer_unaligned_store32(x+3, y4);
2415  EXPECT_POISONED(x[0]);
2416  EXPECT_POISONED(x[1]);
2417  EXPECT_POISONED(x[2]);
2418  EXPECT_POISONED(x[3]);
2419  EXPECT_POISONED(x[4]);
2420  EXPECT_NOT_POISONED(x[5]);
2421  EXPECT_NOT_POISONED(x[6]);
2422  EXPECT_POISONED(x[7]);
2423}
2424
2425TEST(MemorySanitizer, UnalignedStore64) {
2426  char x[16];
2427  U8 y = 0;
2428  __msan_poison(&y, 3);
2429  __msan_poison(((char *)&y) + sizeof(y) - 2, 1);
2430  __sanitizer_unaligned_store64(x+3, y);
2431  EXPECT_POISONED(x[0]);
2432  EXPECT_POISONED(x[1]);
2433  EXPECT_POISONED(x[2]);
2434  EXPECT_POISONED(x[3]);
2435  EXPECT_POISONED(x[4]);
2436  EXPECT_POISONED(x[5]);
2437  EXPECT_NOT_POISONED(x[6]);
2438  EXPECT_NOT_POISONED(x[7]);
2439  EXPECT_NOT_POISONED(x[8]);
2440  EXPECT_POISONED(x[9]);
2441  EXPECT_NOT_POISONED(x[10]);
2442  EXPECT_POISONED(x[11]);
2443}
2444
2445TEST(MemorySanitizerDr, StoreInDSOTest) {
2446  if (!__msan_has_dynamic_component()) return;
2447  char* s = new char[10];
2448  dso_memfill(s, 9);
2449  EXPECT_NOT_POISONED(s[5]);
2450  EXPECT_POISONED(s[9]);
2451}
2452
2453int return_poisoned_int() {
2454  return ReturnPoisoned<U8>();
2455}
2456
2457TEST(MemorySanitizerDr, ReturnFromDSOTest) {
2458  if (!__msan_has_dynamic_component()) return;
2459  EXPECT_NOT_POISONED(dso_callfn(return_poisoned_int));
2460}
2461
2462NOINLINE int TrashParamTLS(long long x, long long y, long long z) {  //NOLINT
2463  EXPECT_POISONED(x);
2464  EXPECT_POISONED(y);
2465  EXPECT_POISONED(z);
2466  return 0;
2467}
2468
2469static int CheckParamTLS(long long x, long long y, long long z) {  //NOLINT
2470  EXPECT_NOT_POISONED(x);
2471  EXPECT_NOT_POISONED(y);
2472  EXPECT_NOT_POISONED(z);
2473  return 0;
2474}
2475
2476TEST(MemorySanitizerDr, CallFromDSOTest) {
2477  if (!__msan_has_dynamic_component()) return;
2478  S8* x = GetPoisoned<S8>();
2479  S8* y = GetPoisoned<S8>();
2480  S8* z = GetPoisoned<S8>();
2481  EXPECT_NOT_POISONED(TrashParamTLS(*x, *y, *z));
2482  EXPECT_NOT_POISONED(dso_callfn1(CheckParamTLS));
2483}
2484
2485static void StackStoreInDSOFn(int* x, int* y) {
2486  EXPECT_NOT_POISONED(*x);
2487  EXPECT_NOT_POISONED(*y);
2488}
2489
2490TEST(MemorySanitizerDr, StackStoreInDSOTest) {
2491  if (!__msan_has_dynamic_component()) return;
2492  dso_stack_store(StackStoreInDSOFn, 1);
2493}
2494
2495TEST(MemorySanitizerOrigins, SetGet) {
2496  EXPECT_EQ(TrackingOrigins(), __msan_get_track_origins());
2497  if (!TrackingOrigins()) return;
2498  int x;
2499  __msan_set_origin(&x, sizeof(x), 1234);
2500  EXPECT_EQ(1234, __msan_get_origin(&x));
2501  __msan_set_origin(&x, sizeof(x), 5678);
2502  EXPECT_EQ(5678, __msan_get_origin(&x));
2503  __msan_set_origin(&x, sizeof(x), 0);
2504  EXPECT_EQ(0, __msan_get_origin(&x));
2505}
2506
2507namespace {
2508struct S {
2509  U4 dummy;
2510  U2 a;
2511  U2 b;
2512};
2513
2514// http://code.google.com/p/memory-sanitizer/issues/detail?id=6
2515TEST(MemorySanitizerOrigins, DISABLED_InitializedStoreDoesNotChangeOrigin) {
2516  if (!TrackingOrigins()) return;
2517
2518  S s;
2519  U4 origin = rand();  // NOLINT
2520  s.a = *GetPoisonedO<U2>(0, origin);
2521  EXPECT_EQ(origin, __msan_get_origin(&s.a));
2522  EXPECT_EQ(origin, __msan_get_origin(&s.b));
2523
2524  s.b = 42;
2525  EXPECT_EQ(origin, __msan_get_origin(&s.a));
2526  EXPECT_EQ(origin, __msan_get_origin(&s.b));
2527}
2528}  // namespace
2529
2530template<class T, class BinaryOp>
2531INLINE
2532void BinaryOpOriginTest(BinaryOp op) {
2533  U4 ox = rand();  //NOLINT
2534  U4 oy = rand();  //NOLINT
2535  T *x = GetPoisonedO<T>(0, ox, 0);
2536  T *y = GetPoisonedO<T>(1, oy, 0);
2537  T *z = GetPoisonedO<T>(2, 0, 0);
2538
2539  *z = op(*x, *y);
2540  U4 origin = __msan_get_origin(z);
2541  EXPECT_POISONED_O(*z, origin);
2542  EXPECT_EQ(true, origin == ox || origin == oy);
2543
2544  // y is poisoned, x is not.
2545  *x = 10101;
2546  *y = *GetPoisonedO<T>(1, oy);
2547  break_optimization(x);
2548  __msan_set_origin(z, sizeof(*z), 0);
2549  *z = op(*x, *y);
2550  EXPECT_POISONED_O(*z, oy);
2551  EXPECT_EQ(__msan_get_origin(z), oy);
2552
2553  // x is poisoned, y is not.
2554  *x = *GetPoisonedO<T>(0, ox);
2555  *y = 10101010;
2556  break_optimization(y);
2557  __msan_set_origin(z, sizeof(*z), 0);
2558  *z = op(*x, *y);
2559  EXPECT_POISONED_O(*z, ox);
2560  EXPECT_EQ(__msan_get_origin(z), ox);
2561}
2562
2563template<class T> INLINE T XOR(const T &a, const T&b) { return a ^ b; }
2564template<class T> INLINE T ADD(const T &a, const T&b) { return a + b; }
2565template<class T> INLINE T SUB(const T &a, const T&b) { return a - b; }
2566template<class T> INLINE T MUL(const T &a, const T&b) { return a * b; }
2567template<class T> INLINE T AND(const T &a, const T&b) { return a & b; }
2568template<class T> INLINE T OR (const T &a, const T&b) { return a | b; }
2569
2570TEST(MemorySanitizerOrigins, BinaryOp) {
2571  if (!TrackingOrigins()) return;
2572  BinaryOpOriginTest<S8>(XOR<S8>);
2573  BinaryOpOriginTest<U8>(ADD<U8>);
2574  BinaryOpOriginTest<S4>(SUB<S4>);
2575  BinaryOpOriginTest<S4>(MUL<S4>);
2576  BinaryOpOriginTest<U4>(OR<U4>);
2577  BinaryOpOriginTest<U4>(AND<U4>);
2578  BinaryOpOriginTest<double>(ADD<U4>);
2579  BinaryOpOriginTest<float>(ADD<S4>);
2580  BinaryOpOriginTest<double>(ADD<double>);
2581  BinaryOpOriginTest<float>(ADD<double>);
2582}
2583
2584TEST(MemorySanitizerOrigins, Unary) {
2585  if (!TrackingOrigins()) return;
2586  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
2587  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
2588  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
2589  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
2590
2591  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2592  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2593  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2594  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2595
2596  EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
2597  EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
2598  EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
2599  EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
2600
2601  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2602  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2603  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2604  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2605
2606  EXPECT_POISONED_O((void*)*GetPoisonedO<S8>(0, __LINE__), __LINE__);
2607  EXPECT_POISONED_O((U8)*GetPoisonedO<void*>(0, __LINE__), __LINE__);
2608}
2609
2610TEST(MemorySanitizerOrigins, EQ) {
2611  if (!TrackingOrigins()) return;
2612  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) <= 11, __LINE__);
2613  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) == 11, __LINE__);
2614  EXPECT_POISONED_O(*GetPoisonedO<float>(0, __LINE__) == 1.1, __LINE__);
2615}
2616
2617TEST(MemorySanitizerOrigins, DIV) {
2618  if (!TrackingOrigins()) return;
2619  EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) / 100, __LINE__);
2620  unsigned o = __LINE__;
2621  EXPECT_UMR_O(volatile unsigned y = 100 / *GetPoisonedO<S4>(0, o, 1), o);
2622}
2623
2624TEST(MemorySanitizerOrigins, SHIFT) {
2625  if (!TrackingOrigins()) return;
2626  EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) >> 10, __LINE__);
2627  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) >> 10, __LINE__);
2628  EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) << 10, __LINE__);
2629  EXPECT_POISONED_O(10U << *GetPoisonedO<U8>(0, __LINE__), __LINE__);
2630  EXPECT_POISONED_O(-10 >> *GetPoisonedO<S8>(0, __LINE__), __LINE__);
2631  EXPECT_POISONED_O(-10 << *GetPoisonedO<S8>(0, __LINE__), __LINE__);
2632}
2633
2634template<class T, int N>
2635void MemCpyTest() {
2636  int ox = __LINE__;
2637  T *x = new T[N];
2638  T *y = new T[N];
2639  T *z = new T[N];
2640  T *q = new T[N];
2641  __msan_poison(x, N * sizeof(T));
2642  __msan_set_origin(x, N * sizeof(T), ox);
2643  __msan_set_origin(y, N * sizeof(T), 777777);
2644  __msan_set_origin(z, N * sizeof(T), 888888);
2645  EXPECT_NOT_POISONED(x);
2646  memcpy(y, x, N * sizeof(T));
2647  EXPECT_POISONED_O(y[0], ox);
2648  EXPECT_POISONED_O(y[N/2], ox);
2649  EXPECT_POISONED_O(y[N-1], ox);
2650  EXPECT_NOT_POISONED(x);
2651  void *res = mempcpy(q, x, N * sizeof(T));
2652  ASSERT_EQ(q + N, res);
2653  EXPECT_POISONED_O(q[0], ox);
2654  EXPECT_POISONED_O(q[N/2], ox);
2655  EXPECT_POISONED_O(q[N-1], ox);
2656  EXPECT_NOT_POISONED(x);
2657  memmove(z, x, N * sizeof(T));
2658  EXPECT_POISONED_O(z[0], ox);
2659  EXPECT_POISONED_O(z[N/2], ox);
2660  EXPECT_POISONED_O(z[N-1], ox);
2661}
2662
2663TEST(MemorySanitizerOrigins, LargeMemCpy) {
2664  if (!TrackingOrigins()) return;
2665  MemCpyTest<U1, 10000>();
2666  MemCpyTest<U8, 10000>();
2667}
2668
2669TEST(MemorySanitizerOrigins, SmallMemCpy) {
2670  if (!TrackingOrigins()) return;
2671  MemCpyTest<U8, 1>();
2672  MemCpyTest<U8, 2>();
2673  MemCpyTest<U8, 3>();
2674}
2675
2676TEST(MemorySanitizerOrigins, Select) {
2677  if (!TrackingOrigins()) return;
2678  EXPECT_NOT_POISONED(g_one ? 1 : *GetPoisonedO<S4>(0, __LINE__));
2679  EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
2680  S4 x;
2681  break_optimization(&x);
2682  x = g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 0;
2683
2684  EXPECT_POISONED_O(g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 1, __LINE__);
2685  EXPECT_POISONED_O(g_0 ? 1 : *GetPoisonedO<S4>(0, __LINE__), __LINE__);
2686}
2687
2688extern "C"
2689NOINLINE char AllocaTO() {
2690  int ar[100];
2691  break_optimization(ar);
2692  return ar[10];
2693  // fprintf(stderr, "Descr: %s\n",
2694  //        __msan_get_origin_descr_if_stack(__msan_get_origin_tls()));
2695}
2696
2697TEST(MemorySanitizerOrigins, Alloca) {
2698  if (!TrackingOrigins()) return;
2699  EXPECT_POISONED_S(AllocaTO(), "ar@AllocaTO");
2700  EXPECT_POISONED_S(AllocaTO(), "ar@AllocaTO");
2701  EXPECT_POISONED_S(AllocaTO(), "ar@AllocaTO");
2702  EXPECT_POISONED_S(AllocaTO(), "ar@AllocaTO");
2703}
2704
2705// FIXME: replace with a lit-like test.
2706TEST(MemorySanitizerOrigins, DISABLED_AllocaDeath) {
2707  if (!TrackingOrigins()) return;
2708  EXPECT_DEATH(AllocaTO(), "ORIGIN: stack allocation: ar@AllocaTO");
2709}
2710
2711NOINLINE int RetvalOriginTest(U4 origin) {
2712  int *a = new int;
2713  break_optimization(a);
2714  __msan_set_origin(a, sizeof(*a), origin);
2715  int res = *a;
2716  delete a;
2717  return res;
2718}
2719
2720TEST(MemorySanitizerOrigins, Retval) {
2721  if (!TrackingOrigins()) return;
2722  EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
2723}
2724
2725NOINLINE void ParamOriginTest(int param, U4 origin) {
2726  EXPECT_POISONED_O(param, origin);
2727}
2728
2729TEST(MemorySanitizerOrigins, Param) {
2730  if (!TrackingOrigins()) return;
2731  int *a = new int;
2732  U4 origin = __LINE__;
2733  break_optimization(a);
2734  __msan_set_origin(a, sizeof(*a), origin);
2735  ParamOriginTest(*a, origin);
2736  delete a;
2737}
2738
2739TEST(MemorySanitizerOrigins, Invoke) {
2740  if (!TrackingOrigins()) return;
2741  StructWithDtor s;  // Will cause the calls to become invokes.
2742  EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
2743}
2744
2745TEST(MemorySanitizerOrigins, strlen) {
2746  S8 alignment;
2747  break_optimization(&alignment);
2748  char x[4] = {'a', 'b', 0, 0};
2749  __msan_poison(&x[2], 1);
2750  U4 origin = __LINE__;
2751  __msan_set_origin(x, sizeof(x), origin);
2752  EXPECT_UMR_O(volatile unsigned y = strlen(x), origin);
2753}
2754
2755TEST(MemorySanitizerOrigins, wcslen) {
2756  wchar_t w[3] = {'a', 'b', 0};
2757  U4 origin = __LINE__;
2758  __msan_set_origin(w, sizeof(w), origin);
2759  __msan_poison(&w[2], sizeof(wchar_t));
2760  EXPECT_UMR_O(volatile unsigned y = wcslen(w), origin);
2761}
2762
2763#if MSAN_HAS_M128
2764TEST(MemorySanitizerOrigins, StoreIntrinsic) {
2765  __m128 x, y;
2766  U4 origin = __LINE__;
2767  __msan_set_origin(&x, sizeof(x), origin);
2768  __msan_poison(&x, sizeof(x));
2769  __builtin_ia32_storeups((float*)&y, x);
2770  EXPECT_POISONED_O(y, origin);
2771}
2772#endif
2773
2774NOINLINE void RecursiveMalloc(int depth) {
2775  static int count;
2776  count++;
2777  if ((count % (1024 * 1024)) == 0)
2778    printf("RecursiveMalloc: %d\n", count);
2779  int *x1 = new int;
2780  int *x2 = new int;
2781  break_optimization(x1);
2782  break_optimization(x2);
2783  if (depth > 0) {
2784    RecursiveMalloc(depth-1);
2785    RecursiveMalloc(depth-1);
2786  }
2787  delete x1;
2788  delete x2;
2789}
2790
2791TEST(MemorySanitizer, CallocOverflow) {
2792  size_t kArraySize = 4096;
2793  volatile size_t kMaxSizeT = std::numeric_limits<size_t>::max();
2794  volatile size_t kArraySize2 = kMaxSizeT / kArraySize + 10;
2795  void *p = calloc(kArraySize, kArraySize2);  // Should return 0.
2796  EXPECT_EQ(0L, Ident(p));
2797}
2798
2799TEST(MemorySanitizerStress, DISABLED_MallocStackTrace) {
2800  RecursiveMalloc(22);
2801}
2802
2803TEST(MemorySanitizerAllocator, get_estimated_allocated_size) {
2804  size_t sizes[] = {0, 20, 5000, 1<<20};
2805  for (size_t i = 0; i < sizeof(sizes) / sizeof(*sizes); ++i) {
2806    size_t alloc_size = __msan_get_estimated_allocated_size(sizes[i]);
2807    EXPECT_EQ(alloc_size, sizes[i]);
2808  }
2809}
2810
2811TEST(MemorySanitizerAllocator, get_allocated_size_and_ownership) {
2812  char *array = reinterpret_cast<char*>(malloc(100));
2813  int *int_ptr = new int;
2814
2815  EXPECT_TRUE(__msan_get_ownership(array));
2816  EXPECT_EQ(100, __msan_get_allocated_size(array));
2817
2818  EXPECT_TRUE(__msan_get_ownership(int_ptr));
2819  EXPECT_EQ(sizeof(*int_ptr), __msan_get_allocated_size(int_ptr));
2820
2821  void *wild_addr = reinterpret_cast<void*>(0x1);
2822  EXPECT_FALSE(__msan_get_ownership(wild_addr));
2823  EXPECT_EQ(0, __msan_get_allocated_size(wild_addr));
2824
2825  EXPECT_FALSE(__msan_get_ownership(array + 50));
2826  EXPECT_EQ(0, __msan_get_allocated_size(array + 50));
2827
2828  // NULL is a valid argument for GetAllocatedSize but is not owned.
2829  EXPECT_FALSE(__msan_get_ownership(NULL));
2830  EXPECT_EQ(0, __msan_get_allocated_size(NULL));
2831
2832  free(array);
2833  EXPECT_FALSE(__msan_get_ownership(array));
2834  EXPECT_EQ(0, __msan_get_allocated_size(array));
2835
2836  delete int_ptr;
2837}
2838