1 //===-- msan_test.cpp -----------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file is a part of MemorySanitizer.
10 //
11 // MemorySanitizer unit tests.
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef MSAN_EXTERNAL_TEST_CONFIG
15 #include "msan_test_config.h"
16 #endif // MSAN_EXTERNAL_TEST_CONFIG
17 
18 #include "sanitizer_common/tests/sanitizer_test_utils.h"
19 
20 #include "sanitizer/allocator_interface.h"
21 #include "sanitizer/msan_interface.h"
22 
23 #if defined(__FreeBSD__)
24 # define _KERNEL  // To declare 'shminfo' structure.
25 # include <sys/shm.h>
26 # undef _KERNEL
27 extern "C" {
28 // <sys/shm.h> doesn't declare these functions in _KERNEL mode.
29 void *shmat(int, const void *, int);
30 int shmget(key_t, size_t, int);
31 int shmctl(int, int, struct shmid_ds *);
32 int shmdt(const void *);
33 }
34 #endif
35 
36 #include <inttypes.h>
37 #include <stdlib.h>
38 #include <stdarg.h>
39 #include <stdio.h>
40 #include <wchar.h>
41 #include <math.h>
42 
43 #include <arpa/inet.h>
44 #include <dlfcn.h>
45 #include <grp.h>
46 #include <unistd.h>
47 #include <link.h>
48 #include <limits.h>
49 #include <sys/time.h>
50 #include <poll.h>
51 #include <sys/types.h>
52 #include <sys/stat.h>
53 #include <fcntl.h>
54 #include <sys/resource.h>
55 #include <sys/ioctl.h>
56 #include <sys/statvfs.h>
57 #include <sys/utsname.h>
58 #include <sys/mman.h>
59 #include <dirent.h>
60 #include <pwd.h>
61 #include <sys/socket.h>
62 #include <netdb.h>
63 #include <wordexp.h>
64 #include <sys/ipc.h>
65 #include <sys/shm.h>
66 
67 #if defined(__NetBSD__)
68 # include <signal.h>
69 # include <netinet/in.h>
70 # include <sys/uio.h>
71 # include <sys/mount.h>
72 # include <sys/sysctl.h>
73 # include <net/if.h>
74 # include <net/if_ether.h>
75 #elif defined(__FreeBSD__)
76 # include <signal.h>
77 # include <netinet/in.h>
78 # include <pthread_np.h>
79 # include <sys/uio.h>
80 # include <sys/mount.h>
81 # include <sys/sysctl.h>
82 # include <net/ethernet.h>
83 # define f_namelen f_namemax  // FreeBSD names this statfs field so.
84 # define cpu_set_t cpuset_t
85 extern "C" {
86 // FreeBSD's <ssp/string.h> defines mempcpy() to be a macro expanding into
87 // a __builtin___mempcpy_chk() call, but since Msan RTL defines it as an
88 // ordinary function, we can declare it here to complete the tests.
89 void *mempcpy(void *dest, const void *src, size_t n);
90 }
91 #else
92 # include <malloc.h>
93 # include <sys/sysinfo.h>
94 # include <sys/vfs.h>
95 # include <mntent.h>
96 # include <netinet/ether.h>
97 # if defined(__linux__)
98 #  include <sys/uio.h>
99 # endif
100 #endif
101 
102 #if defined(__i386__) || defined(__x86_64__)
103 # include <emmintrin.h>
104 # define MSAN_HAS_M128 1
105 #else
106 # define MSAN_HAS_M128 0
107 #endif
108 
109 #ifdef __AVX2__
110 # include <immintrin.h>
111 #endif
112 
113 #if defined(__FreeBSD__) || defined(__NetBSD__)
114 # define FILE_TO_READ "/bin/cat"
115 # define DIR_TO_READ "/bin"
116 # define SUBFILE_TO_READ "cat"
117 # define SYMLINK_TO_READ "/usr/bin/tar"
118 # define SUPERUSER_GROUP "wheel"
119 #else
120 # define FILE_TO_READ "/proc/self/stat"
121 # define DIR_TO_READ "/proc/self"
122 # define SUBFILE_TO_READ "stat"
123 # define SYMLINK_TO_READ "/proc/self/exe"
124 # define SUPERUSER_GROUP "root"
125 #endif
126 
GetPageSize()127 static uintptr_t GetPageSize() {
128   return sysconf(_SC_PAGESIZE);
129 }
130 
131 const size_t kMaxPathLength = 4096;
132 
133 typedef unsigned char U1;
134 typedef unsigned short U2;
135 typedef unsigned int U4;
136 typedef unsigned long long U8;
137 typedef signed char S1;
138 typedef signed short S2;
139 typedef signed int S4;
140 typedef signed long long S8;
141 #define NOINLINE      __attribute__((noinline))
142 #define INLINE      __attribute__((always_inline))
143 
TrackingOrigins()144 static bool TrackingOrigins() {
145   S8 x;
146   __msan_set_origin(&x, sizeof(x), 0x1234);
147   U4 origin = __msan_get_origin(&x);
148   __msan_set_origin(&x, sizeof(x), 0);
149   return __msan_origin_is_descendant_or_same(origin, 0x1234);
150 }
151 
152 #define EXPECT_ORIGIN(expected, origin) \
153   EXPECT_TRUE(__msan_origin_is_descendant_or_same((origin), (expected)))
154 
155 #define EXPECT_UMR(action) \
156     do {                        \
157       __msan_set_expect_umr(1); \
158       action;                   \
159       __msan_set_expect_umr(0); \
160     } while (0)
161 
162 #define EXPECT_UMR_O(action, origin)                                       \
163   do {                                                                     \
164     __msan_set_expect_umr(1);                                              \
165     action;                                                                \
166     __msan_set_expect_umr(0);                                              \
167     if (TrackingOrigins()) EXPECT_ORIGIN(origin, __msan_get_umr_origin()); \
168   } while (0)
169 
170 #define EXPECT_POISONED(x) ExpectPoisoned(x)
171 
172 template <typename T>
ExpectPoisoned(const T & t)173 void ExpectPoisoned(const T& t) {
174   EXPECT_NE(-1, __msan_test_shadow((void*)&t, sizeof(t)));
175 }
176 
177 #define EXPECT_POISONED_O(x, origin) \
178   ExpectPoisonedWithOrigin(x, origin)
179 
180 template<typename T>
ExpectPoisonedWithOrigin(const T & t,unsigned origin)181 void ExpectPoisonedWithOrigin(const T& t, unsigned origin) {
182   EXPECT_NE(-1, __msan_test_shadow((void*)&t, sizeof(t)));
183   if (TrackingOrigins()) EXPECT_ORIGIN(origin, __msan_get_origin((void *)&t));
184 }
185 
186 #define EXPECT_NOT_POISONED(x) EXPECT_EQ(true, TestForNotPoisoned((x)))
187 #define EXPECT_NOT_POISONED2(data, size) \
188   EXPECT_EQ(true, TestForNotPoisoned((data), (size)))
189 
TestForNotPoisoned(const void * data,size_t size)190 bool TestForNotPoisoned(const void *data, size_t size) {
191   return __msan_test_shadow(data, size) == -1;
192 }
193 
194 template<typename T>
TestForNotPoisoned(const T & t)195 bool TestForNotPoisoned(const T& t) {
196   return TestForNotPoisoned((void *)&t, sizeof(t));
197 }
198 
199 static U8 poisoned_array[100];
200 template<class T>
GetPoisoned(int i=0,T val=0)201 T *GetPoisoned(int i = 0, T val = 0) {
202   T *res = (T*)&poisoned_array[i];
203   *res = val;
204   __msan_poison(&poisoned_array[i], sizeof(T));
205   return res;
206 }
207 
208 template<class T>
GetPoisonedO(int i,U4 origin,T val=0)209 T *GetPoisonedO(int i, U4 origin, T val = 0) {
210   T *res = (T*)&poisoned_array[i];
211   *res = val;
212   __msan_poison(&poisoned_array[i], sizeof(T));
213   __msan_set_origin(&poisoned_array[i], sizeof(T), origin);
214   return res;
215 }
216 
217 template<typename T>
Poisoned(T v=0,T s=(T)(-1))218 T Poisoned(T v = 0, T s = (T)(-1)) {
219   __msan_partial_poison(&v, &s, sizeof(T));
220   return v;
221 }
222 
ReturnPoisoned()223 template<class T> NOINLINE T ReturnPoisoned() { return *GetPoisoned<T>(); }
224 
225 static volatile int g_one = 1;
226 static volatile int g_zero = 0;
227 static volatile int g_0 = 0;
228 static volatile int g_1 = 1;
229 
230 S4 a_s4[100];
231 S8 a_s8[100];
232 
233 // Check that malloc poisons memory.
234 // A lot of tests below depend on this.
TEST(MemorySanitizerSanity,PoisonInMalloc)235 TEST(MemorySanitizerSanity, PoisonInMalloc) {
236   int *x = (int*)malloc(sizeof(int));
237   EXPECT_POISONED(*x);
238   free(x);
239 }
240 
TEST(MemorySanitizer,NegativeTest1)241 TEST(MemorySanitizer, NegativeTest1) {
242   S4 *x = GetPoisoned<S4>();
243   if (g_one)
244     *x = 0;
245   EXPECT_NOT_POISONED(*x);
246 }
247 
TEST(MemorySanitizer,PositiveTest1)248 TEST(MemorySanitizer, PositiveTest1) {
249   // Load to store.
250   EXPECT_POISONED(*GetPoisoned<S1>());
251   EXPECT_POISONED(*GetPoisoned<S2>());
252   EXPECT_POISONED(*GetPoisoned<S4>());
253   EXPECT_POISONED(*GetPoisoned<S8>());
254 
255   // S->S conversions.
256   EXPECT_POISONED(*GetPoisoned<S1>());
257   EXPECT_POISONED(*GetPoisoned<S1>());
258   EXPECT_POISONED(*GetPoisoned<S1>());
259 
260   EXPECT_POISONED(*GetPoisoned<S2>());
261   EXPECT_POISONED(*GetPoisoned<S2>());
262   EXPECT_POISONED(*GetPoisoned<S2>());
263 
264   EXPECT_POISONED(*GetPoisoned<S4>());
265   EXPECT_POISONED(*GetPoisoned<S4>());
266   EXPECT_POISONED(*GetPoisoned<S4>());
267 
268   EXPECT_POISONED(*GetPoisoned<S8>());
269   EXPECT_POISONED(*GetPoisoned<S8>());
270   EXPECT_POISONED(*GetPoisoned<S8>());
271 
272   // ZExt
273   EXPECT_POISONED(*GetPoisoned<U1>());
274   EXPECT_POISONED(*GetPoisoned<U1>());
275   EXPECT_POISONED(*GetPoisoned<U1>());
276   EXPECT_POISONED(*GetPoisoned<U2>());
277   EXPECT_POISONED(*GetPoisoned<U2>());
278   EXPECT_POISONED(*GetPoisoned<U4>());
279 
280   // Unary ops.
281   EXPECT_POISONED(- *GetPoisoned<S4>());
282 
283   EXPECT_UMR(a_s4[g_zero] = 100 / *GetPoisoned<S4>(0, 1));
284 
285 
286   a_s4[g_zero] = 1 - *GetPoisoned<S4>();
287   a_s4[g_zero] = 1 + *GetPoisoned<S4>();
288 }
289 
TEST(MemorySanitizer,Phi1)290 TEST(MemorySanitizer, Phi1) {
291   S4 c;
292   if (g_one) {
293     c = *GetPoisoned<S4>();
294   } else {
295     break_optimization(0);
296     c = 0;
297   }
298   EXPECT_POISONED(c);
299 }
300 
TEST(MemorySanitizer,Phi2)301 TEST(MemorySanitizer, Phi2) {
302   S4 i = *GetPoisoned<S4>();
303   S4 n = g_one;
304   EXPECT_UMR(for (; i < g_one; i++););
305   EXPECT_POISONED(i);
306 }
307 
Arg1ExpectUMR(S4 a1)308 NOINLINE void Arg1ExpectUMR(S4 a1) { EXPECT_POISONED(a1); }
Arg2ExpectUMR(S4 a1,S4 a2)309 NOINLINE void Arg2ExpectUMR(S4 a1, S4 a2) { EXPECT_POISONED(a2); }
Arg3ExpectUMR(S1 a1,S4 a2,S8 a3)310 NOINLINE void Arg3ExpectUMR(S1 a1, S4 a2, S8 a3) { EXPECT_POISONED(a3); }
311 
TEST(MemorySanitizer,ArgTest)312 TEST(MemorySanitizer, ArgTest) {
313   Arg1ExpectUMR(*GetPoisoned<S4>());
314   Arg2ExpectUMR(0, *GetPoisoned<S4>());
315   Arg3ExpectUMR(0, 1, *GetPoisoned<S8>());
316 }
317 
318 
TEST(MemorySanitizer,CallAndRet)319 TEST(MemorySanitizer, CallAndRet) {
320   ReturnPoisoned<S1>();
321   ReturnPoisoned<S2>();
322   ReturnPoisoned<S4>();
323   ReturnPoisoned<S8>();
324 
325   EXPECT_POISONED(ReturnPoisoned<S1>());
326   EXPECT_POISONED(ReturnPoisoned<S2>());
327   EXPECT_POISONED(ReturnPoisoned<S4>());
328   EXPECT_POISONED(ReturnPoisoned<S8>());
329 }
330 
331 // malloc() in the following test may be optimized to produce a compile-time
332 // undef value. Check that we trap on the volatile assignment anyway.
TEST(MemorySanitizer,DISABLED_MallocNoIdent)333 TEST(MemorySanitizer, DISABLED_MallocNoIdent) {
334   S4 *x = (int*)malloc(sizeof(S4));
335   EXPECT_POISONED(*x);
336   free(x);
337 }
338 
TEST(MemorySanitizer,Malloc)339 TEST(MemorySanitizer, Malloc) {
340   S4 *x = (int*)Ident(malloc(sizeof(S4)));
341   EXPECT_POISONED(*x);
342   free(x);
343 }
344 
TEST(MemorySanitizer,Realloc)345 TEST(MemorySanitizer, Realloc) {
346   S4 *x = (int*)Ident(realloc(0, sizeof(S4)));
347   EXPECT_POISONED(x[0]);
348   x[0] = 1;
349   x = (int*)Ident(realloc(x, 2 * sizeof(S4)));
350   EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
351   EXPECT_POISONED(x[1]);
352   x = (int*)Ident(realloc(x, 3 * sizeof(S4)));
353   EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
354   EXPECT_POISONED(x[2]);
355   EXPECT_POISONED(x[1]);
356   x[2] = 1;  // Init this here. Check that after realloc it is poisoned again.
357   x = (int*)Ident(realloc(x, 2 * sizeof(S4)));
358   EXPECT_NOT_POISONED(x[0]);  // Ok, was inited before.
359   EXPECT_POISONED(x[1]);
360   x = (int*)Ident(realloc(x, 3 * sizeof(S4)));
361   EXPECT_POISONED(x[1]);
362   EXPECT_POISONED(x[2]);
363   free(x);
364 }
365 
TEST(MemorySanitizer,Calloc)366 TEST(MemorySanitizer, Calloc) {
367   S4 *x = (int*)Ident(calloc(1, sizeof(S4)));
368   EXPECT_NOT_POISONED(*x);  // Should not be poisoned.
369   EXPECT_EQ(0, *x);
370   free(x);
371 }
372 
TEST(MemorySanitizer,CallocReturnsZeroMem)373 TEST(MemorySanitizer, CallocReturnsZeroMem) {
374   size_t sizes[] = {16, 1000, 10000, 100000, 2100000};
375   for (size_t s = 0; s < sizeof(sizes)/sizeof(sizes[0]); s++) {
376     size_t size = sizes[s];
377     for (size_t iter = 0; iter < 5; iter++) {
378       char *x = Ident((char*)calloc(1, size));
379       EXPECT_EQ(x[0], 0);
380       EXPECT_EQ(x[size - 1], 0);
381       EXPECT_EQ(x[size / 2], 0);
382       EXPECT_EQ(x[size / 3], 0);
383       EXPECT_EQ(x[size / 4], 0);
384       memset(x, 0x42, size);
385       free(Ident(x));
386     }
387   }
388 }
389 
TEST(MemorySanitizer,AndOr)390 TEST(MemorySanitizer, AndOr) {
391   U4 *p = GetPoisoned<U4>();
392   // We poison two bytes in the midle of a 4-byte word to make the test
393   // correct regardless of endianness.
394   ((U1*)p)[1] = 0;
395   ((U1*)p)[2] = 0xff;
396   EXPECT_NOT_POISONED(*p & 0x00ffff00);
397   EXPECT_NOT_POISONED(*p & 0x00ff0000);
398   EXPECT_NOT_POISONED(*p & 0x0000ff00);
399   EXPECT_POISONED(*p & 0xff000000);
400   EXPECT_POISONED(*p & 0x000000ff);
401   EXPECT_POISONED(*p & 0x0000ffff);
402   EXPECT_POISONED(*p & 0xffff0000);
403 
404   EXPECT_NOT_POISONED(*p | 0xff0000ff);
405   EXPECT_NOT_POISONED(*p | 0xff00ffff);
406   EXPECT_NOT_POISONED(*p | 0xffff00ff);
407   EXPECT_POISONED(*p | 0xff000000);
408   EXPECT_POISONED(*p | 0x000000ff);
409   EXPECT_POISONED(*p | 0x0000ffff);
410   EXPECT_POISONED(*p | 0xffff0000);
411 
412   EXPECT_POISONED(*GetPoisoned<bool>() & *GetPoisoned<bool>());
413 }
414 
415 template<class T>
applyNot(T value,T shadow)416 static bool applyNot(T value, T shadow) {
417   __msan_partial_poison(&value, &shadow, sizeof(T));
418   return !value;
419 }
420 
TEST(MemorySanitizer,Not)421 TEST(MemorySanitizer, Not) {
422   EXPECT_NOT_POISONED(applyNot<U4>(0x0, 0x0));
423   EXPECT_NOT_POISONED(applyNot<U4>(0xFFFFFFFF, 0x0));
424   EXPECT_POISONED(applyNot<U4>(0xFFFFFFFF, 0xFFFFFFFF));
425   EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x0FFFFFFF));
426   EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x00FFFFFF));
427   EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x0000FFFF));
428   EXPECT_NOT_POISONED(applyNot<U4>(0xFF000000, 0x00000000));
429   EXPECT_POISONED(applyNot<U4>(0xFF000000, 0xFF000000));
430   EXPECT_NOT_POISONED(applyNot<U4>(0xFF800000, 0xFF000000));
431   EXPECT_POISONED(applyNot<U4>(0x00008000, 0x00008000));
432 
433   EXPECT_NOT_POISONED(applyNot<U1>(0x0, 0x0));
434   EXPECT_NOT_POISONED(applyNot<U1>(0xFF, 0xFE));
435   EXPECT_NOT_POISONED(applyNot<U1>(0xFF, 0x0));
436   EXPECT_POISONED(applyNot<U1>(0xFF, 0xFF));
437 
438   EXPECT_POISONED(applyNot<void*>((void*)0xFFFFFF, (void*)(-1)));
439   EXPECT_NOT_POISONED(applyNot<void*>((void*)0xFFFFFF, (void*)(-2)));
440 }
441 
TEST(MemorySanitizer,Shift)442 TEST(MemorySanitizer, Shift) {
443   U4 *up = GetPoisoned<U4>();
444   ((U1*)up)[0] = 0;
445   ((U1*)up)[3] = 0xff;
446   EXPECT_NOT_POISONED(*up >> 30);
447   EXPECT_NOT_POISONED(*up >> 24);
448   EXPECT_POISONED(*up >> 23);
449   EXPECT_POISONED(*up >> 10);
450 
451   EXPECT_NOT_POISONED(*up << 30);
452   EXPECT_NOT_POISONED(*up << 24);
453   EXPECT_POISONED(*up << 23);
454   EXPECT_POISONED(*up << 10);
455 
456   S4 *sp = (S4*)up;
457   EXPECT_NOT_POISONED(*sp >> 30);
458   EXPECT_NOT_POISONED(*sp >> 24);
459   EXPECT_POISONED(*sp >> 23);
460   EXPECT_POISONED(*sp >> 10);
461 
462   sp = GetPoisoned<S4>();
463   ((S1*)sp)[1] = 0;
464   ((S1*)sp)[2] = 0;
465   EXPECT_POISONED(*sp >> 31);
466 
467   EXPECT_POISONED(100 >> *GetPoisoned<S4>());
468   EXPECT_POISONED(100U >> *GetPoisoned<S4>());
469 }
470 
GetPoisonedZero()471 NOINLINE static int GetPoisonedZero() {
472   int *zero = new int;
473   *zero = 0;
474   __msan_poison(zero, sizeof(*zero));
475   int res = *zero;
476   delete zero;
477   return res;
478 }
479 
TEST(MemorySanitizer,LoadFromDirtyAddress)480 TEST(MemorySanitizer, LoadFromDirtyAddress) {
481   int *a = new int;
482   *a = 0;
483   EXPECT_UMR(break_optimization((void*)(U8)a[GetPoisonedZero()]));
484   delete a;
485 }
486 
TEST(MemorySanitizer,StoreToDirtyAddress)487 TEST(MemorySanitizer, StoreToDirtyAddress) {
488   int *a = new int;
489   EXPECT_UMR(a[GetPoisonedZero()] = 0);
490   break_optimization(a);
491   delete a;
492 }
493 
494 
StackTestFunc()495 NOINLINE void StackTestFunc() {
496   S4 p4;
497   S4 ok4 = 1;
498   S2 p2;
499   S2 ok2 = 1;
500   S1 p1;
501   S1 ok1 = 1;
502   break_optimization(&p4);
503   break_optimization(&ok4);
504   break_optimization(&p2);
505   break_optimization(&ok2);
506   break_optimization(&p1);
507   break_optimization(&ok1);
508 
509   EXPECT_POISONED(p4);
510   EXPECT_POISONED(p2);
511   EXPECT_POISONED(p1);
512   EXPECT_NOT_POISONED(ok1);
513   EXPECT_NOT_POISONED(ok2);
514   EXPECT_NOT_POISONED(ok4);
515 }
516 
TEST(MemorySanitizer,StackTest)517 TEST(MemorySanitizer, StackTest) {
518   StackTestFunc();
519 }
520 
StackStressFunc()521 NOINLINE void StackStressFunc() {
522   int foo[10000];
523   break_optimization(foo);
524 }
525 
TEST(MemorySanitizer,DISABLED_StackStressTest)526 TEST(MemorySanitizer, DISABLED_StackStressTest) {
527   for (int i = 0; i < 1000000; i++)
528     StackStressFunc();
529 }
530 
531 template<class T>
TestFloatingPoint()532 void TestFloatingPoint() {
533   static volatile T v;
534   static T g[100];
535   break_optimization(&g);
536   T *x = GetPoisoned<T>();
537   T *y = GetPoisoned<T>(1);
538   EXPECT_POISONED(*x);
539   EXPECT_POISONED((long long)*x);
540   EXPECT_POISONED((int)*x);
541   g[0] = *x;
542   g[1] = *x + *y;
543   g[2] = *x - *y;
544   g[3] = *x * *y;
545 }
546 
TEST(MemorySanitizer,FloatingPointTest)547 TEST(MemorySanitizer, FloatingPointTest) {
548   TestFloatingPoint<float>();
549   TestFloatingPoint<double>();
550 }
551 
TEST(MemorySanitizer,DynMem)552 TEST(MemorySanitizer, DynMem) {
553   S4 x = 0;
554   S4 *y = GetPoisoned<S4>();
555   memcpy(y, &x, g_one * sizeof(S4));
556   EXPECT_NOT_POISONED(*y);
557 }
558 
559 static char *DynRetTestStr;
560 
TEST(MemorySanitizer,DynRet)561 TEST(MemorySanitizer, DynRet) {
562   ReturnPoisoned<S8>();
563   EXPECT_NOT_POISONED(atoi("0"));
564 }
565 
TEST(MemorySanitizer,DynRet1)566 TEST(MemorySanitizer, DynRet1) {
567   ReturnPoisoned<S8>();
568 }
569 
570 struct LargeStruct {
571   S4 x[10];
572 };
573 
574 NOINLINE
LargeRetTest()575 LargeStruct LargeRetTest() {
576   LargeStruct res;
577   res.x[0] = *GetPoisoned<S4>();
578   res.x[1] = *GetPoisoned<S4>();
579   res.x[2] = *GetPoisoned<S4>();
580   res.x[3] = *GetPoisoned<S4>();
581   res.x[4] = *GetPoisoned<S4>();
582   res.x[5] = *GetPoisoned<S4>();
583   res.x[6] = *GetPoisoned<S4>();
584   res.x[7] = *GetPoisoned<S4>();
585   res.x[8] = *GetPoisoned<S4>();
586   res.x[9] = *GetPoisoned<S4>();
587   return res;
588 }
589 
TEST(MemorySanitizer,strcmp)590 TEST(MemorySanitizer, strcmp) {
591   char s1[10];
592   char s2[10];
593   strncpy(s1, "foo", 10);
594   s2[0] = 'f';
595   s2[1] = 'n';
596   EXPECT_GT(strcmp(s1, s2), 0);
597   s2[1] = 'o';
598   int res;
599   EXPECT_UMR(res = strcmp(s1, s2));
600   EXPECT_NOT_POISONED(res);
601   EXPECT_EQ(strncmp(s1, s2, 1), 0);
602 }
603 
TEST(MemorySanitizer,LargeRet)604 TEST(MemorySanitizer, LargeRet) {
605   LargeStruct a = LargeRetTest();
606   EXPECT_POISONED(a.x[0]);
607   EXPECT_POISONED(a.x[9]);
608 }
609 
TEST(MemorySanitizer,strerror)610 TEST(MemorySanitizer, strerror) {
611   char *buf = strerror(EINVAL);
612   EXPECT_NOT_POISONED(strlen(buf));
613   buf = strerror(123456);
614   EXPECT_NOT_POISONED(strlen(buf));
615 }
616 
TEST(MemorySanitizer,strerror_r)617 TEST(MemorySanitizer, strerror_r) {
618   errno = 0;
619   char buf[1000];
620   char *res = (char*) (size_t) strerror_r(EINVAL, buf, sizeof(buf));
621   ASSERT_EQ(0, errno);
622   if (!res) res = buf; // POSIX version success.
623   EXPECT_NOT_POISONED(strlen(res));
624 }
625 
TEST(MemorySanitizer,fread)626 TEST(MemorySanitizer, fread) {
627   char *x = new char[32];
628   FILE *f = fopen(FILE_TO_READ, "r");
629   ASSERT_TRUE(f != NULL);
630   fread(x, 1, 32, f);
631   EXPECT_NOT_POISONED(x[0]);
632   EXPECT_NOT_POISONED(x[16]);
633   EXPECT_NOT_POISONED(x[31]);
634   fclose(f);
635   delete[] x;
636 }
637 
TEST(MemorySanitizer,read)638 TEST(MemorySanitizer, read) {
639   char *x = new char[32];
640   int fd = open(FILE_TO_READ, O_RDONLY);
641   ASSERT_GT(fd, 0);
642   int sz = read(fd, x, 32);
643   ASSERT_EQ(sz, 32);
644   EXPECT_NOT_POISONED(x[0]);
645   EXPECT_NOT_POISONED(x[16]);
646   EXPECT_NOT_POISONED(x[31]);
647   close(fd);
648   delete[] x;
649 }
650 
TEST(MemorySanitizer,pread)651 TEST(MemorySanitizer, pread) {
652   char *x = new char[32];
653   int fd = open(FILE_TO_READ, O_RDONLY);
654   ASSERT_GT(fd, 0);
655   int sz = pread(fd, x, 32, 0);
656   ASSERT_EQ(sz, 32);
657   EXPECT_NOT_POISONED(x[0]);
658   EXPECT_NOT_POISONED(x[16]);
659   EXPECT_NOT_POISONED(x[31]);
660   close(fd);
661   delete[] x;
662 }
663 
TEST(MemorySanitizer,readv)664 TEST(MemorySanitizer, readv) {
665   char buf[2011];
666   struct iovec iov[2];
667   iov[0].iov_base = buf + 1;
668   iov[0].iov_len = 5;
669   iov[1].iov_base = buf + 10;
670   iov[1].iov_len = 2000;
671   int fd = open(FILE_TO_READ, O_RDONLY);
672   ASSERT_GT(fd, 0);
673   int sz = readv(fd, iov, 2);
674   ASSERT_GE(sz, 0);
675   ASSERT_LE(sz, 5 + 2000);
676   ASSERT_GT((size_t)sz, iov[0].iov_len);
677   EXPECT_POISONED(buf[0]);
678   EXPECT_NOT_POISONED(buf[1]);
679   EXPECT_NOT_POISONED(buf[5]);
680   EXPECT_POISONED(buf[6]);
681   EXPECT_POISONED(buf[9]);
682   EXPECT_NOT_POISONED(buf[10]);
683   EXPECT_NOT_POISONED(buf[10 + (sz - 1) - 5]);
684   EXPECT_POISONED(buf[11 + (sz - 1) - 5]);
685   close(fd);
686 }
687 
TEST(MemorySanitizer,preadv)688 TEST(MemorySanitizer, preadv) {
689   char buf[2011];
690   struct iovec iov[2];
691   iov[0].iov_base = buf + 1;
692   iov[0].iov_len = 5;
693   iov[1].iov_base = buf + 10;
694   iov[1].iov_len = 2000;
695   int fd = open(FILE_TO_READ, O_RDONLY);
696   ASSERT_GT(fd, 0);
697   int sz = preadv(fd, iov, 2, 3);
698   ASSERT_GE(sz, 0);
699   ASSERT_LE(sz, 5 + 2000);
700   ASSERT_GT((size_t)sz, iov[0].iov_len);
701   EXPECT_POISONED(buf[0]);
702   EXPECT_NOT_POISONED(buf[1]);
703   EXPECT_NOT_POISONED(buf[5]);
704   EXPECT_POISONED(buf[6]);
705   EXPECT_POISONED(buf[9]);
706   EXPECT_NOT_POISONED(buf[10]);
707   EXPECT_NOT_POISONED(buf[10 + (sz - 1) - 5]);
708   EXPECT_POISONED(buf[11 + (sz - 1) - 5]);
709   close(fd);
710 }
711 
712 // FIXME: fails now.
TEST(MemorySanitizer,DISABLED_ioctl)713 TEST(MemorySanitizer, DISABLED_ioctl) {
714   struct winsize ws;
715   EXPECT_EQ(ioctl(2, TIOCGWINSZ, &ws), 0);
716   EXPECT_NOT_POISONED(ws.ws_col);
717 }
718 
TEST(MemorySanitizer,readlink)719 TEST(MemorySanitizer, readlink) {
720   char *x = new char[1000];
721   readlink(SYMLINK_TO_READ, x, 1000);
722   EXPECT_NOT_POISONED(x[0]);
723   delete [] x;
724 }
725 
TEST(MemorySanitizer,readlinkat)726 TEST(MemorySanitizer, readlinkat) {
727   char *x = new char[1000];
728   readlinkat(AT_FDCWD, SYMLINK_TO_READ, x, 1000);
729   EXPECT_NOT_POISONED(x[0]);
730   delete[] x;
731 }
732 
TEST(MemorySanitizer,stat)733 TEST(MemorySanitizer, stat) {
734   struct stat* st = new struct stat;
735   int res = stat(FILE_TO_READ, st);
736   ASSERT_EQ(0, res);
737   EXPECT_NOT_POISONED(st->st_dev);
738   EXPECT_NOT_POISONED(st->st_mode);
739   EXPECT_NOT_POISONED(st->st_size);
740 }
741 
TEST(MemorySanitizer,fstatat)742 TEST(MemorySanitizer, fstatat) {
743   struct stat* st = new struct stat;
744   int dirfd = open(DIR_TO_READ, O_RDONLY);
745   ASSERT_GT(dirfd, 0);
746   int res = fstatat(dirfd, SUBFILE_TO_READ, st, 0);
747   ASSERT_EQ(0, res);
748   EXPECT_NOT_POISONED(st->st_dev);
749   EXPECT_NOT_POISONED(st->st_mode);
750   EXPECT_NOT_POISONED(st->st_size);
751   close(dirfd);
752 }
753 
754 #if !defined(__NetBSD__)
TEST(MemorySanitizer,statfs)755 TEST(MemorySanitizer, statfs) {
756   struct statfs st;
757   int res = statfs("/", &st);
758   ASSERT_EQ(0, res);
759   EXPECT_NOT_POISONED(st.f_type);
760   EXPECT_NOT_POISONED(st.f_bfree);
761   EXPECT_NOT_POISONED(st.f_namelen);
762 }
763 #endif
764 
TEST(MemorySanitizer,statvfs)765 TEST(MemorySanitizer, statvfs) {
766   struct statvfs st;
767   int res = statvfs("/", &st);
768   ASSERT_EQ(0, res);
769   EXPECT_NOT_POISONED(st.f_bsize);
770   EXPECT_NOT_POISONED(st.f_blocks);
771   EXPECT_NOT_POISONED(st.f_bfree);
772   EXPECT_NOT_POISONED(st.f_namemax);
773 }
774 
TEST(MemorySanitizer,fstatvfs)775 TEST(MemorySanitizer, fstatvfs) {
776   struct statvfs st;
777   int fd = open("/", O_RDONLY | O_DIRECTORY);
778   int res = fstatvfs(fd, &st);
779   ASSERT_EQ(0, res);
780   EXPECT_NOT_POISONED(st.f_bsize);
781   EXPECT_NOT_POISONED(st.f_blocks);
782   EXPECT_NOT_POISONED(st.f_bfree);
783   EXPECT_NOT_POISONED(st.f_namemax);
784   close(fd);
785 }
786 
TEST(MemorySanitizer,pipe)787 TEST(MemorySanitizer, pipe) {
788   int* pipefd = new int[2];
789   int res = pipe(pipefd);
790   ASSERT_EQ(0, res);
791   EXPECT_NOT_POISONED(pipefd[0]);
792   EXPECT_NOT_POISONED(pipefd[1]);
793   close(pipefd[0]);
794   close(pipefd[1]);
795 }
796 
TEST(MemorySanitizer,pipe2)797 TEST(MemorySanitizer, pipe2) {
798   int* pipefd = new int[2];
799   int res = pipe2(pipefd, O_NONBLOCK);
800   ASSERT_EQ(0, res);
801   EXPECT_NOT_POISONED(pipefd[0]);
802   EXPECT_NOT_POISONED(pipefd[1]);
803   close(pipefd[0]);
804   close(pipefd[1]);
805 }
806 
TEST(MemorySanitizer,socketpair)807 TEST(MemorySanitizer, socketpair) {
808   int sv[2];
809   int res = socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
810   ASSERT_EQ(0, res);
811   EXPECT_NOT_POISONED(sv[0]);
812   EXPECT_NOT_POISONED(sv[1]);
813   close(sv[0]);
814   close(sv[1]);
815 }
816 
TEST(MemorySanitizer,poll)817 TEST(MemorySanitizer, poll) {
818   int* pipefd = new int[2];
819   int res = pipe(pipefd);
820   ASSERT_EQ(0, res);
821 
822   char data = 42;
823   res = write(pipefd[1], &data, 1);
824   ASSERT_EQ(1, res);
825 
826   pollfd fds[2];
827   fds[0].fd = pipefd[0];
828   fds[0].events = POLLIN;
829   fds[1].fd = pipefd[1];
830   fds[1].events = POLLIN;
831   res = poll(fds, 2, 500);
832   ASSERT_EQ(1, res);
833   EXPECT_NOT_POISONED(fds[0].revents);
834   EXPECT_NOT_POISONED(fds[1].revents);
835 
836   close(pipefd[0]);
837   close(pipefd[1]);
838 }
839 
840 #if !defined (__FreeBSD__) && !defined (__NetBSD__)
TEST(MemorySanitizer,ppoll)841 TEST(MemorySanitizer, ppoll) {
842   int* pipefd = new int[2];
843   int res = pipe(pipefd);
844   ASSERT_EQ(0, res);
845 
846   char data = 42;
847   res = write(pipefd[1], &data, 1);
848   ASSERT_EQ(1, res);
849 
850   pollfd fds[2];
851   fds[0].fd = pipefd[0];
852   fds[0].events = POLLIN;
853   fds[1].fd = pipefd[1];
854   fds[1].events = POLLIN;
855   sigset_t ss;
856   sigemptyset(&ss);
857   res = ppoll(fds, 2, NULL, &ss);
858   ASSERT_EQ(1, res);
859   EXPECT_NOT_POISONED(fds[0].revents);
860   EXPECT_NOT_POISONED(fds[1].revents);
861 
862   close(pipefd[0]);
863   close(pipefd[1]);
864 }
865 #endif
866 
TEST(MemorySanitizer,poll_positive)867 TEST(MemorySanitizer, poll_positive) {
868   int* pipefd = new int[2];
869   int res = pipe(pipefd);
870   ASSERT_EQ(0, res);
871 
872   pollfd fds[2];
873   fds[0].fd = pipefd[0];
874   fds[0].events = POLLIN;
875   // fds[1].fd uninitialized
876   fds[1].events = POLLIN;
877   EXPECT_UMR(poll(fds, 2, 0));
878 
879   close(pipefd[0]);
880   close(pipefd[1]);
881 }
882 
TEST(MemorySanitizer,bind_getsockname)883 TEST(MemorySanitizer, bind_getsockname) {
884   int sock = socket(AF_UNIX, SOCK_STREAM, 0);
885 
886   struct sockaddr_in sai;
887   memset(&sai, 0, sizeof(sai));
888   sai.sin_family = AF_UNIX;
889   int res = bind(sock, (struct sockaddr *)&sai, sizeof(sai));
890 
891   ASSERT_EQ(0, res);
892   char buf[200];
893   socklen_t addrlen;
894   EXPECT_UMR(getsockname(sock, (struct sockaddr *)&buf, &addrlen));
895 
896   addrlen = sizeof(buf);
897   res = getsockname(sock, (struct sockaddr *)&buf, &addrlen);
898   EXPECT_NOT_POISONED(addrlen);
899   EXPECT_NOT_POISONED(buf[0]);
900   EXPECT_NOT_POISONED(buf[addrlen - 1]);
901   EXPECT_POISONED(buf[addrlen]);
902   close(sock);
903 }
904 
905 class SocketAddr {
906  public:
907   virtual ~SocketAddr() = default;
908   virtual struct sockaddr *ptr() = 0;
909   virtual size_t size() const = 0;
910 
911   template <class... Args>
912   static std::unique_ptr<SocketAddr> Create(int family, Args... args);
913 };
914 
915 class SocketAddr4 : public SocketAddr {
916  public:
SocketAddr4()917   SocketAddr4() { EXPECT_POISONED(sai_); }
SocketAddr4(uint16_t port)918   explicit SocketAddr4(uint16_t port) {
919     memset(&sai_, 0, sizeof(sai_));
920     sai_.sin_family = AF_INET;
921     sai_.sin_port = port;
922     sai_.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
923   }
924 
ptr()925   sockaddr *ptr() override { return reinterpret_cast<sockaddr *>(&sai_); }
926 
size() const927   size_t size() const override { return sizeof(sai_); }
928 
929  private:
930   sockaddr_in sai_;
931 };
932 
933 class SocketAddr6 : public SocketAddr {
934  public:
SocketAddr6()935   SocketAddr6() { EXPECT_POISONED(sai_); }
SocketAddr6(uint16_t port)936   explicit SocketAddr6(uint16_t port) {
937     memset(&sai_, 0, sizeof(sai_));
938     sai_.sin6_family = AF_INET6;
939     sai_.sin6_port = port;
940     sai_.sin6_addr = in6addr_loopback;
941   }
942 
ptr()943   sockaddr *ptr() override { return reinterpret_cast<sockaddr *>(&sai_); }
944 
size() const945   size_t size() const override { return sizeof(sai_); }
946 
947  private:
948   sockaddr_in6 sai_;
949 };
950 
951 template <class... Args>
Create(int family,Args...args)952 std::unique_ptr<SocketAddr> SocketAddr::Create(int family, Args... args) {
953   if (family == AF_INET)
954     return std::unique_ptr<SocketAddr>(new SocketAddr4(args...));
955   return std::unique_ptr<SocketAddr>(new SocketAddr6(args...));
956 }
957 
958 class MemorySanitizerIpTest : public ::testing::TestWithParam<int> {
959  public:
SetUp()960   void SetUp() override {
961     ASSERT_TRUE(GetParam() == AF_INET || GetParam() == AF_INET6);
962   }
963 
964   template <class... Args>
CreateSockAddr(Args...args) const965   std::unique_ptr<SocketAddr> CreateSockAddr(Args... args) const {
966     return SocketAddr::Create(GetParam(), args...);
967   }
968 
CreateSocket(int socket_type) const969   int CreateSocket(int socket_type) const {
970     return socket(GetParam(), socket_type, 0);
971   }
972 };
973 
GetAvailableIpSocketFamilies()974 std::vector<int> GetAvailableIpSocketFamilies() {
975   std::vector<int> result;
976 
977   for (int i : {AF_INET, AF_INET6}) {
978     int s = socket(i, SOCK_STREAM, 0);
979     if (s > 0) {
980       auto sai = SocketAddr::Create(i, 0);
981       if (bind(s, sai->ptr(), sai->size()) == 0) result.push_back(i);
982       close(s);
983     }
984   }
985 
986   return result;
987 }
988 
989 INSTANTIATE_TEST_CASE_P(IpTests, MemorySanitizerIpTest,
990                         ::testing::ValuesIn(GetAvailableIpSocketFamilies()));
991 
TEST_P(MemorySanitizerIpTest,accept)992 TEST_P(MemorySanitizerIpTest, accept) {
993   int listen_socket = CreateSocket(SOCK_STREAM);
994   ASSERT_LT(0, listen_socket);
995 
996   auto sai = CreateSockAddr(0);
997   int res = bind(listen_socket, sai->ptr(), sai->size());
998   ASSERT_EQ(0, res);
999 
1000   res = listen(listen_socket, 1);
1001   ASSERT_EQ(0, res);
1002 
1003   socklen_t sz = sai->size();
1004   res = getsockname(listen_socket, sai->ptr(), &sz);
1005   ASSERT_EQ(0, res);
1006   ASSERT_EQ(sai->size(), sz);
1007 
1008   int connect_socket = CreateSocket(SOCK_STREAM);
1009   ASSERT_LT(0, connect_socket);
1010   res = fcntl(connect_socket, F_SETFL, O_NONBLOCK);
1011   ASSERT_EQ(0, res);
1012   res = connect(connect_socket, sai->ptr(), sai->size());
1013   // On FreeBSD this connection completes immediately.
1014   if (res != 0) {
1015     ASSERT_EQ(-1, res);
1016     ASSERT_EQ(EINPROGRESS, errno);
1017   }
1018 
1019   __msan_poison(sai->ptr(), sai->size());
1020   int new_sock = accept(listen_socket, sai->ptr(), &sz);
1021   ASSERT_LT(0, new_sock);
1022   ASSERT_EQ(sai->size(), sz);
1023   EXPECT_NOT_POISONED2(sai->ptr(), sai->size());
1024 
1025   __msan_poison(sai->ptr(), sai->size());
1026   res = getpeername(new_sock, sai->ptr(), &sz);
1027   ASSERT_EQ(0, res);
1028   ASSERT_EQ(sai->size(), sz);
1029   EXPECT_NOT_POISONED2(sai->ptr(), sai->size());
1030 
1031   close(new_sock);
1032   close(connect_socket);
1033   close(listen_socket);
1034 }
1035 
TEST_P(MemorySanitizerIpTest,recvmsg)1036 TEST_P(MemorySanitizerIpTest, recvmsg) {
1037   int server_socket = CreateSocket(SOCK_DGRAM);
1038   ASSERT_LT(0, server_socket);
1039 
1040   auto sai = CreateSockAddr(0);
1041   int res = bind(server_socket, sai->ptr(), sai->size());
1042   ASSERT_EQ(0, res);
1043 
1044   socklen_t sz = sai->size();
1045   res = getsockname(server_socket, sai->ptr(), &sz);
1046   ASSERT_EQ(0, res);
1047   ASSERT_EQ(sai->size(), sz);
1048 
1049   int client_socket = CreateSocket(SOCK_DGRAM);
1050   ASSERT_LT(0, client_socket);
1051 
1052   auto client_sai = CreateSockAddr(0);
1053   res = bind(client_socket, client_sai->ptr(), client_sai->size());
1054   ASSERT_EQ(0, res);
1055 
1056   sz = client_sai->size();
1057   res = getsockname(client_socket, client_sai->ptr(), &sz);
1058   ASSERT_EQ(0, res);
1059   ASSERT_EQ(client_sai->size(), sz);
1060 
1061   const char *s = "message text";
1062   struct iovec iov;
1063   iov.iov_base = (void *)s;
1064   iov.iov_len = strlen(s) + 1;
1065   struct msghdr msg;
1066   memset(&msg, 0, sizeof(msg));
1067   msg.msg_name = sai->ptr();
1068   msg.msg_namelen = sai->size();
1069   msg.msg_iov = &iov;
1070   msg.msg_iovlen = 1;
1071   res = sendmsg(client_socket, &msg, 0);
1072   ASSERT_LT(0, res);
1073 
1074   char buf[1000];
1075   struct iovec recv_iov;
1076   recv_iov.iov_base = (void *)&buf;
1077   recv_iov.iov_len = sizeof(buf);
1078   auto recv_sai = CreateSockAddr();
1079   struct msghdr recv_msg;
1080   memset(&recv_msg, 0, sizeof(recv_msg));
1081   recv_msg.msg_name = recv_sai->ptr();
1082   recv_msg.msg_namelen = recv_sai->size();
1083   recv_msg.msg_iov = &recv_iov;
1084   recv_msg.msg_iovlen = 1;
1085   res = recvmsg(server_socket, &recv_msg, 0);
1086   ASSERT_LT(0, res);
1087 
1088   ASSERT_EQ(recv_sai->size(), recv_msg.msg_namelen);
1089   EXPECT_NOT_POISONED2(recv_sai->ptr(), recv_sai->size());
1090   EXPECT_STREQ(s, buf);
1091 
1092   close(server_socket);
1093   close(client_socket);
1094 }
1095 
1096 #define EXPECT_HOSTENT_NOT_POISONED(he)        \
1097   do {                                         \
1098     EXPECT_NOT_POISONED(*(he));                \
1099     ASSERT_NE((void *)0, (he)->h_name);        \
1100     ASSERT_NE((void *)0, (he)->h_aliases);     \
1101     ASSERT_NE((void *)0, (he)->h_addr_list);   \
1102     EXPECT_NOT_POISONED(strlen((he)->h_name)); \
1103     char **p = (he)->h_aliases;                \
1104     while (*p) {                               \
1105       EXPECT_NOT_POISONED(strlen(*p));         \
1106       ++p;                                     \
1107     }                                          \
1108     char **q = (he)->h_addr_list;              \
1109     while (*q) {                               \
1110       EXPECT_NOT_POISONED(*q[0]);              \
1111       ++q;                                     \
1112     }                                          \
1113     EXPECT_NOT_POISONED(*q);                   \
1114   } while (0)
1115 
TEST(MemorySanitizer,gethostent)1116 TEST(MemorySanitizer, gethostent) {
1117   struct hostent *he = gethostent();
1118   ASSERT_NE((void *)NULL, he);
1119   EXPECT_HOSTENT_NOT_POISONED(he);
1120 }
1121 
1122 #ifndef MSAN_TEST_DISABLE_GETHOSTBYNAME
1123 
TEST(MemorySanitizer,gethostbyname)1124 TEST(MemorySanitizer, gethostbyname) {
1125   struct hostent *he = gethostbyname("localhost");
1126   ASSERT_NE((void *)NULL, he);
1127   EXPECT_HOSTENT_NOT_POISONED(he);
1128 }
1129 
1130 #endif  // MSAN_TEST_DISABLE_GETHOSTBYNAME
1131 
TEST(MemorySanitizer,getaddrinfo)1132 TEST(MemorySanitizer, getaddrinfo) {
1133   struct addrinfo *ai;
1134   struct addrinfo hints;
1135   memset(&hints, 0, sizeof(hints));
1136   hints.ai_family = AF_INET;
1137   int res = getaddrinfo("localhost", NULL, &hints, &ai);
1138   ASSERT_EQ(0, res);
1139   EXPECT_NOT_POISONED(*ai);
1140   ASSERT_EQ(sizeof(sockaddr_in), ai->ai_addrlen);
1141   EXPECT_NOT_POISONED(*(sockaddr_in *)ai->ai_addr);
1142 }
1143 
TEST(MemorySanitizer,getnameinfo)1144 TEST(MemorySanitizer, getnameinfo) {
1145   struct sockaddr_in sai;
1146   memset(&sai, 0, sizeof(sai));
1147   sai.sin_family = AF_INET;
1148   sai.sin_port = 80;
1149   sai.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
1150   char host[500];
1151   char serv[500];
1152   int res = getnameinfo((struct sockaddr *)&sai, sizeof(sai), host,
1153                         sizeof(host), serv, sizeof(serv), 0);
1154   ASSERT_EQ(0, res);
1155   EXPECT_NOT_POISONED(host[0]);
1156   EXPECT_POISONED(host[sizeof(host) - 1]);
1157 
1158   ASSERT_NE(0U, strlen(host));
1159   EXPECT_NOT_POISONED(serv[0]);
1160   EXPECT_POISONED(serv[sizeof(serv) - 1]);
1161   ASSERT_NE(0U, strlen(serv));
1162 }
1163 
TEST(MemorySanitizer,gethostbyname2)1164 TEST(MemorySanitizer, gethostbyname2) {
1165   struct hostent *he = gethostbyname2("localhost", AF_INET);
1166   ASSERT_NE((void *)NULL, he);
1167   EXPECT_HOSTENT_NOT_POISONED(he);
1168 }
1169 
TEST(MemorySanitizer,gethostbyaddr)1170 TEST(MemorySanitizer, gethostbyaddr) {
1171   in_addr_t addr = inet_addr("127.0.0.1");
1172   EXPECT_NOT_POISONED(addr);
1173   struct hostent *he = gethostbyaddr(&addr, sizeof(addr), AF_INET);
1174   ASSERT_NE((void *)NULL, he);
1175   EXPECT_HOSTENT_NOT_POISONED(he);
1176 }
1177 
1178 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostent_r)1179 TEST(MemorySanitizer, gethostent_r) {
1180   char buf[2000];
1181   struct hostent he;
1182   struct hostent *result;
1183   int err;
1184   int res = gethostent_r(&he, buf, sizeof(buf), &result, &err);
1185   ASSERT_EQ(0, res);
1186   EXPECT_NOT_POISONED(result);
1187   ASSERT_NE((void *)NULL, result);
1188   EXPECT_HOSTENT_NOT_POISONED(result);
1189   EXPECT_NOT_POISONED(err);
1190 }
1191 #endif
1192 
1193 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostbyname_r)1194 TEST(MemorySanitizer, gethostbyname_r) {
1195   char buf[2000];
1196   struct hostent he;
1197   struct hostent *result;
1198   int err;
1199   int res = gethostbyname_r("localhost", &he, buf, sizeof(buf), &result, &err);
1200   ASSERT_EQ(0, res);
1201   EXPECT_NOT_POISONED(result);
1202   ASSERT_NE((void *)NULL, result);
1203   EXPECT_HOSTENT_NOT_POISONED(result);
1204   EXPECT_NOT_POISONED(err);
1205 }
1206 #endif
1207 
1208 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostbyname_r_bad_host_name)1209 TEST(MemorySanitizer, gethostbyname_r_bad_host_name) {
1210   char buf[2000];
1211   struct hostent he;
1212   struct hostent *result;
1213   int err;
1214   int res = gethostbyname_r("bad-host-name", &he, buf, sizeof(buf), &result, &err);
1215   ASSERT_EQ((struct hostent *)0, result);
1216   EXPECT_NOT_POISONED(err);
1217 }
1218 #endif
1219 
1220 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostbyname_r_erange)1221 TEST(MemorySanitizer, gethostbyname_r_erange) {
1222   char buf[5];
1223   struct hostent he;
1224   struct hostent *result;
1225   int err;
1226   gethostbyname_r("localhost", &he, buf, sizeof(buf), &result, &err);
1227   ASSERT_EQ(ERANGE, errno);
1228   EXPECT_NOT_POISONED(err);
1229 }
1230 #endif
1231 
1232 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostbyname2_r)1233 TEST(MemorySanitizer, gethostbyname2_r) {
1234   char buf[2000];
1235   struct hostent he;
1236   struct hostent *result;
1237   int err;
1238   int res = gethostbyname2_r("localhost", AF_INET, &he, buf, sizeof(buf),
1239                              &result, &err);
1240   ASSERT_EQ(0, res);
1241   EXPECT_NOT_POISONED(result);
1242   ASSERT_NE((void *)NULL, result);
1243   EXPECT_HOSTENT_NOT_POISONED(result);
1244   EXPECT_NOT_POISONED(err);
1245 }
1246 #endif
1247 
1248 #if !defined(__NetBSD__)
TEST(MemorySanitizer,gethostbyaddr_r)1249 TEST(MemorySanitizer, gethostbyaddr_r) {
1250   char buf[2000];
1251   struct hostent he;
1252   struct hostent *result;
1253   int err;
1254   in_addr_t addr = inet_addr("127.0.0.1");
1255   EXPECT_NOT_POISONED(addr);
1256   int res = gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &he, buf, sizeof(buf),
1257                             &result, &err);
1258   ASSERT_EQ(0, res);
1259   EXPECT_NOT_POISONED(result);
1260   ASSERT_NE((void *)NULL, result);
1261   EXPECT_HOSTENT_NOT_POISONED(result);
1262   EXPECT_NOT_POISONED(err);
1263 }
1264 #endif
1265 
TEST(MemorySanitizer,getsockopt)1266 TEST(MemorySanitizer, getsockopt) {
1267   int sock = socket(AF_UNIX, SOCK_STREAM, 0);
1268   struct linger l[2];
1269   socklen_t sz = sizeof(l[0]);
1270   int res = getsockopt(sock, SOL_SOCKET, SO_LINGER, &l[0], &sz);
1271   ASSERT_EQ(0, res);
1272   ASSERT_EQ(sizeof(l[0]), sz);
1273   EXPECT_NOT_POISONED(l[0]);
1274   EXPECT_POISONED(*(char *)(l + 1));
1275 }
1276 
TEST(MemorySanitizer,getcwd)1277 TEST(MemorySanitizer, getcwd) {
1278   char path[PATH_MAX + 1];
1279   char* res = getcwd(path, sizeof(path));
1280   ASSERT_TRUE(res != NULL);
1281   EXPECT_NOT_POISONED(path[0]);
1282 }
1283 
TEST(MemorySanitizer,getcwd_gnu)1284 TEST(MemorySanitizer, getcwd_gnu) {
1285   char* res = getcwd(NULL, 0);
1286   ASSERT_TRUE(res != NULL);
1287   EXPECT_NOT_POISONED(res[0]);
1288   free(res);
1289 }
1290 
1291 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,get_current_dir_name)1292 TEST(MemorySanitizer, get_current_dir_name) {
1293   char* res = get_current_dir_name();
1294   ASSERT_TRUE(res != NULL);
1295   EXPECT_NOT_POISONED(res[0]);
1296   free(res);
1297 }
1298 #endif
1299 
TEST(MemorySanitizer,shmctl)1300 TEST(MemorySanitizer, shmctl) {
1301   int id = shmget(IPC_PRIVATE, 4096, 0644 | IPC_CREAT);
1302   ASSERT_GT(id, -1);
1303 
1304   struct shmid_ds ds;
1305   int res = shmctl(id, IPC_STAT, &ds);
1306   ASSERT_GT(res, -1);
1307   EXPECT_NOT_POISONED(ds);
1308 
1309 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
1310   struct shminfo si;
1311   res = shmctl(id, IPC_INFO, (struct shmid_ds *)&si);
1312   ASSERT_GT(res, -1);
1313   EXPECT_NOT_POISONED(si);
1314 
1315   struct shm_info s_i;
1316   res = shmctl(id, SHM_INFO, (struct shmid_ds *)&s_i);
1317   ASSERT_GT(res, -1);
1318   EXPECT_NOT_POISONED(s_i);
1319 #endif
1320 
1321   res = shmctl(id, IPC_RMID, 0);
1322   ASSERT_GT(res, -1);
1323 }
1324 
TEST(MemorySanitizer,shmat)1325 TEST(MemorySanitizer, shmat) {
1326   const int kShmSize = 4096;
1327   void *mapping_start = mmap(NULL, kShmSize + SHMLBA, PROT_READ | PROT_WRITE,
1328                              MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
1329   ASSERT_NE(MAP_FAILED, mapping_start);
1330 
1331   void *p = (void *)(((unsigned long)mapping_start + SHMLBA - 1) / SHMLBA * SHMLBA);
1332   // p is now SHMLBA-aligned;
1333 
1334   ((char *)p)[10] = *GetPoisoned<U1>();
1335   ((char *)p)[kShmSize - 1] = *GetPoisoned<U1>();
1336 
1337   int res = munmap(mapping_start, kShmSize + SHMLBA);
1338   ASSERT_EQ(0, res);
1339 
1340   int id = shmget(IPC_PRIVATE, kShmSize, 0644 | IPC_CREAT);
1341   ASSERT_GT(id, -1);
1342 
1343   void *q = shmat(id, p, 0);
1344   ASSERT_EQ(p, q);
1345 
1346   EXPECT_NOT_POISONED(((char *)q)[0]);
1347   EXPECT_NOT_POISONED(((char *)q)[10]);
1348   EXPECT_NOT_POISONED(((char *)q)[kShmSize - 1]);
1349 
1350   res = shmdt(q);
1351   ASSERT_EQ(0, res);
1352 
1353   res = shmctl(id, IPC_RMID, 0);
1354   ASSERT_GT(res, -1);
1355 }
1356 
1357 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,random_r)1358 TEST(MemorySanitizer, random_r) {
1359   int32_t x;
1360   char z[64];
1361   memset(z, 0, sizeof(z));
1362 
1363   struct random_data buf;
1364   memset(&buf, 0, sizeof(buf));
1365 
1366   int res = initstate_r(0, z, sizeof(z), &buf);
1367   ASSERT_EQ(0, res);
1368 
1369   res = random_r(&buf, &x);
1370   ASSERT_EQ(0, res);
1371   EXPECT_NOT_POISONED(x);
1372 }
1373 #endif
1374 
TEST(MemorySanitizer,confstr)1375 TEST(MemorySanitizer, confstr) {
1376   char buf[3];
1377   size_t res = confstr(_CS_PATH, buf, sizeof(buf));
1378   ASSERT_GT(res, sizeof(buf));
1379   EXPECT_NOT_POISONED(buf[0]);
1380   EXPECT_NOT_POISONED(buf[sizeof(buf) - 1]);
1381 
1382   char buf2[1000];
1383   res = confstr(_CS_PATH, buf2, sizeof(buf2));
1384   ASSERT_LT(res, sizeof(buf2));
1385   EXPECT_NOT_POISONED(buf2[0]);
1386   EXPECT_NOT_POISONED(buf2[res - 1]);
1387   EXPECT_POISONED(buf2[res]);
1388   ASSERT_EQ(res, strlen(buf2) + 1);
1389 }
1390 
TEST(MemorySanitizer,opendir)1391 TEST(MemorySanitizer, opendir) {
1392   DIR *dir = opendir(".");
1393   closedir(dir);
1394 
1395   char name[10] = ".";
1396   __msan_poison(name, sizeof(name));
1397   EXPECT_UMR(dir = opendir(name));
1398   closedir(dir);
1399 }
1400 
TEST(MemorySanitizer,readdir)1401 TEST(MemorySanitizer, readdir) {
1402   DIR *dir = opendir(".");
1403   struct dirent *d = readdir(dir);
1404   ASSERT_TRUE(d != NULL);
1405   EXPECT_NOT_POISONED(d->d_name[0]);
1406   closedir(dir);
1407 }
1408 
TEST(MemorySanitizer,readdir_r)1409 TEST(MemorySanitizer, readdir_r) {
1410   DIR *dir = opendir(".");
1411   struct dirent d;
1412   struct dirent *pd;
1413   int res = readdir_r(dir, &d, &pd);
1414   ASSERT_EQ(0, res);
1415   EXPECT_NOT_POISONED(pd);
1416   EXPECT_NOT_POISONED(d.d_name[0]);
1417   closedir(dir);
1418 }
1419 
TEST(MemorySanitizer,realpath)1420 TEST(MemorySanitizer, realpath) {
1421   const char* relpath = ".";
1422   char path[PATH_MAX + 1];
1423   char* res = realpath(relpath, path);
1424   ASSERT_TRUE(res != NULL);
1425   EXPECT_NOT_POISONED(path[0]);
1426 }
1427 
TEST(MemorySanitizer,realpath_null)1428 TEST(MemorySanitizer, realpath_null) {
1429   const char* relpath = ".";
1430   char* res = realpath(relpath, NULL);
1431   printf("%d, %s\n", errno, strerror(errno));
1432   ASSERT_TRUE(res != NULL);
1433   EXPECT_NOT_POISONED(res[0]);
1434   free(res);
1435 }
1436 
1437 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,canonicalize_file_name)1438 TEST(MemorySanitizer, canonicalize_file_name) {
1439   const char* relpath = ".";
1440   char* res = canonicalize_file_name(relpath);
1441   ASSERT_TRUE(res != NULL);
1442   EXPECT_NOT_POISONED(res[0]);
1443   free(res);
1444 }
1445 #endif
1446 
1447 extern char **environ;
1448 
TEST(MemorySanitizer,setenv)1449 TEST(MemorySanitizer, setenv) {
1450   setenv("AAA", "BBB", 1);
1451   for (char **envp = environ; *envp; ++envp) {
1452     EXPECT_NOT_POISONED(*envp);
1453     EXPECT_NOT_POISONED(*envp[0]);
1454   }
1455 }
1456 
TEST(MemorySanitizer,putenv)1457 TEST(MemorySanitizer, putenv) {
1458   char s[] = "AAA=BBB";
1459   putenv(s);
1460   for (char **envp = environ; *envp; ++envp) {
1461     EXPECT_NOT_POISONED(*envp);
1462     EXPECT_NOT_POISONED(*envp[0]);
1463   }
1464 }
1465 
TEST(MemorySanitizer,memcpy)1466 TEST(MemorySanitizer, memcpy) {
1467   char* x = new char[2];
1468   char* y = new char[2];
1469   x[0] = 1;
1470   x[1] = *GetPoisoned<char>();
1471   memcpy(y, x, 2);
1472   EXPECT_NOT_POISONED(y[0]);
1473   EXPECT_POISONED(y[1]);
1474 }
1475 
TestUnalignedMemcpy(unsigned left,unsigned right,bool src_is_aligned,bool src_is_poisoned,bool dst_is_poisoned)1476 void TestUnalignedMemcpy(unsigned left, unsigned right, bool src_is_aligned,
1477                          bool src_is_poisoned, bool dst_is_poisoned) {
1478   fprintf(stderr, "%s(%d, %d, %d, %d, %d)\n", __func__, left, right,
1479           src_is_aligned, src_is_poisoned, dst_is_poisoned);
1480 
1481   const unsigned sz = 20;
1482   U4 dst_origin, src_origin;
1483   char *dst = (char *)malloc(sz);
1484   if (dst_is_poisoned)
1485     dst_origin = __msan_get_origin(dst);
1486   else
1487     memset(dst, 0, sz);
1488 
1489   char *src = (char *)malloc(sz);
1490   if (src_is_poisoned)
1491     src_origin = __msan_get_origin(src);
1492   else
1493     memset(src, 0, sz);
1494 
1495   memcpy(dst + left, src_is_aligned ? src + left : src, sz - left - right);
1496 
1497   for (unsigned i = 0; i < (left & (~3U)); ++i)
1498     if (dst_is_poisoned)
1499       EXPECT_POISONED_O(dst[i], dst_origin);
1500     else
1501       EXPECT_NOT_POISONED(dst[i]);
1502 
1503   for (unsigned i = 0; i < (right & (~3U)); ++i)
1504     if (dst_is_poisoned)
1505       EXPECT_POISONED_O(dst[sz - i - 1], dst_origin);
1506     else
1507       EXPECT_NOT_POISONED(dst[sz - i - 1]);
1508 
1509   for (unsigned i = left; i < sz - right; ++i)
1510     if (src_is_poisoned)
1511       EXPECT_POISONED_O(dst[i], src_origin);
1512     else
1513       EXPECT_NOT_POISONED(dst[i]);
1514 
1515   free(dst);
1516   free(src);
1517 }
1518 
TEST(MemorySanitizer,memcpy_unaligned)1519 TEST(MemorySanitizer, memcpy_unaligned) {
1520   for (int i = 0; i < 10; ++i)
1521     for (int j = 0; j < 10; ++j)
1522       for (int aligned = 0; aligned < 2; ++aligned)
1523         for (int srcp = 0; srcp < 2; ++srcp)
1524           for (int dstp = 0; dstp < 2; ++dstp)
1525             TestUnalignedMemcpy(i, j, aligned, srcp, dstp);
1526 }
1527 
TEST(MemorySanitizer,memmove)1528 TEST(MemorySanitizer, memmove) {
1529   char* x = new char[2];
1530   char* y = new char[2];
1531   x[0] = 1;
1532   x[1] = *GetPoisoned<char>();
1533   memmove(y, x, 2);
1534   EXPECT_NOT_POISONED(y[0]);
1535   EXPECT_POISONED(y[1]);
1536 }
1537 
TEST(MemorySanitizer,memccpy_nomatch)1538 TEST(MemorySanitizer, memccpy_nomatch) {
1539   char* x = new char[5];
1540   char* y = new char[5];
1541   strcpy(x, "abc");
1542   memccpy(y, x, 'd', 4);
1543   EXPECT_NOT_POISONED(y[0]);
1544   EXPECT_NOT_POISONED(y[1]);
1545   EXPECT_NOT_POISONED(y[2]);
1546   EXPECT_NOT_POISONED(y[3]);
1547   EXPECT_POISONED(y[4]);
1548   delete[] x;
1549   delete[] y;
1550 }
1551 
TEST(MemorySanitizer,memccpy_match)1552 TEST(MemorySanitizer, memccpy_match) {
1553   char* x = new char[5];
1554   char* y = new char[5];
1555   strcpy(x, "abc");
1556   memccpy(y, x, 'b', 4);
1557   EXPECT_NOT_POISONED(y[0]);
1558   EXPECT_NOT_POISONED(y[1]);
1559   EXPECT_POISONED(y[2]);
1560   EXPECT_POISONED(y[3]);
1561   EXPECT_POISONED(y[4]);
1562   delete[] x;
1563   delete[] y;
1564 }
1565 
TEST(MemorySanitizer,memccpy_nomatch_positive)1566 TEST(MemorySanitizer, memccpy_nomatch_positive) {
1567   char* x = new char[5];
1568   char* y = new char[5];
1569   strcpy(x, "abc");
1570   EXPECT_UMR(memccpy(y, x, 'd', 5));
1571   delete[] x;
1572   delete[] y;
1573 }
1574 
TEST(MemorySanitizer,memccpy_match_positive)1575 TEST(MemorySanitizer, memccpy_match_positive) {
1576   char* x = new char[5];
1577   char* y = new char[5];
1578   x[0] = 'a';
1579   x[2] = 'b';
1580   EXPECT_UMR(memccpy(y, x, 'b', 5));
1581   delete[] x;
1582   delete[] y;
1583 }
1584 
TEST(MemorySanitizer,bcopy)1585 TEST(MemorySanitizer, bcopy) {
1586   char* x = new char[2];
1587   char* y = new char[2];
1588   x[0] = 1;
1589   x[1] = *GetPoisoned<char>();
1590   bcopy(x, y, 2);
1591   EXPECT_NOT_POISONED(y[0]);
1592   EXPECT_POISONED(y[1]);
1593 }
1594 
TEST(MemorySanitizer,strdup)1595 TEST(MemorySanitizer, strdup) {
1596   char buf[4] = "abc";
1597   __msan_poison(buf + 2, sizeof(*buf));
1598   char *x = strdup(buf);
1599   EXPECT_NOT_POISONED(x[0]);
1600   EXPECT_NOT_POISONED(x[1]);
1601   EXPECT_POISONED(x[2]);
1602   EXPECT_NOT_POISONED(x[3]);
1603   free(x);
1604 }
1605 
TEST(MemorySanitizer,strndup)1606 TEST(MemorySanitizer, strndup) {
1607   char buf[4] = "abc";
1608   __msan_poison(buf + 2, sizeof(*buf));
1609   char *x;
1610   EXPECT_UMR(x = strndup(buf, 3));
1611   EXPECT_NOT_POISONED(x[0]);
1612   EXPECT_NOT_POISONED(x[1]);
1613   EXPECT_POISONED(x[2]);
1614   EXPECT_NOT_POISONED(x[3]);
1615   free(x);
1616   // Check handling of non 0 terminated strings.
1617   buf[3] = 'z';
1618   __msan_poison(buf + 3, sizeof(*buf));
1619   EXPECT_UMR(x = strndup(buf + 3, 1));
1620   EXPECT_POISONED(x[0]);
1621   EXPECT_NOT_POISONED(x[1]);
1622   free(x);
1623 }
1624 
TEST(MemorySanitizer,strndup_short)1625 TEST(MemorySanitizer, strndup_short) {
1626   char buf[4] = "abc";
1627   __msan_poison(buf + 1, sizeof(*buf));
1628   __msan_poison(buf + 2, sizeof(*buf));
1629   char *x;
1630   EXPECT_UMR(x = strndup(buf, 2));
1631   EXPECT_NOT_POISONED(x[0]);
1632   EXPECT_POISONED(x[1]);
1633   EXPECT_NOT_POISONED(x[2]);
1634   free(x);
1635 }
1636 
1637 
1638 template<class T, int size>
TestOverlapMemmove()1639 void TestOverlapMemmove() {
1640   T *x = new T[size];
1641   ASSERT_GE(size, 3);
1642   x[2] = 0;
1643   memmove(x, x + 1, (size - 1) * sizeof(T));
1644   EXPECT_NOT_POISONED(x[1]);
1645   EXPECT_POISONED(x[0]);
1646   EXPECT_POISONED(x[2]);
1647   delete [] x;
1648 }
1649 
TEST(MemorySanitizer,overlap_memmove)1650 TEST(MemorySanitizer, overlap_memmove) {
1651   TestOverlapMemmove<U1, 10>();
1652   TestOverlapMemmove<U1, 1000>();
1653   TestOverlapMemmove<U8, 4>();
1654   TestOverlapMemmove<U8, 1000>();
1655 }
1656 
TEST(MemorySanitizer,strcpy)1657 TEST(MemorySanitizer, strcpy) {
1658   char* x = new char[3];
1659   char* y = new char[3];
1660   x[0] = 'a';
1661   x[1] = *GetPoisoned<char>(1, 1);
1662   x[2] = 0;
1663   strcpy(y, x);
1664   EXPECT_NOT_POISONED(y[0]);
1665   EXPECT_POISONED(y[1]);
1666   EXPECT_NOT_POISONED(y[2]);
1667 }
1668 
TEST(MemorySanitizer,strncpy)1669 TEST(MemorySanitizer, strncpy) {
1670   char* x = new char[3];
1671   char* y = new char[5];
1672   x[0] = 'a';
1673   x[1] = *GetPoisoned<char>(1, 1);
1674   x[2] = '\0';
1675   strncpy(y, x, 4);
1676   EXPECT_NOT_POISONED(y[0]);
1677   EXPECT_POISONED(y[1]);
1678   EXPECT_NOT_POISONED(y[2]);
1679   EXPECT_NOT_POISONED(y[3]);
1680   EXPECT_POISONED(y[4]);
1681 }
1682 
TEST(MemorySanitizer,stpcpy)1683 TEST(MemorySanitizer, stpcpy) {
1684   char* x = new char[3];
1685   char* y = new char[3];
1686   x[0] = 'a';
1687   x[1] = *GetPoisoned<char>(1, 1);
1688   x[2] = 0;
1689   char *res = stpcpy(y, x);
1690   ASSERT_EQ(res, y + 2);
1691   EXPECT_NOT_POISONED(y[0]);
1692   EXPECT_POISONED(y[1]);
1693   EXPECT_NOT_POISONED(y[2]);
1694 }
1695 
TEST(MemorySanitizer,strcat)1696 TEST(MemorySanitizer, strcat) {
1697   char a[10];
1698   char b[] = "def";
1699   strcpy(a, "abc");
1700   __msan_poison(b + 1, 1);
1701   strcat(a, b);
1702   EXPECT_NOT_POISONED(a[3]);
1703   EXPECT_POISONED(a[4]);
1704   EXPECT_NOT_POISONED(a[5]);
1705   EXPECT_NOT_POISONED(a[6]);
1706   EXPECT_POISONED(a[7]);
1707 }
1708 
TEST(MemorySanitizer,strncat)1709 TEST(MemorySanitizer, strncat) {
1710   char a[10];
1711   char b[] = "def";
1712   strcpy(a, "abc");
1713   __msan_poison(b + 1, 1);
1714   strncat(a, b, 5);
1715   EXPECT_NOT_POISONED(a[3]);
1716   EXPECT_POISONED(a[4]);
1717   EXPECT_NOT_POISONED(a[5]);
1718   EXPECT_NOT_POISONED(a[6]);
1719   EXPECT_POISONED(a[7]);
1720 }
1721 
TEST(MemorySanitizer,strncat_overflow)1722 TEST(MemorySanitizer, strncat_overflow) {
1723   char a[10];
1724   char b[] = "def";
1725   strcpy(a, "abc");
1726   __msan_poison(b + 1, 1);
1727   strncat(a, b, 2);
1728   EXPECT_NOT_POISONED(a[3]);
1729   EXPECT_POISONED(a[4]);
1730   EXPECT_NOT_POISONED(a[5]);
1731   EXPECT_POISONED(a[6]);
1732   EXPECT_POISONED(a[7]);
1733 }
1734 
TEST(MemorySanitizer,wcscat)1735 TEST(MemorySanitizer, wcscat) {
1736   wchar_t a[10];
1737   wchar_t b[] = L"def";
1738   wcscpy(a, L"abc");
1739 
1740   wcscat(a, b);
1741   EXPECT_EQ(6U, wcslen(a));
1742   EXPECT_POISONED(a[7]);
1743 
1744   a[3] = 0;
1745   __msan_poison(b + 1, sizeof(wchar_t));
1746   EXPECT_UMR(wcscat(a, b));
1747 
1748   __msan_unpoison(b + 1, sizeof(wchar_t));
1749   __msan_poison(a + 2, sizeof(wchar_t));
1750   EXPECT_UMR(wcscat(a, b));
1751 }
1752 
TEST(MemorySanitizer,wcsncat)1753 TEST(MemorySanitizer, wcsncat) {
1754   wchar_t a[10];
1755   wchar_t b[] = L"def";
1756   wcscpy(a, L"abc");
1757 
1758   wcsncat(a, b, 5);
1759   EXPECT_EQ(6U, wcslen(a));
1760   EXPECT_POISONED(a[7]);
1761 
1762   a[3] = 0;
1763   __msan_poison(a + 4, sizeof(wchar_t) * 6);
1764   wcsncat(a, b, 2);
1765   EXPECT_EQ(5U, wcslen(a));
1766   EXPECT_POISONED(a[6]);
1767 
1768   a[3] = 0;
1769   __msan_poison(b + 1, sizeof(wchar_t));
1770   EXPECT_UMR(wcsncat(a, b, 2));
1771 
1772   __msan_unpoison(b + 1, sizeof(wchar_t));
1773   __msan_poison(a + 2, sizeof(wchar_t));
1774   EXPECT_UMR(wcsncat(a, b, 2));
1775 }
1776 
1777 #define TEST_STRTO_INT(func_name, char_type, str_prefix) \
1778   TEST(MemorySanitizer, func_name) {                     \
1779     char_type *e;                                        \
1780     EXPECT_EQ(1U, func_name(str_prefix##"1", &e, 10));   \
1781     EXPECT_NOT_POISONED((S8)e);                          \
1782   }
1783 
1784 #define TEST_STRTO_FLOAT(func_name, char_type, str_prefix) \
1785   TEST(MemorySanitizer, func_name) {                       \
1786     char_type *e;                                          \
1787     EXPECT_NE(0, func_name(str_prefix##"1.5", &e));        \
1788     EXPECT_NOT_POISONED((S8)e);                            \
1789   }
1790 
1791 #define TEST_STRTO_FLOAT_LOC(func_name, char_type, str_prefix)   \
1792   TEST(MemorySanitizer, func_name) {                             \
1793     locale_t loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); \
1794     char_type *e;                                                \
1795     EXPECT_NE(0, func_name(str_prefix##"1.5", &e, loc));         \
1796     EXPECT_NOT_POISONED((S8)e);                                  \
1797     freelocale(loc);                                             \
1798   }
1799 
1800 #define TEST_STRTO_INT_LOC(func_name, char_type, str_prefix)     \
1801   TEST(MemorySanitizer, func_name) {                             \
1802     locale_t loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0); \
1803     char_type *e;                                                \
1804     ASSERT_EQ(1U, func_name(str_prefix##"1", &e, 10, loc));      \
1805     EXPECT_NOT_POISONED((S8)e);                                  \
1806     freelocale(loc);                                             \
1807   }
1808 
1809 TEST_STRTO_INT(strtol, char, )
1810 TEST_STRTO_INT(strtoll, char, )
1811 TEST_STRTO_INT(strtoul, char, )
1812 TEST_STRTO_INT(strtoull, char, )
1813 TEST_STRTO_INT(strtouq, char, )
1814 
1815 TEST_STRTO_FLOAT(strtof, char, )
1816 TEST_STRTO_FLOAT(strtod, char, )
1817 TEST_STRTO_FLOAT(strtold, char, )
1818 
1819 TEST_STRTO_FLOAT_LOC(strtof_l, char, )
1820 TEST_STRTO_FLOAT_LOC(strtod_l, char, )
1821 TEST_STRTO_FLOAT_LOC(strtold_l, char, )
1822 
1823 TEST_STRTO_INT_LOC(strtol_l, char, )
1824 TEST_STRTO_INT_LOC(strtoll_l, char, )
1825 TEST_STRTO_INT_LOC(strtoul_l, char, )
1826 TEST_STRTO_INT_LOC(strtoull_l, char, )
1827 
TEST_STRTO_INT(wcstol,wchar_t,L)1828 TEST_STRTO_INT(wcstol, wchar_t, L)
1829 TEST_STRTO_INT(wcstoll, wchar_t, L)
1830 TEST_STRTO_INT(wcstoul, wchar_t, L)
1831 TEST_STRTO_INT(wcstoull, wchar_t, L)
1832 
1833 TEST_STRTO_FLOAT(wcstof, wchar_t, L)
1834 TEST_STRTO_FLOAT(wcstod, wchar_t, L)
1835 TEST_STRTO_FLOAT(wcstold, wchar_t, L)
1836 
1837 TEST_STRTO_FLOAT_LOC(wcstof_l, wchar_t, L)
1838 TEST_STRTO_FLOAT_LOC(wcstod_l, wchar_t, L)
1839 TEST_STRTO_FLOAT_LOC(wcstold_l, wchar_t, L)
1840 
1841 TEST_STRTO_INT_LOC(wcstol_l, wchar_t, L)
1842 TEST_STRTO_INT_LOC(wcstoll_l, wchar_t, L)
1843 TEST_STRTO_INT_LOC(wcstoul_l, wchar_t, L)
1844 TEST_STRTO_INT_LOC(wcstoull_l, wchar_t, L)
1845 
1846 
1847 TEST(MemorySanitizer, strtoimax) {
1848   char *e;
1849   ASSERT_EQ(1, strtoimax("1", &e, 10));
1850   EXPECT_NOT_POISONED((S8) e);
1851 }
1852 
TEST(MemorySanitizer,strtoumax)1853 TEST(MemorySanitizer, strtoumax) {
1854   char *e;
1855   ASSERT_EQ(1U, strtoumax("1", &e, 10));
1856   EXPECT_NOT_POISONED((S8) e);
1857 }
1858 
1859 #ifdef __GLIBC__
1860 extern "C" float __strtof_l(const char *nptr, char **endptr, locale_t loc);
1861 TEST_STRTO_FLOAT_LOC(__strtof_l, char, )
1862 extern "C" double __strtod_l(const char *nptr, char **endptr, locale_t loc);
1863 TEST_STRTO_FLOAT_LOC(__strtod_l, char, )
1864 extern "C" long double __strtold_l(const char *nptr, char **endptr,
1865                                    locale_t loc);
1866 TEST_STRTO_FLOAT_LOC(__strtold_l, char, )
1867 
1868 extern "C" float __wcstof_l(const wchar_t *nptr, wchar_t **endptr, locale_t loc);
1869 TEST_STRTO_FLOAT_LOC(__wcstof_l, wchar_t, L)
1870 extern "C" double __wcstod_l(const wchar_t *nptr, wchar_t **endptr, locale_t loc);
1871 TEST_STRTO_FLOAT_LOC(__wcstod_l, wchar_t, L)
1872 extern "C" long double __wcstold_l(const wchar_t *nptr, wchar_t **endptr,
1873                                    locale_t loc);
TEST_STRTO_FLOAT_LOC(__wcstold_l,wchar_t,L)1874 TEST_STRTO_FLOAT_LOC(__wcstold_l, wchar_t, L)
1875 #endif  // __GLIBC__
1876 
1877 TEST(MemorySanitizer, modf) {
1878   double x, y;
1879   x = modf(2.1, &y);
1880   EXPECT_NOT_POISONED(y);
1881 }
1882 
TEST(MemorySanitizer,modff)1883 TEST(MemorySanitizer, modff) {
1884   float x, y;
1885   x = modff(2.1, &y);
1886   EXPECT_NOT_POISONED(y);
1887 }
1888 
TEST(MemorySanitizer,modfl)1889 TEST(MemorySanitizer, modfl) {
1890   long double x, y;
1891   x = modfl(2.1, &y);
1892   EXPECT_NOT_POISONED(y);
1893 }
1894 
1895 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,sincos)1896 TEST(MemorySanitizer, sincos) {
1897   double s, c;
1898   sincos(0.2, &s, &c);
1899   EXPECT_NOT_POISONED(s);
1900   EXPECT_NOT_POISONED(c);
1901 }
1902 #endif
1903 
1904 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,sincosf)1905 TEST(MemorySanitizer, sincosf) {
1906   float s, c;
1907   sincosf(0.2, &s, &c);
1908   EXPECT_NOT_POISONED(s);
1909   EXPECT_NOT_POISONED(c);
1910 }
1911 #endif
1912 
1913 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,sincosl)1914 TEST(MemorySanitizer, sincosl) {
1915   long double s, c;
1916   sincosl(0.2, &s, &c);
1917   EXPECT_NOT_POISONED(s);
1918   EXPECT_NOT_POISONED(c);
1919 }
1920 #endif
1921 
TEST(MemorySanitizer,remquo)1922 TEST(MemorySanitizer, remquo) {
1923   int quo;
1924   double res = remquo(29.0, 3.0, &quo);
1925   ASSERT_NE(0.0, res);
1926   EXPECT_NOT_POISONED(quo);
1927 }
1928 
TEST(MemorySanitizer,remquof)1929 TEST(MemorySanitizer, remquof) {
1930   int quo;
1931   float res = remquof(29.0, 3.0, &quo);
1932   ASSERT_NE(0.0, res);
1933   EXPECT_NOT_POISONED(quo);
1934 }
1935 
1936 #if !defined(__NetBSD__)
TEST(MemorySanitizer,remquol)1937 TEST(MemorySanitizer, remquol) {
1938   int quo;
1939   long double res = remquof(29.0, 3.0, &quo);
1940   ASSERT_NE(0.0, res);
1941   EXPECT_NOT_POISONED(quo);
1942 }
1943 #endif
1944 
TEST(MemorySanitizer,lgamma)1945 TEST(MemorySanitizer, lgamma) {
1946   double res = lgamma(1.1);
1947   ASSERT_NE(0.0, res);
1948   EXPECT_NOT_POISONED(signgam);
1949 }
1950 
TEST(MemorySanitizer,lgammaf)1951 TEST(MemorySanitizer, lgammaf) {
1952   float res = lgammaf(1.1);
1953   ASSERT_NE(0.0, res);
1954   EXPECT_NOT_POISONED(signgam);
1955 }
1956 
1957 #if !defined(__NetBSD__)
TEST(MemorySanitizer,lgammal)1958 TEST(MemorySanitizer, lgammal) {
1959   long double res = lgammal(1.1);
1960   ASSERT_NE(0.0, res);
1961   EXPECT_NOT_POISONED(signgam);
1962 }
1963 #endif
1964 
TEST(MemorySanitizer,lgamma_r)1965 TEST(MemorySanitizer, lgamma_r) {
1966   int sgn;
1967   double res = lgamma_r(1.1, &sgn);
1968   ASSERT_NE(0.0, res);
1969   EXPECT_NOT_POISONED(sgn);
1970 }
1971 
TEST(MemorySanitizer,lgammaf_r)1972 TEST(MemorySanitizer, lgammaf_r) {
1973   int sgn;
1974   float res = lgammaf_r(1.1, &sgn);
1975   ASSERT_NE(0.0, res);
1976   EXPECT_NOT_POISONED(sgn);
1977 }
1978 
1979 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,lgammal_r)1980 TEST(MemorySanitizer, lgammal_r) {
1981   int sgn;
1982   long double res = lgammal_r(1.1, &sgn);
1983   ASSERT_NE(0.0, res);
1984   EXPECT_NOT_POISONED(sgn);
1985 }
1986 #endif
1987 
1988 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,drand48_r)1989 TEST(MemorySanitizer, drand48_r) {
1990   struct drand48_data buf;
1991   srand48_r(0, &buf);
1992   double d;
1993   drand48_r(&buf, &d);
1994   EXPECT_NOT_POISONED(d);
1995 }
1996 #endif
1997 
1998 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,lrand48_r)1999 TEST(MemorySanitizer, lrand48_r) {
2000   struct drand48_data buf;
2001   srand48_r(0, &buf);
2002   long d;
2003   lrand48_r(&buf, &d);
2004   EXPECT_NOT_POISONED(d);
2005 }
2006 #endif
2007 
TEST(MemorySanitizer,sprintf)2008 TEST(MemorySanitizer, sprintf) {
2009   char buff[10];
2010   break_optimization(buff);
2011   EXPECT_POISONED(buff[0]);
2012   int res = sprintf(buff, "%d", 1234567);
2013   ASSERT_EQ(res, 7);
2014   ASSERT_EQ(buff[0], '1');
2015   ASSERT_EQ(buff[1], '2');
2016   ASSERT_EQ(buff[2], '3');
2017   ASSERT_EQ(buff[6], '7');
2018   ASSERT_EQ(buff[7], 0);
2019   EXPECT_POISONED(buff[8]);
2020 }
2021 
TEST(MemorySanitizer,snprintf)2022 TEST(MemorySanitizer, snprintf) {
2023   char buff[10];
2024   break_optimization(buff);
2025   EXPECT_POISONED(buff[0]);
2026   int res = snprintf(buff, sizeof(buff), "%d", 1234567);
2027   ASSERT_EQ(res, 7);
2028   ASSERT_EQ(buff[0], '1');
2029   ASSERT_EQ(buff[1], '2');
2030   ASSERT_EQ(buff[2], '3');
2031   ASSERT_EQ(buff[6], '7');
2032   ASSERT_EQ(buff[7], 0);
2033   EXPECT_POISONED(buff[8]);
2034 }
2035 
TEST(MemorySanitizer,swprintf)2036 TEST(MemorySanitizer, swprintf) {
2037   wchar_t buff[10];
2038   ASSERT_EQ(4U, sizeof(wchar_t));
2039   break_optimization(buff);
2040   EXPECT_POISONED(buff[0]);
2041   int res = swprintf(buff, 9, L"%d", 1234567);
2042   ASSERT_EQ(res, 7);
2043   ASSERT_EQ(buff[0], '1');
2044   ASSERT_EQ(buff[1], '2');
2045   ASSERT_EQ(buff[2], '3');
2046   ASSERT_EQ(buff[6], '7');
2047   ASSERT_EQ(buff[7], L'\0');
2048   EXPECT_POISONED(buff[8]);
2049 }
2050 
TEST(MemorySanitizer,asprintf)2051 TEST(MemorySanitizer, asprintf) {
2052   char *pbuf;
2053   EXPECT_POISONED(pbuf);
2054   int res = asprintf(&pbuf, "%d", 1234567);
2055   ASSERT_EQ(res, 7);
2056   EXPECT_NOT_POISONED(pbuf);
2057   ASSERT_EQ(pbuf[0], '1');
2058   ASSERT_EQ(pbuf[1], '2');
2059   ASSERT_EQ(pbuf[2], '3');
2060   ASSERT_EQ(pbuf[6], '7');
2061   ASSERT_EQ(pbuf[7], 0);
2062   free(pbuf);
2063 }
2064 
TEST(MemorySanitizer,mbstowcs)2065 TEST(MemorySanitizer, mbstowcs) {
2066   const char *x = "abc";
2067   wchar_t buff[10];
2068   int res = mbstowcs(buff, x, 2);
2069   EXPECT_EQ(2, res);
2070   EXPECT_EQ(L'a', buff[0]);
2071   EXPECT_EQ(L'b', buff[1]);
2072   EXPECT_POISONED(buff[2]);
2073   res = mbstowcs(buff, x, 10);
2074   EXPECT_EQ(3, res);
2075   EXPECT_NOT_POISONED(buff[3]);
2076 }
2077 
TEST(MemorySanitizer,wcstombs)2078 TEST(MemorySanitizer, wcstombs) {
2079   const wchar_t *x = L"abc";
2080   char buff[10];
2081   int res = wcstombs(buff, x, 4);
2082   EXPECT_EQ(res, 3);
2083   EXPECT_EQ(buff[0], 'a');
2084   EXPECT_EQ(buff[1], 'b');
2085   EXPECT_EQ(buff[2], 'c');
2086 }
2087 
TEST(MemorySanitizer,wcsrtombs)2088 TEST(MemorySanitizer, wcsrtombs) {
2089   const wchar_t *x = L"abc";
2090   const wchar_t *p = x;
2091   char buff[10];
2092   mbstate_t mbs;
2093   memset(&mbs, 0, sizeof(mbs));
2094   int res = wcsrtombs(buff, &p, 4, &mbs);
2095   EXPECT_EQ(res, 3);
2096   EXPECT_EQ(buff[0], 'a');
2097   EXPECT_EQ(buff[1], 'b');
2098   EXPECT_EQ(buff[2], 'c');
2099   EXPECT_EQ(buff[3], '\0');
2100   EXPECT_POISONED(buff[4]);
2101 }
2102 
TEST(MemorySanitizer,wcsnrtombs)2103 TEST(MemorySanitizer, wcsnrtombs) {
2104   const wchar_t *x = L"abc";
2105   const wchar_t *p = x;
2106   char buff[10];
2107   mbstate_t mbs;
2108   memset(&mbs, 0, sizeof(mbs));
2109   int res = wcsnrtombs(buff, &p, 2, 4, &mbs);
2110   EXPECT_EQ(res, 2);
2111   EXPECT_EQ(buff[0], 'a');
2112   EXPECT_EQ(buff[1], 'b');
2113   EXPECT_POISONED(buff[2]);
2114 }
2115 
TEST(MemorySanitizer,wcrtomb)2116 TEST(MemorySanitizer, wcrtomb) {
2117   wchar_t x = L'a';
2118   char buff[10];
2119   mbstate_t mbs;
2120   memset(&mbs, 0, sizeof(mbs));
2121   size_t res = wcrtomb(buff, x, &mbs);
2122   EXPECT_EQ(res, (size_t)1);
2123   EXPECT_EQ(buff[0], 'a');
2124 }
2125 
TEST(MemorySanitizer,wctomb)2126 TEST(MemorySanitizer, wctomb) {
2127   wchar_t x = L'a';
2128   char buff[10];
2129   wctomb(nullptr, x);
2130   int res = wctomb(buff, x);
2131   EXPECT_EQ(res, 1);
2132   EXPECT_EQ(buff[0], 'a');
2133   EXPECT_POISONED(buff[1]);
2134 }
2135 
TEST(MemorySanitizer,wmemset)2136 TEST(MemorySanitizer, wmemset) {
2137     wchar_t x[25];
2138     break_optimization(x);
2139     EXPECT_POISONED(x[0]);
2140     wmemset(x, L'A', 10);
2141     EXPECT_EQ(x[0], L'A');
2142     EXPECT_EQ(x[9], L'A');
2143     EXPECT_POISONED(x[10]);
2144 }
2145 
TEST(MemorySanitizer,mbtowc)2146 TEST(MemorySanitizer, mbtowc) {
2147   const char *x = "abc";
2148   wchar_t wx;
2149   int res = mbtowc(&wx, x, 3);
2150   EXPECT_GT(res, 0);
2151   EXPECT_NOT_POISONED(wx);
2152 }
2153 
TEST(MemorySanitizer,mbrtowc)2154 TEST(MemorySanitizer, mbrtowc) {
2155   mbstate_t mbs = {};
2156 
2157   wchar_t wc;
2158   size_t res = mbrtowc(&wc, "\377", 1, &mbs);
2159   EXPECT_EQ(res, -1ULL);
2160 
2161   res = mbrtowc(&wc, "abc", 3, &mbs);
2162   EXPECT_GT(res, 0ULL);
2163   EXPECT_NOT_POISONED(wc);
2164 }
2165 
TEST(MemorySanitizer,wcsftime)2166 TEST(MemorySanitizer, wcsftime) {
2167   wchar_t x[100];
2168   time_t t = time(NULL);
2169   struct tm tms;
2170   struct tm *tmres = localtime_r(&t, &tms);
2171   ASSERT_NE((void *)0, tmres);
2172   size_t res = wcsftime(x, sizeof(x) / sizeof(x[0]), L"%Y-%m-%d", tmres);
2173   EXPECT_GT(res, 0UL);
2174   EXPECT_EQ(res, wcslen(x));
2175 }
2176 
TEST(MemorySanitizer,gettimeofday)2177 TEST(MemorySanitizer, gettimeofday) {
2178   struct timeval tv;
2179   struct timezone tz;
2180   break_optimization(&tv);
2181   break_optimization(&tz);
2182   ASSERT_EQ(16U, sizeof(tv));
2183   ASSERT_EQ(8U, sizeof(tz));
2184   EXPECT_POISONED(tv.tv_sec);
2185   EXPECT_POISONED(tv.tv_usec);
2186   EXPECT_POISONED(tz.tz_minuteswest);
2187   EXPECT_POISONED(tz.tz_dsttime);
2188   ASSERT_EQ(0, gettimeofday(&tv, &tz));
2189   EXPECT_NOT_POISONED(tv.tv_sec);
2190   EXPECT_NOT_POISONED(tv.tv_usec);
2191   EXPECT_NOT_POISONED(tz.tz_minuteswest);
2192   EXPECT_NOT_POISONED(tz.tz_dsttime);
2193 }
2194 
TEST(MemorySanitizer,clock_gettime)2195 TEST(MemorySanitizer, clock_gettime) {
2196   struct timespec tp;
2197   EXPECT_POISONED(tp.tv_sec);
2198   EXPECT_POISONED(tp.tv_nsec);
2199   ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &tp));
2200   EXPECT_NOT_POISONED(tp.tv_sec);
2201   EXPECT_NOT_POISONED(tp.tv_nsec);
2202 }
2203 
TEST(MemorySanitizer,clock_getres)2204 TEST(MemorySanitizer, clock_getres) {
2205   struct timespec tp;
2206   EXPECT_POISONED(tp.tv_sec);
2207   EXPECT_POISONED(tp.tv_nsec);
2208   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, 0));
2209   EXPECT_POISONED(tp.tv_sec);
2210   EXPECT_POISONED(tp.tv_nsec);
2211   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &tp));
2212   EXPECT_NOT_POISONED(tp.tv_sec);
2213   EXPECT_NOT_POISONED(tp.tv_nsec);
2214 }
2215 
TEST(MemorySanitizer,getitimer)2216 TEST(MemorySanitizer, getitimer) {
2217   struct itimerval it1, it2;
2218   int res;
2219   EXPECT_POISONED(it1.it_interval.tv_sec);
2220   EXPECT_POISONED(it1.it_interval.tv_usec);
2221   EXPECT_POISONED(it1.it_value.tv_sec);
2222   EXPECT_POISONED(it1.it_value.tv_usec);
2223   res = getitimer(ITIMER_VIRTUAL, &it1);
2224   ASSERT_EQ(0, res);
2225   EXPECT_NOT_POISONED(it1.it_interval.tv_sec);
2226   EXPECT_NOT_POISONED(it1.it_interval.tv_usec);
2227   EXPECT_NOT_POISONED(it1.it_value.tv_sec);
2228   EXPECT_NOT_POISONED(it1.it_value.tv_usec);
2229 
2230   it1.it_interval.tv_sec = it1.it_value.tv_sec = 10000;
2231   it1.it_interval.tv_usec = it1.it_value.tv_usec = 0;
2232 
2233   res = setitimer(ITIMER_VIRTUAL, &it1, &it2);
2234   ASSERT_EQ(0, res);
2235   EXPECT_NOT_POISONED(it2.it_interval.tv_sec);
2236   EXPECT_NOT_POISONED(it2.it_interval.tv_usec);
2237   EXPECT_NOT_POISONED(it2.it_value.tv_sec);
2238   EXPECT_NOT_POISONED(it2.it_value.tv_usec);
2239 
2240   // Check that old_value can be 0, and disable the timer.
2241   memset(&it1, 0, sizeof(it1));
2242   res = setitimer(ITIMER_VIRTUAL, &it1, 0);
2243   ASSERT_EQ(0, res);
2244 }
2245 
TEST(MemorySanitizer,setitimer_null)2246 TEST(MemorySanitizer, setitimer_null) {
2247   setitimer(ITIMER_VIRTUAL, 0, 0);
2248   // Not testing the return value, since it the behaviour seems to differ
2249   // between libc implementations and POSIX.
2250   // Should never crash, though.
2251 }
2252 
TEST(MemorySanitizer,time)2253 TEST(MemorySanitizer, time) {
2254   time_t t;
2255   EXPECT_POISONED(t);
2256   time_t t2 = time(&t);
2257   ASSERT_NE(t2, (time_t)-1);
2258   EXPECT_NOT_POISONED(t);
2259 }
2260 
TEST(MemorySanitizer,strptime)2261 TEST(MemorySanitizer, strptime) {
2262   struct tm time;
2263   char *p = strptime("11/1/2013-05:39", "%m/%d/%Y-%H:%M", &time);
2264   ASSERT_TRUE(p != NULL);
2265   EXPECT_NOT_POISONED(time.tm_sec);
2266   EXPECT_NOT_POISONED(time.tm_hour);
2267   EXPECT_NOT_POISONED(time.tm_year);
2268 }
2269 
TEST(MemorySanitizer,localtime)2270 TEST(MemorySanitizer, localtime) {
2271   time_t t = 123;
2272   struct tm *time = localtime(&t);
2273   ASSERT_TRUE(time != NULL);
2274   EXPECT_NOT_POISONED(time->tm_sec);
2275   EXPECT_NOT_POISONED(time->tm_hour);
2276   EXPECT_NOT_POISONED(time->tm_year);
2277   EXPECT_NOT_POISONED(time->tm_isdst);
2278   EXPECT_NE(0U, strlen(time->tm_zone));
2279 }
2280 
TEST(MemorySanitizer,localtime_r)2281 TEST(MemorySanitizer, localtime_r) {
2282   time_t t = 123;
2283   struct tm time;
2284   struct tm *res = localtime_r(&t, &time);
2285   ASSERT_TRUE(res != NULL);
2286   EXPECT_NOT_POISONED(time.tm_sec);
2287   EXPECT_NOT_POISONED(time.tm_hour);
2288   EXPECT_NOT_POISONED(time.tm_year);
2289   EXPECT_NOT_POISONED(time.tm_isdst);
2290   EXPECT_NE(0U, strlen(time.tm_zone));
2291 }
2292 
2293 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
2294 /* Creates a temporary file with contents similar to /etc/fstab to be used
2295    with getmntent{_r}.  */
2296 class TempFstabFile {
2297  public:
TempFstabFile()2298    TempFstabFile() : fd (-1) { }
~TempFstabFile()2299    ~TempFstabFile() {
2300      if (fd >= 0)
2301        close (fd);
2302    }
2303 
Create(void)2304    bool Create(void) {
2305      snprintf(tmpfile, sizeof(tmpfile), "/tmp/msan.getmntent.tmp.XXXXXX");
2306 
2307      fd = mkstemp(tmpfile);
2308      if (fd == -1)
2309        return false;
2310 
2311      const char entry[] = "/dev/root / ext4 errors=remount-ro 0 1";
2312      size_t entrylen = sizeof(entry);
2313 
2314      size_t bytesWritten = write(fd, entry, entrylen);
2315      if (entrylen != bytesWritten)
2316        return false;
2317 
2318      return true;
2319    }
2320 
FileName(void)2321    const char* FileName(void) {
2322      return tmpfile;
2323    }
2324 
2325  private:
2326   char tmpfile[128];
2327   int fd;
2328 };
2329 #endif
2330 
2331 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,getmntent)2332 TEST(MemorySanitizer, getmntent) {
2333   TempFstabFile fstabtmp;
2334   ASSERT_TRUE(fstabtmp.Create());
2335   FILE *fp = setmntent(fstabtmp.FileName(), "r");
2336 
2337   struct mntent *mnt = getmntent(fp);
2338   ASSERT_TRUE(mnt != NULL);
2339   ASSERT_NE(0U, strlen(mnt->mnt_fsname));
2340   ASSERT_NE(0U, strlen(mnt->mnt_dir));
2341   ASSERT_NE(0U, strlen(mnt->mnt_type));
2342   ASSERT_NE(0U, strlen(mnt->mnt_opts));
2343   EXPECT_NOT_POISONED(mnt->mnt_freq);
2344   EXPECT_NOT_POISONED(mnt->mnt_passno);
2345   fclose(fp);
2346 }
2347 #endif
2348 
2349 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,getmntent_r)2350 TEST(MemorySanitizer, getmntent_r) {
2351   TempFstabFile fstabtmp;
2352   ASSERT_TRUE(fstabtmp.Create());
2353   FILE *fp = setmntent(fstabtmp.FileName(), "r");
2354 
2355   struct mntent mntbuf;
2356   char buf[1000];
2357   struct mntent *mnt = getmntent_r(fp, &mntbuf, buf, sizeof(buf));
2358   ASSERT_TRUE(mnt != NULL);
2359   ASSERT_NE(0U, strlen(mnt->mnt_fsname));
2360   ASSERT_NE(0U, strlen(mnt->mnt_dir));
2361   ASSERT_NE(0U, strlen(mnt->mnt_type));
2362   ASSERT_NE(0U, strlen(mnt->mnt_opts));
2363   EXPECT_NOT_POISONED(mnt->mnt_freq);
2364   EXPECT_NOT_POISONED(mnt->mnt_passno);
2365   fclose(fp);
2366 }
2367 #endif
2368 
2369 #if !defined(__NetBSD__)
TEST(MemorySanitizer,ether)2370 TEST(MemorySanitizer, ether) {
2371   const char *asc = "11:22:33:44:55:66";
2372   struct ether_addr *paddr = ether_aton(asc);
2373   EXPECT_NOT_POISONED(*paddr);
2374 
2375   struct ether_addr addr;
2376   paddr = ether_aton_r(asc, &addr);
2377   ASSERT_EQ(paddr, &addr);
2378   EXPECT_NOT_POISONED(addr);
2379 
2380   char *s = ether_ntoa(&addr);
2381   ASSERT_NE(0U, strlen(s));
2382 
2383   char buf[100];
2384   s = ether_ntoa_r(&addr, buf);
2385   ASSERT_EQ(s, buf);
2386   ASSERT_NE(0U, strlen(buf));
2387 }
2388 #endif
2389 
TEST(MemorySanitizer,mmap)2390 TEST(MemorySanitizer, mmap) {
2391   const int size = 4096;
2392   void *p1, *p2;
2393   p1 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
2394   __msan_poison(p1, size);
2395   munmap(p1, size);
2396   for (int i = 0; i < 1000; i++) {
2397     p2 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
2398     if (p2 == p1)
2399       break;
2400     else
2401       munmap(p2, size);
2402   }
2403   if (p1 == p2) {
2404     EXPECT_NOT_POISONED(*(char*)p2);
2405     munmap(p2, size);
2406   }
2407 }
2408 
2409 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
2410 // FIXME: enable and add ecvt.
2411 // FIXME: check why msandr does nt handle fcvt.
TEST(MemorySanitizer,fcvt)2412 TEST(MemorySanitizer, fcvt) {
2413   int a, b;
2414   break_optimization(&a);
2415   break_optimization(&b);
2416   EXPECT_POISONED(a);
2417   EXPECT_POISONED(b);
2418   char *str = fcvt(12345.6789, 10, &a, &b);
2419   EXPECT_NOT_POISONED(a);
2420   EXPECT_NOT_POISONED(b);
2421   ASSERT_NE(nullptr, str);
2422   EXPECT_NOT_POISONED(str[0]);
2423   ASSERT_NE(0U, strlen(str));
2424 }
2425 #endif
2426 
2427 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,fcvt_long)2428 TEST(MemorySanitizer, fcvt_long) {
2429   int a, b;
2430   break_optimization(&a);
2431   break_optimization(&b);
2432   EXPECT_POISONED(a);
2433   EXPECT_POISONED(b);
2434   char *str = fcvt(111111112345.6789, 10, &a, &b);
2435   EXPECT_NOT_POISONED(a);
2436   EXPECT_NOT_POISONED(b);
2437   ASSERT_NE(nullptr, str);
2438   EXPECT_NOT_POISONED(str[0]);
2439   ASSERT_NE(0U, strlen(str));
2440 }
2441 #endif
2442 
TEST(MemorySanitizer,memchr)2443 TEST(MemorySanitizer, memchr) {
2444   char x[10];
2445   break_optimization(x);
2446   EXPECT_POISONED(x[0]);
2447   x[2] = '2';
2448   void *res;
2449   EXPECT_UMR(res = memchr(x, '2', 10));
2450   EXPECT_NOT_POISONED(res);
2451   x[0] = '0';
2452   x[1] = '1';
2453   res = memchr(x, '2', 10);
2454   EXPECT_EQ(&x[2], res);
2455   EXPECT_UMR(res = memchr(x, '3', 10));
2456   EXPECT_NOT_POISONED(res);
2457 }
2458 
TEST(MemorySanitizer,memrchr)2459 TEST(MemorySanitizer, memrchr) {
2460   char x[10];
2461   break_optimization(x);
2462   EXPECT_POISONED(x[0]);
2463   x[9] = '9';
2464   void *res;
2465   EXPECT_UMR(res = memrchr(x, '9', 10));
2466   EXPECT_NOT_POISONED(res);
2467   x[0] = '0';
2468   x[1] = '1';
2469   res = memrchr(x, '0', 2);
2470   EXPECT_EQ(&x[0], res);
2471   EXPECT_UMR(res = memrchr(x, '7', 10));
2472   EXPECT_NOT_POISONED(res);
2473 }
2474 
TEST(MemorySanitizer,frexp)2475 TEST(MemorySanitizer, frexp) {
2476   int x;
2477   x = *GetPoisoned<int>();
2478   double r = frexp(1.1, &x);
2479   EXPECT_NOT_POISONED(r);
2480   EXPECT_NOT_POISONED(x);
2481 
2482   x = *GetPoisoned<int>();
2483   float rf = frexpf(1.1, &x);
2484   EXPECT_NOT_POISONED(rf);
2485   EXPECT_NOT_POISONED(x);
2486 
2487   x = *GetPoisoned<int>();
2488   double rl = frexpl(1.1, &x);
2489   EXPECT_NOT_POISONED(rl);
2490   EXPECT_NOT_POISONED(x);
2491 }
2492 
2493 namespace {
2494 
2495 static int cnt;
2496 
SigactionHandler(int signo,siginfo_t * si,void * uc)2497 void SigactionHandler(int signo, siginfo_t* si, void* uc) {
2498   ASSERT_EQ(signo, SIGPROF);
2499   ASSERT_TRUE(si != NULL);
2500   EXPECT_NOT_POISONED(si->si_errno);
2501   EXPECT_NOT_POISONED(si->si_pid);
2502 #ifdef _UC_MACHINE_PC
2503   EXPECT_NOT_POISONED(_UC_MACHINE_PC((ucontext_t*)uc));
2504 #else
2505 # if __linux__
2506 #  if defined(__x86_64__)
2507   EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_RIP]);
2508 #  elif defined(__i386__)
2509   EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_EIP]);
2510 #  endif
2511 # endif
2512 #endif
2513   ++cnt;
2514 }
2515 
TEST(MemorySanitizer,sigaction)2516 TEST(MemorySanitizer, sigaction) {
2517   struct sigaction act = {};
2518   struct sigaction oldact = {};
2519   struct sigaction origact = {};
2520 
2521   sigaction(SIGPROF, 0, &origact);
2522 
2523   act.sa_flags |= SA_SIGINFO;
2524   act.sa_sigaction = &SigactionHandler;
2525   sigaction(SIGPROF, &act, 0);
2526 
2527   kill(getpid(), SIGPROF);
2528 
2529   act.sa_flags &= ~SA_SIGINFO;
2530   act.sa_handler = SIG_DFL;
2531   sigaction(SIGPROF, &act, 0);
2532 
2533   act.sa_flags &= ~SA_SIGINFO;
2534   act.sa_handler = SIG_IGN;
2535   sigaction(SIGPROF, &act, &oldact);
2536   EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
2537   EXPECT_EQ(SIG_DFL, oldact.sa_handler);
2538   kill(getpid(), SIGPROF);
2539 
2540   act.sa_flags |= SA_SIGINFO;
2541   act.sa_sigaction = &SigactionHandler;
2542   sigaction(SIGPROF, &act, &oldact);
2543   EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
2544   EXPECT_EQ(SIG_IGN, oldact.sa_handler);
2545   kill(getpid(), SIGPROF);
2546 
2547   act.sa_flags &= ~SA_SIGINFO;
2548   act.sa_handler = SIG_DFL;
2549   sigaction(SIGPROF, &act, &oldact);
2550   EXPECT_TRUE(oldact.sa_flags & SA_SIGINFO);
2551   EXPECT_EQ(&SigactionHandler, oldact.sa_sigaction);
2552   EXPECT_EQ(2, cnt);
2553 
2554   sigaction(SIGPROF, &origact, 0);
2555 }
2556 
2557 } // namespace
2558 
2559 
TEST(MemorySanitizer,sigemptyset)2560 TEST(MemorySanitizer, sigemptyset) {
2561   sigset_t s;
2562   EXPECT_POISONED(s);
2563   int res = sigemptyset(&s);
2564   ASSERT_EQ(0, res);
2565   EXPECT_NOT_POISONED(s);
2566 }
2567 
TEST(MemorySanitizer,sigfillset)2568 TEST(MemorySanitizer, sigfillset) {
2569   sigset_t s;
2570   EXPECT_POISONED(s);
2571   int res = sigfillset(&s);
2572   ASSERT_EQ(0, res);
2573   EXPECT_NOT_POISONED(s);
2574 }
2575 
TEST(MemorySanitizer,sigpending)2576 TEST(MemorySanitizer, sigpending) {
2577   sigset_t s;
2578   EXPECT_POISONED(s);
2579   int res = sigpending(&s);
2580   ASSERT_EQ(0, res);
2581   EXPECT_NOT_POISONED(s);
2582 }
2583 
TEST(MemorySanitizer,sigprocmask)2584 TEST(MemorySanitizer, sigprocmask) {
2585   sigset_t s;
2586   EXPECT_POISONED(s);
2587   int res = sigprocmask(SIG_BLOCK, 0, &s);
2588   ASSERT_EQ(0, res);
2589   EXPECT_NOT_POISONED(s);
2590 }
2591 
TEST(MemorySanitizer,pthread_sigmask)2592 TEST(MemorySanitizer, pthread_sigmask) {
2593   sigset_t s;
2594   EXPECT_POISONED(s);
2595   int res = pthread_sigmask(SIG_BLOCK, 0, &s);
2596   ASSERT_EQ(0, res);
2597   EXPECT_NOT_POISONED(s);
2598 }
2599 
2600 struct StructWithDtor {
2601   ~StructWithDtor();
2602 };
2603 
~StructWithDtor()2604 NOINLINE StructWithDtor::~StructWithDtor() {
2605   break_optimization(0);
2606 }
2607 
TEST(MemorySanitizer,Invoke)2608 TEST(MemorySanitizer, Invoke) {
2609   StructWithDtor s;  // Will cause the calls to become invokes.
2610   EXPECT_NOT_POISONED(0);
2611   EXPECT_POISONED(*GetPoisoned<int>());
2612   EXPECT_NOT_POISONED(0);
2613   EXPECT_POISONED(*GetPoisoned<int>());
2614   EXPECT_POISONED(ReturnPoisoned<S4>());
2615 }
2616 
TEST(MemorySanitizer,ptrtoint)2617 TEST(MemorySanitizer, ptrtoint) {
2618   // Test that shadow is propagated through pointer-to-integer conversion.
2619   unsigned char c = 0;
2620   __msan_poison(&c, 1);
2621   uintptr_t u = (uintptr_t)c << 8;
2622   EXPECT_NOT_POISONED(u & 0xFF00FF);
2623   EXPECT_POISONED(u & 0xFF00);
2624 
2625   break_optimization(&u);
2626   void* p = (void*)u;
2627 
2628   break_optimization(&p);
2629   EXPECT_POISONED(p);
2630   EXPECT_NOT_POISONED(((uintptr_t)p) & 0xFF00FF);
2631   EXPECT_POISONED(((uintptr_t)p) & 0xFF00);
2632 }
2633 
vaargsfn2(int guard,...)2634 static void vaargsfn2(int guard, ...) {
2635   va_list vl;
2636   va_start(vl, guard);
2637   EXPECT_NOT_POISONED(va_arg(vl, int));
2638   EXPECT_NOT_POISONED(va_arg(vl, int));
2639   EXPECT_NOT_POISONED(va_arg(vl, int));
2640   EXPECT_POISONED(va_arg(vl, double));
2641   va_end(vl);
2642 }
2643 
vaargsfn(int guard,...)2644 static void vaargsfn(int guard, ...) {
2645   va_list vl;
2646   va_start(vl, guard);
2647   EXPECT_NOT_POISONED(va_arg(vl, int));
2648   EXPECT_POISONED(va_arg(vl, int));
2649   // The following call will overwrite __msan_param_tls.
2650   // Checks after it test that arg shadow was somehow saved across the call.
2651   vaargsfn2(1, 2, 3, 4, *GetPoisoned<double>());
2652   EXPECT_NOT_POISONED(va_arg(vl, int));
2653   EXPECT_POISONED(va_arg(vl, int));
2654   va_end(vl);
2655 }
2656 
TEST(MemorySanitizer,VAArgTest)2657 TEST(MemorySanitizer, VAArgTest) {
2658   int* x = GetPoisoned<int>();
2659   int* y = GetPoisoned<int>(4);
2660   vaargsfn(1, 13, *x, 42, *y);
2661 }
2662 
vaargsfn_many(int guard,...)2663 static void vaargsfn_many(int guard, ...) {
2664   va_list vl;
2665   va_start(vl, guard);
2666   EXPECT_NOT_POISONED(va_arg(vl, int));
2667   EXPECT_POISONED(va_arg(vl, int));
2668   EXPECT_NOT_POISONED(va_arg(vl, int));
2669   EXPECT_NOT_POISONED(va_arg(vl, int));
2670   EXPECT_NOT_POISONED(va_arg(vl, int));
2671   EXPECT_NOT_POISONED(va_arg(vl, int));
2672   EXPECT_NOT_POISONED(va_arg(vl, int));
2673   EXPECT_NOT_POISONED(va_arg(vl, int));
2674   EXPECT_NOT_POISONED(va_arg(vl, int));
2675   EXPECT_POISONED(va_arg(vl, int));
2676   va_end(vl);
2677 }
2678 
TEST(MemorySanitizer,VAArgManyTest)2679 TEST(MemorySanitizer, VAArgManyTest) {
2680   int* x = GetPoisoned<int>();
2681   int* y = GetPoisoned<int>(4);
2682   vaargsfn_many(1, 2, *x, 3, 4, 5, 6, 7, 8, 9, *y);
2683 }
2684 
vaargsfn_manyfix(int g1,int g2,int g3,int g4,int g5,int g6,int g7,int g8,int g9,...)2685 static void vaargsfn_manyfix(int g1, int g2, int g3, int g4, int g5, int g6, int g7, int g8, int g9, ...) {
2686   va_list vl;
2687   va_start(vl, g9);
2688   EXPECT_NOT_POISONED(va_arg(vl, int));
2689   EXPECT_POISONED(va_arg(vl, int));
2690   va_end(vl);
2691 }
2692 
TEST(MemorySanitizer,VAArgManyFixTest)2693 TEST(MemorySanitizer, VAArgManyFixTest) {
2694   int* x = GetPoisoned<int>();
2695   int* y = GetPoisoned<int>();
2696   vaargsfn_manyfix(1, *x, 3, 4, 5, 6, 7, 8, 9, 10, *y);
2697 }
2698 
vaargsfn_pass2(va_list vl)2699 static void vaargsfn_pass2(va_list vl) {
2700   EXPECT_NOT_POISONED(va_arg(vl, int));
2701   EXPECT_NOT_POISONED(va_arg(vl, int));
2702   EXPECT_POISONED(va_arg(vl, int));
2703 }
2704 
vaargsfn_pass(int guard,...)2705 static void vaargsfn_pass(int guard, ...) {
2706   va_list vl;
2707   va_start(vl, guard);
2708   EXPECT_POISONED(va_arg(vl, int));
2709   vaargsfn_pass2(vl);
2710   va_end(vl);
2711 }
2712 
TEST(MemorySanitizer,VAArgPass)2713 TEST(MemorySanitizer, VAArgPass) {
2714   int* x = GetPoisoned<int>();
2715   int* y = GetPoisoned<int>(4);
2716   vaargsfn_pass(1, *x, 2, 3, *y);
2717 }
2718 
vaargsfn_copy2(va_list vl)2719 static void vaargsfn_copy2(va_list vl) {
2720   EXPECT_NOT_POISONED(va_arg(vl, int));
2721   EXPECT_POISONED(va_arg(vl, int));
2722 }
2723 
vaargsfn_copy(int guard,...)2724 static void vaargsfn_copy(int guard, ...) {
2725   va_list vl;
2726   va_start(vl, guard);
2727   EXPECT_NOT_POISONED(va_arg(vl, int));
2728   EXPECT_POISONED(va_arg(vl, int));
2729   va_list vl2;
2730   va_copy(vl2, vl);
2731   vaargsfn_copy2(vl2);
2732   EXPECT_NOT_POISONED(va_arg(vl, int));
2733   EXPECT_POISONED(va_arg(vl, int));
2734   va_end(vl);
2735 }
2736 
TEST(MemorySanitizer,VAArgCopy)2737 TEST(MemorySanitizer, VAArgCopy) {
2738   int* x = GetPoisoned<int>();
2739   int* y = GetPoisoned<int>(4);
2740   vaargsfn_copy(1, 2, *x, 3, *y);
2741 }
2742 
vaargsfn_ptr(int guard,...)2743 static void vaargsfn_ptr(int guard, ...) {
2744   va_list vl;
2745   va_start(vl, guard);
2746   EXPECT_NOT_POISONED(va_arg(vl, int*));
2747   EXPECT_POISONED(va_arg(vl, int*));
2748   EXPECT_NOT_POISONED(va_arg(vl, int*));
2749   EXPECT_POISONED(va_arg(vl, double*));
2750   va_end(vl);
2751 }
2752 
TEST(MemorySanitizer,VAArgPtr)2753 TEST(MemorySanitizer, VAArgPtr) {
2754   int** x = GetPoisoned<int*>();
2755   double** y = GetPoisoned<double*>(8);
2756   int z;
2757   vaargsfn_ptr(1, &z, *x, &z, *y);
2758 }
2759 
vaargsfn_overflow(int guard,...)2760 static void vaargsfn_overflow(int guard, ...) {
2761   va_list vl;
2762   va_start(vl, guard);
2763   EXPECT_NOT_POISONED(va_arg(vl, int));
2764   EXPECT_NOT_POISONED(va_arg(vl, int));
2765   EXPECT_POISONED(va_arg(vl, int));
2766   EXPECT_NOT_POISONED(va_arg(vl, int));
2767   EXPECT_NOT_POISONED(va_arg(vl, int));
2768   EXPECT_NOT_POISONED(va_arg(vl, int));
2769 
2770   EXPECT_NOT_POISONED(va_arg(vl, double));
2771   EXPECT_NOT_POISONED(va_arg(vl, double));
2772   EXPECT_NOT_POISONED(va_arg(vl, double));
2773   EXPECT_POISONED(va_arg(vl, double));
2774   EXPECT_NOT_POISONED(va_arg(vl, double));
2775   EXPECT_POISONED(va_arg(vl, int*));
2776   EXPECT_NOT_POISONED(va_arg(vl, double));
2777   EXPECT_NOT_POISONED(va_arg(vl, double));
2778 
2779   EXPECT_POISONED(va_arg(vl, int));
2780   EXPECT_POISONED(va_arg(vl, double));
2781   EXPECT_POISONED(va_arg(vl, int*));
2782 
2783   EXPECT_NOT_POISONED(va_arg(vl, int));
2784   EXPECT_NOT_POISONED(va_arg(vl, double));
2785   EXPECT_NOT_POISONED(va_arg(vl, int*));
2786 
2787   EXPECT_POISONED(va_arg(vl, int));
2788   EXPECT_POISONED(va_arg(vl, double));
2789   EXPECT_POISONED(va_arg(vl, int*));
2790 
2791   va_end(vl);
2792 }
2793 
TEST(MemorySanitizer,VAArgOverflow)2794 TEST(MemorySanitizer, VAArgOverflow) {
2795   int* x = GetPoisoned<int>();
2796   double* y = GetPoisoned<double>(8);
2797   int** p = GetPoisoned<int*>(16);
2798   int z;
2799   vaargsfn_overflow(1,
2800       1, 2, *x, 4, 5, 6,
2801       1.1, 2.2, 3.3, *y, 5.5, *p, 7.7, 8.8,
2802       // the following args will overflow for sure
2803       *x, *y, *p,
2804       7, 9.9, &z,
2805       *x, *y, *p);
2806 }
2807 
vaargsfn_tlsoverwrite2(int guard,...)2808 static void vaargsfn_tlsoverwrite2(int guard, ...) {
2809   va_list vl;
2810   va_start(vl, guard);
2811   for (int i = 0; i < 20; ++i)
2812     EXPECT_NOT_POISONED(va_arg(vl, int));
2813   va_end(vl);
2814 }
2815 
vaargsfn_tlsoverwrite(int guard,...)2816 static void vaargsfn_tlsoverwrite(int guard, ...) {
2817   // This call will overwrite TLS contents unless it's backed up somewhere.
2818   vaargsfn_tlsoverwrite2(2,
2819       42, 42, 42, 42, 42,
2820       42, 42, 42, 42, 42,
2821       42, 42, 42, 42, 42,
2822       42, 42, 42, 42, 42); // 20x
2823   va_list vl;
2824   va_start(vl, guard);
2825   for (int i = 0; i < 20; ++i)
2826     EXPECT_POISONED(va_arg(vl, int));
2827   va_end(vl);
2828 }
2829 
TEST(MemorySanitizer,VAArgTLSOverwrite)2830 TEST(MemorySanitizer, VAArgTLSOverwrite) {
2831   int* x = GetPoisoned<int>();
2832   vaargsfn_tlsoverwrite(1,
2833       *x, *x, *x, *x, *x,
2834       *x, *x, *x, *x, *x,
2835       *x, *x, *x, *x, *x,
2836       *x, *x, *x, *x, *x); // 20x
2837 
2838 }
2839 
2840 struct StructByVal {
2841   int a, b, c, d, e, f;
2842 };
2843 
vaargsfn_structbyval(int guard,...)2844 static void vaargsfn_structbyval(int guard, ...) {
2845   va_list vl;
2846   va_start(vl, guard);
2847   {
2848     StructByVal s = va_arg(vl, StructByVal);
2849     EXPECT_NOT_POISONED(s.a);
2850     EXPECT_POISONED(s.b);
2851     EXPECT_NOT_POISONED(s.c);
2852     EXPECT_POISONED(s.d);
2853     EXPECT_NOT_POISONED(s.e);
2854     EXPECT_POISONED(s.f);
2855   }
2856   {
2857     StructByVal s = va_arg(vl, StructByVal);
2858     EXPECT_NOT_POISONED(s.a);
2859     EXPECT_POISONED(s.b);
2860     EXPECT_NOT_POISONED(s.c);
2861     EXPECT_POISONED(s.d);
2862     EXPECT_NOT_POISONED(s.e);
2863     EXPECT_POISONED(s.f);
2864   }
2865   va_end(vl);
2866 }
2867 
TEST(MemorySanitizer,VAArgStructByVal)2868 TEST(MemorySanitizer, VAArgStructByVal) {
2869   StructByVal s;
2870   s.a = 1;
2871   s.b = *GetPoisoned<int>();
2872   s.c = 2;
2873   s.d = *GetPoisoned<int>();
2874   s.e = 3;
2875   s.f = *GetPoisoned<int>();
2876   vaargsfn_structbyval(0, s, s);
2877 }
2878 
StructByValTestFunc(struct StructByVal s)2879 NOINLINE void StructByValTestFunc(struct StructByVal s) {
2880   EXPECT_NOT_POISONED(s.a);
2881   EXPECT_POISONED(s.b);
2882   EXPECT_NOT_POISONED(s.c);
2883   EXPECT_POISONED(s.d);
2884   EXPECT_NOT_POISONED(s.e);
2885   EXPECT_POISONED(s.f);
2886 }
2887 
StructByValTestFunc1(struct StructByVal s)2888 NOINLINE void StructByValTestFunc1(struct StructByVal s) {
2889   StructByValTestFunc(s);
2890 }
2891 
StructByValTestFunc2(int z,struct StructByVal s)2892 NOINLINE void StructByValTestFunc2(int z, struct StructByVal s) {
2893   StructByValTestFunc(s);
2894 }
2895 
TEST(MemorySanitizer,StructByVal)2896 TEST(MemorySanitizer, StructByVal) {
2897   // Large aggregates are passed as "byval" pointer argument in LLVM.
2898   struct StructByVal s;
2899   s.a = 1;
2900   s.b = *GetPoisoned<int>();
2901   s.c = 2;
2902   s.d = *GetPoisoned<int>();
2903   s.e = 3;
2904   s.f = *GetPoisoned<int>();
2905   StructByValTestFunc(s);
2906   StructByValTestFunc1(s);
2907   StructByValTestFunc2(0, s);
2908 }
2909 
2910 
2911 #if MSAN_HAS_M128
m128Eq(__m128i * a,__m128i * b)2912 NOINLINE __m128i m128Eq(__m128i *a, __m128i *b) { return _mm_cmpeq_epi16(*a, *b); }
m128Lt(__m128i * a,__m128i * b)2913 NOINLINE __m128i m128Lt(__m128i *a, __m128i *b) { return _mm_cmplt_epi16(*a, *b); }
TEST(MemorySanitizer,m128)2914 TEST(MemorySanitizer, m128) {
2915   __m128i a = _mm_set1_epi16(0x1234);
2916   __m128i b = _mm_set1_epi16(0x7890);
2917   EXPECT_NOT_POISONED(m128Eq(&a, &b));
2918   EXPECT_NOT_POISONED(m128Lt(&a, &b));
2919 }
2920 // FIXME: add more tests for __m128i.
2921 #endif  // MSAN_HAS_M128
2922 
2923 // We should not complain when copying this poisoned hole.
2924 struct StructWithHole {
2925   U4  a;
2926   // 4-byte hole.
2927   U8  b;
2928 };
2929 
ReturnStructWithHole()2930 NOINLINE StructWithHole ReturnStructWithHole() {
2931   StructWithHole res;
2932   __msan_poison(&res, sizeof(res));
2933   res.a = 1;
2934   res.b = 2;
2935   return res;
2936 }
2937 
TEST(MemorySanitizer,StructWithHole)2938 TEST(MemorySanitizer, StructWithHole) {
2939   StructWithHole a = ReturnStructWithHole();
2940   break_optimization(&a);
2941 }
2942 
2943 template <class T>
ReturnStruct()2944 NOINLINE T ReturnStruct() {
2945   T res;
2946   __msan_poison(&res, sizeof(res));
2947   res.a = 1;
2948   return res;
2949 }
2950 
2951 template <class T>
TestReturnStruct()2952 NOINLINE void TestReturnStruct() {
2953   T s1 = ReturnStruct<T>();
2954   EXPECT_NOT_POISONED(s1.a);
2955   EXPECT_POISONED(s1.b);
2956 }
2957 
2958 struct SSS1 {
2959   int a, b, c;
2960 };
2961 struct SSS2 {
2962   int b, a, c;
2963 };
2964 struct SSS3 {
2965   int b, c, a;
2966 };
2967 struct SSS4 {
2968   int c, b, a;
2969 };
2970 
2971 struct SSS5 {
2972   int a;
2973   float b;
2974 };
2975 struct SSS6 {
2976   int a;
2977   double b;
2978 };
2979 struct SSS7 {
2980   S8 b;
2981   int a;
2982 };
2983 struct SSS8 {
2984   S2 b;
2985   S8 a;
2986 };
2987 
TEST(MemorySanitizer,IntStruct3)2988 TEST(MemorySanitizer, IntStruct3) {
2989   TestReturnStruct<SSS1>();
2990   TestReturnStruct<SSS2>();
2991   TestReturnStruct<SSS3>();
2992   TestReturnStruct<SSS4>();
2993   TestReturnStruct<SSS5>();
2994   TestReturnStruct<SSS6>();
2995   TestReturnStruct<SSS7>();
2996   TestReturnStruct<SSS8>();
2997 }
2998 
2999 struct LongStruct {
3000   U1 a1, b1;
3001   U2 a2, b2;
3002   U4 a4, b4;
3003   U8 a8, b8;
3004 };
3005 
ReturnLongStruct1()3006 NOINLINE LongStruct ReturnLongStruct1() {
3007   LongStruct res;
3008   __msan_poison(&res, sizeof(res));
3009   res.a1 = res.a2 = res.a4 = res.a8 = 111;
3010   // leaves b1, .., b8 poisoned.
3011   return res;
3012 }
3013 
ReturnLongStruct2()3014 NOINLINE LongStruct ReturnLongStruct2() {
3015   LongStruct res;
3016   __msan_poison(&res, sizeof(res));
3017   res.b1 = res.b2 = res.b4 = res.b8 = 111;
3018   // leaves a1, .., a8 poisoned.
3019   return res;
3020 }
3021 
TEST(MemorySanitizer,LongStruct)3022 TEST(MemorySanitizer, LongStruct) {
3023   LongStruct s1 = ReturnLongStruct1();
3024   __msan_print_shadow(&s1, sizeof(s1));
3025   EXPECT_NOT_POISONED(s1.a1);
3026   EXPECT_NOT_POISONED(s1.a2);
3027   EXPECT_NOT_POISONED(s1.a4);
3028   EXPECT_NOT_POISONED(s1.a8);
3029 
3030   EXPECT_POISONED(s1.b1);
3031   EXPECT_POISONED(s1.b2);
3032   EXPECT_POISONED(s1.b4);
3033   EXPECT_POISONED(s1.b8);
3034 
3035   LongStruct s2 = ReturnLongStruct2();
3036   __msan_print_shadow(&s2, sizeof(s2));
3037   EXPECT_NOT_POISONED(s2.b1);
3038   EXPECT_NOT_POISONED(s2.b2);
3039   EXPECT_NOT_POISONED(s2.b4);
3040   EXPECT_NOT_POISONED(s2.b8);
3041 
3042   EXPECT_POISONED(s2.a1);
3043   EXPECT_POISONED(s2.a2);
3044   EXPECT_POISONED(s2.a4);
3045   EXPECT_POISONED(s2.a8);
3046 }
3047 
3048 #if defined(__FreeBSD__) || defined(__NetBSD__)
3049 #define MSAN_TEST_PRLIMIT 0
3050 #elif defined(__GLIBC__)
3051 #define MSAN_TEST_PRLIMIT __GLIBC_PREREQ(2, 13)
3052 #else
3053 #define MSAN_TEST_PRLIMIT 1
3054 #endif
3055 
TEST(MemorySanitizer,getrlimit)3056 TEST(MemorySanitizer, getrlimit) {
3057   struct rlimit limit;
3058   __msan_poison(&limit, sizeof(limit));
3059   int result = getrlimit(RLIMIT_DATA, &limit);
3060   ASSERT_EQ(result, 0);
3061   EXPECT_NOT_POISONED(limit.rlim_cur);
3062   EXPECT_NOT_POISONED(limit.rlim_max);
3063 
3064 #if MSAN_TEST_PRLIMIT
3065   struct rlimit limit2;
3066   __msan_poison(&limit2, sizeof(limit2));
3067   result = prlimit(getpid(), RLIMIT_DATA, &limit, &limit2);
3068   ASSERT_EQ(result, 0);
3069   EXPECT_NOT_POISONED(limit2.rlim_cur);
3070   EXPECT_NOT_POISONED(limit2.rlim_max);
3071 
3072   __msan_poison(&limit, sizeof(limit));
3073   result = prlimit(getpid(), RLIMIT_DATA, nullptr, &limit);
3074   ASSERT_EQ(result, 0);
3075   EXPECT_NOT_POISONED(limit.rlim_cur);
3076   EXPECT_NOT_POISONED(limit.rlim_max);
3077 
3078   result = prlimit(getpid(), RLIMIT_DATA, &limit, nullptr);
3079   ASSERT_EQ(result, 0);
3080 #endif
3081 }
3082 
TEST(MemorySanitizer,getrusage)3083 TEST(MemorySanitizer, getrusage) {
3084   struct rusage usage;
3085   __msan_poison(&usage, sizeof(usage));
3086   int result = getrusage(RUSAGE_SELF, &usage);
3087   ASSERT_EQ(result, 0);
3088   EXPECT_NOT_POISONED(usage.ru_utime.tv_sec);
3089   EXPECT_NOT_POISONED(usage.ru_utime.tv_usec);
3090   EXPECT_NOT_POISONED(usage.ru_stime.tv_sec);
3091   EXPECT_NOT_POISONED(usage.ru_stime.tv_usec);
3092   EXPECT_NOT_POISONED(usage.ru_maxrss);
3093   EXPECT_NOT_POISONED(usage.ru_minflt);
3094   EXPECT_NOT_POISONED(usage.ru_majflt);
3095   EXPECT_NOT_POISONED(usage.ru_inblock);
3096   EXPECT_NOT_POISONED(usage.ru_oublock);
3097   EXPECT_NOT_POISONED(usage.ru_nvcsw);
3098   EXPECT_NOT_POISONED(usage.ru_nivcsw);
3099 }
3100 
3101 #if defined(__FreeBSD__) || defined(__NetBSD__)
GetProgramPath(char * buf,size_t sz)3102 static void GetProgramPath(char *buf, size_t sz) {
3103 #if defined(__FreeBSD__)
3104   int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
3105 #elif defined(__NetBSD__)
3106   int mib[4] = { CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
3107 #endif
3108   int res = sysctl(mib, 4, buf, &sz, NULL, 0);
3109   ASSERT_EQ(0, res);
3110 }
3111 #elif defined(__GLIBC__)
GetProgramPath(char * buf,size_t sz)3112 static void GetProgramPath(char *buf, size_t sz) {
3113   extern char *program_invocation_name;
3114   int res = snprintf(buf, sz, "%s", program_invocation_name);
3115   ASSERT_GE(res, 0);
3116   ASSERT_LT((size_t)res, sz);
3117 }
3118 #else
3119 # error "TODO: port this"
3120 #endif
3121 
dladdr_testfn()3122 static void dladdr_testfn() {}
3123 
TEST(MemorySanitizer,dladdr)3124 TEST(MemorySanitizer, dladdr) {
3125   Dl_info info;
3126   __msan_poison(&info, sizeof(info));
3127   int result = dladdr((const void*)dladdr_testfn, &info);
3128   ASSERT_NE(result, 0);
3129   EXPECT_NOT_POISONED((unsigned long)info.dli_fname);
3130   if (info.dli_fname)
3131     EXPECT_NOT_POISONED(strlen(info.dli_fname));
3132   EXPECT_NOT_POISONED((unsigned long)info.dli_fbase);
3133   EXPECT_NOT_POISONED((unsigned long)info.dli_sname);
3134   if (info.dli_sname)
3135     EXPECT_NOT_POISONED(strlen(info.dli_sname));
3136   EXPECT_NOT_POISONED((unsigned long)info.dli_saddr);
3137 }
3138 
3139 #ifndef MSAN_TEST_DISABLE_DLOPEN
3140 
dl_phdr_callback(struct dl_phdr_info * info,size_t size,void * data)3141 static int dl_phdr_callback(struct dl_phdr_info *info, size_t size, void *data) {
3142   (*(int *)data)++;
3143   EXPECT_NOT_POISONED(info->dlpi_addr);
3144   EXPECT_NOT_POISONED(strlen(info->dlpi_name));
3145   EXPECT_NOT_POISONED(info->dlpi_phnum);
3146   for (int i = 0; i < info->dlpi_phnum; ++i)
3147     EXPECT_NOT_POISONED(info->dlpi_phdr[i]);
3148   return 0;
3149 }
3150 
3151 // Compute the path to our loadable DSO.  We assume it's in the same
3152 // directory.  Only use string routines that we intercept so far to do this.
GetPathToLoadable(char * buf,size_t sz)3153 static void GetPathToLoadable(char *buf, size_t sz) {
3154   char program_path[kMaxPathLength];
3155   GetProgramPath(program_path, sizeof(program_path));
3156 
3157   const char *last_slash = strrchr(program_path, '/');
3158   ASSERT_NE(nullptr, last_slash);
3159   size_t dir_len = (size_t)(last_slash - program_path);
3160 #if defined(__x86_64__)
3161   static const char basename[] = "libmsan_loadable.x86_64.so";
3162 #elif defined(__MIPSEB__) || defined(MIPSEB)
3163   static const char basename[] = "libmsan_loadable.mips64.so";
3164 #elif defined(__mips64)
3165   static const char basename[] = "libmsan_loadable.mips64el.so";
3166 #elif defined(__aarch64__)
3167   static const char basename[] = "libmsan_loadable.aarch64.so";
3168 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
3169   static const char basename[] = "libmsan_loadable.powerpc64.so";
3170 #elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
3171   static const char basename[] = "libmsan_loadable.powerpc64le.so";
3172 #endif
3173   int res = snprintf(buf, sz, "%.*s/%s",
3174                      (int)dir_len, program_path, basename);
3175   ASSERT_GE(res, 0);
3176   ASSERT_LT((size_t)res, sz);
3177 }
3178 
TEST(MemorySanitizer,dl_iterate_phdr)3179 TEST(MemorySanitizer, dl_iterate_phdr) {
3180   char path[kMaxPathLength];
3181   GetPathToLoadable(path, sizeof(path));
3182 
3183   // Having at least one dlopen'ed library in the process makes this more
3184   // entertaining.
3185   void *lib = dlopen(path, RTLD_LAZY);
3186   ASSERT_NE((void*)0, lib);
3187 
3188   int count = 0;
3189   int result = dl_iterate_phdr(dl_phdr_callback, &count);
3190   ASSERT_GT(count, 0);
3191 
3192   dlclose(lib);
3193 }
3194 
TEST(MemorySanitizer,dlopen)3195 TEST(MemorySanitizer, dlopen) {
3196   char path[kMaxPathLength];
3197   GetPathToLoadable(path, sizeof(path));
3198 
3199   // We need to clear shadow for globals when doing dlopen.  In order to test
3200   // this, we have to poison the shadow for the DSO before we load it.  In
3201   // general this is difficult, but the loader tends to reload things in the
3202   // same place, so we open, close, and then reopen.  The global should always
3203   // start out clean after dlopen.
3204   for (int i = 0; i < 2; i++) {
3205     void *lib = dlopen(path, RTLD_LAZY);
3206     if (lib == NULL) {
3207       printf("dlerror: %s\n", dlerror());
3208       ASSERT_TRUE(lib != NULL);
3209     }
3210     void **(*get_dso_global)() = (void **(*)())dlsym(lib, "get_dso_global");
3211     ASSERT_TRUE(get_dso_global != NULL);
3212     void **dso_global = get_dso_global();
3213     EXPECT_NOT_POISONED(*dso_global);
3214     __msan_poison(dso_global, sizeof(*dso_global));
3215     EXPECT_POISONED(*dso_global);
3216     dlclose(lib);
3217   }
3218 }
3219 
3220 // Regression test for a crash in dlopen() interceptor.
TEST(MemorySanitizer,dlopenFailed)3221 TEST(MemorySanitizer, dlopenFailed) {
3222   const char *path = "/libmsan_loadable_does_not_exist.so";
3223   void *lib = dlopen(path, RTLD_LAZY);
3224   ASSERT_TRUE(lib == NULL);
3225 }
3226 
3227 #endif // MSAN_TEST_DISABLE_DLOPEN
3228 
3229 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,sched_getaffinity)3230 TEST(MemorySanitizer, sched_getaffinity) {
3231   cpu_set_t mask;
3232   int res = sched_getaffinity(getpid(), sizeof(mask), &mask);
3233   ASSERT_EQ(0, res);
3234   EXPECT_NOT_POISONED(mask);
3235 }
3236 #endif
3237 
TEST(MemorySanitizer,scanf)3238 TEST(MemorySanitizer, scanf) {
3239   const char *input = "42 hello";
3240   int* d = new int;
3241   char* s = new char[7];
3242   int res = sscanf(input, "%d %5s", d, s);
3243   printf("res %d\n", res);
3244   ASSERT_EQ(res, 2);
3245   EXPECT_NOT_POISONED(*d);
3246   EXPECT_NOT_POISONED(s[0]);
3247   EXPECT_NOT_POISONED(s[1]);
3248   EXPECT_NOT_POISONED(s[2]);
3249   EXPECT_NOT_POISONED(s[3]);
3250   EXPECT_NOT_POISONED(s[4]);
3251   EXPECT_NOT_POISONED(s[5]);
3252   EXPECT_POISONED(s[6]);
3253   delete[] s;
3254   delete d;
3255 }
3256 
SimpleThread_threadfn(void * data)3257 static void *SimpleThread_threadfn(void* data) {
3258   return new int;
3259 }
3260 
TEST(MemorySanitizer,SimpleThread)3261 TEST(MemorySanitizer, SimpleThread) {
3262   pthread_t t;
3263   void *p;
3264   int res = pthread_create(&t, NULL, SimpleThread_threadfn, NULL);
3265   ASSERT_EQ(0, res);
3266   EXPECT_NOT_POISONED(t);
3267   res = pthread_join(t, &p);
3268   ASSERT_EQ(0, res);
3269   EXPECT_NOT_POISONED(p);
3270   delete (int*)p;
3271 }
3272 
SmallStackThread_threadfn(void * data)3273 static void *SmallStackThread_threadfn(void* data) {
3274   return 0;
3275 }
3276 
3277 #ifdef PTHREAD_STACK_MIN
3278 constexpr int kThreadStackMin = PTHREAD_STACK_MIN;
3279 #else
3280 constexpr int kThreadStackMin = 0;
3281 #endif
3282 
TEST(MemorySanitizer,SmallStackThread)3283 TEST(MemorySanitizer, SmallStackThread) {
3284   pthread_attr_t attr;
3285   pthread_t t;
3286   void *p;
3287   int res;
3288   res = pthread_attr_init(&attr);
3289   ASSERT_EQ(0, res);
3290   res = pthread_attr_setstacksize(&attr, std::max(kThreadStackMin, 64 * 1024));
3291   ASSERT_EQ(0, res);
3292   res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
3293   ASSERT_EQ(0, res);
3294   res = pthread_join(t, &p);
3295   ASSERT_EQ(0, res);
3296   res = pthread_attr_destroy(&attr);
3297   ASSERT_EQ(0, res);
3298 }
3299 
TEST(MemorySanitizer,SmallPreAllocatedStackThread)3300 TEST(MemorySanitizer, SmallPreAllocatedStackThread) {
3301   pthread_attr_t attr;
3302   pthread_t t;
3303   int res;
3304   res = pthread_attr_init(&attr);
3305   ASSERT_EQ(0, res);
3306   void *stack;
3307   const size_t kStackSize = std::max(kThreadStackMin, 32 * 1024);
3308   res = posix_memalign(&stack, 4096, kStackSize);
3309   ASSERT_EQ(0, res);
3310   res = pthread_attr_setstack(&attr, stack, kStackSize);
3311   ASSERT_EQ(0, res);
3312   res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
3313   EXPECT_EQ(0, res);
3314   res = pthread_join(t, NULL);
3315   ASSERT_EQ(0, res);
3316   res = pthread_attr_destroy(&attr);
3317   ASSERT_EQ(0, res);
3318 }
3319 
TEST(MemorySanitizer,pthread_attr_get)3320 TEST(MemorySanitizer, pthread_attr_get) {
3321   pthread_attr_t attr;
3322   int res;
3323   res = pthread_attr_init(&attr);
3324   ASSERT_EQ(0, res);
3325   {
3326     int v;
3327     res = pthread_attr_getdetachstate(&attr, &v);
3328     ASSERT_EQ(0, res);
3329     EXPECT_NOT_POISONED(v);
3330   }
3331   {
3332     size_t v;
3333     res = pthread_attr_getguardsize(&attr, &v);
3334     ASSERT_EQ(0, res);
3335     EXPECT_NOT_POISONED(v);
3336   }
3337   {
3338     struct sched_param v;
3339     res = pthread_attr_getschedparam(&attr, &v);
3340     ASSERT_EQ(0, res);
3341     EXPECT_NOT_POISONED(v);
3342   }
3343   {
3344     int v;
3345     res = pthread_attr_getschedpolicy(&attr, &v);
3346     ASSERT_EQ(0, res);
3347     EXPECT_NOT_POISONED(v);
3348   }
3349   {
3350     int v;
3351     res = pthread_attr_getinheritsched(&attr, &v);
3352     ASSERT_EQ(0, res);
3353     EXPECT_NOT_POISONED(v);
3354   }
3355   {
3356     int v;
3357     res = pthread_attr_getscope(&attr, &v);
3358     ASSERT_EQ(0, res);
3359     EXPECT_NOT_POISONED(v);
3360   }
3361   {
3362     size_t v;
3363     res = pthread_attr_getstacksize(&attr, &v);
3364     ASSERT_EQ(0, res);
3365     EXPECT_NOT_POISONED(v);
3366   }
3367   {
3368     void *v;
3369     size_t w;
3370     res = pthread_attr_getstack(&attr, &v, &w);
3371     ASSERT_EQ(0, res);
3372     EXPECT_NOT_POISONED(v);
3373     EXPECT_NOT_POISONED(w);
3374   }
3375 #if !defined(__NetBSD__)
3376   {
3377     cpu_set_t v;
3378     res = pthread_attr_getaffinity_np(&attr, sizeof(v), &v);
3379     ASSERT_EQ(0, res);
3380     EXPECT_NOT_POISONED(v);
3381   }
3382 #endif
3383   res = pthread_attr_destroy(&attr);
3384   ASSERT_EQ(0, res);
3385 }
3386 
TEST(MemorySanitizer,pthread_getschedparam)3387 TEST(MemorySanitizer, pthread_getschedparam) {
3388   int policy;
3389   struct sched_param param;
3390   int res = pthread_getschedparam(pthread_self(), &policy, &param);
3391   ASSERT_EQ(0, res);
3392   EXPECT_NOT_POISONED(policy);
3393   EXPECT_NOT_POISONED(param.sched_priority);
3394 }
3395 
TEST(MemorySanitizer,pthread_key_create)3396 TEST(MemorySanitizer, pthread_key_create) {
3397   pthread_key_t key;
3398   int res = pthread_key_create(&key, NULL);
3399   ASSERT_EQ(0, res);
3400   EXPECT_NOT_POISONED(key);
3401   res = pthread_key_delete(key);
3402   ASSERT_EQ(0, res);
3403 }
3404 
3405 namespace {
3406 struct SignalCondArg {
3407   pthread_cond_t* cond;
3408   pthread_mutex_t* mu;
3409   bool broadcast;
3410 };
3411 
SignalCond(void * param)3412 void *SignalCond(void *param) {
3413   SignalCondArg *arg = reinterpret_cast<SignalCondArg *>(param);
3414   pthread_mutex_lock(arg->mu);
3415   if (arg->broadcast)
3416     pthread_cond_broadcast(arg->cond);
3417   else
3418     pthread_cond_signal(arg->cond);
3419   pthread_mutex_unlock(arg->mu);
3420   return 0;
3421 }
3422 }  // namespace
3423 
TEST(MemorySanitizer,pthread_cond_wait)3424 TEST(MemorySanitizer, pthread_cond_wait) {
3425   pthread_cond_t cond;
3426   pthread_mutex_t mu;
3427   SignalCondArg args = {&cond, &mu, false};
3428   pthread_cond_init(&cond, 0);
3429   pthread_mutex_init(&mu, 0);
3430   pthread_mutex_lock(&mu);
3431 
3432   // signal
3433   pthread_t thr;
3434   pthread_create(&thr, 0, SignalCond, &args);
3435   int res = pthread_cond_wait(&cond, &mu);
3436   ASSERT_EQ(0, res);
3437   pthread_join(thr, 0);
3438 
3439   // broadcast
3440   args.broadcast = true;
3441   pthread_create(&thr, 0, SignalCond, &args);
3442   res = pthread_cond_wait(&cond, &mu);
3443   ASSERT_EQ(0, res);
3444   pthread_join(thr, 0);
3445 
3446   pthread_mutex_unlock(&mu);
3447   pthread_mutex_destroy(&mu);
3448   pthread_cond_destroy(&cond);
3449 }
3450 
TEST(MemorySanitizer,tmpnam)3451 TEST(MemorySanitizer, tmpnam) {
3452   char s[L_tmpnam];
3453   char *res = tmpnam(s);
3454   ASSERT_EQ(s, res);
3455   EXPECT_NOT_POISONED(strlen(res));
3456 }
3457 
TEST(MemorySanitizer,tempnam)3458 TEST(MemorySanitizer, tempnam) {
3459   char *res = tempnam(NULL, "zzz");
3460   EXPECT_NOT_POISONED(strlen(res));
3461   free(res);
3462 }
3463 
TEST(MemorySanitizer,posix_memalign)3464 TEST(MemorySanitizer, posix_memalign) {
3465   void *p;
3466   EXPECT_POISONED(p);
3467   int res = posix_memalign(&p, 4096, 13);
3468   ASSERT_EQ(0, res);
3469   EXPECT_NOT_POISONED(p);
3470   EXPECT_EQ(0U, (uintptr_t)p % 4096);
3471   free(p);
3472 }
3473 
3474 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,memalign)3475 TEST(MemorySanitizer, memalign) {
3476   void *p = memalign(4096, 13);
3477   EXPECT_EQ(0U, (uintptr_t)p % 4096);
3478   free(p);
3479 }
3480 #endif
3481 
TEST(MemorySanitizer,valloc)3482 TEST(MemorySanitizer, valloc) {
3483   void *a = valloc(100);
3484   uintptr_t PageSize = GetPageSize();
3485   EXPECT_EQ(0U, (uintptr_t)a % PageSize);
3486   free(a);
3487 }
3488 
3489 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,pvalloc)3490 TEST(MemorySanitizer, pvalloc) {
3491   uintptr_t PageSize = GetPageSize();
3492   void *p = pvalloc(PageSize + 100);
3493   EXPECT_EQ(0U, (uintptr_t)p % PageSize);
3494   EXPECT_EQ(2 * PageSize, __sanitizer_get_allocated_size(p));
3495   free(p);
3496 
3497   p = pvalloc(0);  // pvalloc(0) should allocate at least one page.
3498   EXPECT_EQ(0U, (uintptr_t)p % PageSize);
3499   EXPECT_EQ(PageSize, __sanitizer_get_allocated_size(p));
3500   free(p);
3501 }
3502 #endif
3503 
TEST(MemorySanitizer,inet_pton)3504 TEST(MemorySanitizer, inet_pton) {
3505   const char *s = "1:0:0:0:0:0:0:8";
3506   unsigned char buf[sizeof(struct in6_addr)];
3507   int res = inet_pton(AF_INET6, s, buf);
3508   ASSERT_EQ(1, res);
3509   EXPECT_NOT_POISONED(buf[0]);
3510   EXPECT_NOT_POISONED(buf[sizeof(struct in6_addr) - 1]);
3511 
3512   char s_out[INET6_ADDRSTRLEN];
3513   EXPECT_POISONED(s_out[3]);
3514   const char *q = inet_ntop(AF_INET6, buf, s_out, INET6_ADDRSTRLEN);
3515   ASSERT_NE((void*)0, q);
3516   EXPECT_NOT_POISONED(s_out[3]);
3517 }
3518 
TEST(MemorySanitizer,inet_aton)3519 TEST(MemorySanitizer, inet_aton) {
3520   const char *s = "127.0.0.1";
3521   struct in_addr in[2];
3522   int res = inet_aton(s, in);
3523   ASSERT_NE(0, res);
3524   EXPECT_NOT_POISONED(in[0]);
3525   EXPECT_POISONED(*(char *)(in + 1));
3526 }
3527 
TEST(MemorySanitizer,uname)3528 TEST(MemorySanitizer, uname) {
3529   struct utsname u;
3530   int res = uname(&u);
3531   ASSERT_EQ(0, res);
3532   EXPECT_NOT_POISONED(strlen(u.sysname));
3533   EXPECT_NOT_POISONED(strlen(u.nodename));
3534   EXPECT_NOT_POISONED(strlen(u.release));
3535   EXPECT_NOT_POISONED(strlen(u.version));
3536   EXPECT_NOT_POISONED(strlen(u.machine));
3537 }
3538 
TEST(MemorySanitizer,gethostname)3539 TEST(MemorySanitizer, gethostname) {
3540   char buf[100];
3541   int res = gethostname(buf, 100);
3542   ASSERT_EQ(0, res);
3543   EXPECT_NOT_POISONED(strlen(buf));
3544 }
3545 
3546 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,sysinfo)3547 TEST(MemorySanitizer, sysinfo) {
3548   struct sysinfo info;
3549   int res = sysinfo(&info);
3550   ASSERT_EQ(0, res);
3551   EXPECT_NOT_POISONED(info);
3552 }
3553 #endif
3554 
TEST(MemorySanitizer,getpwuid)3555 TEST(MemorySanitizer, getpwuid) {
3556   struct passwd *p = getpwuid(0); // root
3557   ASSERT_TRUE(p != NULL);
3558   EXPECT_NOT_POISONED(p->pw_name);
3559   ASSERT_TRUE(p->pw_name != NULL);
3560   EXPECT_NOT_POISONED(p->pw_name[0]);
3561   EXPECT_NOT_POISONED(p->pw_uid);
3562   ASSERT_EQ(0U, p->pw_uid);
3563 }
3564 
TEST(MemorySanitizer,getpwuid_r)3565 TEST(MemorySanitizer, getpwuid_r) {
3566   struct passwd pwd;
3567   struct passwd *pwdres;
3568   char buf[10000];
3569   int res = getpwuid_r(0, &pwd, buf, sizeof(buf), &pwdres);
3570   ASSERT_EQ(0, res);
3571   EXPECT_NOT_POISONED(pwd.pw_name);
3572   ASSERT_TRUE(pwd.pw_name != NULL);
3573   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3574   EXPECT_NOT_POISONED(pwd.pw_uid);
3575   ASSERT_EQ(0U, pwd.pw_uid);
3576   EXPECT_NOT_POISONED(pwdres);
3577 }
3578 
TEST(MemorySanitizer,getpwnam_r)3579 TEST(MemorySanitizer, getpwnam_r) {
3580   struct passwd pwd;
3581   struct passwd *pwdres;
3582   char buf[10000];
3583   int res = getpwnam_r("root", &pwd, buf, sizeof(buf), &pwdres);
3584   ASSERT_EQ(0, res);
3585   EXPECT_NOT_POISONED(pwd.pw_name);
3586   ASSERT_TRUE(pwd.pw_name != NULL);
3587   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3588   EXPECT_NOT_POISONED(pwd.pw_uid);
3589   ASSERT_EQ(0U, pwd.pw_uid);
3590   EXPECT_NOT_POISONED(pwdres);
3591 }
3592 
TEST(MemorySanitizer,getpwnam_r_positive)3593 TEST(MemorySanitizer, getpwnam_r_positive) {
3594   struct passwd pwd;
3595   struct passwd *pwdres;
3596   char s[5];
3597   strncpy(s, "abcd", 5);
3598   __msan_poison(s, 5);
3599   char buf[10000];
3600   int res;
3601   EXPECT_UMR(res = getpwnam_r(s, &pwd, buf, sizeof(buf), &pwdres));
3602 }
3603 
TEST(MemorySanitizer,getgrnam_r)3604 TEST(MemorySanitizer, getgrnam_r) {
3605   struct group grp;
3606   struct group *grpres;
3607   char buf[10000];
3608   int res = getgrnam_r(SUPERUSER_GROUP, &grp, buf, sizeof(buf), &grpres);
3609   ASSERT_EQ(0, res);
3610   // Note that getgrnam_r() returns 0 if the matching group is not found.
3611   ASSERT_NE(nullptr, grpres);
3612   EXPECT_NOT_POISONED(grp.gr_name);
3613   ASSERT_TRUE(grp.gr_name != NULL);
3614   EXPECT_NOT_POISONED(grp.gr_name[0]);
3615   EXPECT_NOT_POISONED(grp.gr_gid);
3616   EXPECT_NOT_POISONED(grpres);
3617 }
3618 
TEST(MemorySanitizer,getpwent)3619 TEST(MemorySanitizer, getpwent) {
3620   setpwent();
3621   struct passwd *p = getpwent();
3622   ASSERT_TRUE(p != NULL);
3623   EXPECT_NOT_POISONED(p->pw_name);
3624   ASSERT_TRUE(p->pw_name != NULL);
3625   EXPECT_NOT_POISONED(p->pw_name[0]);
3626   EXPECT_NOT_POISONED(p->pw_uid);
3627 }
3628 
TEST(MemorySanitizer,getpwent_r)3629 TEST(MemorySanitizer, getpwent_r) {
3630   struct passwd pwd;
3631   struct passwd *pwdres;
3632   char buf[10000];
3633   setpwent();
3634   int res = getpwent_r(&pwd, buf, sizeof(buf), &pwdres);
3635   ASSERT_EQ(0, res);
3636   EXPECT_NOT_POISONED(pwd.pw_name);
3637   ASSERT_TRUE(pwd.pw_name != NULL);
3638   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3639   EXPECT_NOT_POISONED(pwd.pw_uid);
3640   EXPECT_NOT_POISONED(pwdres);
3641 }
3642 
3643 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,fgetpwent)3644 TEST(MemorySanitizer, fgetpwent) {
3645   FILE *fp = fopen("/etc/passwd", "r");
3646   struct passwd *p = fgetpwent(fp);
3647   ASSERT_TRUE(p != NULL);
3648   EXPECT_NOT_POISONED(p->pw_name);
3649   ASSERT_TRUE(p->pw_name != NULL);
3650   EXPECT_NOT_POISONED(p->pw_name[0]);
3651   EXPECT_NOT_POISONED(p->pw_uid);
3652   fclose(fp);
3653 }
3654 #endif
3655 
TEST(MemorySanitizer,getgrent)3656 TEST(MemorySanitizer, getgrent) {
3657   setgrent();
3658   struct group *p = getgrent();
3659   ASSERT_TRUE(p != NULL);
3660   EXPECT_NOT_POISONED(p->gr_name);
3661   ASSERT_TRUE(p->gr_name != NULL);
3662   EXPECT_NOT_POISONED(p->gr_name[0]);
3663   EXPECT_NOT_POISONED(p->gr_gid);
3664 }
3665 
3666 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,fgetgrent)3667 TEST(MemorySanitizer, fgetgrent) {
3668   FILE *fp = fopen("/etc/group", "r");
3669   struct group *grp = fgetgrent(fp);
3670   ASSERT_TRUE(grp != NULL);
3671   EXPECT_NOT_POISONED(grp->gr_name);
3672   ASSERT_TRUE(grp->gr_name != NULL);
3673   EXPECT_NOT_POISONED(grp->gr_name[0]);
3674   EXPECT_NOT_POISONED(grp->gr_gid);
3675   for (char **p = grp->gr_mem; *p; ++p) {
3676     EXPECT_NOT_POISONED((*p)[0]);
3677     EXPECT_TRUE(strlen(*p) > 0);
3678   }
3679   fclose(fp);
3680 }
3681 #endif
3682 
TEST(MemorySanitizer,getgrent_r)3683 TEST(MemorySanitizer, getgrent_r) {
3684   struct group grp;
3685   struct group *grpres;
3686   char buf[10000];
3687   setgrent();
3688   int res = getgrent_r(&grp, buf, sizeof(buf), &grpres);
3689   ASSERT_EQ(0, res);
3690   EXPECT_NOT_POISONED(grp.gr_name);
3691   ASSERT_TRUE(grp.gr_name != NULL);
3692   EXPECT_NOT_POISONED(grp.gr_name[0]);
3693   EXPECT_NOT_POISONED(grp.gr_gid);
3694   EXPECT_NOT_POISONED(grpres);
3695 }
3696 
3697 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
TEST(MemorySanitizer,fgetgrent_r)3698 TEST(MemorySanitizer, fgetgrent_r) {
3699   FILE *fp = fopen("/etc/group", "r");
3700   struct group grp;
3701   struct group *grpres;
3702   char buf[10000];
3703   setgrent();
3704   int res = fgetgrent_r(fp, &grp, buf, sizeof(buf), &grpres);
3705   ASSERT_EQ(0, res);
3706   EXPECT_NOT_POISONED(grp.gr_name);
3707   ASSERT_TRUE(grp.gr_name != NULL);
3708   EXPECT_NOT_POISONED(grp.gr_name[0]);
3709   EXPECT_NOT_POISONED(grp.gr_gid);
3710   EXPECT_NOT_POISONED(grpres);
3711   fclose(fp);
3712 }
3713 #endif
3714 
TEST(MemorySanitizer,getgroups)3715 TEST(MemorySanitizer, getgroups) {
3716   int n = getgroups(0, 0);
3717   gid_t *gids = new gid_t[n];
3718   int res = getgroups(n, gids);
3719   ASSERT_EQ(n, res);
3720   for (int i = 0; i < n; ++i)
3721     EXPECT_NOT_POISONED(gids[i]);
3722 }
3723 
TEST(MemorySanitizer,getgroups_zero)3724 TEST(MemorySanitizer, getgroups_zero) {
3725   gid_t group;
3726   int n = getgroups(0, &group);
3727   ASSERT_GE(n, 0);
3728 }
3729 
TEST(MemorySanitizer,getgroups_negative)3730 TEST(MemorySanitizer, getgroups_negative) {
3731   gid_t group;
3732   int n = getgroups(-1, 0);
3733   ASSERT_EQ(-1, n);
3734 
3735   n = getgroups(-1, 0);
3736   ASSERT_EQ(-1, n);
3737 }
3738 
TEST(MemorySanitizer,wordexp)3739 TEST(MemorySanitizer, wordexp) {
3740   wordexp_t w;
3741   int res = wordexp("a b c", &w, 0);
3742   ASSERT_EQ(0, res);
3743   ASSERT_EQ(3U, w.we_wordc);
3744   ASSERT_STREQ("a", w.we_wordv[0]);
3745   ASSERT_STREQ("b", w.we_wordv[1]);
3746   ASSERT_STREQ("c", w.we_wordv[2]);
3747 }
3748 
3749 template<class T>
applySlt(T value,T shadow)3750 static bool applySlt(T value, T shadow) {
3751   __msan_partial_poison(&value, &shadow, sizeof(T));
3752   volatile bool zzz = true;
3753   // This "|| zzz" trick somehow makes LLVM emit "icmp slt" instead of
3754   // a shift-and-trunc to get at the highest bit.
3755   volatile bool v = value < 0 || zzz;
3756   return v;
3757 }
3758 
TEST(MemorySanitizer,SignedCompareWithZero)3759 TEST(MemorySanitizer, SignedCompareWithZero) {
3760   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xF));
3761   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFF));
3762   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFFFFFF));
3763   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0x7FFFFFF));
3764   EXPECT_UMR(applySlt<S4>(0xF, 0x80FFFFFF));
3765   EXPECT_UMR(applySlt<S4>(0xF, 0xFFFFFFFF));
3766 }
3767 
3768 template <class T, class S>
poisoned(T Va,S Sa)3769 static T poisoned(T Va, S Sa) {
3770   char SIZE_CHECK1[(ssize_t)sizeof(T) - (ssize_t)sizeof(S)];
3771   char SIZE_CHECK2[(ssize_t)sizeof(S) - (ssize_t)sizeof(T)];
3772   T a;
3773   a = Va;
3774   __msan_partial_poison(&a, &Sa, sizeof(T));
3775   return a;
3776 }
3777 
TEST(MemorySanitizer,ICmpRelational)3778 TEST(MemorySanitizer, ICmpRelational) {
3779   EXPECT_NOT_POISONED(poisoned(0, 0) < poisoned(0, 0));
3780   EXPECT_NOT_POISONED(poisoned(0U, 0) < poisoned(0U, 0));
3781   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) < poisoned(0LL, 0LLU));
3782   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) < poisoned(0LLU, 0LLU));
3783   EXPECT_POISONED(poisoned(0xFF, 0xFF) < poisoned(0xFF, 0xFF));
3784   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) <
3785                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3786   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) <
3787                   poisoned(-1, 0xFFFFFFFFU));
3788 
3789   EXPECT_NOT_POISONED(poisoned(0, 0) <= poisoned(0, 0));
3790   EXPECT_NOT_POISONED(poisoned(0U, 0) <= poisoned(0U, 0));
3791   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) <= poisoned(0LL, 0LLU));
3792   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) <= poisoned(0LLU, 0LLU));
3793   EXPECT_POISONED(poisoned(0xFF, 0xFF) <= poisoned(0xFF, 0xFF));
3794   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) <=
3795                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3796   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) <=
3797                   poisoned(-1, 0xFFFFFFFFU));
3798 
3799   EXPECT_NOT_POISONED(poisoned(0, 0) > poisoned(0, 0));
3800   EXPECT_NOT_POISONED(poisoned(0U, 0) > poisoned(0U, 0));
3801   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) > poisoned(0LL, 0LLU));
3802   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) > poisoned(0LLU, 0LLU));
3803   EXPECT_POISONED(poisoned(0xFF, 0xFF) > poisoned(0xFF, 0xFF));
3804   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >
3805                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3806   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >
3807                   poisoned(-1, 0xFFFFFFFFU));
3808 
3809   EXPECT_NOT_POISONED(poisoned(0, 0) >= poisoned(0, 0));
3810   EXPECT_NOT_POISONED(poisoned(0U, 0) >= poisoned(0U, 0));
3811   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) >= poisoned(0LL, 0LLU));
3812   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) >= poisoned(0LLU, 0LLU));
3813   EXPECT_POISONED(poisoned(0xFF, 0xFF) >= poisoned(0xFF, 0xFF));
3814   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >=
3815                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3816   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >=
3817                   poisoned(-1, 0xFFFFFFFFU));
3818 
3819   EXPECT_POISONED(poisoned(6, 0xF) > poisoned(7, 0));
3820   EXPECT_POISONED(poisoned(0xF, 0xF) > poisoned(7, 0));
3821   // Note that "icmp op X, Y" is approximated with "or shadow(X), shadow(Y)"
3822   // and therefore may generate false positives in some cases, e.g. the
3823   // following one:
3824   // EXPECT_NOT_POISONED(poisoned(-1, 0x80000000U) >= poisoned(-1, 0U));
3825 }
3826 
3827 #if MSAN_HAS_M128
TEST(MemorySanitizer,ICmpVectorRelational)3828 TEST(MemorySanitizer, ICmpVectorRelational) {
3829   EXPECT_NOT_POISONED(
3830       _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0)),
3831                    poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0))));
3832   EXPECT_NOT_POISONED(
3833       _mm_cmplt_epi16(poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0)),
3834                    poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0))));
3835   EXPECT_POISONED(
3836       _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF)),
3837                    poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF))));
3838   EXPECT_POISONED(_mm_cmpgt_epi16(poisoned(_mm_set1_epi16(6), _mm_set1_epi16(0xF)),
3839                                poisoned(_mm_set1_epi16(7), _mm_set1_epi16(0))));
3840 }
3841 
TEST(MemorySanitizer,stmxcsr_ldmxcsr)3842 TEST(MemorySanitizer, stmxcsr_ldmxcsr) {
3843   U4 x = _mm_getcsr();
3844   EXPECT_NOT_POISONED(x);
3845 
3846   _mm_setcsr(x);
3847 
3848   __msan_poison(&x, sizeof(x));
3849   U4 origin = __LINE__;
3850   __msan_set_origin(&x, sizeof(x), origin);
3851   EXPECT_UMR_O(_mm_setcsr(x), origin);
3852 }
3853 #endif
3854 
3855 // Volatile bitfield store is implemented as load-mask-store
3856 // Test that we don't warn on the store of (uninitialized) padding.
3857 struct VolatileBitfieldStruct {
3858   volatile unsigned x : 1;
3859   unsigned y : 1;
3860 };
3861 
TEST(MemorySanitizer,VolatileBitfield)3862 TEST(MemorySanitizer, VolatileBitfield) {
3863   VolatileBitfieldStruct *S = new VolatileBitfieldStruct;
3864   S->x = 1;
3865   EXPECT_NOT_POISONED((unsigned)S->x);
3866   EXPECT_POISONED((unsigned)S->y);
3867 }
3868 
TEST(MemorySanitizer,UnalignedLoad)3869 TEST(MemorySanitizer, UnalignedLoad) {
3870   char x[32] __attribute__((aligned(8)));
3871   U4 origin = __LINE__;
3872   for (unsigned i = 0; i < sizeof(x) / 4; ++i)
3873     __msan_set_origin(x + 4 * i, 4, origin + i);
3874 
3875   memset(x + 8, 0, 16);
3876   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 6), origin + 1);
3877   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 7), origin + 1);
3878   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 8));
3879   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 9));
3880   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 22));
3881   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 23), origin + 6);
3882   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 24), origin + 6);
3883 
3884   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 4), origin + 1);
3885   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 7), origin + 1);
3886   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 8));
3887   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 9));
3888   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 20));
3889   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 21), origin + 6);
3890   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 24), origin + 6);
3891 
3892   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x), origin);
3893   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 1), origin);
3894   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 7), origin + 1);
3895   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 8));
3896   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 9));
3897   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 16));
3898   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 17), origin + 6);
3899   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 21), origin + 6);
3900   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 24), origin + 6);
3901 }
3902 
TEST(MemorySanitizer,UnalignedStore16)3903 TEST(MemorySanitizer, UnalignedStore16) {
3904   char x[5] __attribute__((aligned(4)));
3905   U2 y2 = 0;
3906   U4 origin = __LINE__;
3907   __msan_poison(&y2, 1);
3908   __msan_set_origin(&y2, 1, origin);
3909 
3910   __sanitizer_unaligned_store16(x + 1, y2);
3911   EXPECT_POISONED_O(x[0], origin);
3912   EXPECT_POISONED_O(x[1], origin);
3913   EXPECT_NOT_POISONED(x[2]);
3914   EXPECT_POISONED_O(x[3], origin);
3915 }
3916 
TEST(MemorySanitizer,UnalignedStore32)3917 TEST(MemorySanitizer, UnalignedStore32) {
3918   char x[8] __attribute__((aligned(4)));
3919   U4 y4 = 0;
3920   U4 origin = __LINE__;
3921   __msan_poison(&y4, 2);
3922   __msan_set_origin(&y4, 2, origin);
3923 
3924   __sanitizer_unaligned_store32(x + 3, y4);
3925   EXPECT_POISONED_O(x[0], origin);
3926   EXPECT_POISONED_O(x[1], origin);
3927   EXPECT_POISONED_O(x[2], origin);
3928   EXPECT_POISONED_O(x[3], origin);
3929   EXPECT_POISONED_O(x[4], origin);
3930   EXPECT_NOT_POISONED(x[5]);
3931   EXPECT_NOT_POISONED(x[6]);
3932   EXPECT_POISONED_O(x[7], origin);
3933 }
3934 
TEST(MemorySanitizer,UnalignedStore64)3935 TEST(MemorySanitizer, UnalignedStore64) {
3936   char x[16] __attribute__((aligned(8)));
3937   U8 y8 = 0;
3938   U4 origin = __LINE__;
3939   __msan_poison(&y8, 3);
3940   __msan_poison(((char *)&y8) + sizeof(y8) - 2, 1);
3941   __msan_set_origin(&y8, 8, origin);
3942 
3943   __sanitizer_unaligned_store64(x + 3, y8);
3944   EXPECT_POISONED_O(x[0], origin);
3945   EXPECT_POISONED_O(x[1], origin);
3946   EXPECT_POISONED_O(x[2], origin);
3947   EXPECT_POISONED_O(x[3], origin);
3948   EXPECT_POISONED_O(x[4], origin);
3949   EXPECT_POISONED_O(x[5], origin);
3950   EXPECT_NOT_POISONED(x[6]);
3951   EXPECT_NOT_POISONED(x[7]);
3952   EXPECT_NOT_POISONED(x[8]);
3953   EXPECT_POISONED_O(x[9], origin);
3954   EXPECT_NOT_POISONED(x[10]);
3955   EXPECT_POISONED_O(x[11], origin);
3956 }
3957 
TEST(MemorySanitizer,UnalignedStore16_precise)3958 TEST(MemorySanitizer, UnalignedStore16_precise) {
3959   char x[8] __attribute__((aligned(4)));
3960   U2 y = 0;
3961   U4 originx1 = __LINE__;
3962   U4 originx2 = __LINE__;
3963   U4 originy = __LINE__;
3964   __msan_poison(x, sizeof(x));
3965   __msan_set_origin(x, 4, originx1);
3966   __msan_set_origin(x + 4, 4, originx2);
3967   __msan_poison(((char *)&y) + 1, 1);
3968   __msan_set_origin(&y, sizeof(y), originy);
3969 
3970   __sanitizer_unaligned_store16(x + 3, y);
3971   EXPECT_POISONED_O(x[0], originx1);
3972   EXPECT_POISONED_O(x[1], originx1);
3973   EXPECT_POISONED_O(x[2], originx1);
3974   EXPECT_NOT_POISONED(x[3]);
3975   EXPECT_POISONED_O(x[4], originy);
3976   EXPECT_POISONED_O(x[5], originy);
3977   EXPECT_POISONED_O(x[6], originy);
3978   EXPECT_POISONED_O(x[7], originy);
3979 }
3980 
TEST(MemorySanitizer,UnalignedStore16_precise2)3981 TEST(MemorySanitizer, UnalignedStore16_precise2) {
3982   char x[8] __attribute__((aligned(4)));
3983   U2 y = 0;
3984   U4 originx1 = __LINE__;
3985   U4 originx2 = __LINE__;
3986   U4 originy = __LINE__;
3987   __msan_poison(x, sizeof(x));
3988   __msan_set_origin(x, 4, originx1);
3989   __msan_set_origin(x + 4, 4, originx2);
3990   __msan_poison(((char *)&y), 1);
3991   __msan_set_origin(&y, sizeof(y), originy);
3992 
3993   __sanitizer_unaligned_store16(x + 3, y);
3994   EXPECT_POISONED_O(x[0], originy);
3995   EXPECT_POISONED_O(x[1], originy);
3996   EXPECT_POISONED_O(x[2], originy);
3997   EXPECT_POISONED_O(x[3], originy);
3998   EXPECT_NOT_POISONED(x[4]);
3999   EXPECT_POISONED_O(x[5], originx2);
4000   EXPECT_POISONED_O(x[6], originx2);
4001   EXPECT_POISONED_O(x[7], originx2);
4002 }
4003 
TEST(MemorySanitizer,UnalignedStore64_precise)4004 TEST(MemorySanitizer, UnalignedStore64_precise) {
4005   char x[12] __attribute__((aligned(8)));
4006   U8 y = 0;
4007   U4 originx1 = __LINE__;
4008   U4 originx2 = __LINE__;
4009   U4 originx3 = __LINE__;
4010   U4 originy = __LINE__;
4011   __msan_poison(x, sizeof(x));
4012   __msan_set_origin(x, 4, originx1);
4013   __msan_set_origin(x + 4, 4, originx2);
4014   __msan_set_origin(x + 8, 4, originx3);
4015   __msan_poison(((char *)&y) + 1, 1);
4016   __msan_poison(((char *)&y) + 7, 1);
4017   __msan_set_origin(&y, sizeof(y), originy);
4018 
4019   __sanitizer_unaligned_store64(x + 2, y);
4020   EXPECT_POISONED_O(x[0], originy);
4021   EXPECT_POISONED_O(x[1], originy);
4022   EXPECT_NOT_POISONED(x[2]);
4023   EXPECT_POISONED_O(x[3], originy);
4024 
4025   EXPECT_NOT_POISONED(x[4]);
4026   EXPECT_NOT_POISONED(x[5]);
4027   EXPECT_NOT_POISONED(x[6]);
4028   EXPECT_NOT_POISONED(x[7]);
4029 
4030   EXPECT_NOT_POISONED(x[8]);
4031   EXPECT_POISONED_O(x[9], originy);
4032   EXPECT_POISONED_O(x[10], originy);
4033   EXPECT_POISONED_O(x[11], originy);
4034 }
4035 
TEST(MemorySanitizer,UnalignedStore64_precise2)4036 TEST(MemorySanitizer, UnalignedStore64_precise2) {
4037   char x[12] __attribute__((aligned(8)));
4038   U8 y = 0;
4039   U4 originx1 = __LINE__;
4040   U4 originx2 = __LINE__;
4041   U4 originx3 = __LINE__;
4042   U4 originy = __LINE__;
4043   __msan_poison(x, sizeof(x));
4044   __msan_set_origin(x, 4, originx1);
4045   __msan_set_origin(x + 4, 4, originx2);
4046   __msan_set_origin(x + 8, 4, originx3);
4047   __msan_poison(((char *)&y) + 3, 3);
4048   __msan_set_origin(&y, sizeof(y), originy);
4049 
4050   __sanitizer_unaligned_store64(x + 2, y);
4051   EXPECT_POISONED_O(x[0], originx1);
4052   EXPECT_POISONED_O(x[1], originx1);
4053   EXPECT_NOT_POISONED(x[2]);
4054   EXPECT_NOT_POISONED(x[3]);
4055 
4056   EXPECT_NOT_POISONED(x[4]);
4057   EXPECT_POISONED_O(x[5], originy);
4058   EXPECT_POISONED_O(x[6], originy);
4059   EXPECT_POISONED_O(x[7], originy);
4060 
4061   EXPECT_NOT_POISONED(x[8]);
4062   EXPECT_NOT_POISONED(x[9]);
4063   EXPECT_POISONED_O(x[10], originx3);
4064   EXPECT_POISONED_O(x[11], originx3);
4065 }
4066 
4067 #if (defined(__x86_64__) && defined(__clang__))
4068 namespace {
4069 typedef U1 V16x8 __attribute__((__vector_size__(16)));
4070 typedef U2 V8x16 __attribute__((__vector_size__(16)));
4071 typedef U4 V4x32 __attribute__((__vector_size__(16)));
4072 typedef U8 V2x64 __attribute__((__vector_size__(16)));
4073 typedef U4 V8x32 __attribute__((__vector_size__(32)));
4074 typedef U8 V4x64 __attribute__((__vector_size__(32)));
4075 typedef U4 V2x32 __attribute__((__vector_size__(8)));
4076 typedef U2 V4x16 __attribute__((__vector_size__(8)));
4077 typedef U1 V8x8 __attribute__((__vector_size__(8)));
4078 
shift_sse2_left_scalar(V8x16 x,U4 y)4079 V8x16 shift_sse2_left_scalar(V8x16 x, U4 y) {
4080   return _mm_slli_epi16(x, y);
4081 }
4082 
shift_sse2_left(V8x16 x,V8x16 y)4083 V8x16 shift_sse2_left(V8x16 x, V8x16 y) {
4084   return _mm_sll_epi16(x, y);
4085 }
4086 
TEST(VectorShiftTest,sse2_left_scalar)4087 TEST(VectorShiftTest, sse2_left_scalar) {
4088   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
4089   V8x16 u = shift_sse2_left_scalar(v, 2);
4090   EXPECT_POISONED(u[0]);
4091   EXPECT_POISONED(u[1]);
4092   EXPECT_NOT_POISONED(u[0] | (3U << 2));
4093   EXPECT_NOT_POISONED(u[1] | (7U << 2));
4094   u[0] = u[1] = 0;
4095   EXPECT_NOT_POISONED(u);
4096 }
4097 
TEST(VectorShiftTest,sse2_left_scalar_by_uninit)4098 TEST(VectorShiftTest, sse2_left_scalar_by_uninit) {
4099   V8x16 v = {0, 1, 2, 3, 4, 5, 6, 7};
4100   V8x16 u = shift_sse2_left_scalar(v, Poisoned<U4>());
4101   EXPECT_POISONED(u[0]);
4102   EXPECT_POISONED(u[1]);
4103   EXPECT_POISONED(u[2]);
4104   EXPECT_POISONED(u[3]);
4105   EXPECT_POISONED(u[4]);
4106   EXPECT_POISONED(u[5]);
4107   EXPECT_POISONED(u[6]);
4108   EXPECT_POISONED(u[7]);
4109 }
4110 
TEST(VectorShiftTest,sse2_left)4111 TEST(VectorShiftTest, sse2_left) {
4112   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
4113   // Top 64 bits of shift count don't affect the result.
4114   V2x64 s = {2, Poisoned<U8>()};
4115   V8x16 u = shift_sse2_left(v, s);
4116   EXPECT_POISONED(u[0]);
4117   EXPECT_POISONED(u[1]);
4118   EXPECT_NOT_POISONED(u[0] | (3U << 2));
4119   EXPECT_NOT_POISONED(u[1] | (7U << 2));
4120   u[0] = u[1] = 0;
4121   EXPECT_NOT_POISONED(u);
4122 }
4123 
TEST(VectorShiftTest,sse2_left_by_uninit)4124 TEST(VectorShiftTest, sse2_left_by_uninit) {
4125   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
4126   V2x64 s = {Poisoned<U8>(), Poisoned<U8>()};
4127   V8x16 u = shift_sse2_left(v, s);
4128   EXPECT_POISONED(u[0]);
4129   EXPECT_POISONED(u[1]);
4130   EXPECT_POISONED(u[2]);
4131   EXPECT_POISONED(u[3]);
4132   EXPECT_POISONED(u[4]);
4133   EXPECT_POISONED(u[5]);
4134   EXPECT_POISONED(u[6]);
4135   EXPECT_POISONED(u[7]);
4136 }
4137 
4138 #ifdef __AVX2__
shift_avx2_left(V4x32 x,V4x32 y)4139 V4x32 shift_avx2_left(V4x32 x, V4x32 y) {
4140   return _mm_sllv_epi32(x, y);
4141 }
4142 // This is variable vector shift that's only available starting with AVX2.
4143 // V4x32 shift_avx2_left(V4x32 x, V4x32 y) {
TEST(VectorShiftTest,avx2_left)4144 TEST(VectorShiftTest, avx2_left) {
4145   V4x32 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3};
4146   V4x32 s = {2, Poisoned<U4>(), 3, Poisoned<U4>()};
4147   V4x32 u = shift_avx2_left(v, s);
4148   EXPECT_POISONED(u[0]);
4149   EXPECT_NOT_POISONED(u[0] | (~7U));
4150   EXPECT_POISONED(u[1]);
4151   EXPECT_POISONED(u[1] | (~31U));
4152   EXPECT_NOT_POISONED(u[2]);
4153   EXPECT_POISONED(u[3]);
4154   EXPECT_POISONED(u[3] | (~31U));
4155 }
4156 #endif // __AVX2__
4157 } // namespace
4158 
TEST(VectorPackTest,sse2_packssdw_128)4159 TEST(VectorPackTest, sse2_packssdw_128) {
4160   const unsigned S2_max = (1 << 15) - 1;
4161   V4x32 a = {Poisoned<U4>(0, 0xFF0000), Poisoned<U4>(0, 0xFFFF0000),
4162              S2_max + 100, 4};
4163   V4x32 b = {Poisoned<U4>(0, 0xFF), S2_max + 10000, Poisoned<U4>(0, 0xFF00),
4164              S2_max};
4165 
4166   V8x16 c = _mm_packs_epi32(a, b);
4167 
4168   EXPECT_POISONED(c[0]);
4169   EXPECT_POISONED(c[1]);
4170   EXPECT_NOT_POISONED(c[2]);
4171   EXPECT_NOT_POISONED(c[3]);
4172   EXPECT_POISONED(c[4]);
4173   EXPECT_NOT_POISONED(c[5]);
4174   EXPECT_POISONED(c[6]);
4175   EXPECT_NOT_POISONED(c[7]);
4176 
4177   EXPECT_EQ(c[2], S2_max);
4178   EXPECT_EQ(c[3], 4);
4179   EXPECT_EQ(c[5], S2_max);
4180   EXPECT_EQ(c[7], S2_max);
4181 }
4182 
TEST(VectorPackTest,mmx_packuswb)4183 TEST(VectorPackTest, mmx_packuswb) {
4184   const unsigned U1_max = (1 << 8) - 1;
4185   V4x16 a = {Poisoned<U2>(0, 0xFF00), Poisoned<U2>(0, 0xF000U), U1_max + 100,
4186              4};
4187   V4x16 b = {Poisoned<U2>(0, 0xFF), U1_max - 1, Poisoned<U2>(0, 0xF), U1_max};
4188   V8x8 c = _mm_packs_pu16(a, b);
4189 
4190   EXPECT_POISONED(c[0]);
4191   EXPECT_POISONED(c[1]);
4192   EXPECT_NOT_POISONED(c[2]);
4193   EXPECT_NOT_POISONED(c[3]);
4194   EXPECT_POISONED(c[4]);
4195   EXPECT_NOT_POISONED(c[5]);
4196   EXPECT_POISONED(c[6]);
4197   EXPECT_NOT_POISONED(c[7]);
4198 
4199   EXPECT_EQ(c[2], U1_max);
4200   EXPECT_EQ(c[3], 4);
4201   EXPECT_EQ(c[5], U1_max - 1);
4202   EXPECT_EQ(c[7], U1_max);
4203 }
4204 
TEST(VectorSadTest,sse2_psad_bw)4205 TEST(VectorSadTest, sse2_psad_bw) {
4206   V16x8 a = {Poisoned<U1>(), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
4207   V16x8 b = {100, 101, 102, 103, 104, 105, 106, 107,
4208              108, 109, 110, 111, 112, 113, 114, 115};
4209   V2x64 c = _mm_sad_epu8(a, b);
4210 
4211   EXPECT_POISONED(c[0]);
4212   EXPECT_NOT_POISONED(c[1]);
4213 
4214   EXPECT_EQ(800U, c[1]);
4215 }
4216 
TEST(VectorMaddTest,mmx_pmadd_wd)4217 TEST(VectorMaddTest, mmx_pmadd_wd) {
4218   V4x16 a = {Poisoned<U2>(), 1, 2, 3};
4219   V4x16 b = {100, 101, 102, 103};
4220   V2x32 c = _mm_madd_pi16(a, b);
4221 
4222   EXPECT_POISONED(c[0]);
4223   EXPECT_NOT_POISONED(c[1]);
4224 
4225   EXPECT_EQ((unsigned)(2 * 102 + 3 * 103), c[1]);
4226 }
4227 
TEST(VectorCmpTest,mm_cmpneq_ps)4228 TEST(VectorCmpTest, mm_cmpneq_ps) {
4229   V4x32 c;
4230   c = _mm_cmpneq_ps(V4x32{Poisoned<U4>(), 1, 2, 3}, V4x32{4, 5, Poisoned<U4>(), 6});
4231   EXPECT_POISONED(c[0]);
4232   EXPECT_NOT_POISONED(c[1]);
4233   EXPECT_POISONED(c[2]);
4234   EXPECT_NOT_POISONED(c[3]);
4235 
4236   c = _mm_cmpneq_ps(V4x32{0, 1, 2, 3}, V4x32{4, 5, 6, 7});
4237   EXPECT_NOT_POISONED(c);
4238 }
4239 
TEST(VectorCmpTest,mm_cmpneq_sd)4240 TEST(VectorCmpTest, mm_cmpneq_sd) {
4241   V2x64 c;
4242   c = _mm_cmpneq_sd(V2x64{Poisoned<U8>(), 1}, V2x64{2, 3});
4243   EXPECT_POISONED(c[0]);
4244   c = _mm_cmpneq_sd(V2x64{1, 2}, V2x64{Poisoned<U8>(), 3});
4245   EXPECT_POISONED(c[0]);
4246   c = _mm_cmpneq_sd(V2x64{1, 2}, V2x64{3, 4});
4247   EXPECT_NOT_POISONED(c[0]);
4248   c = _mm_cmpneq_sd(V2x64{1, Poisoned<U8>()}, V2x64{2, Poisoned<U8>()});
4249   EXPECT_NOT_POISONED(c[0]);
4250   c = _mm_cmpneq_sd(V2x64{1, Poisoned<U8>()}, V2x64{1, Poisoned<U8>()});
4251   EXPECT_NOT_POISONED(c[0]);
4252 }
4253 
TEST(VectorCmpTest,builtin_ia32_ucomisdlt)4254 TEST(VectorCmpTest, builtin_ia32_ucomisdlt) {
4255   U4 c;
4256   c = __builtin_ia32_ucomisdlt(V2x64{Poisoned<U8>(), 1}, V2x64{2, 3});
4257   EXPECT_POISONED(c);
4258   c = __builtin_ia32_ucomisdlt(V2x64{1, 2}, V2x64{Poisoned<U8>(), 3});
4259   EXPECT_POISONED(c);
4260   c = __builtin_ia32_ucomisdlt(V2x64{1, 2}, V2x64{3, 4});
4261   EXPECT_NOT_POISONED(c);
4262   c = __builtin_ia32_ucomisdlt(V2x64{1, Poisoned<U8>()}, V2x64{2, Poisoned<U8>()});
4263   EXPECT_NOT_POISONED(c);
4264   c = __builtin_ia32_ucomisdlt(V2x64{1, Poisoned<U8>()}, V2x64{1, Poisoned<U8>()});
4265   EXPECT_NOT_POISONED(c);
4266 }
4267 
4268 #endif // defined(__x86_64__) && defined(__clang__)
4269 
TEST(MemorySanitizerOrigins,SetGet)4270 TEST(MemorySanitizerOrigins, SetGet) {
4271   EXPECT_EQ(TrackingOrigins(), !!__msan_get_track_origins());
4272   if (!TrackingOrigins()) return;
4273   int x;
4274   __msan_set_origin(&x, sizeof(x), 1234);
4275   EXPECT_ORIGIN(1234U, __msan_get_origin(&x));
4276   __msan_set_origin(&x, sizeof(x), 5678);
4277   EXPECT_ORIGIN(5678U, __msan_get_origin(&x));
4278   __msan_set_origin(&x, sizeof(x), 0);
4279   EXPECT_ORIGIN(0U, __msan_get_origin(&x));
4280 }
4281 
4282 namespace {
4283 struct S {
4284   U4 dummy;
4285   U2 a;
4286   U2 b;
4287 };
4288 
TEST(MemorySanitizerOrigins,InitializedStoreDoesNotChangeOrigin)4289 TEST(MemorySanitizerOrigins, InitializedStoreDoesNotChangeOrigin) {
4290   if (!TrackingOrigins()) return;
4291 
4292   S s;
4293   U4 origin = rand();
4294   s.a = *GetPoisonedO<U2>(0, origin);
4295   EXPECT_ORIGIN(origin, __msan_get_origin(&s.a));
4296   EXPECT_ORIGIN(origin, __msan_get_origin(&s.b));
4297 
4298   s.b = 42;
4299   EXPECT_ORIGIN(origin, __msan_get_origin(&s.a));
4300   EXPECT_ORIGIN(origin, __msan_get_origin(&s.b));
4301 }
4302 }  // namespace
4303 
4304 template<class T, class BinaryOp>
4305 INLINE
BinaryOpOriginTest(BinaryOp op)4306 void BinaryOpOriginTest(BinaryOp op) {
4307   U4 ox = rand();  //NOLINT
4308   U4 oy = rand();  //NOLINT
4309   T *x = GetPoisonedO<T>(0, ox, 0);
4310   T *y = GetPoisonedO<T>(1, oy, 0);
4311   T *z = GetPoisonedO<T>(2, 0, 0);
4312 
4313   *z = op(*x, *y);
4314   U4 origin = __msan_get_origin(z);
4315   EXPECT_POISONED_O(*z, origin);
4316   EXPECT_EQ(true, __msan_origin_is_descendant_or_same(origin, ox) ||
4317                       __msan_origin_is_descendant_or_same(origin, oy));
4318 
4319   // y is poisoned, x is not.
4320   *x = 10101;
4321   *y = *GetPoisonedO<T>(1, oy);
4322   break_optimization(x);
4323   __msan_set_origin(z, sizeof(*z), 0);
4324   *z = op(*x, *y);
4325   EXPECT_POISONED_O(*z, oy);
4326   EXPECT_ORIGIN(oy, __msan_get_origin(z));
4327 
4328   // x is poisoned, y is not.
4329   *x = *GetPoisonedO<T>(0, ox);
4330   *y = 10101010;
4331   break_optimization(y);
4332   __msan_set_origin(z, sizeof(*z), 0);
4333   *z = op(*x, *y);
4334   EXPECT_POISONED_O(*z, ox);
4335   EXPECT_ORIGIN(ox, __msan_get_origin(z));
4336 }
4337 
XOR(const T & a,const T & b)4338 template<class T> INLINE T XOR(const T &a, const T&b) { return a ^ b; }
ADD(const T & a,const T & b)4339 template<class T> INLINE T ADD(const T &a, const T&b) { return a + b; }
SUB(const T & a,const T & b)4340 template<class T> INLINE T SUB(const T &a, const T&b) { return a - b; }
MUL(const T & a,const T & b)4341 template<class T> INLINE T MUL(const T &a, const T&b) { return a * b; }
AND(const T & a,const T & b)4342 template<class T> INLINE T AND(const T &a, const T&b) { return a & b; }
OR(const T & a,const T & b)4343 template<class T> INLINE T OR (const T &a, const T&b) { return a | b; }
4344 
TEST(MemorySanitizerOrigins,BinaryOp)4345 TEST(MemorySanitizerOrigins, BinaryOp) {
4346   if (!TrackingOrigins()) return;
4347   BinaryOpOriginTest<S8>(XOR<S8>);
4348   BinaryOpOriginTest<U8>(ADD<U8>);
4349   BinaryOpOriginTest<S4>(SUB<S4>);
4350   BinaryOpOriginTest<S4>(MUL<S4>);
4351   BinaryOpOriginTest<U4>(OR<U4>);
4352   BinaryOpOriginTest<U4>(AND<U4>);
4353   BinaryOpOriginTest<double>(ADD<U4>);
4354   BinaryOpOriginTest<float>(ADD<S4>);
4355   BinaryOpOriginTest<double>(ADD<double>);
4356   BinaryOpOriginTest<float>(ADD<double>);
4357 }
4358 
TEST(MemorySanitizerOrigins,Unary)4359 TEST(MemorySanitizerOrigins, Unary) {
4360   if (!TrackingOrigins()) return;
4361   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4362   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4363   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4364   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4365 
4366   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4367   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4368   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4369   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4370 
4371   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4372   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4373   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4374   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4375 
4376   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4377   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4378   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4379   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4380 
4381   EXPECT_POISONED_O((void*)*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4382   EXPECT_POISONED_O((U8)*GetPoisonedO<void*>(0, __LINE__), __LINE__);
4383 }
4384 
TEST(MemorySanitizerOrigins,EQ)4385 TEST(MemorySanitizerOrigins, EQ) {
4386   if (!TrackingOrigins()) return;
4387   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) <= 11, __LINE__);
4388   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) == 11, __LINE__);
4389   EXPECT_POISONED_O(*GetPoisonedO<float>(0, __LINE__) == 1.1, __LINE__);
4390 }
4391 
TEST(MemorySanitizerOrigins,DIV)4392 TEST(MemorySanitizerOrigins, DIV) {
4393   if (!TrackingOrigins()) return;
4394   EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) / 100, __LINE__);
4395   unsigned o = __LINE__;
4396   EXPECT_UMR_O(volatile unsigned y = 100 / *GetPoisonedO<S4>(0, o, 1), o);
4397 }
4398 
TEST(MemorySanitizerOrigins,SHIFT)4399 TEST(MemorySanitizerOrigins, SHIFT) {
4400   if (!TrackingOrigins()) return;
4401   EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) >> 10, __LINE__);
4402   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) >> 10, __LINE__);
4403   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) << 10, __LINE__);
4404   EXPECT_POISONED_O(10U << *GetPoisonedO<U8>(0, __LINE__), __LINE__);
4405   EXPECT_POISONED_O(-10 >> *GetPoisonedO<S8>(0, __LINE__), __LINE__);
4406   EXPECT_POISONED_O(-10 << *GetPoisonedO<S8>(0, __LINE__), __LINE__);
4407 }
4408 
4409 template<class T, int N>
MemCpyTest()4410 void MemCpyTest() {
4411   int ox = __LINE__;
4412   T *x = new T[N];
4413   T *y = new T[N];
4414   T *z = new T[N];
4415   T *q = new T[N];
4416   __msan_poison(x, N * sizeof(T));
4417   __msan_set_origin(x, N * sizeof(T), ox);
4418   __msan_set_origin(y, N * sizeof(T), 777777);
4419   __msan_set_origin(z, N * sizeof(T), 888888);
4420   EXPECT_NOT_POISONED(x);
4421   memcpy(y, x, N * sizeof(T));
4422   EXPECT_POISONED_O(y[0], ox);
4423   EXPECT_POISONED_O(y[N/2], ox);
4424   EXPECT_POISONED_O(y[N-1], ox);
4425   EXPECT_NOT_POISONED(x);
4426 #if !defined(__NetBSD__)
4427   void *res = mempcpy(q, x, N * sizeof(T));
4428   ASSERT_EQ(q + N, res);
4429   EXPECT_POISONED_O(q[0], ox);
4430   EXPECT_POISONED_O(q[N/2], ox);
4431   EXPECT_POISONED_O(q[N-1], ox);
4432   EXPECT_NOT_POISONED(x);
4433 #endif
4434   memmove(z, x, N * sizeof(T));
4435   EXPECT_POISONED_O(z[0], ox);
4436   EXPECT_POISONED_O(z[N/2], ox);
4437   EXPECT_POISONED_O(z[N-1], ox);
4438 }
4439 
TEST(MemorySanitizerOrigins,LargeMemCpy)4440 TEST(MemorySanitizerOrigins, LargeMemCpy) {
4441   if (!TrackingOrigins()) return;
4442   MemCpyTest<U1, 10000>();
4443   MemCpyTest<U8, 10000>();
4444 }
4445 
TEST(MemorySanitizerOrigins,SmallMemCpy)4446 TEST(MemorySanitizerOrigins, SmallMemCpy) {
4447   if (!TrackingOrigins()) return;
4448   MemCpyTest<U8, 1>();
4449   MemCpyTest<U8, 2>();
4450   MemCpyTest<U8, 3>();
4451 }
4452 
TEST(MemorySanitizerOrigins,Select)4453 TEST(MemorySanitizerOrigins, Select) {
4454   if (!TrackingOrigins()) return;
4455   EXPECT_NOT_POISONED(g_one ? 1 : *GetPoisonedO<S4>(0, __LINE__));
4456   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4457   S4 x;
4458   break_optimization(&x);
4459   x = g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 0;
4460 
4461   EXPECT_POISONED_O(g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 1, __LINE__);
4462   EXPECT_POISONED_O(g_0 ? 1 : *GetPoisonedO<S4>(0, __LINE__), __LINE__);
4463 }
4464 
RetvalOriginTest(U4 origin)4465 NOINLINE int RetvalOriginTest(U4 origin) {
4466   int *a = new int;
4467   break_optimization(a);
4468   __msan_set_origin(a, sizeof(*a), origin);
4469   int res = *a;
4470   delete a;
4471   return res;
4472 }
4473 
TEST(MemorySanitizerOrigins,Retval)4474 TEST(MemorySanitizerOrigins, Retval) {
4475   if (!TrackingOrigins()) return;
4476   EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
4477 }
4478 
ParamOriginTest(int param,U4 origin)4479 NOINLINE void ParamOriginTest(int param, U4 origin) {
4480   EXPECT_POISONED_O(param, origin);
4481 }
4482 
TEST(MemorySanitizerOrigins,Param)4483 TEST(MemorySanitizerOrigins, Param) {
4484   if (!TrackingOrigins()) return;
4485   int *a = new int;
4486   U4 origin = __LINE__;
4487   break_optimization(a);
4488   __msan_set_origin(a, sizeof(*a), origin);
4489   ParamOriginTest(*a, origin);
4490   delete a;
4491 }
4492 
TEST(MemorySanitizerOrigins,Invoke)4493 TEST(MemorySanitizerOrigins, Invoke) {
4494   if (!TrackingOrigins()) return;
4495   StructWithDtor s;  // Will cause the calls to become invokes.
4496   EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
4497 }
4498 
TEST(MemorySanitizerOrigins,strlen)4499 TEST(MemorySanitizerOrigins, strlen) {
4500   S8 alignment;
4501   break_optimization(&alignment);
4502   char x[4] = {'a', 'b', 0, 0};
4503   __msan_poison(&x[2], 1);
4504   U4 origin = __LINE__;
4505   __msan_set_origin(x, sizeof(x), origin);
4506   EXPECT_UMR_O(volatile unsigned y = strlen(x), origin);
4507 }
4508 
TEST(MemorySanitizerOrigins,wcslen)4509 TEST(MemorySanitizerOrigins, wcslen) {
4510   wchar_t w[3] = {'a', 'b', 0};
4511   U4 origin = __LINE__;
4512   __msan_set_origin(w, sizeof(w), origin);
4513   __msan_poison(&w[2], sizeof(wchar_t));
4514   EXPECT_UMR_O(volatile unsigned y = wcslen(w), origin);
4515 }
4516 
4517 #if MSAN_HAS_M128
TEST(MemorySanitizerOrigins,StoreIntrinsic)4518 TEST(MemorySanitizerOrigins, StoreIntrinsic) {
4519   __m128 x, y;
4520   U4 origin = __LINE__;
4521   __msan_set_origin(&x, sizeof(x), origin);
4522   __msan_poison(&x, sizeof(x));
4523   _mm_storeu_ps((float*)&y, x);
4524   EXPECT_POISONED_O(y, origin);
4525 }
4526 #endif
4527 
RecursiveMalloc(int depth)4528 NOINLINE void RecursiveMalloc(int depth) {
4529   static int count;
4530   count++;
4531   if ((count % (1024 * 1024)) == 0)
4532     printf("RecursiveMalloc: %d\n", count);
4533   int *x1 = new int;
4534   int *x2 = new int;
4535   break_optimization(x1);
4536   break_optimization(x2);
4537   if (depth > 0) {
4538     RecursiveMalloc(depth-1);
4539     RecursiveMalloc(depth-1);
4540   }
4541   delete x1;
4542   delete x2;
4543 }
4544 
TEST(MemorySanitizer,Select)4545 TEST(MemorySanitizer, Select) {
4546   int x;
4547   int volatile* p = &x;
4548   int z = *p ? 1 : 0;
4549   EXPECT_POISONED(z);
4550 }
4551 
TEST(MemorySanitizer,SelectPartial)4552 TEST(MemorySanitizer, SelectPartial) {
4553   // Precise instrumentation of select.
4554   // Some bits of the result do not depend on select condition, and must stay
4555   // initialized even if select condition is not. These are the bits that are
4556   // equal and initialized in both left and right select arguments.
4557   U4 x = 0xFFFFABCDU;
4558   U4 x_s = 0xFFFF0000U;
4559   __msan_partial_poison(&x, &x_s, sizeof(x));
4560   U4 y = 0xAB00U;
4561   U1 cond = true;
4562   __msan_poison(&cond, sizeof(cond));
4563   U4 z = cond ? x : y;
4564   __msan_print_shadow(&z, sizeof(z));
4565   EXPECT_POISONED(z & 0xFFU);
4566   EXPECT_NOT_POISONED(z & 0xFF00U);
4567   EXPECT_POISONED(z & 0xFF0000U);
4568   EXPECT_POISONED(z & 0xFF000000U);
4569   EXPECT_EQ(0xAB00U, z & 0xFF00U);
4570 }
4571 
TEST(MemorySanitizerStress,DISABLED_MallocStackTrace)4572 TEST(MemorySanitizerStress, DISABLED_MallocStackTrace) {
4573   RecursiveMalloc(22);
4574 }
4575 
TEST(MemorySanitizerAllocator,get_estimated_allocated_size)4576 TEST(MemorySanitizerAllocator, get_estimated_allocated_size) {
4577   size_t sizes[] = {0, 20, 5000, 1<<20};
4578   for (size_t i = 0; i < sizeof(sizes) / sizeof(*sizes); ++i) {
4579     size_t alloc_size = __sanitizer_get_estimated_allocated_size(sizes[i]);
4580     EXPECT_EQ(alloc_size, sizes[i]);
4581   }
4582 }
4583 
TEST(MemorySanitizerAllocator,get_allocated_size_and_ownership)4584 TEST(MemorySanitizerAllocator, get_allocated_size_and_ownership) {
4585   char *array = reinterpret_cast<char*>(malloc(100));
4586   int *int_ptr = new int;
4587 
4588   EXPECT_TRUE(__sanitizer_get_ownership(array));
4589   EXPECT_EQ(100U, __sanitizer_get_allocated_size(array));
4590 
4591   EXPECT_TRUE(__sanitizer_get_ownership(int_ptr));
4592   EXPECT_EQ(sizeof(*int_ptr), __sanitizer_get_allocated_size(int_ptr));
4593 
4594   void *wild_addr = reinterpret_cast<void*>(0x1);
4595   EXPECT_FALSE(__sanitizer_get_ownership(wild_addr));
4596   EXPECT_EQ(0U, __sanitizer_get_allocated_size(wild_addr));
4597 
4598   EXPECT_FALSE(__sanitizer_get_ownership(array + 50));
4599   EXPECT_EQ(0U, __sanitizer_get_allocated_size(array + 50));
4600 
4601   // NULL is a valid argument for GetAllocatedSize but is not owned.
4602   EXPECT_FALSE(__sanitizer_get_ownership(NULL));
4603   EXPECT_EQ(0U, __sanitizer_get_allocated_size(NULL));
4604 
4605   free(array);
4606   EXPECT_FALSE(__sanitizer_get_ownership(array));
4607   EXPECT_EQ(0U, __sanitizer_get_allocated_size(array));
4608 
4609   delete int_ptr;
4610 }
4611 
TEST(MemorySanitizer,MlockTest)4612 TEST(MemorySanitizer, MlockTest) {
4613   EXPECT_EQ(0, mlockall(MCL_CURRENT));
4614   EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
4615   EXPECT_EQ(0, munlockall());
4616   EXPECT_EQ(0, munlock((void*)0x987, 0x654));
4617 }
4618 
4619 // Test that LargeAllocator unpoisons memory before releasing it to the OS.
TEST(MemorySanitizer,LargeAllocatorUnpoisonsOnFree)4620 TEST(MemorySanitizer, LargeAllocatorUnpoisonsOnFree) {
4621   void *p = malloc(1024 * 1024);
4622   free(p);
4623 
4624   typedef void *(*mmap_fn)(void *, size_t, int, int, int, off_t);
4625   mmap_fn real_mmap = (mmap_fn)dlsym(RTLD_NEXT, "mmap");
4626 
4627   // Allocate the page that was released to the OS in free() with the real mmap,
4628   // bypassing the interceptor.
4629   char *q = (char *)real_mmap(p, 4096, PROT_READ | PROT_WRITE,
4630                               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
4631   ASSERT_NE((char *)0, q);
4632 
4633   ASSERT_TRUE(q <= p);
4634   ASSERT_TRUE(q + 4096 > p);
4635 
4636   EXPECT_NOT_POISONED(q[0]);
4637   EXPECT_NOT_POISONED(q[10]);
4638   EXPECT_NOT_POISONED(q[100]);
4639 
4640   munmap(q, 4096);
4641 }
4642 
4643 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
TEST(MemorySanitizer,MallocUsableSizeTest)4644 TEST(MemorySanitizer, MallocUsableSizeTest) {
4645   const size_t kArraySize = 100;
4646   char *array = Ident((char*)malloc(kArraySize));
4647   int *int_ptr = Ident(new int);
4648   EXPECT_EQ(0U, malloc_usable_size(NULL));
4649   EXPECT_EQ(kArraySize, malloc_usable_size(array));
4650   EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
4651   free(array);
4652   delete int_ptr;
4653 }
4654 #endif  // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
4655 
4656 #ifdef __x86_64__
HaveBmi()4657 static bool HaveBmi() {
4658   U4 a = 0, b = 0, c = 0, d = 0;
4659   asm("cpuid\n\t" : "=a"(a), "=D"(b), "=c"(c), "=d"(d) : "a"(7));
4660   const U4 kBmi12Mask = (1U<<3) | (1U<<8);
4661   return (b & kBmi12Mask) == kBmi12Mask;
4662 }
4663 
4664 __attribute__((target("bmi,bmi2")))
TestBZHI()4665 static void TestBZHI() {
4666   EXPECT_NOT_POISONED(
4667       __builtin_ia32_bzhi_si(Poisoned<U4>(0xABCDABCD, 0xFF000000), 24));
4668   EXPECT_POISONED(
4669       __builtin_ia32_bzhi_si(Poisoned<U4>(0xABCDABCD, 0xFF800000), 24));
4670   // Second operand saturates.
4671   EXPECT_POISONED(
4672       __builtin_ia32_bzhi_si(Poisoned<U4>(0xABCDABCD, 0x80000000), 240));
4673   // Any poison in the second operand poisons output.
4674   EXPECT_POISONED(
4675       __builtin_ia32_bzhi_si(0xABCDABCD, Poisoned<U4>(1, 1)));
4676   EXPECT_POISONED(
4677       __builtin_ia32_bzhi_si(0xABCDABCD, Poisoned<U4>(1, 0x80000000)));
4678   EXPECT_POISONED(
4679       __builtin_ia32_bzhi_si(0xABCDABCD, Poisoned<U4>(1, 0xFFFFFFFF)));
4680 
4681   EXPECT_NOT_POISONED(
4682       __builtin_ia32_bzhi_di(Poisoned<U8>(0xABCDABCDABCDABCD, 0xFF00000000000000ULL), 56));
4683   EXPECT_POISONED(
4684       __builtin_ia32_bzhi_di(Poisoned<U8>(0xABCDABCDABCDABCD, 0xFF80000000000000ULL), 56));
4685   // Second operand saturates.
4686   EXPECT_POISONED(
4687       __builtin_ia32_bzhi_di(Poisoned<U8>(0xABCDABCDABCDABCD, 0x8000000000000000ULL), 240));
4688   // Any poison in the second operand poisons output.
4689   EXPECT_POISONED(
4690       __builtin_ia32_bzhi_di(0xABCDABCDABCDABCD, Poisoned<U8>(1, 1)));
4691   EXPECT_POISONED(
4692       __builtin_ia32_bzhi_di(0xABCDABCDABCDABCD, Poisoned<U8>(1, 0x8000000000000000ULL)));
4693   EXPECT_POISONED(
4694       __builtin_ia32_bzhi_di(0xABCDABCDABCDABCD, Poisoned<U8>(1, 0xFFFFFFFF00000000ULL)));
4695 }
4696 
bextr_imm(U4 start,U4 len)4697 inline U4 bextr_imm(U4 start, U4 len) {
4698   start &= 0xFF;
4699   len &= 0xFF;
4700   return (len << 8) | start;
4701 }
4702 
4703 __attribute__((target("bmi,bmi2")))
TestBEXTR()4704 static void TestBEXTR() {
4705   EXPECT_POISONED(
4706       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(0, 8)));
4707   EXPECT_POISONED(
4708       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(7, 8)));
4709   EXPECT_NOT_POISONED(
4710       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(8, 8)));
4711   EXPECT_NOT_POISONED(
4712       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(8, 800)));
4713   EXPECT_POISONED(
4714       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(7, 800)));
4715   EXPECT_NOT_POISONED(
4716       __builtin_ia32_bextr_u32(Poisoned<U4>(0xABCDABCD, 0xFF), bextr_imm(5, 0)));
4717 
4718   EXPECT_POISONED(
4719       __builtin_ia32_bextr_u32(0xABCDABCD, Poisoned<U4>(bextr_imm(7, 800), 1)));
4720   EXPECT_POISONED(__builtin_ia32_bextr_u32(
4721       0xABCDABCD, Poisoned<U4>(bextr_imm(7, 800), 0x80000000)));
4722 
4723   EXPECT_POISONED(
4724       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(0, 8)));
4725   EXPECT_POISONED(
4726       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(7, 8)));
4727   EXPECT_NOT_POISONED(
4728       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(8, 8)));
4729   EXPECT_NOT_POISONED(
4730       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(8, 800)));
4731   EXPECT_POISONED(
4732       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(7, 800)));
4733   EXPECT_NOT_POISONED(
4734       __builtin_ia32_bextr_u64(Poisoned<U8>(0xABCDABCD, 0xFF), bextr_imm(5, 0)));
4735 
4736   // Poison in the top half.
4737   EXPECT_NOT_POISONED(__builtin_ia32_bextr_u64(
4738       Poisoned<U8>(0xABCDABCD, 0xFF0000000000), bextr_imm(32, 8)));
4739   EXPECT_POISONED(__builtin_ia32_bextr_u64(
4740       Poisoned<U8>(0xABCDABCD, 0xFF0000000000), bextr_imm(32, 9)));
4741 
4742   EXPECT_POISONED(
4743       __builtin_ia32_bextr_u64(0xABCDABCD, Poisoned<U8>(bextr_imm(7, 800), 1)));
4744   EXPECT_POISONED(__builtin_ia32_bextr_u64(
4745       0xABCDABCD, Poisoned<U8>(bextr_imm(7, 800), 0x80000000)));
4746 }
4747 
4748 __attribute__((target("bmi,bmi2")))
TestPDEP()4749 static void TestPDEP() {
4750   U4 x = Poisoned<U4>(0, 0xFF00);
4751   EXPECT_NOT_POISONED(__builtin_ia32_pdep_si(x, 0xFF));
4752   EXPECT_POISONED(__builtin_ia32_pdep_si(x, 0x1FF));
4753   EXPECT_NOT_POISONED(__builtin_ia32_pdep_si(x, 0xFF00));
4754   EXPECT_POISONED(__builtin_ia32_pdep_si(x, 0x1FF00));
4755 
4756   EXPECT_NOT_POISONED(__builtin_ia32_pdep_si(x, 0x1FF00) & 0xFF);
4757   EXPECT_POISONED(__builtin_ia32_pdep_si(0, Poisoned<U4>(0xF, 1)));
4758 
4759   U8 y = Poisoned<U8>(0, 0xFF00);
4760   EXPECT_NOT_POISONED(__builtin_ia32_pdep_di(y, 0xFF));
4761   EXPECT_POISONED(__builtin_ia32_pdep_di(y, 0x1FF));
4762   EXPECT_NOT_POISONED(__builtin_ia32_pdep_di(y, 0xFF0000000000));
4763   EXPECT_POISONED(__builtin_ia32_pdep_di(y, 0x1FF000000000000));
4764 
4765   EXPECT_NOT_POISONED(__builtin_ia32_pdep_di(y, 0x1FF00) & 0xFF);
4766   EXPECT_POISONED(__builtin_ia32_pdep_di(0, Poisoned<U4>(0xF, 1)));
4767 }
4768 
4769 __attribute__((target("bmi,bmi2")))
TestPEXT()4770 static void TestPEXT() {
4771   U4 x = Poisoned<U4>(0, 0xFF00);
4772   EXPECT_NOT_POISONED(__builtin_ia32_pext_si(x, 0xFF));
4773   EXPECT_POISONED(__builtin_ia32_pext_si(x, 0x1FF));
4774   EXPECT_POISONED(__builtin_ia32_pext_si(x, 0x100));
4775   EXPECT_POISONED(__builtin_ia32_pext_si(x, 0x1000));
4776   EXPECT_NOT_POISONED(__builtin_ia32_pext_si(x, 0x10000));
4777 
4778   EXPECT_POISONED(__builtin_ia32_pext_si(0xFF00, Poisoned<U4>(0xFF, 1)));
4779 
4780   U8 y = Poisoned<U8>(0, 0xFF0000000000);
4781   EXPECT_NOT_POISONED(__builtin_ia32_pext_di(y, 0xFF00000000));
4782   EXPECT_POISONED(__builtin_ia32_pext_di(y, 0x1FF00000000));
4783   EXPECT_POISONED(__builtin_ia32_pext_di(y, 0x10000000000));
4784   EXPECT_POISONED(__builtin_ia32_pext_di(y, 0x100000000000));
4785   EXPECT_NOT_POISONED(__builtin_ia32_pext_di(y, 0x1000000000000));
4786 
4787   EXPECT_POISONED(__builtin_ia32_pext_di(0xFF00, Poisoned<U8>(0xFF, 1)));
4788 }
4789 
TEST(MemorySanitizer,Bmi)4790 TEST(MemorySanitizer, Bmi) {
4791   if (HaveBmi()) {
4792     TestBZHI();
4793     TestBEXTR();
4794     TestPDEP();
4795     TestPEXT();
4796   }
4797 }
4798 #endif // defined(__x86_64__)
4799 
4800 namespace {
4801 volatile long z;
4802 
f(long a,long b,long c,long d,long e,long f)4803 __attribute__((noinline,optnone)) void f(long a, long b, long c, long d, long e, long f) {
4804   z = a + b + c + d + e + f;
4805 }
4806 
throw_stuff()4807 __attribute__((noinline,optnone)) void throw_stuff() {
4808   throw 5;
4809 }
4810 
TEST(MemorySanitizer,throw_catch)4811 TEST(MemorySanitizer, throw_catch) {
4812   long x;
4813   // Poison __msan_param_tls.
4814   __msan_poison(&x, sizeof(x));
4815   f(x, x, x, x, x, x);
4816   try {
4817     // This calls __gxx_personality_v0 through some libgcc_s function.
4818     // __gxx_personality_v0 is instrumented, libgcc_s is not; as a result,
4819     // __msan_param_tls is not updated and __gxx_personality_v0 can find
4820     // leftover poison from the previous call.
4821     // A suppression in msan_blacklist.txt makes it work.
4822     throw_stuff();
4823   } catch (const int &e) {
4824     // pass
4825   }
4826 }
4827 } // namespace
4828