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