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