• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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], L'\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,wcrtomb)1955 TEST(MemorySanitizer, wcrtomb) {
1956   wchar_t x = L'a';
1957   char buff[10];
1958   mbstate_t mbs;
1959   memset(&mbs, 0, sizeof(mbs));
1960   size_t res = wcrtomb(buff, x, &mbs);
1961   EXPECT_EQ(res, (size_t)1);
1962   EXPECT_EQ(buff[0], 'a');
1963 }
1964 
TEST(MemorySanitizer,wmemset)1965 TEST(MemorySanitizer, wmemset) {
1966     wchar_t x[25];
1967     break_optimization(x);
1968     EXPECT_POISONED(x[0]);
1969     wmemset(x, L'A', 10);
1970     EXPECT_EQ(x[0], L'A');
1971     EXPECT_EQ(x[9], L'A');
1972     EXPECT_POISONED(x[10]);
1973 }
1974 
TEST(MemorySanitizer,mbtowc)1975 TEST(MemorySanitizer, mbtowc) {
1976   const char *x = "abc";
1977   wchar_t wx;
1978   int res = mbtowc(&wx, x, 3);
1979   EXPECT_GT(res, 0);
1980   EXPECT_NOT_POISONED(wx);
1981 }
1982 
TEST(MemorySanitizer,mbrtowc)1983 TEST(MemorySanitizer, mbrtowc) {
1984   const char *x = "abc";
1985   wchar_t wx;
1986   mbstate_t mbs;
1987   memset(&mbs, 0, sizeof(mbs));
1988   int res = mbrtowc(&wx, x, 3, &mbs);
1989   EXPECT_GT(res, 0);
1990   EXPECT_NOT_POISONED(wx);
1991 }
1992 
TEST(MemorySanitizer,wcsftime)1993 TEST(MemorySanitizer, wcsftime) {
1994   wchar_t x[100];
1995   time_t t = time(NULL);
1996   struct tm tms;
1997   struct tm *tmres = localtime_r(&t, &tms);
1998   ASSERT_NE((void *)0, tmres);
1999   size_t res = wcsftime(x, sizeof(x) / sizeof(x[0]), L"%Y-%m-%d", tmres);
2000   EXPECT_GT(res, 0UL);
2001   EXPECT_EQ(res, wcslen(x));
2002 }
2003 
TEST(MemorySanitizer,gettimeofday)2004 TEST(MemorySanitizer, gettimeofday) {
2005   struct timeval tv;
2006   struct timezone tz;
2007   break_optimization(&tv);
2008   break_optimization(&tz);
2009   ASSERT_EQ(16U, sizeof(tv));
2010   ASSERT_EQ(8U, sizeof(tz));
2011   EXPECT_POISONED(tv.tv_sec);
2012   EXPECT_POISONED(tv.tv_usec);
2013   EXPECT_POISONED(tz.tz_minuteswest);
2014   EXPECT_POISONED(tz.tz_dsttime);
2015   ASSERT_EQ(0, gettimeofday(&tv, &tz));
2016   EXPECT_NOT_POISONED(tv.tv_sec);
2017   EXPECT_NOT_POISONED(tv.tv_usec);
2018   EXPECT_NOT_POISONED(tz.tz_minuteswest);
2019   EXPECT_NOT_POISONED(tz.tz_dsttime);
2020 }
2021 
TEST(MemorySanitizer,clock_gettime)2022 TEST(MemorySanitizer, clock_gettime) {
2023   struct timespec tp;
2024   EXPECT_POISONED(tp.tv_sec);
2025   EXPECT_POISONED(tp.tv_nsec);
2026   ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &tp));
2027   EXPECT_NOT_POISONED(tp.tv_sec);
2028   EXPECT_NOT_POISONED(tp.tv_nsec);
2029 }
2030 
TEST(MemorySanitizer,clock_getres)2031 TEST(MemorySanitizer, clock_getres) {
2032   struct timespec tp;
2033   EXPECT_POISONED(tp.tv_sec);
2034   EXPECT_POISONED(tp.tv_nsec);
2035   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, 0));
2036   EXPECT_POISONED(tp.tv_sec);
2037   EXPECT_POISONED(tp.tv_nsec);
2038   ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &tp));
2039   EXPECT_NOT_POISONED(tp.tv_sec);
2040   EXPECT_NOT_POISONED(tp.tv_nsec);
2041 }
2042 
TEST(MemorySanitizer,getitimer)2043 TEST(MemorySanitizer, getitimer) {
2044   struct itimerval it1, it2;
2045   int res;
2046   EXPECT_POISONED(it1.it_interval.tv_sec);
2047   EXPECT_POISONED(it1.it_interval.tv_usec);
2048   EXPECT_POISONED(it1.it_value.tv_sec);
2049   EXPECT_POISONED(it1.it_value.tv_usec);
2050   res = getitimer(ITIMER_VIRTUAL, &it1);
2051   ASSERT_EQ(0, res);
2052   EXPECT_NOT_POISONED(it1.it_interval.tv_sec);
2053   EXPECT_NOT_POISONED(it1.it_interval.tv_usec);
2054   EXPECT_NOT_POISONED(it1.it_value.tv_sec);
2055   EXPECT_NOT_POISONED(it1.it_value.tv_usec);
2056 
2057   it1.it_interval.tv_sec = it1.it_value.tv_sec = 10000;
2058   it1.it_interval.tv_usec = it1.it_value.tv_usec = 0;
2059 
2060   res = setitimer(ITIMER_VIRTUAL, &it1, &it2);
2061   ASSERT_EQ(0, res);
2062   EXPECT_NOT_POISONED(it2.it_interval.tv_sec);
2063   EXPECT_NOT_POISONED(it2.it_interval.tv_usec);
2064   EXPECT_NOT_POISONED(it2.it_value.tv_sec);
2065   EXPECT_NOT_POISONED(it2.it_value.tv_usec);
2066 
2067   // Check that old_value can be 0, and disable the timer.
2068   memset(&it1, 0, sizeof(it1));
2069   res = setitimer(ITIMER_VIRTUAL, &it1, 0);
2070   ASSERT_EQ(0, res);
2071 }
2072 
TEST(MemorySanitizer,setitimer_null)2073 TEST(MemorySanitizer, setitimer_null) {
2074   setitimer(ITIMER_VIRTUAL, 0, 0);
2075   // Not testing the return value, since it the behaviour seems to differ
2076   // between libc implementations and POSIX.
2077   // Should never crash, though.
2078 }
2079 
TEST(MemorySanitizer,time)2080 TEST(MemorySanitizer, time) {
2081   time_t t;
2082   EXPECT_POISONED(t);
2083   time_t t2 = time(&t);
2084   ASSERT_NE(t2, (time_t)-1);
2085   EXPECT_NOT_POISONED(t);
2086 }
2087 
TEST(MemorySanitizer,strptime)2088 TEST(MemorySanitizer, strptime) {
2089   struct tm time;
2090   char *p = strptime("11/1/2013-05:39", "%m/%d/%Y-%H:%M", &time);
2091   ASSERT_TRUE(p != NULL);
2092   EXPECT_NOT_POISONED(time.tm_sec);
2093   EXPECT_NOT_POISONED(time.tm_hour);
2094   EXPECT_NOT_POISONED(time.tm_year);
2095 }
2096 
TEST(MemorySanitizer,localtime)2097 TEST(MemorySanitizer, localtime) {
2098   time_t t = 123;
2099   struct tm *time = localtime(&t);
2100   ASSERT_TRUE(time != NULL);
2101   EXPECT_NOT_POISONED(time->tm_sec);
2102   EXPECT_NOT_POISONED(time->tm_hour);
2103   EXPECT_NOT_POISONED(time->tm_year);
2104   EXPECT_NOT_POISONED(time->tm_isdst);
2105   EXPECT_NE(0U, strlen(time->tm_zone));
2106 }
2107 
TEST(MemorySanitizer,localtime_r)2108 TEST(MemorySanitizer, localtime_r) {
2109   time_t t = 123;
2110   struct tm time;
2111   struct tm *res = localtime_r(&t, &time);
2112   ASSERT_TRUE(res != NULL);
2113   EXPECT_NOT_POISONED(time.tm_sec);
2114   EXPECT_NOT_POISONED(time.tm_hour);
2115   EXPECT_NOT_POISONED(time.tm_year);
2116   EXPECT_NOT_POISONED(time.tm_isdst);
2117   EXPECT_NE(0U, strlen(time.tm_zone));
2118 }
2119 
2120 // There's no getmntent() on FreeBSD.
2121 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,getmntent)2122 TEST(MemorySanitizer, getmntent) {
2123   FILE *fp = setmntent("/etc/fstab", "r");
2124   struct mntent *mnt = getmntent(fp);
2125   ASSERT_TRUE(mnt != NULL);
2126   ASSERT_NE(0U, strlen(mnt->mnt_fsname));
2127   ASSERT_NE(0U, strlen(mnt->mnt_dir));
2128   ASSERT_NE(0U, strlen(mnt->mnt_type));
2129   ASSERT_NE(0U, strlen(mnt->mnt_opts));
2130   EXPECT_NOT_POISONED(mnt->mnt_freq);
2131   EXPECT_NOT_POISONED(mnt->mnt_passno);
2132   fclose(fp);
2133 }
2134 #endif
2135 
2136 // There's no getmntent_r() on FreeBSD.
2137 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,getmntent_r)2138 TEST(MemorySanitizer, getmntent_r) {
2139   FILE *fp = setmntent("/etc/fstab", "r");
2140   struct mntent mntbuf;
2141   char buf[1000];
2142   struct mntent *mnt = getmntent_r(fp, &mntbuf, buf, sizeof(buf));
2143   ASSERT_TRUE(mnt != NULL);
2144   ASSERT_NE(0U, strlen(mnt->mnt_fsname));
2145   ASSERT_NE(0U, strlen(mnt->mnt_dir));
2146   ASSERT_NE(0U, strlen(mnt->mnt_type));
2147   ASSERT_NE(0U, strlen(mnt->mnt_opts));
2148   EXPECT_NOT_POISONED(mnt->mnt_freq);
2149   EXPECT_NOT_POISONED(mnt->mnt_passno);
2150   fclose(fp);
2151 }
2152 #endif
2153 
TEST(MemorySanitizer,ether)2154 TEST(MemorySanitizer, ether) {
2155   const char *asc = "11:22:33:44:55:66";
2156   struct ether_addr *paddr = ether_aton(asc);
2157   EXPECT_NOT_POISONED(*paddr);
2158 
2159   struct ether_addr addr;
2160   paddr = ether_aton_r(asc, &addr);
2161   ASSERT_EQ(paddr, &addr);
2162   EXPECT_NOT_POISONED(addr);
2163 
2164   char *s = ether_ntoa(&addr);
2165   ASSERT_NE(0U, strlen(s));
2166 
2167   char buf[100];
2168   s = ether_ntoa_r(&addr, buf);
2169   ASSERT_EQ(s, buf);
2170   ASSERT_NE(0U, strlen(buf));
2171 }
2172 
TEST(MemorySanitizer,mmap)2173 TEST(MemorySanitizer, mmap) {
2174   const int size = 4096;
2175   void *p1, *p2;
2176   p1 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
2177   __msan_poison(p1, size);
2178   munmap(p1, size);
2179   for (int i = 0; i < 1000; i++) {
2180     p2 = mmap(0, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANON, -1, 0);
2181     if (p2 == p1)
2182       break;
2183     else
2184       munmap(p2, size);
2185   }
2186   if (p1 == p2) {
2187     EXPECT_NOT_POISONED(*(char*)p2);
2188     munmap(p2, size);
2189   }
2190 }
2191 
2192 // There's no fcvt() on FreeBSD.
2193 #if !defined(__FreeBSD__)
2194 // FIXME: enable and add ecvt.
2195 // FIXME: check why msandr does nt handle fcvt.
TEST(MemorySanitizer,fcvt)2196 TEST(MemorySanitizer, fcvt) {
2197   int a, b;
2198   break_optimization(&a);
2199   break_optimization(&b);
2200   EXPECT_POISONED(a);
2201   EXPECT_POISONED(b);
2202   char *str = fcvt(12345.6789, 10, &a, &b);
2203   EXPECT_NOT_POISONED(a);
2204   EXPECT_NOT_POISONED(b);
2205   ASSERT_NE(nullptr, str);
2206   EXPECT_NOT_POISONED(str[0]);
2207   ASSERT_NE(0U, strlen(str));
2208 }
2209 #endif
2210 
2211 // There's no fcvt_long() on FreeBSD.
2212 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,fcvt_long)2213 TEST(MemorySanitizer, fcvt_long) {
2214   int a, b;
2215   break_optimization(&a);
2216   break_optimization(&b);
2217   EXPECT_POISONED(a);
2218   EXPECT_POISONED(b);
2219   char *str = fcvt(111111112345.6789, 10, &a, &b);
2220   EXPECT_NOT_POISONED(a);
2221   EXPECT_NOT_POISONED(b);
2222   ASSERT_NE(nullptr, str);
2223   EXPECT_NOT_POISONED(str[0]);
2224   ASSERT_NE(0U, strlen(str));
2225 }
2226 #endif
2227 
TEST(MemorySanitizer,memchr)2228 TEST(MemorySanitizer, memchr) {
2229   char x[10];
2230   break_optimization(x);
2231   EXPECT_POISONED(x[0]);
2232   x[2] = '2';
2233   void *res;
2234   EXPECT_UMR(res = memchr(x, '2', 10));
2235   EXPECT_NOT_POISONED(res);
2236   x[0] = '0';
2237   x[1] = '1';
2238   res = memchr(x, '2', 10);
2239   EXPECT_EQ(&x[2], res);
2240   EXPECT_UMR(res = memchr(x, '3', 10));
2241   EXPECT_NOT_POISONED(res);
2242 }
2243 
TEST(MemorySanitizer,memrchr)2244 TEST(MemorySanitizer, memrchr) {
2245   char x[10];
2246   break_optimization(x);
2247   EXPECT_POISONED(x[0]);
2248   x[9] = '9';
2249   void *res;
2250   EXPECT_UMR(res = memrchr(x, '9', 10));
2251   EXPECT_NOT_POISONED(res);
2252   x[0] = '0';
2253   x[1] = '1';
2254   res = memrchr(x, '0', 2);
2255   EXPECT_EQ(&x[0], res);
2256   EXPECT_UMR(res = memrchr(x, '7', 10));
2257   EXPECT_NOT_POISONED(res);
2258 }
2259 
TEST(MemorySanitizer,frexp)2260 TEST(MemorySanitizer, frexp) {
2261   int x;
2262   x = *GetPoisoned<int>();
2263   double r = frexp(1.1, &x);
2264   EXPECT_NOT_POISONED(r);
2265   EXPECT_NOT_POISONED(x);
2266 
2267   x = *GetPoisoned<int>();
2268   float rf = frexpf(1.1, &x);
2269   EXPECT_NOT_POISONED(rf);
2270   EXPECT_NOT_POISONED(x);
2271 
2272   x = *GetPoisoned<int>();
2273   double rl = frexpl(1.1, &x);
2274   EXPECT_NOT_POISONED(rl);
2275   EXPECT_NOT_POISONED(x);
2276 }
2277 
2278 namespace {
2279 
2280 static int cnt;
2281 
SigactionHandler(int signo,siginfo_t * si,void * uc)2282 void SigactionHandler(int signo, siginfo_t* si, void* uc) {
2283   ASSERT_EQ(signo, SIGPROF);
2284   ASSERT_TRUE(si != NULL);
2285   EXPECT_NOT_POISONED(si->si_errno);
2286   EXPECT_NOT_POISONED(si->si_pid);
2287 #if __linux__
2288 # if defined(__x86_64__)
2289   EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_RIP]);
2290 # elif defined(__i386__)
2291   EXPECT_NOT_POISONED(((ucontext_t*)uc)->uc_mcontext.gregs[REG_EIP]);
2292 # endif
2293 #endif
2294   ++cnt;
2295 }
2296 
TEST(MemorySanitizer,sigaction)2297 TEST(MemorySanitizer, sigaction) {
2298   struct sigaction act = {};
2299   struct sigaction oldact = {};
2300   struct sigaction origact = {};
2301 
2302   sigaction(SIGPROF, 0, &origact);
2303 
2304   act.sa_flags |= SA_SIGINFO;
2305   act.sa_sigaction = &SigactionHandler;
2306   sigaction(SIGPROF, &act, 0);
2307 
2308   kill(getpid(), SIGPROF);
2309 
2310   act.sa_flags &= ~SA_SIGINFO;
2311   act.sa_handler = SIG_DFL;
2312   sigaction(SIGPROF, &act, 0);
2313 
2314   act.sa_flags &= ~SA_SIGINFO;
2315   act.sa_handler = SIG_IGN;
2316   sigaction(SIGPROF, &act, &oldact);
2317   EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
2318   EXPECT_EQ(SIG_DFL, oldact.sa_handler);
2319   kill(getpid(), SIGPROF);
2320 
2321   act.sa_flags |= SA_SIGINFO;
2322   act.sa_sigaction = &SigactionHandler;
2323   sigaction(SIGPROF, &act, &oldact);
2324   EXPECT_FALSE(oldact.sa_flags & SA_SIGINFO);
2325   EXPECT_EQ(SIG_IGN, oldact.sa_handler);
2326   kill(getpid(), SIGPROF);
2327 
2328   act.sa_flags &= ~SA_SIGINFO;
2329   act.sa_handler = SIG_DFL;
2330   sigaction(SIGPROF, &act, &oldact);
2331   EXPECT_TRUE(oldact.sa_flags & SA_SIGINFO);
2332   EXPECT_EQ(&SigactionHandler, oldact.sa_sigaction);
2333   EXPECT_EQ(2, cnt);
2334 
2335   sigaction(SIGPROF, &origact, 0);
2336 }
2337 
2338 } // namespace
2339 
2340 
TEST(MemorySanitizer,sigemptyset)2341 TEST(MemorySanitizer, sigemptyset) {
2342   sigset_t s;
2343   EXPECT_POISONED(s);
2344   int res = sigemptyset(&s);
2345   ASSERT_EQ(0, res);
2346   EXPECT_NOT_POISONED(s);
2347 }
2348 
TEST(MemorySanitizer,sigfillset)2349 TEST(MemorySanitizer, sigfillset) {
2350   sigset_t s;
2351   EXPECT_POISONED(s);
2352   int res = sigfillset(&s);
2353   ASSERT_EQ(0, res);
2354   EXPECT_NOT_POISONED(s);
2355 }
2356 
TEST(MemorySanitizer,sigpending)2357 TEST(MemorySanitizer, sigpending) {
2358   sigset_t s;
2359   EXPECT_POISONED(s);
2360   int res = sigpending(&s);
2361   ASSERT_EQ(0, res);
2362   EXPECT_NOT_POISONED(s);
2363 }
2364 
TEST(MemorySanitizer,sigprocmask)2365 TEST(MemorySanitizer, sigprocmask) {
2366   sigset_t s;
2367   EXPECT_POISONED(s);
2368   int res = sigprocmask(SIG_BLOCK, 0, &s);
2369   ASSERT_EQ(0, res);
2370   EXPECT_NOT_POISONED(s);
2371 }
2372 
2373 struct StructWithDtor {
2374   ~StructWithDtor();
2375 };
2376 
~StructWithDtor()2377 NOINLINE StructWithDtor::~StructWithDtor() {
2378   break_optimization(0);
2379 }
2380 
TEST(MemorySanitizer,Invoke)2381 TEST(MemorySanitizer, Invoke) {
2382   StructWithDtor s;  // Will cause the calls to become invokes.
2383   EXPECT_NOT_POISONED(0);
2384   EXPECT_POISONED(*GetPoisoned<int>());
2385   EXPECT_NOT_POISONED(0);
2386   EXPECT_POISONED(*GetPoisoned<int>());
2387   EXPECT_POISONED(ReturnPoisoned<S4>());
2388 }
2389 
TEST(MemorySanitizer,ptrtoint)2390 TEST(MemorySanitizer, ptrtoint) {
2391   // Test that shadow is propagated through pointer-to-integer conversion.
2392   void* p = (void*)0xABCD;
2393   __msan_poison(((char*)&p) + 1, sizeof(p));
2394   EXPECT_NOT_POISONED((((uintptr_t)p) & 0xFF) == 0);
2395 
2396   void* q = (void*)0xABCD;
2397   __msan_poison(&q, sizeof(q) - 1);
2398   EXPECT_POISONED((((uintptr_t)q) & 0xFF) == 0);
2399 }
2400 
vaargsfn2(int guard,...)2401 static void vaargsfn2(int guard, ...) {
2402   va_list vl;
2403   va_start(vl, guard);
2404   EXPECT_NOT_POISONED(va_arg(vl, int));
2405   EXPECT_NOT_POISONED(va_arg(vl, int));
2406   EXPECT_NOT_POISONED(va_arg(vl, int));
2407   EXPECT_POISONED(va_arg(vl, double));
2408   va_end(vl);
2409 }
2410 
vaargsfn(int guard,...)2411 static void vaargsfn(int guard, ...) {
2412   va_list vl;
2413   va_start(vl, guard);
2414   EXPECT_NOT_POISONED(va_arg(vl, int));
2415   EXPECT_POISONED(va_arg(vl, int));
2416   // The following call will overwrite __msan_param_tls.
2417   // Checks after it test that arg shadow was somehow saved across the call.
2418   vaargsfn2(1, 2, 3, 4, *GetPoisoned<double>());
2419   EXPECT_NOT_POISONED(va_arg(vl, int));
2420   EXPECT_POISONED(va_arg(vl, int));
2421   va_end(vl);
2422 }
2423 
TEST(MemorySanitizer,VAArgTest)2424 TEST(MemorySanitizer, VAArgTest) {
2425   int* x = GetPoisoned<int>();
2426   int* y = GetPoisoned<int>(4);
2427   vaargsfn(1, 13, *x, 42, *y);
2428 }
2429 
vaargsfn_many(int guard,...)2430 static void vaargsfn_many(int guard, ...) {
2431   va_list vl;
2432   va_start(vl, guard);
2433   EXPECT_NOT_POISONED(va_arg(vl, int));
2434   EXPECT_POISONED(va_arg(vl, int));
2435   EXPECT_NOT_POISONED(va_arg(vl, int));
2436   EXPECT_NOT_POISONED(va_arg(vl, int));
2437   EXPECT_NOT_POISONED(va_arg(vl, int));
2438   EXPECT_NOT_POISONED(va_arg(vl, int));
2439   EXPECT_NOT_POISONED(va_arg(vl, int));
2440   EXPECT_NOT_POISONED(va_arg(vl, int));
2441   EXPECT_NOT_POISONED(va_arg(vl, int));
2442   EXPECT_POISONED(va_arg(vl, int));
2443   va_end(vl);
2444 }
2445 
TEST(MemorySanitizer,VAArgManyTest)2446 TEST(MemorySanitizer, VAArgManyTest) {
2447   int* x = GetPoisoned<int>();
2448   int* y = GetPoisoned<int>(4);
2449   vaargsfn_many(1, 2, *x, 3, 4, 5, 6, 7, 8, 9, *y);
2450 }
2451 
vaargsfn_pass2(va_list vl)2452 static void vaargsfn_pass2(va_list vl) {
2453   EXPECT_NOT_POISONED(va_arg(vl, int));
2454   EXPECT_NOT_POISONED(va_arg(vl, int));
2455   EXPECT_POISONED(va_arg(vl, int));
2456 }
2457 
vaargsfn_pass(int guard,...)2458 static void vaargsfn_pass(int guard, ...) {
2459   va_list vl;
2460   va_start(vl, guard);
2461   EXPECT_POISONED(va_arg(vl, int));
2462   vaargsfn_pass2(vl);
2463   va_end(vl);
2464 }
2465 
TEST(MemorySanitizer,VAArgPass)2466 TEST(MemorySanitizer, VAArgPass) {
2467   int* x = GetPoisoned<int>();
2468   int* y = GetPoisoned<int>(4);
2469   vaargsfn_pass(1, *x, 2, 3, *y);
2470 }
2471 
vaargsfn_copy2(va_list vl)2472 static void vaargsfn_copy2(va_list vl) {
2473   EXPECT_NOT_POISONED(va_arg(vl, int));
2474   EXPECT_POISONED(va_arg(vl, int));
2475 }
2476 
vaargsfn_copy(int guard,...)2477 static void vaargsfn_copy(int guard, ...) {
2478   va_list vl;
2479   va_start(vl, guard);
2480   EXPECT_NOT_POISONED(va_arg(vl, int));
2481   EXPECT_POISONED(va_arg(vl, int));
2482   va_list vl2;
2483   va_copy(vl2, vl);
2484   vaargsfn_copy2(vl2);
2485   EXPECT_NOT_POISONED(va_arg(vl, int));
2486   EXPECT_POISONED(va_arg(vl, int));
2487   va_end(vl);
2488 }
2489 
TEST(MemorySanitizer,VAArgCopy)2490 TEST(MemorySanitizer, VAArgCopy) {
2491   int* x = GetPoisoned<int>();
2492   int* y = GetPoisoned<int>(4);
2493   vaargsfn_copy(1, 2, *x, 3, *y);
2494 }
2495 
vaargsfn_ptr(int guard,...)2496 static void vaargsfn_ptr(int guard, ...) {
2497   va_list vl;
2498   va_start(vl, guard);
2499   EXPECT_NOT_POISONED(va_arg(vl, int*));
2500   EXPECT_POISONED(va_arg(vl, int*));
2501   EXPECT_NOT_POISONED(va_arg(vl, int*));
2502   EXPECT_POISONED(va_arg(vl, double*));
2503   va_end(vl);
2504 }
2505 
TEST(MemorySanitizer,VAArgPtr)2506 TEST(MemorySanitizer, VAArgPtr) {
2507   int** x = GetPoisoned<int*>();
2508   double** y = GetPoisoned<double*>(8);
2509   int z;
2510   vaargsfn_ptr(1, &z, *x, &z, *y);
2511 }
2512 
vaargsfn_overflow(int guard,...)2513 static void vaargsfn_overflow(int guard, ...) {
2514   va_list vl;
2515   va_start(vl, guard);
2516   EXPECT_NOT_POISONED(va_arg(vl, int));
2517   EXPECT_NOT_POISONED(va_arg(vl, int));
2518   EXPECT_POISONED(va_arg(vl, int));
2519   EXPECT_NOT_POISONED(va_arg(vl, int));
2520   EXPECT_NOT_POISONED(va_arg(vl, int));
2521   EXPECT_NOT_POISONED(va_arg(vl, int));
2522 
2523   EXPECT_NOT_POISONED(va_arg(vl, double));
2524   EXPECT_NOT_POISONED(va_arg(vl, double));
2525   EXPECT_NOT_POISONED(va_arg(vl, double));
2526   EXPECT_POISONED(va_arg(vl, double));
2527   EXPECT_NOT_POISONED(va_arg(vl, double));
2528   EXPECT_POISONED(va_arg(vl, int*));
2529   EXPECT_NOT_POISONED(va_arg(vl, double));
2530   EXPECT_NOT_POISONED(va_arg(vl, double));
2531 
2532   EXPECT_POISONED(va_arg(vl, int));
2533   EXPECT_POISONED(va_arg(vl, double));
2534   EXPECT_POISONED(va_arg(vl, int*));
2535 
2536   EXPECT_NOT_POISONED(va_arg(vl, int));
2537   EXPECT_NOT_POISONED(va_arg(vl, double));
2538   EXPECT_NOT_POISONED(va_arg(vl, int*));
2539 
2540   EXPECT_POISONED(va_arg(vl, int));
2541   EXPECT_POISONED(va_arg(vl, double));
2542   EXPECT_POISONED(va_arg(vl, int*));
2543 
2544   va_end(vl);
2545 }
2546 
TEST(MemorySanitizer,VAArgOverflow)2547 TEST(MemorySanitizer, VAArgOverflow) {
2548   int* x = GetPoisoned<int>();
2549   double* y = GetPoisoned<double>(8);
2550   int** p = GetPoisoned<int*>(16);
2551   int z;
2552   vaargsfn_overflow(1,
2553       1, 2, *x, 4, 5, 6,
2554       1.1, 2.2, 3.3, *y, 5.5, *p, 7.7, 8.8,
2555       // the following args will overflow for sure
2556       *x, *y, *p,
2557       7, 9.9, &z,
2558       *x, *y, *p);
2559 }
2560 
vaargsfn_tlsoverwrite2(int guard,...)2561 static void vaargsfn_tlsoverwrite2(int guard, ...) {
2562   va_list vl;
2563   va_start(vl, guard);
2564   for (int i = 0; i < 20; ++i)
2565     EXPECT_NOT_POISONED(va_arg(vl, int));
2566   va_end(vl);
2567 }
2568 
vaargsfn_tlsoverwrite(int guard,...)2569 static void vaargsfn_tlsoverwrite(int guard, ...) {
2570   // This call will overwrite TLS contents unless it's backed up somewhere.
2571   vaargsfn_tlsoverwrite2(2,
2572       42, 42, 42, 42, 42,
2573       42, 42, 42, 42, 42,
2574       42, 42, 42, 42, 42,
2575       42, 42, 42, 42, 42); // 20x
2576   va_list vl;
2577   va_start(vl, guard);
2578   for (int i = 0; i < 20; ++i)
2579     EXPECT_POISONED(va_arg(vl, int));
2580   va_end(vl);
2581 }
2582 
TEST(MemorySanitizer,VAArgTLSOverwrite)2583 TEST(MemorySanitizer, VAArgTLSOverwrite) {
2584   int* x = GetPoisoned<int>();
2585   vaargsfn_tlsoverwrite(1,
2586       *x, *x, *x, *x, *x,
2587       *x, *x, *x, *x, *x,
2588       *x, *x, *x, *x, *x,
2589       *x, *x, *x, *x, *x); // 20x
2590 
2591 }
2592 
2593 struct StructByVal {
2594   int a, b, c, d, e, f;
2595 };
2596 
vaargsfn_structbyval(int guard,...)2597 static void vaargsfn_structbyval(int guard, ...) {
2598   va_list vl;
2599   va_start(vl, guard);
2600   {
2601     StructByVal s = va_arg(vl, StructByVal);
2602     EXPECT_NOT_POISONED(s.a);
2603     EXPECT_POISONED(s.b);
2604     EXPECT_NOT_POISONED(s.c);
2605     EXPECT_POISONED(s.d);
2606     EXPECT_NOT_POISONED(s.e);
2607     EXPECT_POISONED(s.f);
2608   }
2609   {
2610     StructByVal s = va_arg(vl, StructByVal);
2611     EXPECT_NOT_POISONED(s.a);
2612     EXPECT_POISONED(s.b);
2613     EXPECT_NOT_POISONED(s.c);
2614     EXPECT_POISONED(s.d);
2615     EXPECT_NOT_POISONED(s.e);
2616     EXPECT_POISONED(s.f);
2617   }
2618   va_end(vl);
2619 }
2620 
TEST(MemorySanitizer,VAArgStructByVal)2621 TEST(MemorySanitizer, VAArgStructByVal) {
2622   StructByVal s;
2623   s.a = 1;
2624   s.b = *GetPoisoned<int>();
2625   s.c = 2;
2626   s.d = *GetPoisoned<int>();
2627   s.e = 3;
2628   s.f = *GetPoisoned<int>();
2629   vaargsfn_structbyval(0, s, s);
2630 }
2631 
StructByValTestFunc(struct StructByVal s)2632 NOINLINE void StructByValTestFunc(struct StructByVal s) {
2633   EXPECT_NOT_POISONED(s.a);
2634   EXPECT_POISONED(s.b);
2635   EXPECT_NOT_POISONED(s.c);
2636   EXPECT_POISONED(s.d);
2637   EXPECT_NOT_POISONED(s.e);
2638   EXPECT_POISONED(s.f);
2639 }
2640 
StructByValTestFunc1(struct StructByVal s)2641 NOINLINE void StructByValTestFunc1(struct StructByVal s) {
2642   StructByValTestFunc(s);
2643 }
2644 
StructByValTestFunc2(int z,struct StructByVal s)2645 NOINLINE void StructByValTestFunc2(int z, struct StructByVal s) {
2646   StructByValTestFunc(s);
2647 }
2648 
TEST(MemorySanitizer,StructByVal)2649 TEST(MemorySanitizer, StructByVal) {
2650   // Large aggregates are passed as "byval" pointer argument in LLVM.
2651   struct StructByVal s;
2652   s.a = 1;
2653   s.b = *GetPoisoned<int>();
2654   s.c = 2;
2655   s.d = *GetPoisoned<int>();
2656   s.e = 3;
2657   s.f = *GetPoisoned<int>();
2658   StructByValTestFunc(s);
2659   StructByValTestFunc1(s);
2660   StructByValTestFunc2(0, s);
2661 }
2662 
2663 
2664 #if MSAN_HAS_M128
m128Eq(__m128i * a,__m128i * b)2665 NOINLINE __m128i m128Eq(__m128i *a, __m128i *b) { return _mm_cmpeq_epi16(*a, *b); }
m128Lt(__m128i * a,__m128i * b)2666 NOINLINE __m128i m128Lt(__m128i *a, __m128i *b) { return _mm_cmplt_epi16(*a, *b); }
TEST(MemorySanitizer,m128)2667 TEST(MemorySanitizer, m128) {
2668   __m128i a = _mm_set1_epi16(0x1234);
2669   __m128i b = _mm_set1_epi16(0x7890);
2670   EXPECT_NOT_POISONED(m128Eq(&a, &b));
2671   EXPECT_NOT_POISONED(m128Lt(&a, &b));
2672 }
2673 // FIXME: add more tests for __m128i.
2674 #endif  // MSAN_HAS_M128
2675 
2676 // We should not complain when copying this poisoned hole.
2677 struct StructWithHole {
2678   U4  a;
2679   // 4-byte hole.
2680   U8  b;
2681 };
2682 
ReturnStructWithHole()2683 NOINLINE StructWithHole ReturnStructWithHole() {
2684   StructWithHole res;
2685   __msan_poison(&res, sizeof(res));
2686   res.a = 1;
2687   res.b = 2;
2688   return res;
2689 }
2690 
TEST(MemorySanitizer,StructWithHole)2691 TEST(MemorySanitizer, StructWithHole) {
2692   StructWithHole a = ReturnStructWithHole();
2693   break_optimization(&a);
2694 }
2695 
2696 template <class T>
ReturnStruct()2697 NOINLINE T ReturnStruct() {
2698   T res;
2699   __msan_poison(&res, sizeof(res));
2700   res.a = 1;
2701   return res;
2702 }
2703 
2704 template <class T>
TestReturnStruct()2705 NOINLINE void TestReturnStruct() {
2706   T s1 = ReturnStruct<T>();
2707   EXPECT_NOT_POISONED(s1.a);
2708   EXPECT_POISONED(s1.b);
2709 }
2710 
2711 struct SSS1 {
2712   int a, b, c;
2713 };
2714 struct SSS2 {
2715   int b, a, c;
2716 };
2717 struct SSS3 {
2718   int b, c, a;
2719 };
2720 struct SSS4 {
2721   int c, b, a;
2722 };
2723 
2724 struct SSS5 {
2725   int a;
2726   float b;
2727 };
2728 struct SSS6 {
2729   int a;
2730   double b;
2731 };
2732 struct SSS7 {
2733   S8 b;
2734   int a;
2735 };
2736 struct SSS8 {
2737   S2 b;
2738   S8 a;
2739 };
2740 
TEST(MemorySanitizer,IntStruct3)2741 TEST(MemorySanitizer, IntStruct3) {
2742   TestReturnStruct<SSS1>();
2743   TestReturnStruct<SSS2>();
2744   TestReturnStruct<SSS3>();
2745   TestReturnStruct<SSS4>();
2746   TestReturnStruct<SSS5>();
2747   TestReturnStruct<SSS6>();
2748   TestReturnStruct<SSS7>();
2749   TestReturnStruct<SSS8>();
2750 }
2751 
2752 struct LongStruct {
2753   U1 a1, b1;
2754   U2 a2, b2;
2755   U4 a4, b4;
2756   U8 a8, b8;
2757 };
2758 
ReturnLongStruct1()2759 NOINLINE LongStruct ReturnLongStruct1() {
2760   LongStruct res;
2761   __msan_poison(&res, sizeof(res));
2762   res.a1 = res.a2 = res.a4 = res.a8 = 111;
2763   // leaves b1, .., b8 poisoned.
2764   return res;
2765 }
2766 
ReturnLongStruct2()2767 NOINLINE LongStruct ReturnLongStruct2() {
2768   LongStruct res;
2769   __msan_poison(&res, sizeof(res));
2770   res.b1 = res.b2 = res.b4 = res.b8 = 111;
2771   // leaves a1, .., a8 poisoned.
2772   return res;
2773 }
2774 
TEST(MemorySanitizer,LongStruct)2775 TEST(MemorySanitizer, LongStruct) {
2776   LongStruct s1 = ReturnLongStruct1();
2777   __msan_print_shadow(&s1, sizeof(s1));
2778   EXPECT_NOT_POISONED(s1.a1);
2779   EXPECT_NOT_POISONED(s1.a2);
2780   EXPECT_NOT_POISONED(s1.a4);
2781   EXPECT_NOT_POISONED(s1.a8);
2782 
2783   EXPECT_POISONED(s1.b1);
2784   EXPECT_POISONED(s1.b2);
2785   EXPECT_POISONED(s1.b4);
2786   EXPECT_POISONED(s1.b8);
2787 
2788   LongStruct s2 = ReturnLongStruct2();
2789   __msan_print_shadow(&s2, sizeof(s2));
2790   EXPECT_NOT_POISONED(s2.b1);
2791   EXPECT_NOT_POISONED(s2.b2);
2792   EXPECT_NOT_POISONED(s2.b4);
2793   EXPECT_NOT_POISONED(s2.b8);
2794 
2795   EXPECT_POISONED(s2.a1);
2796   EXPECT_POISONED(s2.a2);
2797   EXPECT_POISONED(s2.a4);
2798   EXPECT_POISONED(s2.a8);
2799 }
2800 
TEST(MemorySanitizer,getrlimit)2801 TEST(MemorySanitizer, getrlimit) {
2802   struct rlimit limit;
2803   __msan_poison(&limit, sizeof(limit));
2804   int result = getrlimit(RLIMIT_DATA, &limit);
2805   ASSERT_EQ(result, 0);
2806   EXPECT_NOT_POISONED(limit.rlim_cur);
2807   EXPECT_NOT_POISONED(limit.rlim_max);
2808 }
2809 
TEST(MemorySanitizer,getrusage)2810 TEST(MemorySanitizer, getrusage) {
2811   struct rusage usage;
2812   __msan_poison(&usage, sizeof(usage));
2813   int result = getrusage(RUSAGE_SELF, &usage);
2814   ASSERT_EQ(result, 0);
2815   EXPECT_NOT_POISONED(usage.ru_utime.tv_sec);
2816   EXPECT_NOT_POISONED(usage.ru_utime.tv_usec);
2817   EXPECT_NOT_POISONED(usage.ru_stime.tv_sec);
2818   EXPECT_NOT_POISONED(usage.ru_stime.tv_usec);
2819   EXPECT_NOT_POISONED(usage.ru_maxrss);
2820   EXPECT_NOT_POISONED(usage.ru_minflt);
2821   EXPECT_NOT_POISONED(usage.ru_majflt);
2822   EXPECT_NOT_POISONED(usage.ru_inblock);
2823   EXPECT_NOT_POISONED(usage.ru_oublock);
2824   EXPECT_NOT_POISONED(usage.ru_nvcsw);
2825   EXPECT_NOT_POISONED(usage.ru_nivcsw);
2826 }
2827 
2828 #if defined(__FreeBSD__)
GetProgramPath(char * buf,size_t sz)2829 static void GetProgramPath(char *buf, size_t sz) {
2830   int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
2831   int res = sysctl(mib, 4, buf, &sz, NULL, 0);
2832   ASSERT_EQ(0, res);
2833 }
2834 #elif defined(__GLIBC__)
GetProgramPath(char * buf,size_t sz)2835 static void GetProgramPath(char *buf, size_t sz) {
2836   extern char *program_invocation_name;
2837   int res = snprintf(buf, sz, "%s", program_invocation_name);
2838   ASSERT_GE(res, 0);
2839   ASSERT_LT((size_t)res, sz);
2840 }
2841 #else
2842 # error "TODO: port this"
2843 #endif
2844 
dladdr_testfn()2845 static void dladdr_testfn() {}
2846 
TEST(MemorySanitizer,dladdr)2847 TEST(MemorySanitizer, dladdr) {
2848   Dl_info info;
2849   __msan_poison(&info, sizeof(info));
2850   int result = dladdr((const void*)dladdr_testfn, &info);
2851   ASSERT_NE(result, 0);
2852   EXPECT_NOT_POISONED((unsigned long)info.dli_fname);
2853   if (info.dli_fname)
2854     EXPECT_NOT_POISONED(strlen(info.dli_fname));
2855   EXPECT_NOT_POISONED((unsigned long)info.dli_fbase);
2856   EXPECT_NOT_POISONED((unsigned long)info.dli_sname);
2857   if (info.dli_sname)
2858     EXPECT_NOT_POISONED(strlen(info.dli_sname));
2859   EXPECT_NOT_POISONED((unsigned long)info.dli_saddr);
2860 }
2861 
2862 #ifndef MSAN_TEST_DISABLE_DLOPEN
2863 
dl_phdr_callback(struct dl_phdr_info * info,size_t size,void * data)2864 static int dl_phdr_callback(struct dl_phdr_info *info, size_t size, void *data) {
2865   (*(int *)data)++;
2866   EXPECT_NOT_POISONED(info->dlpi_addr);
2867   EXPECT_NOT_POISONED(strlen(info->dlpi_name));
2868   EXPECT_NOT_POISONED(info->dlpi_phnum);
2869   for (int i = 0; i < info->dlpi_phnum; ++i)
2870     EXPECT_NOT_POISONED(info->dlpi_phdr[i]);
2871   return 0;
2872 }
2873 
2874 // Compute the path to our loadable DSO.  We assume it's in the same
2875 // directory.  Only use string routines that we intercept so far to do this.
GetPathToLoadable(char * buf,size_t sz)2876 static void GetPathToLoadable(char *buf, size_t sz) {
2877   char program_path[kMaxPathLength];
2878   GetProgramPath(program_path, sizeof(program_path));
2879 
2880   const char *last_slash = strrchr(program_path, '/');
2881   ASSERT_NE(nullptr, last_slash);
2882   size_t dir_len = (size_t)(last_slash - program_path);
2883 #if defined(__x86_64__)
2884   static const char basename[] = "libmsan_loadable.x86_64.so";
2885 #elif defined(__MIPSEB__) || defined(MIPSEB)
2886   static const char basename[] = "libmsan_loadable.mips64.so";
2887 #elif defined(__mips64)
2888   static const char basename[] = "libmsan_loadable.mips64el.so";
2889 #elif defined(__aarch64__)
2890   static const char basename[] = "libmsan_loadable.aarch64.so";
2891 #endif
2892   int res = snprintf(buf, sz, "%.*s/%s",
2893                      (int)dir_len, program_path, basename);
2894   ASSERT_GE(res, 0);
2895   ASSERT_LT((size_t)res, sz);
2896 }
2897 
TEST(MemorySanitizer,dl_iterate_phdr)2898 TEST(MemorySanitizer, dl_iterate_phdr) {
2899   char path[kMaxPathLength];
2900   GetPathToLoadable(path, sizeof(path));
2901 
2902   // Having at least one dlopen'ed library in the process makes this more
2903   // entertaining.
2904   void *lib = dlopen(path, RTLD_LAZY);
2905   ASSERT_NE((void*)0, lib);
2906 
2907   int count = 0;
2908   int result = dl_iterate_phdr(dl_phdr_callback, &count);
2909   ASSERT_GT(count, 0);
2910 
2911   dlclose(lib);
2912 }
2913 
TEST(MemorySanitizer,dlopen)2914 TEST(MemorySanitizer, dlopen) {
2915   char path[kMaxPathLength];
2916   GetPathToLoadable(path, sizeof(path));
2917 
2918   // We need to clear shadow for globals when doing dlopen.  In order to test
2919   // this, we have to poison the shadow for the DSO before we load it.  In
2920   // general this is difficult, but the loader tends to reload things in the
2921   // same place, so we open, close, and then reopen.  The global should always
2922   // start out clean after dlopen.
2923   for (int i = 0; i < 2; i++) {
2924     void *lib = dlopen(path, RTLD_LAZY);
2925     if (lib == NULL) {
2926       printf("dlerror: %s\n", dlerror());
2927       ASSERT_TRUE(lib != NULL);
2928     }
2929     void **(*get_dso_global)() = (void **(*)())dlsym(lib, "get_dso_global");
2930     ASSERT_TRUE(get_dso_global != NULL);
2931     void **dso_global = get_dso_global();
2932     EXPECT_NOT_POISONED(*dso_global);
2933     __msan_poison(dso_global, sizeof(*dso_global));
2934     EXPECT_POISONED(*dso_global);
2935     dlclose(lib);
2936   }
2937 }
2938 
2939 // Regression test for a crash in dlopen() interceptor.
TEST(MemorySanitizer,dlopenFailed)2940 TEST(MemorySanitizer, dlopenFailed) {
2941   const char *path = "/libmsan_loadable_does_not_exist.so";
2942   void *lib = dlopen(path, RTLD_LAZY);
2943   ASSERT_TRUE(lib == NULL);
2944 }
2945 
2946 #endif // MSAN_TEST_DISABLE_DLOPEN
2947 
2948 // There's no sched_getaffinity() on FreeBSD.
2949 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,sched_getaffinity)2950 TEST(MemorySanitizer, sched_getaffinity) {
2951   cpu_set_t mask;
2952   int res = sched_getaffinity(getpid(), sizeof(mask), &mask);
2953   ASSERT_EQ(0, res);
2954   EXPECT_NOT_POISONED(mask);
2955 }
2956 #endif
2957 
TEST(MemorySanitizer,scanf)2958 TEST(MemorySanitizer, scanf) {
2959   const char *input = "42 hello";
2960   int* d = new int;
2961   char* s = new char[7];
2962   int res = sscanf(input, "%d %5s", d, s);
2963   printf("res %d\n", res);
2964   ASSERT_EQ(res, 2);
2965   EXPECT_NOT_POISONED(*d);
2966   EXPECT_NOT_POISONED(s[0]);
2967   EXPECT_NOT_POISONED(s[1]);
2968   EXPECT_NOT_POISONED(s[2]);
2969   EXPECT_NOT_POISONED(s[3]);
2970   EXPECT_NOT_POISONED(s[4]);
2971   EXPECT_NOT_POISONED(s[5]);
2972   EXPECT_POISONED(s[6]);
2973   delete[] s;
2974   delete d;
2975 }
2976 
SimpleThread_threadfn(void * data)2977 static void *SimpleThread_threadfn(void* data) {
2978   return new int;
2979 }
2980 
TEST(MemorySanitizer,SimpleThread)2981 TEST(MemorySanitizer, SimpleThread) {
2982   pthread_t t;
2983   void *p;
2984   int res = pthread_create(&t, NULL, SimpleThread_threadfn, NULL);
2985   ASSERT_EQ(0, res);
2986   EXPECT_NOT_POISONED(t);
2987   res = pthread_join(t, &p);
2988   ASSERT_EQ(0, res);
2989   EXPECT_NOT_POISONED(p);
2990   delete (int*)p;
2991 }
2992 
SmallStackThread_threadfn(void * data)2993 static void *SmallStackThread_threadfn(void* data) {
2994   return 0;
2995 }
2996 
2997 #ifdef PTHREAD_STACK_MIN
2998 # define SMALLSTACKSIZE    PTHREAD_STACK_MIN
2999 # define SMALLPRESTACKSIZE PTHREAD_STACK_MIN
3000 #else
3001 # define SMALLSTACKSIZE    64 * 1024
3002 # define SMALLPRESTACKSIZE 16 * 1024
3003 #endif
3004 
TEST(MemorySanitizer,SmallStackThread)3005 TEST(MemorySanitizer, SmallStackThread) {
3006   pthread_attr_t attr;
3007   pthread_t t;
3008   void *p;
3009   int res;
3010   res = pthread_attr_init(&attr);
3011   ASSERT_EQ(0, res);
3012   res = pthread_attr_setstacksize(&attr, SMALLSTACKSIZE);
3013   ASSERT_EQ(0, res);
3014   res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
3015   ASSERT_EQ(0, res);
3016   res = pthread_join(t, &p);
3017   ASSERT_EQ(0, res);
3018   res = pthread_attr_destroy(&attr);
3019   ASSERT_EQ(0, res);
3020 }
3021 
TEST(MemorySanitizer,SmallPreAllocatedStackThread)3022 TEST(MemorySanitizer, SmallPreAllocatedStackThread) {
3023   pthread_attr_t attr;
3024   pthread_t t;
3025   int res;
3026   res = pthread_attr_init(&attr);
3027   ASSERT_EQ(0, res);
3028   void *stack;
3029   const size_t kStackSize = SMALLPRESTACKSIZE;
3030   res = posix_memalign(&stack, 4096, kStackSize);
3031   ASSERT_EQ(0, res);
3032   res = pthread_attr_setstack(&attr, stack, kStackSize);
3033   ASSERT_EQ(0, res);
3034   res = pthread_create(&t, &attr, SmallStackThread_threadfn, NULL);
3035   EXPECT_EQ(0, res);
3036   res = pthread_join(t, NULL);
3037   ASSERT_EQ(0, res);
3038   res = pthread_attr_destroy(&attr);
3039   ASSERT_EQ(0, res);
3040 }
3041 
TEST(MemorySanitizer,pthread_attr_get)3042 TEST(MemorySanitizer, pthread_attr_get) {
3043   pthread_attr_t attr;
3044   int res;
3045   res = pthread_attr_init(&attr);
3046   ASSERT_EQ(0, res);
3047   {
3048     int v;
3049     res = pthread_attr_getdetachstate(&attr, &v);
3050     ASSERT_EQ(0, res);
3051     EXPECT_NOT_POISONED(v);
3052   }
3053   {
3054     size_t v;
3055     res = pthread_attr_getguardsize(&attr, &v);
3056     ASSERT_EQ(0, res);
3057     EXPECT_NOT_POISONED(v);
3058   }
3059   {
3060     struct sched_param v;
3061     res = pthread_attr_getschedparam(&attr, &v);
3062     ASSERT_EQ(0, res);
3063     EXPECT_NOT_POISONED(v);
3064   }
3065   {
3066     int v;
3067     res = pthread_attr_getschedpolicy(&attr, &v);
3068     ASSERT_EQ(0, res);
3069     EXPECT_NOT_POISONED(v);
3070   }
3071   {
3072     int v;
3073     res = pthread_attr_getinheritsched(&attr, &v);
3074     ASSERT_EQ(0, res);
3075     EXPECT_NOT_POISONED(v);
3076   }
3077   {
3078     int v;
3079     res = pthread_attr_getscope(&attr, &v);
3080     ASSERT_EQ(0, res);
3081     EXPECT_NOT_POISONED(v);
3082   }
3083   {
3084     size_t v;
3085     res = pthread_attr_getstacksize(&attr, &v);
3086     ASSERT_EQ(0, res);
3087     EXPECT_NOT_POISONED(v);
3088   }
3089   {
3090     void *v;
3091     size_t w;
3092     res = pthread_attr_getstack(&attr, &v, &w);
3093     ASSERT_EQ(0, res);
3094     EXPECT_NOT_POISONED(v);
3095     EXPECT_NOT_POISONED(w);
3096   }
3097   {
3098     cpu_set_t v;
3099     res = pthread_attr_getaffinity_np(&attr, sizeof(v), &v);
3100     ASSERT_EQ(0, res);
3101     EXPECT_NOT_POISONED(v);
3102   }
3103   res = pthread_attr_destroy(&attr);
3104   ASSERT_EQ(0, res);
3105 }
3106 
TEST(MemorySanitizer,pthread_getschedparam)3107 TEST(MemorySanitizer, pthread_getschedparam) {
3108   int policy;
3109   struct sched_param param;
3110   int res = pthread_getschedparam(pthread_self(), &policy, &param);
3111   ASSERT_EQ(0, res);
3112   EXPECT_NOT_POISONED(policy);
3113   EXPECT_NOT_POISONED(param.sched_priority);
3114 }
3115 
TEST(MemorySanitizer,pthread_key_create)3116 TEST(MemorySanitizer, pthread_key_create) {
3117   pthread_key_t key;
3118   int res = pthread_key_create(&key, NULL);
3119   ASSERT_EQ(0, res);
3120   EXPECT_NOT_POISONED(key);
3121   res = pthread_key_delete(key);
3122   ASSERT_EQ(0, res);
3123 }
3124 
3125 namespace {
3126 struct SignalCondArg {
3127   pthread_cond_t* cond;
3128   pthread_mutex_t* mu;
3129   bool broadcast;
3130 };
3131 
SignalCond(void * param)3132 void *SignalCond(void *param) {
3133   SignalCondArg *arg = reinterpret_cast<SignalCondArg *>(param);
3134   pthread_mutex_lock(arg->mu);
3135   if (arg->broadcast)
3136     pthread_cond_broadcast(arg->cond);
3137   else
3138     pthread_cond_signal(arg->cond);
3139   pthread_mutex_unlock(arg->mu);
3140   return 0;
3141 }
3142 }  // namespace
3143 
TEST(MemorySanitizer,pthread_cond_wait)3144 TEST(MemorySanitizer, pthread_cond_wait) {
3145   pthread_cond_t cond;
3146   pthread_mutex_t mu;
3147   SignalCondArg args = {&cond, &mu, false};
3148   pthread_cond_init(&cond, 0);
3149   pthread_mutex_init(&mu, 0);
3150   pthread_mutex_lock(&mu);
3151 
3152   // signal
3153   pthread_t thr;
3154   pthread_create(&thr, 0, SignalCond, &args);
3155   int res = pthread_cond_wait(&cond, &mu);
3156   ASSERT_EQ(0, res);
3157   pthread_join(thr, 0);
3158 
3159   // broadcast
3160   args.broadcast = true;
3161   pthread_create(&thr, 0, SignalCond, &args);
3162   res = pthread_cond_wait(&cond, &mu);
3163   ASSERT_EQ(0, res);
3164   pthread_join(thr, 0);
3165 
3166   pthread_mutex_unlock(&mu);
3167   pthread_mutex_destroy(&mu);
3168   pthread_cond_destroy(&cond);
3169 }
3170 
TEST(MemorySanitizer,tmpnam)3171 TEST(MemorySanitizer, tmpnam) {
3172   char s[L_tmpnam];
3173   char *res = tmpnam(s);
3174   ASSERT_EQ(s, res);
3175   EXPECT_NOT_POISONED(strlen(res));
3176 }
3177 
TEST(MemorySanitizer,tempnam)3178 TEST(MemorySanitizer, tempnam) {
3179   char *res = tempnam(NULL, "zzz");
3180   EXPECT_NOT_POISONED(strlen(res));
3181   free(res);
3182 }
3183 
TEST(MemorySanitizer,posix_memalign)3184 TEST(MemorySanitizer, posix_memalign) {
3185   void *p;
3186   EXPECT_POISONED(p);
3187   int res = posix_memalign(&p, 4096, 13);
3188   ASSERT_EQ(0, res);
3189   EXPECT_NOT_POISONED(p);
3190   EXPECT_EQ(0U, (uintptr_t)p % 4096);
3191   free(p);
3192 }
3193 
3194 // There's no memalign() on FreeBSD.
3195 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,memalign)3196 TEST(MemorySanitizer, memalign) {
3197   void *p = memalign(4096, 13);
3198   EXPECT_EQ(0U, (uintptr_t)p % kPageSize);
3199   free(p);
3200 }
3201 #endif
3202 
TEST(MemorySanitizer,valloc)3203 TEST(MemorySanitizer, valloc) {
3204   void *a = valloc(100);
3205   EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
3206   free(a);
3207 }
3208 
3209 // There's no pvalloc() on FreeBSD.
3210 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,pvalloc)3211 TEST(MemorySanitizer, pvalloc) {
3212   void *p = pvalloc(kPageSize + 100);
3213   EXPECT_EQ(0U, (uintptr_t)p % kPageSize);
3214   EXPECT_EQ(2 * kPageSize, __sanitizer_get_allocated_size(p));
3215   free(p);
3216 
3217   p = pvalloc(0);  // pvalloc(0) should allocate at least one page.
3218   EXPECT_EQ(0U, (uintptr_t)p % kPageSize);
3219   EXPECT_EQ(kPageSize, __sanitizer_get_allocated_size(p));
3220   free(p);
3221 }
3222 #endif
3223 
TEST(MemorySanitizer,inet_pton)3224 TEST(MemorySanitizer, inet_pton) {
3225   const char *s = "1:0:0:0:0:0:0:8";
3226   unsigned char buf[sizeof(struct in6_addr)];
3227   int res = inet_pton(AF_INET6, s, buf);
3228   ASSERT_EQ(1, res);
3229   EXPECT_NOT_POISONED(buf[0]);
3230   EXPECT_NOT_POISONED(buf[sizeof(struct in6_addr) - 1]);
3231 
3232   char s_out[INET6_ADDRSTRLEN];
3233   EXPECT_POISONED(s_out[3]);
3234   const char *q = inet_ntop(AF_INET6, buf, s_out, INET6_ADDRSTRLEN);
3235   ASSERT_NE((void*)0, q);
3236   EXPECT_NOT_POISONED(s_out[3]);
3237 }
3238 
TEST(MemorySanitizer,inet_aton)3239 TEST(MemorySanitizer, inet_aton) {
3240   const char *s = "127.0.0.1";
3241   struct in_addr in[2];
3242   int res = inet_aton(s, in);
3243   ASSERT_NE(0, res);
3244   EXPECT_NOT_POISONED(in[0]);
3245   EXPECT_POISONED(*(char *)(in + 1));
3246 }
3247 
TEST(MemorySanitizer,uname)3248 TEST(MemorySanitizer, uname) {
3249   struct utsname u;
3250   int res = uname(&u);
3251   ASSERT_EQ(0, res);
3252   EXPECT_NOT_POISONED(strlen(u.sysname));
3253   EXPECT_NOT_POISONED(strlen(u.nodename));
3254   EXPECT_NOT_POISONED(strlen(u.release));
3255   EXPECT_NOT_POISONED(strlen(u.version));
3256   EXPECT_NOT_POISONED(strlen(u.machine));
3257 }
3258 
TEST(MemorySanitizer,gethostname)3259 TEST(MemorySanitizer, gethostname) {
3260   char buf[100];
3261   int res = gethostname(buf, 100);
3262   ASSERT_EQ(0, res);
3263   EXPECT_NOT_POISONED(strlen(buf));
3264 }
3265 
3266 // There's no sysinfo() on FreeBSD.
3267 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,sysinfo)3268 TEST(MemorySanitizer, sysinfo) {
3269   struct sysinfo info;
3270   int res = sysinfo(&info);
3271   ASSERT_EQ(0, res);
3272   EXPECT_NOT_POISONED(info);
3273 }
3274 #endif
3275 
TEST(MemorySanitizer,getpwuid)3276 TEST(MemorySanitizer, getpwuid) {
3277   struct passwd *p = getpwuid(0); // root
3278   ASSERT_TRUE(p != NULL);
3279   EXPECT_NOT_POISONED(p->pw_name);
3280   ASSERT_TRUE(p->pw_name != NULL);
3281   EXPECT_NOT_POISONED(p->pw_name[0]);
3282   EXPECT_NOT_POISONED(p->pw_uid);
3283   ASSERT_EQ(0U, p->pw_uid);
3284 }
3285 
TEST(MemorySanitizer,getpwuid_r)3286 TEST(MemorySanitizer, getpwuid_r) {
3287   struct passwd pwd;
3288   struct passwd *pwdres;
3289   char buf[10000];
3290   int res = getpwuid_r(0, &pwd, buf, sizeof(buf), &pwdres);
3291   ASSERT_EQ(0, res);
3292   EXPECT_NOT_POISONED(pwd.pw_name);
3293   ASSERT_TRUE(pwd.pw_name != NULL);
3294   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3295   EXPECT_NOT_POISONED(pwd.pw_uid);
3296   ASSERT_EQ(0U, pwd.pw_uid);
3297   EXPECT_NOT_POISONED(pwdres);
3298 }
3299 
TEST(MemorySanitizer,getpwnam_r)3300 TEST(MemorySanitizer, getpwnam_r) {
3301   struct passwd pwd;
3302   struct passwd *pwdres;
3303   char buf[10000];
3304   int res = getpwnam_r("root", &pwd, buf, sizeof(buf), &pwdres);
3305   ASSERT_EQ(0, res);
3306   EXPECT_NOT_POISONED(pwd.pw_name);
3307   ASSERT_TRUE(pwd.pw_name != NULL);
3308   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3309   EXPECT_NOT_POISONED(pwd.pw_uid);
3310   ASSERT_EQ(0U, pwd.pw_uid);
3311   EXPECT_NOT_POISONED(pwdres);
3312 }
3313 
TEST(MemorySanitizer,getpwnam_r_positive)3314 TEST(MemorySanitizer, getpwnam_r_positive) {
3315   struct passwd pwd;
3316   struct passwd *pwdres;
3317   char s[5];
3318   strncpy(s, "abcd", 5);
3319   __msan_poison(s, 5);
3320   char buf[10000];
3321   int res;
3322   EXPECT_UMR(res = getpwnam_r(s, &pwd, buf, sizeof(buf), &pwdres));
3323 }
3324 
TEST(MemorySanitizer,getgrnam_r)3325 TEST(MemorySanitizer, getgrnam_r) {
3326   struct group grp;
3327   struct group *grpres;
3328   char buf[10000];
3329   int res = getgrnam_r(SUPERUSER_GROUP, &grp, buf, sizeof(buf), &grpres);
3330   ASSERT_EQ(0, res);
3331   // Note that getgrnam_r() returns 0 if the matching group is not found.
3332   ASSERT_NE(nullptr, grpres);
3333   EXPECT_NOT_POISONED(grp.gr_name);
3334   ASSERT_TRUE(grp.gr_name != NULL);
3335   EXPECT_NOT_POISONED(grp.gr_name[0]);
3336   EXPECT_NOT_POISONED(grp.gr_gid);
3337   EXPECT_NOT_POISONED(grpres);
3338 }
3339 
TEST(MemorySanitizer,getpwent)3340 TEST(MemorySanitizer, getpwent) {
3341   setpwent();
3342   struct passwd *p = getpwent();
3343   ASSERT_TRUE(p != NULL);
3344   EXPECT_NOT_POISONED(p->pw_name);
3345   ASSERT_TRUE(p->pw_name != NULL);
3346   EXPECT_NOT_POISONED(p->pw_name[0]);
3347   EXPECT_NOT_POISONED(p->pw_uid);
3348 }
3349 
TEST(MemorySanitizer,getpwent_r)3350 TEST(MemorySanitizer, getpwent_r) {
3351   struct passwd pwd;
3352   struct passwd *pwdres;
3353   char buf[10000];
3354   setpwent();
3355   int res = getpwent_r(&pwd, buf, sizeof(buf), &pwdres);
3356   ASSERT_EQ(0, res);
3357   EXPECT_NOT_POISONED(pwd.pw_name);
3358   ASSERT_TRUE(pwd.pw_name != NULL);
3359   EXPECT_NOT_POISONED(pwd.pw_name[0]);
3360   EXPECT_NOT_POISONED(pwd.pw_uid);
3361   EXPECT_NOT_POISONED(pwdres);
3362 }
3363 
3364 // There's no fgetpwent() on FreeBSD.
3365 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,fgetpwent)3366 TEST(MemorySanitizer, fgetpwent) {
3367   FILE *fp = fopen("/etc/passwd", "r");
3368   struct passwd *p = fgetpwent(fp);
3369   ASSERT_TRUE(p != NULL);
3370   EXPECT_NOT_POISONED(p->pw_name);
3371   ASSERT_TRUE(p->pw_name != NULL);
3372   EXPECT_NOT_POISONED(p->pw_name[0]);
3373   EXPECT_NOT_POISONED(p->pw_uid);
3374   fclose(fp);
3375 }
3376 #endif
3377 
TEST(MemorySanitizer,getgrent)3378 TEST(MemorySanitizer, getgrent) {
3379   setgrent();
3380   struct group *p = getgrent();
3381   ASSERT_TRUE(p != NULL);
3382   EXPECT_NOT_POISONED(p->gr_name);
3383   ASSERT_TRUE(p->gr_name != NULL);
3384   EXPECT_NOT_POISONED(p->gr_name[0]);
3385   EXPECT_NOT_POISONED(p->gr_gid);
3386 }
3387 
3388 // There's no fgetgrent() on FreeBSD.
3389 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,fgetgrent)3390 TEST(MemorySanitizer, fgetgrent) {
3391   FILE *fp = fopen("/etc/group", "r");
3392   struct group *grp = fgetgrent(fp);
3393   ASSERT_TRUE(grp != NULL);
3394   EXPECT_NOT_POISONED(grp->gr_name);
3395   ASSERT_TRUE(grp->gr_name != NULL);
3396   EXPECT_NOT_POISONED(grp->gr_name[0]);
3397   EXPECT_NOT_POISONED(grp->gr_gid);
3398   for (char **p = grp->gr_mem; *p; ++p) {
3399     EXPECT_NOT_POISONED((*p)[0]);
3400     EXPECT_TRUE(strlen(*p) > 0);
3401   }
3402   fclose(fp);
3403 }
3404 #endif
3405 
TEST(MemorySanitizer,getgrent_r)3406 TEST(MemorySanitizer, getgrent_r) {
3407   struct group grp;
3408   struct group *grpres;
3409   char buf[10000];
3410   setgrent();
3411   int res = getgrent_r(&grp, buf, sizeof(buf), &grpres);
3412   ASSERT_EQ(0, res);
3413   EXPECT_NOT_POISONED(grp.gr_name);
3414   ASSERT_TRUE(grp.gr_name != NULL);
3415   EXPECT_NOT_POISONED(grp.gr_name[0]);
3416   EXPECT_NOT_POISONED(grp.gr_gid);
3417   EXPECT_NOT_POISONED(grpres);
3418 }
3419 
3420 // There's no fgetgrent_r() on FreeBSD.
3421 #if !defined(__FreeBSD__)
TEST(MemorySanitizer,fgetgrent_r)3422 TEST(MemorySanitizer, fgetgrent_r) {
3423   FILE *fp = fopen("/etc/group", "r");
3424   struct group grp;
3425   struct group *grpres;
3426   char buf[10000];
3427   setgrent();
3428   int res = fgetgrent_r(fp, &grp, buf, sizeof(buf), &grpres);
3429   ASSERT_EQ(0, res);
3430   EXPECT_NOT_POISONED(grp.gr_name);
3431   ASSERT_TRUE(grp.gr_name != NULL);
3432   EXPECT_NOT_POISONED(grp.gr_name[0]);
3433   EXPECT_NOT_POISONED(grp.gr_gid);
3434   EXPECT_NOT_POISONED(grpres);
3435   fclose(fp);
3436 }
3437 #endif
3438 
TEST(MemorySanitizer,getgroups)3439 TEST(MemorySanitizer, getgroups) {
3440   int n = getgroups(0, 0);
3441   gid_t *gids = new gid_t[n];
3442   int res = getgroups(n, gids);
3443   ASSERT_EQ(n, res);
3444   for (int i = 0; i < n; ++i)
3445     EXPECT_NOT_POISONED(gids[i]);
3446 }
3447 
TEST(MemorySanitizer,wordexp)3448 TEST(MemorySanitizer, wordexp) {
3449   wordexp_t w;
3450   int res = wordexp("a b c", &w, 0);
3451   ASSERT_EQ(0, res);
3452   ASSERT_EQ(3U, w.we_wordc);
3453   ASSERT_STREQ("a", w.we_wordv[0]);
3454   ASSERT_STREQ("b", w.we_wordv[1]);
3455   ASSERT_STREQ("c", w.we_wordv[2]);
3456 }
3457 
3458 template<class T>
applySlt(T value,T shadow)3459 static bool applySlt(T value, T shadow) {
3460   __msan_partial_poison(&value, &shadow, sizeof(T));
3461   volatile bool zzz = true;
3462   // This "|| zzz" trick somehow makes LLVM emit "icmp slt" instead of
3463   // a shift-and-trunc to get at the highest bit.
3464   volatile bool v = value < 0 || zzz;
3465   return v;
3466 }
3467 
TEST(MemorySanitizer,SignedCompareWithZero)3468 TEST(MemorySanitizer, SignedCompareWithZero) {
3469   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xF));
3470   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFF));
3471   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0xFFFFFF));
3472   EXPECT_NOT_POISONED(applySlt<S4>(0xF, 0x7FFFFFF));
3473   EXPECT_UMR(applySlt<S4>(0xF, 0x80FFFFFF));
3474   EXPECT_UMR(applySlt<S4>(0xF, 0xFFFFFFFF));
3475 }
3476 
3477 template <class T, class S>
poisoned(T Va,S Sa)3478 static T poisoned(T Va, S Sa) {
3479   char SIZE_CHECK1[(ssize_t)sizeof(T) - (ssize_t)sizeof(S)];
3480   char SIZE_CHECK2[(ssize_t)sizeof(S) - (ssize_t)sizeof(T)];
3481   T a;
3482   a = Va;
3483   __msan_partial_poison(&a, &Sa, sizeof(T));
3484   return a;
3485 }
3486 
TEST(MemorySanitizer,ICmpRelational)3487 TEST(MemorySanitizer, ICmpRelational) {
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_NOT_POISONED(poisoned(0, 0) > poisoned(0, 0));
3509   EXPECT_NOT_POISONED(poisoned(0U, 0) > poisoned(0U, 0));
3510   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) > poisoned(0LL, 0LLU));
3511   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) > poisoned(0LLU, 0LLU));
3512   EXPECT_POISONED(poisoned(0xFF, 0xFF) > poisoned(0xFF, 0xFF));
3513   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >
3514                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3515   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >
3516                   poisoned(-1, 0xFFFFFFFFU));
3517 
3518   EXPECT_NOT_POISONED(poisoned(0, 0) >= poisoned(0, 0));
3519   EXPECT_NOT_POISONED(poisoned(0U, 0) >= poisoned(0U, 0));
3520   EXPECT_NOT_POISONED(poisoned(0LL, 0LLU) >= poisoned(0LL, 0LLU));
3521   EXPECT_NOT_POISONED(poisoned(0LLU, 0LLU) >= poisoned(0LLU, 0LLU));
3522   EXPECT_POISONED(poisoned(0xFF, 0xFF) >= poisoned(0xFF, 0xFF));
3523   EXPECT_POISONED(poisoned(0xFFFFFFFFU, 0xFFFFFFFFU) >=
3524                   poisoned(0xFFFFFFFFU, 0xFFFFFFFFU));
3525   EXPECT_POISONED(poisoned(-1, 0xFFFFFFFFU) >=
3526                   poisoned(-1, 0xFFFFFFFFU));
3527 
3528   EXPECT_POISONED(poisoned(6, 0xF) > poisoned(7, 0));
3529   EXPECT_POISONED(poisoned(0xF, 0xF) > poisoned(7, 0));
3530 
3531   EXPECT_NOT_POISONED(poisoned(-1, 0x80000000U) >= poisoned(-1, 0U));
3532 }
3533 
3534 #if MSAN_HAS_M128
TEST(MemorySanitizer,ICmpVectorRelational)3535 TEST(MemorySanitizer, ICmpVectorRelational) {
3536   EXPECT_NOT_POISONED(
3537       _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0)),
3538                    poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0))));
3539   EXPECT_NOT_POISONED(
3540       _mm_cmplt_epi16(poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0)),
3541                    poisoned(_mm_set1_epi32(0), _mm_set1_epi32(0))));
3542   EXPECT_POISONED(
3543       _mm_cmplt_epi16(poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF)),
3544                    poisoned(_mm_set1_epi16(0), _mm_set1_epi16(0xFFFF))));
3545   EXPECT_POISONED(_mm_cmpgt_epi16(poisoned(_mm_set1_epi16(6), _mm_set1_epi16(0xF)),
3546                                poisoned(_mm_set1_epi16(7), _mm_set1_epi16(0))));
3547 }
3548 #endif
3549 
3550 // Volatile bitfield store is implemented as load-mask-store
3551 // Test that we don't warn on the store of (uninitialized) padding.
3552 struct VolatileBitfieldStruct {
3553   volatile unsigned x : 1;
3554   unsigned y : 1;
3555 };
3556 
TEST(MemorySanitizer,VolatileBitfield)3557 TEST(MemorySanitizer, VolatileBitfield) {
3558   VolatileBitfieldStruct *S = new VolatileBitfieldStruct;
3559   S->x = 1;
3560   EXPECT_NOT_POISONED((unsigned)S->x);
3561   EXPECT_POISONED((unsigned)S->y);
3562 }
3563 
TEST(MemorySanitizer,UnalignedLoad)3564 TEST(MemorySanitizer, UnalignedLoad) {
3565   char x[32] __attribute__((aligned(8)));
3566   U4 origin = __LINE__;
3567   for (unsigned i = 0; i < sizeof(x) / 4; ++i)
3568     __msan_set_origin(x + 4 * i, 4, origin + i);
3569 
3570   memset(x + 8, 0, 16);
3571   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 6), origin + 1);
3572   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 7), origin + 1);
3573   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 8));
3574   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 9));
3575   EXPECT_NOT_POISONED(__sanitizer_unaligned_load16(x + 22));
3576   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 23), origin + 6);
3577   EXPECT_POISONED_O(__sanitizer_unaligned_load16(x + 24), origin + 6);
3578 
3579   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 4), origin + 1);
3580   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 7), origin + 1);
3581   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 8));
3582   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 9));
3583   EXPECT_NOT_POISONED(__sanitizer_unaligned_load32(x + 20));
3584   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 21), origin + 6);
3585   EXPECT_POISONED_O(__sanitizer_unaligned_load32(x + 24), origin + 6);
3586 
3587   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x), origin);
3588   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 1), origin);
3589   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 7), origin + 1);
3590   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 8));
3591   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 9));
3592   EXPECT_NOT_POISONED(__sanitizer_unaligned_load64(x + 16));
3593   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 17), origin + 6);
3594   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 21), origin + 6);
3595   EXPECT_POISONED_O(__sanitizer_unaligned_load64(x + 24), origin + 6);
3596 }
3597 
TEST(MemorySanitizer,UnalignedStore16)3598 TEST(MemorySanitizer, UnalignedStore16) {
3599   char x[5] __attribute__((aligned(4)));
3600   U2 y2 = 0;
3601   U4 origin = __LINE__;
3602   __msan_poison(&y2, 1);
3603   __msan_set_origin(&y2, 1, origin);
3604 
3605   __sanitizer_unaligned_store16(x + 1, y2);
3606   EXPECT_POISONED_O(x[0], origin);
3607   EXPECT_POISONED_O(x[1], origin);
3608   EXPECT_NOT_POISONED(x[2]);
3609   EXPECT_POISONED_O(x[3], origin);
3610 }
3611 
TEST(MemorySanitizer,UnalignedStore32)3612 TEST(MemorySanitizer, UnalignedStore32) {
3613   char x[8] __attribute__((aligned(4)));
3614   U4 y4 = 0;
3615   U4 origin = __LINE__;
3616   __msan_poison(&y4, 2);
3617   __msan_set_origin(&y4, 2, origin);
3618 
3619   __sanitizer_unaligned_store32(x + 3, y4);
3620   EXPECT_POISONED_O(x[0], origin);
3621   EXPECT_POISONED_O(x[1], origin);
3622   EXPECT_POISONED_O(x[2], origin);
3623   EXPECT_POISONED_O(x[3], origin);
3624   EXPECT_POISONED_O(x[4], origin);
3625   EXPECT_NOT_POISONED(x[5]);
3626   EXPECT_NOT_POISONED(x[6]);
3627   EXPECT_POISONED_O(x[7], origin);
3628 }
3629 
TEST(MemorySanitizer,UnalignedStore64)3630 TEST(MemorySanitizer, UnalignedStore64) {
3631   char x[16] __attribute__((aligned(8)));
3632   U8 y8 = 0;
3633   U4 origin = __LINE__;
3634   __msan_poison(&y8, 3);
3635   __msan_poison(((char *)&y8) + sizeof(y8) - 2, 1);
3636   __msan_set_origin(&y8, 8, origin);
3637 
3638   __sanitizer_unaligned_store64(x + 3, y8);
3639   EXPECT_POISONED_O(x[0], origin);
3640   EXPECT_POISONED_O(x[1], origin);
3641   EXPECT_POISONED_O(x[2], origin);
3642   EXPECT_POISONED_O(x[3], origin);
3643   EXPECT_POISONED_O(x[4], origin);
3644   EXPECT_POISONED_O(x[5], origin);
3645   EXPECT_NOT_POISONED(x[6]);
3646   EXPECT_NOT_POISONED(x[7]);
3647   EXPECT_NOT_POISONED(x[8]);
3648   EXPECT_POISONED_O(x[9], origin);
3649   EXPECT_NOT_POISONED(x[10]);
3650   EXPECT_POISONED_O(x[11], origin);
3651 }
3652 
TEST(MemorySanitizer,UnalignedStore16_precise)3653 TEST(MemorySanitizer, UnalignedStore16_precise) {
3654   char x[8] __attribute__((aligned(4)));
3655   U2 y = 0;
3656   U4 originx1 = __LINE__;
3657   U4 originx2 = __LINE__;
3658   U4 originy = __LINE__;
3659   __msan_poison(x, sizeof(x));
3660   __msan_set_origin(x, 4, originx1);
3661   __msan_set_origin(x + 4, 4, originx2);
3662   __msan_poison(((char *)&y) + 1, 1);
3663   __msan_set_origin(&y, sizeof(y), originy);
3664 
3665   __sanitizer_unaligned_store16(x + 3, y);
3666   EXPECT_POISONED_O(x[0], originx1);
3667   EXPECT_POISONED_O(x[1], originx1);
3668   EXPECT_POISONED_O(x[2], originx1);
3669   EXPECT_NOT_POISONED(x[3]);
3670   EXPECT_POISONED_O(x[4], originy);
3671   EXPECT_POISONED_O(x[5], originy);
3672   EXPECT_POISONED_O(x[6], originy);
3673   EXPECT_POISONED_O(x[7], originy);
3674 }
3675 
TEST(MemorySanitizer,UnalignedStore16_precise2)3676 TEST(MemorySanitizer, UnalignedStore16_precise2) {
3677   char x[8] __attribute__((aligned(4)));
3678   U2 y = 0;
3679   U4 originx1 = __LINE__;
3680   U4 originx2 = __LINE__;
3681   U4 originy = __LINE__;
3682   __msan_poison(x, sizeof(x));
3683   __msan_set_origin(x, 4, originx1);
3684   __msan_set_origin(x + 4, 4, originx2);
3685   __msan_poison(((char *)&y), 1);
3686   __msan_set_origin(&y, sizeof(y), originy);
3687 
3688   __sanitizer_unaligned_store16(x + 3, y);
3689   EXPECT_POISONED_O(x[0], originy);
3690   EXPECT_POISONED_O(x[1], originy);
3691   EXPECT_POISONED_O(x[2], originy);
3692   EXPECT_POISONED_O(x[3], originy);
3693   EXPECT_NOT_POISONED(x[4]);
3694   EXPECT_POISONED_O(x[5], originx2);
3695   EXPECT_POISONED_O(x[6], originx2);
3696   EXPECT_POISONED_O(x[7], originx2);
3697 }
3698 
TEST(MemorySanitizer,UnalignedStore64_precise)3699 TEST(MemorySanitizer, UnalignedStore64_precise) {
3700   char x[12] __attribute__((aligned(8)));
3701   U8 y = 0;
3702   U4 originx1 = __LINE__;
3703   U4 originx2 = __LINE__;
3704   U4 originx3 = __LINE__;
3705   U4 originy = __LINE__;
3706   __msan_poison(x, sizeof(x));
3707   __msan_set_origin(x, 4, originx1);
3708   __msan_set_origin(x + 4, 4, originx2);
3709   __msan_set_origin(x + 8, 4, originx3);
3710   __msan_poison(((char *)&y) + 1, 1);
3711   __msan_poison(((char *)&y) + 7, 1);
3712   __msan_set_origin(&y, sizeof(y), originy);
3713 
3714   __sanitizer_unaligned_store64(x + 2, y);
3715   EXPECT_POISONED_O(x[0], originy);
3716   EXPECT_POISONED_O(x[1], originy);
3717   EXPECT_NOT_POISONED(x[2]);
3718   EXPECT_POISONED_O(x[3], originy);
3719 
3720   EXPECT_NOT_POISONED(x[4]);
3721   EXPECT_NOT_POISONED(x[5]);
3722   EXPECT_NOT_POISONED(x[6]);
3723   EXPECT_NOT_POISONED(x[7]);
3724 
3725   EXPECT_NOT_POISONED(x[8]);
3726   EXPECT_POISONED_O(x[9], originy);
3727   EXPECT_POISONED_O(x[10], originy);
3728   EXPECT_POISONED_O(x[11], originy);
3729 }
3730 
TEST(MemorySanitizer,UnalignedStore64_precise2)3731 TEST(MemorySanitizer, UnalignedStore64_precise2) {
3732   char x[12] __attribute__((aligned(8)));
3733   U8 y = 0;
3734   U4 originx1 = __LINE__;
3735   U4 originx2 = __LINE__;
3736   U4 originx3 = __LINE__;
3737   U4 originy = __LINE__;
3738   __msan_poison(x, sizeof(x));
3739   __msan_set_origin(x, 4, originx1);
3740   __msan_set_origin(x + 4, 4, originx2);
3741   __msan_set_origin(x + 8, 4, originx3);
3742   __msan_poison(((char *)&y) + 3, 3);
3743   __msan_set_origin(&y, sizeof(y), originy);
3744 
3745   __sanitizer_unaligned_store64(x + 2, y);
3746   EXPECT_POISONED_O(x[0], originx1);
3747   EXPECT_POISONED_O(x[1], originx1);
3748   EXPECT_NOT_POISONED(x[2]);
3749   EXPECT_NOT_POISONED(x[3]);
3750 
3751   EXPECT_NOT_POISONED(x[4]);
3752   EXPECT_POISONED_O(x[5], originy);
3753   EXPECT_POISONED_O(x[6], originy);
3754   EXPECT_POISONED_O(x[7], originy);
3755 
3756   EXPECT_NOT_POISONED(x[8]);
3757   EXPECT_NOT_POISONED(x[9]);
3758   EXPECT_POISONED_O(x[10], originx3);
3759   EXPECT_POISONED_O(x[11], originx3);
3760 }
3761 
3762 #if (defined(__x86_64__) && defined(__clang__))
3763 namespace {
3764 typedef U1 V16x8 __attribute__((__vector_size__(16)));
3765 typedef U2 V8x16 __attribute__((__vector_size__(16)));
3766 typedef U4 V4x32 __attribute__((__vector_size__(16)));
3767 typedef U8 V2x64 __attribute__((__vector_size__(16)));
3768 typedef U4 V8x32 __attribute__((__vector_size__(32)));
3769 typedef U8 V4x64 __attribute__((__vector_size__(32)));
3770 typedef U4 V2x32 __attribute__((__vector_size__(8)));
3771 typedef U2 V4x16 __attribute__((__vector_size__(8)));
3772 typedef U1 V8x8 __attribute__((__vector_size__(8)));
3773 
3774 
shift_sse2_left_scalar(V8x16 x,U4 y)3775 V8x16 shift_sse2_left_scalar(V8x16 x, U4 y) {
3776   return _mm_slli_epi16(x, y);
3777 }
3778 
shift_sse2_left(V8x16 x,V8x16 y)3779 V8x16 shift_sse2_left(V8x16 x, V8x16 y) {
3780   return _mm_sll_epi16(x, y);
3781 }
3782 
TEST(VectorShiftTest,sse2_left_scalar)3783 TEST(VectorShiftTest, sse2_left_scalar) {
3784   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
3785   V8x16 u = shift_sse2_left_scalar(v, 2);
3786   EXPECT_POISONED(u[0]);
3787   EXPECT_POISONED(u[1]);
3788   EXPECT_NOT_POISONED(u[0] | (3U << 2));
3789   EXPECT_NOT_POISONED(u[1] | (7U << 2));
3790   u[0] = u[1] = 0;
3791   EXPECT_NOT_POISONED(u);
3792 }
3793 
TEST(VectorShiftTest,sse2_left_scalar_by_uninit)3794 TEST(VectorShiftTest, sse2_left_scalar_by_uninit) {
3795   V8x16 v = {0, 1, 2, 3, 4, 5, 6, 7};
3796   V8x16 u = shift_sse2_left_scalar(v, Poisoned<U4>());
3797   EXPECT_POISONED(u[0]);
3798   EXPECT_POISONED(u[1]);
3799   EXPECT_POISONED(u[2]);
3800   EXPECT_POISONED(u[3]);
3801   EXPECT_POISONED(u[4]);
3802   EXPECT_POISONED(u[5]);
3803   EXPECT_POISONED(u[6]);
3804   EXPECT_POISONED(u[7]);
3805 }
3806 
TEST(VectorShiftTest,sse2_left)3807 TEST(VectorShiftTest, sse2_left) {
3808   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
3809   // Top 64 bits of shift count don't affect the result.
3810   V2x64 s = {2, Poisoned<U8>()};
3811   V8x16 u = shift_sse2_left(v, s);
3812   EXPECT_POISONED(u[0]);
3813   EXPECT_POISONED(u[1]);
3814   EXPECT_NOT_POISONED(u[0] | (3U << 2));
3815   EXPECT_NOT_POISONED(u[1] | (7U << 2));
3816   u[0] = u[1] = 0;
3817   EXPECT_NOT_POISONED(u);
3818 }
3819 
TEST(VectorShiftTest,sse2_left_by_uninit)3820 TEST(VectorShiftTest, sse2_left_by_uninit) {
3821   V8x16 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3, 4, 5, 6, 7};
3822   V2x64 s = {Poisoned<U8>(), Poisoned<U8>()};
3823   V8x16 u = shift_sse2_left(v, s);
3824   EXPECT_POISONED(u[0]);
3825   EXPECT_POISONED(u[1]);
3826   EXPECT_POISONED(u[2]);
3827   EXPECT_POISONED(u[3]);
3828   EXPECT_POISONED(u[4]);
3829   EXPECT_POISONED(u[5]);
3830   EXPECT_POISONED(u[6]);
3831   EXPECT_POISONED(u[7]);
3832 }
3833 
3834 #ifdef __AVX2__
shift_avx2_left(V4x32 x,V4x32 y)3835 V4x32 shift_avx2_left(V4x32 x, V4x32 y) {
3836   return _mm_sllv_epi32(x, y);
3837 }
3838 // This is variable vector shift that's only available starting with AVX2.
3839 // V4x32 shift_avx2_left(V4x32 x, V4x32 y) {
TEST(VectorShiftTest,avx2_left)3840 TEST(VectorShiftTest, avx2_left) {
3841   V4x32 v = {Poisoned<U2>(0, 3), Poisoned<U2>(0, 7), 2, 3};
3842   V4x32 s = {2, Poisoned<U4>(), 3, Poisoned<U4>()};
3843   V4x32 u = shift_avx2_left(v, s);
3844   EXPECT_POISONED(u[0]);
3845   EXPECT_NOT_POISONED(u[0] | (~7U));
3846   EXPECT_POISONED(u[1]);
3847   EXPECT_POISONED(u[1] | (~31U));
3848   EXPECT_NOT_POISONED(u[2]);
3849   EXPECT_POISONED(u[3]);
3850   EXPECT_POISONED(u[3] | (~31U));
3851 }
3852 #endif // __AVX2__
3853 } // namespace
3854 
TEST(VectorPackTest,sse2_packssdw_128)3855 TEST(VectorPackTest, sse2_packssdw_128) {
3856   const unsigned S2_max = (1 << 15) - 1;
3857   V4x32 a = {Poisoned<U4>(0, 0xFF0000), Poisoned<U4>(0, 0xFFFF0000),
3858              S2_max + 100, 4};
3859   V4x32 b = {Poisoned<U4>(0, 0xFF), S2_max + 10000, Poisoned<U4>(0, 0xFF00),
3860              S2_max};
3861 
3862   V8x16 c = _mm_packs_epi32(a, b);
3863 
3864   EXPECT_POISONED(c[0]);
3865   EXPECT_POISONED(c[1]);
3866   EXPECT_NOT_POISONED(c[2]);
3867   EXPECT_NOT_POISONED(c[3]);
3868   EXPECT_POISONED(c[4]);
3869   EXPECT_NOT_POISONED(c[5]);
3870   EXPECT_POISONED(c[6]);
3871   EXPECT_NOT_POISONED(c[7]);
3872 
3873   EXPECT_EQ(c[2], S2_max);
3874   EXPECT_EQ(c[3], 4);
3875   EXPECT_EQ(c[5], S2_max);
3876   EXPECT_EQ(c[7], S2_max);
3877 }
3878 
TEST(VectorPackTest,mmx_packuswb)3879 TEST(VectorPackTest, mmx_packuswb) {
3880   const unsigned U1_max = (1 << 8) - 1;
3881   V4x16 a = {Poisoned<U2>(0, 0xFF00), Poisoned<U2>(0, 0xF000U), U1_max + 100,
3882              4};
3883   V4x16 b = {Poisoned<U2>(0, 0xFF), U1_max - 1, Poisoned<U2>(0, 0xF), U1_max};
3884   V8x8 c = _mm_packs_pu16(a, b);
3885 
3886   EXPECT_POISONED(c[0]);
3887   EXPECT_POISONED(c[1]);
3888   EXPECT_NOT_POISONED(c[2]);
3889   EXPECT_NOT_POISONED(c[3]);
3890   EXPECT_POISONED(c[4]);
3891   EXPECT_NOT_POISONED(c[5]);
3892   EXPECT_POISONED(c[6]);
3893   EXPECT_NOT_POISONED(c[7]);
3894 
3895   EXPECT_EQ(c[2], U1_max);
3896   EXPECT_EQ(c[3], 4);
3897   EXPECT_EQ(c[5], U1_max - 1);
3898   EXPECT_EQ(c[7], U1_max);
3899 }
3900 
TEST(VectorSadTest,sse2_psad_bw)3901 TEST(VectorSadTest, sse2_psad_bw) {
3902   V16x8 a = {Poisoned<U1>(), 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
3903   V16x8 b = {100, 101, 102, 103, 104, 105, 106, 107,
3904              108, 109, 110, 111, 112, 113, 114, 115};
3905   V2x64 c = _mm_sad_epu8(a, b);
3906 
3907   EXPECT_POISONED(c[0]);
3908   EXPECT_NOT_POISONED(c[1]);
3909 
3910   EXPECT_EQ(800U, c[1]);
3911 }
3912 
TEST(VectorMaddTest,mmx_pmadd_wd)3913 TEST(VectorMaddTest, mmx_pmadd_wd) {
3914   V4x16 a = {Poisoned<U2>(), 1, 2, 3};
3915   V4x16 b = {100, 101, 102, 103};
3916   V2x32 c = _mm_madd_pi16(a, b);
3917 
3918   EXPECT_POISONED(c[0]);
3919   EXPECT_NOT_POISONED(c[1]);
3920 
3921   EXPECT_EQ((unsigned)(2 * 102 + 3 * 103), c[1]);
3922 }
3923 #endif  // defined(__clang__)
3924 
TEST(MemorySanitizerOrigins,SetGet)3925 TEST(MemorySanitizerOrigins, SetGet) {
3926   EXPECT_EQ(TrackingOrigins(), !!__msan_get_track_origins());
3927   if (!TrackingOrigins()) return;
3928   int x;
3929   __msan_set_origin(&x, sizeof(x), 1234);
3930   EXPECT_ORIGIN(1234U, __msan_get_origin(&x));
3931   __msan_set_origin(&x, sizeof(x), 5678);
3932   EXPECT_ORIGIN(5678U, __msan_get_origin(&x));
3933   __msan_set_origin(&x, sizeof(x), 0);
3934   EXPECT_ORIGIN(0U, __msan_get_origin(&x));
3935 }
3936 
3937 namespace {
3938 struct S {
3939   U4 dummy;
3940   U2 a;
3941   U2 b;
3942 };
3943 
TEST(MemorySanitizerOrigins,InitializedStoreDoesNotChangeOrigin)3944 TEST(MemorySanitizerOrigins, InitializedStoreDoesNotChangeOrigin) {
3945   if (!TrackingOrigins()) return;
3946 
3947   S s;
3948   U4 origin = rand();  // NOLINT
3949   s.a = *GetPoisonedO<U2>(0, origin);
3950   EXPECT_ORIGIN(origin, __msan_get_origin(&s.a));
3951   EXPECT_ORIGIN(origin, __msan_get_origin(&s.b));
3952 
3953   s.b = 42;
3954   EXPECT_ORIGIN(origin, __msan_get_origin(&s.a));
3955   EXPECT_ORIGIN(origin, __msan_get_origin(&s.b));
3956 }
3957 }  // namespace
3958 
3959 template<class T, class BinaryOp>
3960 INLINE
BinaryOpOriginTest(BinaryOp op)3961 void BinaryOpOriginTest(BinaryOp op) {
3962   U4 ox = rand();  //NOLINT
3963   U4 oy = rand();  //NOLINT
3964   T *x = GetPoisonedO<T>(0, ox, 0);
3965   T *y = GetPoisonedO<T>(1, oy, 0);
3966   T *z = GetPoisonedO<T>(2, 0, 0);
3967 
3968   *z = op(*x, *y);
3969   U4 origin = __msan_get_origin(z);
3970   EXPECT_POISONED_O(*z, origin);
3971   EXPECT_EQ(true, __msan_origin_is_descendant_or_same(origin, ox) ||
3972                       __msan_origin_is_descendant_or_same(origin, oy));
3973 
3974   // y is poisoned, x is not.
3975   *x = 10101;
3976   *y = *GetPoisonedO<T>(1, oy);
3977   break_optimization(x);
3978   __msan_set_origin(z, sizeof(*z), 0);
3979   *z = op(*x, *y);
3980   EXPECT_POISONED_O(*z, oy);
3981   EXPECT_ORIGIN(oy, __msan_get_origin(z));
3982 
3983   // x is poisoned, y is not.
3984   *x = *GetPoisonedO<T>(0, ox);
3985   *y = 10101010;
3986   break_optimization(y);
3987   __msan_set_origin(z, sizeof(*z), 0);
3988   *z = op(*x, *y);
3989   EXPECT_POISONED_O(*z, ox);
3990   EXPECT_ORIGIN(ox, __msan_get_origin(z));
3991 }
3992 
XOR(const T & a,const T & b)3993 template<class T> INLINE T XOR(const T &a, const T&b) { return a ^ b; }
ADD(const T & a,const T & b)3994 template<class T> INLINE T ADD(const T &a, const T&b) { return a + b; }
SUB(const T & a,const T & b)3995 template<class T> INLINE T SUB(const T &a, const T&b) { return a - b; }
MUL(const T & a,const T & b)3996 template<class T> INLINE T MUL(const T &a, const T&b) { return a * b; }
AND(const T & a,const T & b)3997 template<class T> INLINE T AND(const T &a, const T&b) { return a & b; }
OR(const T & a,const T & b)3998 template<class T> INLINE T OR (const T &a, const T&b) { return a | b; }
3999 
TEST(MemorySanitizerOrigins,BinaryOp)4000 TEST(MemorySanitizerOrigins, BinaryOp) {
4001   if (!TrackingOrigins()) return;
4002   BinaryOpOriginTest<S8>(XOR<S8>);
4003   BinaryOpOriginTest<U8>(ADD<U8>);
4004   BinaryOpOriginTest<S4>(SUB<S4>);
4005   BinaryOpOriginTest<S4>(MUL<S4>);
4006   BinaryOpOriginTest<U4>(OR<U4>);
4007   BinaryOpOriginTest<U4>(AND<U4>);
4008   BinaryOpOriginTest<double>(ADD<U4>);
4009   BinaryOpOriginTest<float>(ADD<S4>);
4010   BinaryOpOriginTest<double>(ADD<double>);
4011   BinaryOpOriginTest<float>(ADD<double>);
4012 }
4013 
TEST(MemorySanitizerOrigins,Unary)4014 TEST(MemorySanitizerOrigins, Unary) {
4015   if (!TrackingOrigins()) return;
4016   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4017   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4018   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4019   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4020 
4021   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4022   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4023   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4024   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4025 
4026   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4027   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4028   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4029   EXPECT_POISONED_O(*GetPoisonedO<U4>(0, __LINE__), __LINE__);
4030 
4031   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4032   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4033   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4034   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4035 
4036   EXPECT_POISONED_O((void*)*GetPoisonedO<S8>(0, __LINE__), __LINE__);
4037   EXPECT_POISONED_O((U8)*GetPoisonedO<void*>(0, __LINE__), __LINE__);
4038 }
4039 
TEST(MemorySanitizerOrigins,EQ)4040 TEST(MemorySanitizerOrigins, EQ) {
4041   if (!TrackingOrigins()) return;
4042   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) <= 11, __LINE__);
4043   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__) == 11, __LINE__);
4044   EXPECT_POISONED_O(*GetPoisonedO<float>(0, __LINE__) == 1.1, __LINE__);
4045 }
4046 
TEST(MemorySanitizerOrigins,DIV)4047 TEST(MemorySanitizerOrigins, DIV) {
4048   if (!TrackingOrigins()) return;
4049   EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) / 100, __LINE__);
4050   unsigned o = __LINE__;
4051   EXPECT_UMR_O(volatile unsigned y = 100 / *GetPoisonedO<S4>(0, o, 1), o);
4052 }
4053 
TEST(MemorySanitizerOrigins,SHIFT)4054 TEST(MemorySanitizerOrigins, SHIFT) {
4055   if (!TrackingOrigins()) return;
4056   EXPECT_POISONED_O(*GetPoisonedO<U8>(0, __LINE__) >> 10, __LINE__);
4057   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) >> 10, __LINE__);
4058   EXPECT_POISONED_O(*GetPoisonedO<S8>(0, __LINE__) << 10, __LINE__);
4059   EXPECT_POISONED_O(10U << *GetPoisonedO<U8>(0, __LINE__), __LINE__);
4060   EXPECT_POISONED_O(-10 >> *GetPoisonedO<S8>(0, __LINE__), __LINE__);
4061   EXPECT_POISONED_O(-10 << *GetPoisonedO<S8>(0, __LINE__), __LINE__);
4062 }
4063 
4064 template<class T, int N>
MemCpyTest()4065 void MemCpyTest() {
4066   int ox = __LINE__;
4067   T *x = new T[N];
4068   T *y = new T[N];
4069   T *z = new T[N];
4070   T *q = new T[N];
4071   __msan_poison(x, N * sizeof(T));
4072   __msan_set_origin(x, N * sizeof(T), ox);
4073   __msan_set_origin(y, N * sizeof(T), 777777);
4074   __msan_set_origin(z, N * sizeof(T), 888888);
4075   EXPECT_NOT_POISONED(x);
4076   memcpy(y, x, N * sizeof(T));
4077   EXPECT_POISONED_O(y[0], ox);
4078   EXPECT_POISONED_O(y[N/2], ox);
4079   EXPECT_POISONED_O(y[N-1], ox);
4080   EXPECT_NOT_POISONED(x);
4081   void *res = mempcpy(q, x, N * sizeof(T));
4082   ASSERT_EQ(q + N, res);
4083   EXPECT_POISONED_O(q[0], ox);
4084   EXPECT_POISONED_O(q[N/2], ox);
4085   EXPECT_POISONED_O(q[N-1], ox);
4086   EXPECT_NOT_POISONED(x);
4087   memmove(z, x, N * sizeof(T));
4088   EXPECT_POISONED_O(z[0], ox);
4089   EXPECT_POISONED_O(z[N/2], ox);
4090   EXPECT_POISONED_O(z[N-1], ox);
4091 }
4092 
TEST(MemorySanitizerOrigins,LargeMemCpy)4093 TEST(MemorySanitizerOrigins, LargeMemCpy) {
4094   if (!TrackingOrigins()) return;
4095   MemCpyTest<U1, 10000>();
4096   MemCpyTest<U8, 10000>();
4097 }
4098 
TEST(MemorySanitizerOrigins,SmallMemCpy)4099 TEST(MemorySanitizerOrigins, SmallMemCpy) {
4100   if (!TrackingOrigins()) return;
4101   MemCpyTest<U8, 1>();
4102   MemCpyTest<U8, 2>();
4103   MemCpyTest<U8, 3>();
4104 }
4105 
TEST(MemorySanitizerOrigins,Select)4106 TEST(MemorySanitizerOrigins, Select) {
4107   if (!TrackingOrigins()) return;
4108   EXPECT_NOT_POISONED(g_one ? 1 : *GetPoisonedO<S4>(0, __LINE__));
4109   EXPECT_POISONED_O(*GetPoisonedO<S4>(0, __LINE__), __LINE__);
4110   S4 x;
4111   break_optimization(&x);
4112   x = g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 0;
4113 
4114   EXPECT_POISONED_O(g_1 ? *GetPoisonedO<S4>(0, __LINE__) : 1, __LINE__);
4115   EXPECT_POISONED_O(g_0 ? 1 : *GetPoisonedO<S4>(0, __LINE__), __LINE__);
4116 }
4117 
RetvalOriginTest(U4 origin)4118 NOINLINE int RetvalOriginTest(U4 origin) {
4119   int *a = new int;
4120   break_optimization(a);
4121   __msan_set_origin(a, sizeof(*a), origin);
4122   int res = *a;
4123   delete a;
4124   return res;
4125 }
4126 
TEST(MemorySanitizerOrigins,Retval)4127 TEST(MemorySanitizerOrigins, Retval) {
4128   if (!TrackingOrigins()) return;
4129   EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
4130 }
4131 
ParamOriginTest(int param,U4 origin)4132 NOINLINE void ParamOriginTest(int param, U4 origin) {
4133   EXPECT_POISONED_O(param, origin);
4134 }
4135 
TEST(MemorySanitizerOrigins,Param)4136 TEST(MemorySanitizerOrigins, Param) {
4137   if (!TrackingOrigins()) return;
4138   int *a = new int;
4139   U4 origin = __LINE__;
4140   break_optimization(a);
4141   __msan_set_origin(a, sizeof(*a), origin);
4142   ParamOriginTest(*a, origin);
4143   delete a;
4144 }
4145 
TEST(MemorySanitizerOrigins,Invoke)4146 TEST(MemorySanitizerOrigins, Invoke) {
4147   if (!TrackingOrigins()) return;
4148   StructWithDtor s;  // Will cause the calls to become invokes.
4149   EXPECT_POISONED_O(RetvalOriginTest(__LINE__), __LINE__);
4150 }
4151 
TEST(MemorySanitizerOrigins,strlen)4152 TEST(MemorySanitizerOrigins, strlen) {
4153   S8 alignment;
4154   break_optimization(&alignment);
4155   char x[4] = {'a', 'b', 0, 0};
4156   __msan_poison(&x[2], 1);
4157   U4 origin = __LINE__;
4158   __msan_set_origin(x, sizeof(x), origin);
4159   EXPECT_UMR_O(volatile unsigned y = strlen(x), origin);
4160 }
4161 
TEST(MemorySanitizerOrigins,wcslen)4162 TEST(MemorySanitizerOrigins, wcslen) {
4163   wchar_t w[3] = {'a', 'b', 0};
4164   U4 origin = __LINE__;
4165   __msan_set_origin(w, sizeof(w), origin);
4166   __msan_poison(&w[2], sizeof(wchar_t));
4167   EXPECT_UMR_O(volatile unsigned y = wcslen(w), origin);
4168 }
4169 
4170 #if MSAN_HAS_M128
TEST(MemorySanitizerOrigins,StoreIntrinsic)4171 TEST(MemorySanitizerOrigins, StoreIntrinsic) {
4172   __m128 x, y;
4173   U4 origin = __LINE__;
4174   __msan_set_origin(&x, sizeof(x), origin);
4175   __msan_poison(&x, sizeof(x));
4176   __builtin_ia32_storeups((float*)&y, x);
4177   EXPECT_POISONED_O(y, origin);
4178 }
4179 #endif
4180 
RecursiveMalloc(int depth)4181 NOINLINE void RecursiveMalloc(int depth) {
4182   static int count;
4183   count++;
4184   if ((count % (1024 * 1024)) == 0)
4185     printf("RecursiveMalloc: %d\n", count);
4186   int *x1 = new int;
4187   int *x2 = new int;
4188   break_optimization(x1);
4189   break_optimization(x2);
4190   if (depth > 0) {
4191     RecursiveMalloc(depth-1);
4192     RecursiveMalloc(depth-1);
4193   }
4194   delete x1;
4195   delete x2;
4196 }
4197 
TEST(MemorySanitizer,Select)4198 TEST(MemorySanitizer, Select) {
4199   int x;
4200   int volatile* p = &x;
4201   int z = *p ? 1 : 0;
4202   EXPECT_POISONED(z);
4203 }
4204 
TEST(MemorySanitizer,SelectPartial)4205 TEST(MemorySanitizer, SelectPartial) {
4206   // Precise instrumentation of select.
4207   // Some bits of the result do not depend on select condition, and must stay
4208   // initialized even if select condition is not. These are the bits that are
4209   // equal and initialized in both left and right select arguments.
4210   U4 x = 0xFFFFABCDU;
4211   U4 x_s = 0xFFFF0000U;
4212   __msan_partial_poison(&x, &x_s, sizeof(x));
4213   U4 y = 0xAB00U;
4214   U1 cond = true;
4215   __msan_poison(&cond, sizeof(cond));
4216   U4 z = cond ? x : y;
4217   __msan_print_shadow(&z, sizeof(z));
4218   EXPECT_POISONED(z & 0xFFU);
4219   EXPECT_NOT_POISONED(z & 0xFF00U);
4220   EXPECT_POISONED(z & 0xFF0000U);
4221   EXPECT_POISONED(z & 0xFF000000U);
4222   EXPECT_EQ(0xAB00U, z & 0xFF00U);
4223 }
4224 
TEST(MemorySanitizerStress,DISABLED_MallocStackTrace)4225 TEST(MemorySanitizerStress, DISABLED_MallocStackTrace) {
4226   RecursiveMalloc(22);
4227 }
4228 
TEST(MemorySanitizerAllocator,get_estimated_allocated_size)4229 TEST(MemorySanitizerAllocator, get_estimated_allocated_size) {
4230   size_t sizes[] = {0, 20, 5000, 1<<20};
4231   for (size_t i = 0; i < sizeof(sizes) / sizeof(*sizes); ++i) {
4232     size_t alloc_size = __sanitizer_get_estimated_allocated_size(sizes[i]);
4233     EXPECT_EQ(alloc_size, sizes[i]);
4234   }
4235 }
4236 
TEST(MemorySanitizerAllocator,get_allocated_size_and_ownership)4237 TEST(MemorySanitizerAllocator, get_allocated_size_and_ownership) {
4238   char *array = reinterpret_cast<char*>(malloc(100));
4239   int *int_ptr = new int;
4240 
4241   EXPECT_TRUE(__sanitizer_get_ownership(array));
4242   EXPECT_EQ(100U, __sanitizer_get_allocated_size(array));
4243 
4244   EXPECT_TRUE(__sanitizer_get_ownership(int_ptr));
4245   EXPECT_EQ(sizeof(*int_ptr), __sanitizer_get_allocated_size(int_ptr));
4246 
4247   void *wild_addr = reinterpret_cast<void*>(0x1);
4248   EXPECT_FALSE(__sanitizer_get_ownership(wild_addr));
4249   EXPECT_EQ(0U, __sanitizer_get_allocated_size(wild_addr));
4250 
4251   EXPECT_FALSE(__sanitizer_get_ownership(array + 50));
4252   EXPECT_EQ(0U, __sanitizer_get_allocated_size(array + 50));
4253 
4254   // NULL is a valid argument for GetAllocatedSize but is not owned.
4255   EXPECT_FALSE(__sanitizer_get_ownership(NULL));
4256   EXPECT_EQ(0U, __sanitizer_get_allocated_size(NULL));
4257 
4258   free(array);
4259   EXPECT_FALSE(__sanitizer_get_ownership(array));
4260   EXPECT_EQ(0U, __sanitizer_get_allocated_size(array));
4261 
4262   delete int_ptr;
4263 }
4264 
TEST(MemorySanitizer,MlockTest)4265 TEST(MemorySanitizer, MlockTest) {
4266   EXPECT_EQ(0, mlockall(MCL_CURRENT));
4267   EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
4268   EXPECT_EQ(0, munlockall());
4269   EXPECT_EQ(0, munlock((void*)0x987, 0x654));
4270 }
4271 
4272 // Test that LargeAllocator unpoisons memory before releasing it to the OS.
TEST(MemorySanitizer,LargeAllocatorUnpoisonsOnFree)4273 TEST(MemorySanitizer, LargeAllocatorUnpoisonsOnFree) {
4274   void *p = malloc(1024 * 1024);
4275   free(p);
4276 
4277   typedef void *(*mmap_fn)(void *, size_t, int, int, int, off_t);
4278   mmap_fn real_mmap = (mmap_fn)dlsym(RTLD_NEXT, "mmap");
4279 
4280   // Allocate the page that was released to the OS in free() with the real mmap,
4281   // bypassing the interceptor.
4282   char *q = (char *)real_mmap(p, 4096, PROT_READ | PROT_WRITE,
4283                               MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
4284   ASSERT_NE((char *)0, q);
4285 
4286   ASSERT_TRUE(q <= p);
4287   ASSERT_TRUE(q + 4096 > p);
4288 
4289   EXPECT_NOT_POISONED(q[0]);
4290   EXPECT_NOT_POISONED(q[10]);
4291   EXPECT_NOT_POISONED(q[100]);
4292 
4293   munmap(q, 4096);
4294 }
4295 
4296 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
TEST(MemorySanitizer,MallocUsableSizeTest)4297 TEST(MemorySanitizer, MallocUsableSizeTest) {
4298   const size_t kArraySize = 100;
4299   char *array = Ident((char*)malloc(kArraySize));
4300   int *int_ptr = Ident(new int);
4301   EXPECT_EQ(0U, malloc_usable_size(NULL));
4302   EXPECT_EQ(kArraySize, malloc_usable_size(array));
4303   EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
4304   free(array);
4305   delete int_ptr;
4306 }
4307 #endif  // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
4308