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

source code of compiler-rt/lib/msan/tests/msan_test.cpp