• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===-- asan_test.cc ------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file is a part of AddressSanitizer, an address sanity checker.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "asan_test_utils.h"
14 
malloc_fff(size_t size)15 NOINLINE void *malloc_fff(size_t size) {
16   void *res = malloc/**/(size); break_optimization(0); return res;}
malloc_eee(size_t size)17 NOINLINE void *malloc_eee(size_t size) {
18   void *res = malloc_fff(size); break_optimization(0); return res;}
malloc_ddd(size_t size)19 NOINLINE void *malloc_ddd(size_t size) {
20   void *res = malloc_eee(size); break_optimization(0); return res;}
malloc_ccc(size_t size)21 NOINLINE void *malloc_ccc(size_t size) {
22   void *res = malloc_ddd(size); break_optimization(0); return res;}
malloc_bbb(size_t size)23 NOINLINE void *malloc_bbb(size_t size) {
24   void *res = malloc_ccc(size); break_optimization(0); return res;}
malloc_aaa(size_t size)25 NOINLINE void *malloc_aaa(size_t size) {
26   void *res = malloc_bbb(size); break_optimization(0); return res;}
27 
free_ccc(void * p)28 NOINLINE void free_ccc(void *p) { free(p); break_optimization(0);}
free_bbb(void * p)29 NOINLINE void free_bbb(void *p) { free_ccc(p); break_optimization(0);}
free_aaa(void * p)30 NOINLINE void free_aaa(void *p) { free_bbb(p); break_optimization(0);}
31 
32 template<typename T>
uaf_test(int size,int off)33 NOINLINE void uaf_test(int size, int off) {
34   void *p = malloc_aaa(size);
35   free_aaa(p);
36   for (int i = 1; i < 100; i++)
37     free_aaa(malloc_aaa(i));
38   fprintf(stderr, "writing %ld byte(s) at %p with offset %d\n",
39           (long)sizeof(T), p, off);
40   asan_write((T *)((char *)p + off));
41 }
42 
TEST(AddressSanitizer,HasFeatureAddressSanitizerTest)43 TEST(AddressSanitizer, HasFeatureAddressSanitizerTest) {
44 #if defined(__has_feature) && __has_feature(address_sanitizer)
45   bool asan = 1;
46 #elif defined(__SANITIZE_ADDRESS__)
47   bool asan = 1;
48 #else
49   bool asan = 0;
50 #endif
51   EXPECT_EQ(true, asan);
52 }
53 
TEST(AddressSanitizer,SimpleDeathTest)54 TEST(AddressSanitizer, SimpleDeathTest) {
55   EXPECT_DEATH(exit(1), "");
56 }
57 
TEST(AddressSanitizer,VariousMallocsTest)58 TEST(AddressSanitizer, VariousMallocsTest) {
59   int *a = (int*)malloc(100 * sizeof(int));
60   a[50] = 0;
61   free(a);
62 
63   int *r = (int*)malloc(10);
64   r = (int*)realloc(r, 2000 * sizeof(int));
65   r[1000] = 0;
66   free(r);
67 
68   int *b = new int[100];
69   b[50] = 0;
70   delete [] b;
71 
72   int *c = new int;
73   *c = 0;
74   delete c;
75 
76 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
77   int *pm;
78   int pm_res = posix_memalign((void**)&pm, kPageSize, kPageSize);
79   EXPECT_EQ(0, pm_res);
80   free(pm);
81 #endif  // SANITIZER_TEST_HAS_POSIX_MEMALIGN
82 
83 #if SANITIZER_TEST_HAS_MEMALIGN
84   int *ma = (int*)memalign(kPageSize, kPageSize);
85   EXPECT_EQ(0U, (uintptr_t)ma % kPageSize);
86   ma[123] = 0;
87   free(ma);
88 #endif  // SANITIZER_TEST_HAS_MEMALIGN
89 }
90 
TEST(AddressSanitizer,CallocTest)91 TEST(AddressSanitizer, CallocTest) {
92   int *a = (int*)calloc(100, sizeof(int));
93   EXPECT_EQ(0, a[10]);
94   free(a);
95 }
96 
TEST(AddressSanitizer,CallocReturnsZeroMem)97 TEST(AddressSanitizer, CallocReturnsZeroMem) {
98   size_t sizes[] = {16, 1000, 10000, 100000, 2100000};
99   for (size_t s = 0; s < sizeof(sizes)/sizeof(sizes[0]); s++) {
100     size_t size = sizes[s];
101     for (size_t iter = 0; iter < 5; iter++) {
102       char *x = Ident((char*)calloc(1, size));
103       EXPECT_EQ(x[0], 0);
104       EXPECT_EQ(x[size - 1], 0);
105       EXPECT_EQ(x[size / 2], 0);
106       EXPECT_EQ(x[size / 3], 0);
107       EXPECT_EQ(x[size / 4], 0);
108       memset(x, 0x42, size);
109       free(Ident(x));
110 #if !defined(_WIN32)
111       // FIXME: OOM on Windows. We should just make this a lit test
112       // with quarantine size set to 1.
113       free(Ident(malloc(Ident(1 << 27))));  // Try to drain the quarantine.
114 #endif
115     }
116   }
117 }
118 
119 // No valloc on Windows or Android.
120 #if !defined(_WIN32) && !defined(__ANDROID__)
TEST(AddressSanitizer,VallocTest)121 TEST(AddressSanitizer, VallocTest) {
122   void *a = valloc(100);
123   EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
124   free(a);
125 }
126 #endif
127 
128 #if SANITIZER_TEST_HAS_PVALLOC
TEST(AddressSanitizer,PvallocTest)129 TEST(AddressSanitizer, PvallocTest) {
130   char *a = (char*)pvalloc(kPageSize + 100);
131   EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
132   a[kPageSize + 101] = 1;  // we should not report an error here.
133   free(a);
134 
135   a = (char*)pvalloc(0);  // pvalloc(0) should allocate at least one page.
136   EXPECT_EQ(0U, (uintptr_t)a % kPageSize);
137   a[101] = 1;  // we should not report an error here.
138   free(a);
139 }
140 #endif  // SANITIZER_TEST_HAS_PVALLOC
141 
142 #if !defined(_WIN32)
143 // FIXME: Use an equivalent of pthread_setspecific on Windows.
TSDWorker(void * test_key)144 void *TSDWorker(void *test_key) {
145   if (test_key) {
146     pthread_setspecific(*(pthread_key_t*)test_key, (void*)0xfeedface);
147   }
148   return NULL;
149 }
150 
TSDDestructor(void * tsd)151 void TSDDestructor(void *tsd) {
152   // Spawning a thread will check that the current thread id is not -1.
153   pthread_t th;
154   PTHREAD_CREATE(&th, NULL, TSDWorker, NULL);
155   PTHREAD_JOIN(th, NULL);
156 }
157 
158 // This tests triggers the thread-specific data destruction fiasco which occurs
159 // if we don't manage the TSD destructors ourselves. We create a new pthread
160 // key with a non-NULL destructor which is likely to be put after the destructor
161 // of AsanThread in the list of destructors.
162 // In this case the TSD for AsanThread will be destroyed before TSDDestructor
163 // is called for the child thread, and a CHECK will fail when we call
164 // pthread_create() to spawn the grandchild.
TEST(AddressSanitizer,DISABLED_TSDTest)165 TEST(AddressSanitizer, DISABLED_TSDTest) {
166   pthread_t th;
167   pthread_key_t test_key;
168   pthread_key_create(&test_key, TSDDestructor);
169   PTHREAD_CREATE(&th, NULL, TSDWorker, &test_key);
170   PTHREAD_JOIN(th, NULL);
171   pthread_key_delete(test_key);
172 }
173 #endif
174 
TEST(AddressSanitizer,UAF_char)175 TEST(AddressSanitizer, UAF_char) {
176   const char *uaf_string = "AddressSanitizer:.*heap-use-after-free";
177   EXPECT_DEATH(uaf_test<U1>(1, 0), uaf_string);
178   EXPECT_DEATH(uaf_test<U1>(10, 0), uaf_string);
179   EXPECT_DEATH(uaf_test<U1>(10, 10), uaf_string);
180   EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, 0), uaf_string);
181   EXPECT_DEATH(uaf_test<U1>(kLargeMalloc, kLargeMalloc / 2), uaf_string);
182 }
183 
TEST(AddressSanitizer,UAF_long_double)184 TEST(AddressSanitizer, UAF_long_double) {
185   if (sizeof(long double) == sizeof(double)) return;
186   long double *p = Ident(new long double[10]);
187   EXPECT_DEATH(Ident(p)[12] = 0, "WRITE of size 1[026]");
188   EXPECT_DEATH(Ident(p)[0] = Ident(p)[12], "READ of size 1[026]");
189   delete [] Ident(p);
190 }
191 
192 #if !defined(_WIN32)
193 struct Packed5 {
194   int x;
195   char c;
196 } __attribute__((packed));
197 #else
198 # pragma pack(push, 1)
199 struct Packed5 {
200   int x;
201   char c;
202 };
203 # pragma pack(pop)
204 #endif
205 
TEST(AddressSanitizer,UAF_Packed5)206 TEST(AddressSanitizer, UAF_Packed5) {
207   static_assert(sizeof(Packed5) == 5, "Please check the keywords used");
208   Packed5 *p = Ident(new Packed5[2]);
209   EXPECT_DEATH(p[0] = p[3], "READ of size 5");
210   EXPECT_DEATH(p[3] = p[0], "WRITE of size 5");
211   delete [] Ident(p);
212 }
213 
214 #if ASAN_HAS_BLACKLIST
TEST(AddressSanitizer,IgnoreTest)215 TEST(AddressSanitizer, IgnoreTest) {
216   int *x = Ident(new int);
217   delete Ident(x);
218   *x = 0;
219 }
220 #endif  // ASAN_HAS_BLACKLIST
221 
222 struct StructWithBitField {
223   int bf1:1;
224   int bf2:1;
225   int bf3:1;
226   int bf4:29;
227 };
228 
TEST(AddressSanitizer,BitFieldPositiveTest)229 TEST(AddressSanitizer, BitFieldPositiveTest) {
230   StructWithBitField *x = new StructWithBitField;
231   delete Ident(x);
232   EXPECT_DEATH(x->bf1 = 0, "use-after-free");
233   EXPECT_DEATH(x->bf2 = 0, "use-after-free");
234   EXPECT_DEATH(x->bf3 = 0, "use-after-free");
235   EXPECT_DEATH(x->bf4 = 0, "use-after-free");
236 }
237 
238 struct StructWithBitFields_8_24 {
239   int a:8;
240   int b:24;
241 };
242 
TEST(AddressSanitizer,BitFieldNegativeTest)243 TEST(AddressSanitizer, BitFieldNegativeTest) {
244   StructWithBitFields_8_24 *x = Ident(new StructWithBitFields_8_24);
245   x->a = 0;
246   x->b = 0;
247   delete Ident(x);
248 }
249 
250 #if ASAN_NEEDS_SEGV
251 namespace {
252 
253 const char kSEGVCrash[] = "AddressSanitizer: SEGV on unknown address";
254 const char kOverriddenHandler[] = "ASan signal handler has been overridden\n";
255 
TEST(AddressSanitizer,WildAddressTest)256 TEST(AddressSanitizer, WildAddressTest) {
257   char *c = (char*)0x123;
258   EXPECT_DEATH(*c = 0, kSEGVCrash);
259 }
260 
my_sigaction_sighandler(int,siginfo_t *,void *)261 void my_sigaction_sighandler(int, siginfo_t*, void*) {
262   fprintf(stderr, kOverriddenHandler);
263   exit(1);
264 }
265 
my_signal_sighandler(int signum)266 void my_signal_sighandler(int signum) {
267   fprintf(stderr, kOverriddenHandler);
268   exit(1);
269 }
270 
TEST(AddressSanitizer,SignalTest)271 TEST(AddressSanitizer, SignalTest) {
272   struct sigaction sigact;
273   memset(&sigact, 0, sizeof(sigact));
274   sigact.sa_sigaction = my_sigaction_sighandler;
275   sigact.sa_flags = SA_SIGINFO;
276   // ASan should silently ignore sigaction()...
277   EXPECT_EQ(0, sigaction(SIGSEGV, &sigact, 0));
278 #ifdef __APPLE__
279   EXPECT_EQ(0, sigaction(SIGBUS, &sigact, 0));
280 #endif
281   char *c = (char*)0x123;
282   EXPECT_DEATH(*c = 0, kSEGVCrash);
283   // ... and signal().
284   EXPECT_EQ(0, signal(SIGSEGV, my_signal_sighandler));
285   EXPECT_DEATH(*c = 0, kSEGVCrash);
286 }
287 }  // namespace
288 #endif
289 
TestLargeMalloc(size_t size)290 static void TestLargeMalloc(size_t size) {
291   char buff[1024];
292   sprintf(buff, "is located 1 bytes to the left of %lu-byte", (long)size);
293   EXPECT_DEATH(Ident((char*)malloc(size))[-1] = 0, buff);
294 }
295 
TEST(AddressSanitizer,LargeMallocTest)296 TEST(AddressSanitizer, LargeMallocTest) {
297   const int max_size = (SANITIZER_WORDSIZE == 32) ? 1 << 26 : 1 << 28;
298   for (int i = 113; i < max_size; i = i * 2 + 13) {
299     TestLargeMalloc(i);
300   }
301 }
302 
303 #if !GTEST_USES_SIMPLE_RE
TEST(AddressSanitizer,HugeMallocTest)304 TEST(AddressSanitizer, HugeMallocTest) {
305   if (SANITIZER_WORDSIZE != 64 || ASAN_AVOID_EXPENSIVE_TESTS) return;
306   size_t n_megs = 4100;
307   EXPECT_DEATH(Ident((char*)malloc(n_megs << 20))[-1] = 0,
308                "is located 1 bytes to the left|"
309                "AddressSanitizer failed to allocate");
310 }
311 #endif
312 
313 #if SANITIZER_TEST_HAS_MEMALIGN
MemalignRun(size_t align,size_t size,int idx)314 void MemalignRun(size_t align, size_t size, int idx) {
315   char *p = (char *)memalign(align, size);
316   Ident(p)[idx] = 0;
317   free(p);
318 }
319 
TEST(AddressSanitizer,memalign)320 TEST(AddressSanitizer, memalign) {
321   for (int align = 16; align <= (1 << 23); align *= 2) {
322     size_t size = align * 5;
323     EXPECT_DEATH(MemalignRun(align, size, -1),
324                  "is located 1 bytes to the left");
325     EXPECT_DEATH(MemalignRun(align, size, size + 1),
326                  "is located 1 bytes to the right");
327   }
328 }
329 #endif  // SANITIZER_TEST_HAS_MEMALIGN
330 
ManyThreadsWorker(void * a)331 void *ManyThreadsWorker(void *a) {
332   for (int iter = 0; iter < 100; iter++) {
333     for (size_t size = 100; size < 2000; size *= 2) {
334       free(Ident(malloc(size)));
335     }
336   }
337   return 0;
338 }
339 
340 #if !defined(__aarch64__)
341 // FIXME: Infinite loop in AArch64 (PR24389).
TEST(AddressSanitizer,ManyThreadsTest)342 TEST(AddressSanitizer, ManyThreadsTest) {
343   const size_t kNumThreads =
344       (SANITIZER_WORDSIZE == 32 || ASAN_AVOID_EXPENSIVE_TESTS) ? 30 : 1000;
345   pthread_t t[kNumThreads];
346   for (size_t i = 0; i < kNumThreads; i++) {
347     PTHREAD_CREATE(&t[i], 0, ManyThreadsWorker, (void*)i);
348   }
349   for (size_t i = 0; i < kNumThreads; i++) {
350     PTHREAD_JOIN(t[i], 0);
351   }
352 }
353 #endif
354 
TEST(AddressSanitizer,ReallocTest)355 TEST(AddressSanitizer, ReallocTest) {
356   const int kMinElem = 5;
357   int *ptr = (int*)malloc(sizeof(int) * kMinElem);
358   ptr[3] = 3;
359   for (int i = 0; i < 10000; i++) {
360     ptr = (int*)realloc(ptr,
361         (my_rand() % 1000 + kMinElem) * sizeof(int));
362     EXPECT_EQ(3, ptr[3]);
363   }
364   free(ptr);
365   // Realloc pointer returned by malloc(0).
366   int *ptr2 = Ident((int*)malloc(0));
367   ptr2 = Ident((int*)realloc(ptr2, sizeof(*ptr2)));
368   *ptr2 = 42;
369   EXPECT_EQ(42, *ptr2);
370   free(ptr2);
371 }
372 
TEST(AddressSanitizer,ReallocFreedPointerTest)373 TEST(AddressSanitizer, ReallocFreedPointerTest) {
374   void *ptr = Ident(malloc(42));
375   ASSERT_TRUE(NULL != ptr);
376   free(ptr);
377   EXPECT_DEATH(ptr = realloc(ptr, 77), "attempting double-free");
378 }
379 
TEST(AddressSanitizer,ReallocInvalidPointerTest)380 TEST(AddressSanitizer, ReallocInvalidPointerTest) {
381   void *ptr = Ident(malloc(42));
382   EXPECT_DEATH(ptr = realloc((int*)ptr + 1, 77), "attempting free.*not malloc");
383   free(ptr);
384 }
385 
TEST(AddressSanitizer,ZeroSizeMallocTest)386 TEST(AddressSanitizer, ZeroSizeMallocTest) {
387   // Test that malloc(0) and similar functions don't return NULL.
388   void *ptr = Ident(malloc(0));
389   EXPECT_TRUE(NULL != ptr);
390   free(ptr);
391 #if SANITIZER_TEST_HAS_POSIX_MEMALIGN
392   int pm_res = posix_memalign(&ptr, 1<<20, 0);
393   EXPECT_EQ(0, pm_res);
394   EXPECT_TRUE(NULL != ptr);
395   free(ptr);
396 #endif  // SANITIZER_TEST_HAS_POSIX_MEMALIGN
397   int *int_ptr = new int[0];
398   int *int_ptr2 = new int[0];
399   EXPECT_TRUE(NULL != int_ptr);
400   EXPECT_TRUE(NULL != int_ptr2);
401   EXPECT_NE(int_ptr, int_ptr2);
402   delete[] int_ptr;
403   delete[] int_ptr2;
404 }
405 
406 #if SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
407 static const char *kMallocUsableSizeErrorMsg =
408   "AddressSanitizer: attempting to call malloc_usable_size()";
409 
TEST(AddressSanitizer,MallocUsableSizeTest)410 TEST(AddressSanitizer, MallocUsableSizeTest) {
411   const size_t kArraySize = 100;
412   char *array = Ident((char*)malloc(kArraySize));
413   int *int_ptr = Ident(new int);
414   EXPECT_EQ(0U, malloc_usable_size(NULL));
415   EXPECT_EQ(kArraySize, malloc_usable_size(array));
416   EXPECT_EQ(sizeof(int), malloc_usable_size(int_ptr));
417   EXPECT_DEATH(malloc_usable_size((void*)0x123), kMallocUsableSizeErrorMsg);
418   EXPECT_DEATH(malloc_usable_size(array + kArraySize / 2),
419                kMallocUsableSizeErrorMsg);
420   free(array);
421   EXPECT_DEATH(malloc_usable_size(array), kMallocUsableSizeErrorMsg);
422   delete int_ptr;
423 }
424 #endif  // SANITIZER_TEST_HAS_MALLOC_USABLE_SIZE
425 
WrongFree()426 void WrongFree() {
427   int *x = (int*)malloc(100 * sizeof(int));
428   // Use the allocated memory, otherwise Clang will optimize it out.
429   Ident(x);
430   free(x + 1);
431 }
432 
433 #if !defined(_WIN32)  // FIXME: This should be a lit test.
TEST(AddressSanitizer,WrongFreeTest)434 TEST(AddressSanitizer, WrongFreeTest) {
435   EXPECT_DEATH(WrongFree(), ASAN_PCRE_DOTALL
436                "ERROR: AddressSanitizer: attempting free.*not malloc"
437                ".*is located 4 bytes inside of 400-byte region"
438                ".*allocated by thread");
439 }
440 #endif
441 
DoubleFree()442 void DoubleFree() {
443   int *x = (int*)malloc(100 * sizeof(int));
444   fprintf(stderr, "DoubleFree: x=%p\n", (void *)x);
445   free(x);
446   free(x);
447   fprintf(stderr, "should have failed in the second free(%p)\n", (void *)x);
448   abort();
449 }
450 
451 #if !defined(_WIN32)  // FIXME: This should be a lit test.
TEST(AddressSanitizer,DoubleFreeTest)452 TEST(AddressSanitizer, DoubleFreeTest) {
453   EXPECT_DEATH(DoubleFree(), ASAN_PCRE_DOTALL
454                "ERROR: AddressSanitizer: attempting double-free"
455                ".*is located 0 bytes inside of 400-byte region"
456                ".*freed by thread T0 here"
457                ".*previously allocated by thread T0 here");
458 }
459 #endif
460 
461 template<int kSize>
SizedStackTest()462 NOINLINE void SizedStackTest() {
463   char a[kSize];
464   char  *A = Ident((char*)&a);
465   const char *expected_death = "AddressSanitizer: stack-buffer-";
466   for (size_t i = 0; i < kSize; i++)
467     A[i] = i;
468   EXPECT_DEATH(A[-1] = 0, expected_death);
469   EXPECT_DEATH(A[-5] = 0, expected_death);
470   EXPECT_DEATH(A[kSize] = 0, expected_death);
471   EXPECT_DEATH(A[kSize + 1] = 0, expected_death);
472   EXPECT_DEATH(A[kSize + 5] = 0, expected_death);
473   if (kSize > 16)
474     EXPECT_DEATH(A[kSize + 31] = 0, expected_death);
475 }
476 
TEST(AddressSanitizer,SimpleStackTest)477 TEST(AddressSanitizer, SimpleStackTest) {
478   SizedStackTest<1>();
479   SizedStackTest<2>();
480   SizedStackTest<3>();
481   SizedStackTest<4>();
482   SizedStackTest<5>();
483   SizedStackTest<6>();
484   SizedStackTest<7>();
485   SizedStackTest<16>();
486   SizedStackTest<25>();
487   SizedStackTest<34>();
488   SizedStackTest<43>();
489   SizedStackTest<51>();
490   SizedStackTest<62>();
491   SizedStackTest<64>();
492   SizedStackTest<128>();
493 }
494 
495 #if !defined(_WIN32)
496 // FIXME: It's a bit hard to write multi-line death test expectations
497 // in a portable way.  Anyways, this should just be turned into a lit test.
TEST(AddressSanitizer,ManyStackObjectsTest)498 TEST(AddressSanitizer, ManyStackObjectsTest) {
499   char XXX[10];
500   char YYY[20];
501   char ZZZ[30];
502   Ident(XXX);
503   Ident(YYY);
504   EXPECT_DEATH(Ident(ZZZ)[-1] = 0, ASAN_PCRE_DOTALL "XXX.*YYY.*ZZZ");
505 }
506 #endif
507 
508 #if 0  // This test requires online symbolizer.
509 // Moved to lit_tests/stack-oob-frames.cc.
510 // Reenable here once we have online symbolizer by default.
511 NOINLINE static void Frame0(int frame, char *a, char *b, char *c) {
512   char d[4] = {0};
513   char *D = Ident(d);
514   switch (frame) {
515     case 3: a[5]++; break;
516     case 2: b[5]++; break;
517     case 1: c[5]++; break;
518     case 0: D[5]++; break;
519   }
520 }
521 NOINLINE static void Frame1(int frame, char *a, char *b) {
522   char c[4] = {0}; Frame0(frame, a, b, c);
523   break_optimization(0);
524 }
525 NOINLINE static void Frame2(int frame, char *a) {
526   char b[4] = {0}; Frame1(frame, a, b);
527   break_optimization(0);
528 }
529 NOINLINE static void Frame3(int frame) {
530   char a[4] = {0}; Frame2(frame, a);
531   break_optimization(0);
532 }
533 
534 TEST(AddressSanitizer, GuiltyStackFrame0Test) {
535   EXPECT_DEATH(Frame3(0), "located .*in frame <.*Frame0");
536 }
537 TEST(AddressSanitizer, GuiltyStackFrame1Test) {
538   EXPECT_DEATH(Frame3(1), "located .*in frame <.*Frame1");
539 }
540 TEST(AddressSanitizer, GuiltyStackFrame2Test) {
541   EXPECT_DEATH(Frame3(2), "located .*in frame <.*Frame2");
542 }
543 TEST(AddressSanitizer, GuiltyStackFrame3Test) {
544   EXPECT_DEATH(Frame3(3), "located .*in frame <.*Frame3");
545 }
546 #endif
547 
LongJmpFunc1(jmp_buf buf)548 NOINLINE void LongJmpFunc1(jmp_buf buf) {
549   // create three red zones for these two stack objects.
550   int a;
551   int b;
552 
553   int *A = Ident(&a);
554   int *B = Ident(&b);
555   *A = *B;
556   longjmp(buf, 1);
557 }
558 
TouchStackFunc()559 NOINLINE void TouchStackFunc() {
560   int a[100];  // long array will intersect with redzones from LongJmpFunc1.
561   int *A = Ident(a);
562   for (int i = 0; i < 100; i++)
563     A[i] = i*i;
564 }
565 
566 // Test that we handle longjmp and do not report false positives on stack.
TEST(AddressSanitizer,LongJmpTest)567 TEST(AddressSanitizer, LongJmpTest) {
568   static jmp_buf buf;
569   if (!setjmp(buf)) {
570     LongJmpFunc1(buf);
571   } else {
572     TouchStackFunc();
573   }
574 }
575 
576 #if !defined(_WIN32)  // Only basic longjmp is available on Windows.
UnderscopeLongJmpFunc1(jmp_buf buf)577 NOINLINE void UnderscopeLongJmpFunc1(jmp_buf buf) {
578   // create three red zones for these two stack objects.
579   int a;
580   int b;
581 
582   int *A = Ident(&a);
583   int *B = Ident(&b);
584   *A = *B;
585   _longjmp(buf, 1);
586 }
587 
SigLongJmpFunc1(sigjmp_buf buf)588 NOINLINE void SigLongJmpFunc1(sigjmp_buf buf) {
589   // create three red zones for these two stack objects.
590   int a;
591   int b;
592 
593   int *A = Ident(&a);
594   int *B = Ident(&b);
595   *A = *B;
596   siglongjmp(buf, 1);
597 }
598 
599 #if !defined(__ANDROID__) && !defined(__arm__) && \
600     !defined(__aarch64__) && !defined(__mips__) && \
601     !defined(__mips64) && !defined(__s390__)
BuiltinLongJmpFunc1(jmp_buf buf)602 NOINLINE void BuiltinLongJmpFunc1(jmp_buf buf) {
603   // create three red zones for these two stack objects.
604   int a;
605   int b;
606 
607   int *A = Ident(&a);
608   int *B = Ident(&b);
609   *A = *B;
610   __builtin_longjmp((void**)buf, 1);
611 }
612 
613 // Does not work on ARM:
614 // https://github.com/google/sanitizers/issues/185
TEST(AddressSanitizer,BuiltinLongJmpTest)615 TEST(AddressSanitizer, BuiltinLongJmpTest) {
616   static jmp_buf buf;
617   if (!__builtin_setjmp((void**)buf)) {
618     BuiltinLongJmpFunc1(buf);
619   } else {
620     TouchStackFunc();
621   }
622 }
623 #endif  // !defined(__ANDROID__) && !defined(__arm__) &&
624         // !defined(__aarch64__) && !defined(__mips__)
625         // !defined(__mips64) && !defined(__s390__)
626 
TEST(AddressSanitizer,UnderscopeLongJmpTest)627 TEST(AddressSanitizer, UnderscopeLongJmpTest) {
628   static jmp_buf buf;
629   if (!_setjmp(buf)) {
630     UnderscopeLongJmpFunc1(buf);
631   } else {
632     TouchStackFunc();
633   }
634 }
635 
TEST(AddressSanitizer,SigLongJmpTest)636 TEST(AddressSanitizer, SigLongJmpTest) {
637   static sigjmp_buf buf;
638   if (!sigsetjmp(buf, 1)) {
639     SigLongJmpFunc1(buf);
640   } else {
641     TouchStackFunc();
642   }
643 }
644 #endif
645 
646 // FIXME: Why does clang-cl define __EXCEPTIONS?
647 #if defined(__EXCEPTIONS) && !defined(_WIN32)
ThrowFunc()648 NOINLINE void ThrowFunc() {
649   // create three red zones for these two stack objects.
650   int a;
651   int b;
652 
653   int *A = Ident(&a);
654   int *B = Ident(&b);
655   *A = *B;
656   ASAN_THROW(1);
657 }
658 
TEST(AddressSanitizer,CxxExceptionTest)659 TEST(AddressSanitizer, CxxExceptionTest) {
660   if (ASAN_UAR) return;
661   // TODO(kcc): this test crashes on 32-bit for some reason...
662   if (SANITIZER_WORDSIZE == 32) return;
663   try {
664     ThrowFunc();
665   } catch(...) {}
666   TouchStackFunc();
667 }
668 #endif
669 
ThreadStackReuseFunc1(void * unused)670 void *ThreadStackReuseFunc1(void *unused) {
671   // create three red zones for these two stack objects.
672   int a;
673   int b;
674 
675   int *A = Ident(&a);
676   int *B = Ident(&b);
677   *A = *B;
678   pthread_exit(0);
679   return 0;
680 }
681 
ThreadStackReuseFunc2(void * unused)682 void *ThreadStackReuseFunc2(void *unused) {
683   TouchStackFunc();
684   return 0;
685 }
686 
TEST(AddressSanitizer,ThreadStackReuseTest)687 TEST(AddressSanitizer, ThreadStackReuseTest) {
688   pthread_t t;
689   PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc1, 0);
690   PTHREAD_JOIN(t, 0);
691   PTHREAD_CREATE(&t, 0, ThreadStackReuseFunc2, 0);
692   PTHREAD_JOIN(t, 0);
693 }
694 
695 #if defined(__i686__) || defined(__x86_64__)
696 #include <emmintrin.h>
TEST(AddressSanitizer,Store128Test)697 TEST(AddressSanitizer, Store128Test) {
698   char *a = Ident((char*)malloc(Ident(12)));
699   char *p = a;
700   if (((uintptr_t)a % 16) != 0)
701     p = a + 8;
702   assert(((uintptr_t)p % 16) == 0);
703   __m128i value_wide = _mm_set1_epi16(0x1234);
704   EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
705                "AddressSanitizer: heap-buffer-overflow");
706   EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
707                "WRITE of size 16");
708   EXPECT_DEATH(_mm_store_si128((__m128i*)p, value_wide),
709                "located 0 bytes to the right of 12-byte");
710   free(a);
711 }
712 #endif
713 
714 // FIXME: All tests that use this function should be turned into lit tests.
RightOOBErrorMessage(int oob_distance,bool is_write)715 string RightOOBErrorMessage(int oob_distance, bool is_write) {
716   assert(oob_distance >= 0);
717   char expected_str[100];
718   sprintf(expected_str, ASAN_PCRE_DOTALL
719 #if !GTEST_USES_SIMPLE_RE
720           "buffer-overflow.*%s.*"
721 #endif
722           "located %d bytes to the right",
723 #if !GTEST_USES_SIMPLE_RE
724           is_write ? "WRITE" : "READ",
725 #endif
726           oob_distance);
727   return string(expected_str);
728 }
729 
RightOOBWriteMessage(int oob_distance)730 string RightOOBWriteMessage(int oob_distance) {
731   return RightOOBErrorMessage(oob_distance, /*is_write*/true);
732 }
733 
RightOOBReadMessage(int oob_distance)734 string RightOOBReadMessage(int oob_distance) {
735   return RightOOBErrorMessage(oob_distance, /*is_write*/false);
736 }
737 
738 // FIXME: All tests that use this function should be turned into lit tests.
LeftOOBErrorMessage(int oob_distance,bool is_write)739 string LeftOOBErrorMessage(int oob_distance, bool is_write) {
740   assert(oob_distance > 0);
741   char expected_str[100];
742   sprintf(expected_str,
743 #if !GTEST_USES_SIMPLE_RE
744           ASAN_PCRE_DOTALL "%s.*"
745 #endif
746           "located %d bytes to the left",
747 #if !GTEST_USES_SIMPLE_RE
748           is_write ? "WRITE" : "READ",
749 #endif
750           oob_distance);
751   return string(expected_str);
752 }
753 
LeftOOBWriteMessage(int oob_distance)754 string LeftOOBWriteMessage(int oob_distance) {
755   return LeftOOBErrorMessage(oob_distance, /*is_write*/true);
756 }
757 
LeftOOBReadMessage(int oob_distance)758 string LeftOOBReadMessage(int oob_distance) {
759   return LeftOOBErrorMessage(oob_distance, /*is_write*/false);
760 }
761 
LeftOOBAccessMessage(int oob_distance)762 string LeftOOBAccessMessage(int oob_distance) {
763   assert(oob_distance > 0);
764   char expected_str[100];
765   sprintf(expected_str, "located %d bytes to the left", oob_distance);
766   return string(expected_str);
767 }
768 
MallocAndMemsetString(size_t size,char ch)769 char* MallocAndMemsetString(size_t size, char ch) {
770   char *s = Ident((char*)malloc(size));
771   memset(s, ch, size);
772   return s;
773 }
774 
MallocAndMemsetString(size_t size)775 char* MallocAndMemsetString(size_t size) {
776   return MallocAndMemsetString(size, 'z');
777 }
778 
779 #if defined(__linux__) && !defined(__ANDROID__)
780 #define READ_TEST(READ_N_BYTES)                                          \
781   char *x = new char[10];                                                \
782   int fd = open("/proc/self/stat", O_RDONLY);                            \
783   ASSERT_GT(fd, 0);                                                      \
784   EXPECT_DEATH(READ_N_BYTES,                                             \
785                ASAN_PCRE_DOTALL                                          \
786                "AddressSanitizer: heap-buffer-overflow"                  \
787                ".* is located 0 bytes to the right of 10-byte region");  \
788   close(fd);                                                             \
789   delete [] x;                                                           \
790 
TEST(AddressSanitizer,pread)791 TEST(AddressSanitizer, pread) {
792   READ_TEST(pread(fd, x, 15, 0));
793 }
794 
TEST(AddressSanitizer,pread64)795 TEST(AddressSanitizer, pread64) {
796   READ_TEST(pread64(fd, x, 15, 0));
797 }
798 
TEST(AddressSanitizer,read)799 TEST(AddressSanitizer, read) {
800   READ_TEST(read(fd, x, 15));
801 }
802 #endif  // defined(__linux__) && !defined(__ANDROID__)
803 
804 // This test case fails
805 // Clang optimizes memcpy/memset calls which lead to unaligned access
TEST(AddressSanitizer,DISABLED_MemIntrinsicUnalignedAccessTest)806 TEST(AddressSanitizer, DISABLED_MemIntrinsicUnalignedAccessTest) {
807   int size = Ident(4096);
808   char *s = Ident((char*)malloc(size));
809   EXPECT_DEATH(memset(s + size - 1, 0, 2), RightOOBWriteMessage(0));
810   free(s);
811 }
812 
LargeFunction(bool do_bad_access)813 NOINLINE static int LargeFunction(bool do_bad_access) {
814   int *x = new int[100];
815   x[0]++;
816   x[1]++;
817   x[2]++;
818   x[3]++;
819   x[4]++;
820   x[5]++;
821   x[6]++;
822   x[7]++;
823   x[8]++;
824   x[9]++;
825 
826   x[do_bad_access ? 100 : 0]++; int res = __LINE__;
827 
828   x[10]++;
829   x[11]++;
830   x[12]++;
831   x[13]++;
832   x[14]++;
833   x[15]++;
834   x[16]++;
835   x[17]++;
836   x[18]++;
837   x[19]++;
838 
839   delete[] x;
840   return res;
841 }
842 
843 // Test the we have correct debug info for the failing instruction.
844 // This test requires the in-process symbolizer to be enabled by default.
TEST(AddressSanitizer,DISABLED_LargeFunctionSymbolizeTest)845 TEST(AddressSanitizer, DISABLED_LargeFunctionSymbolizeTest) {
846   int failing_line = LargeFunction(false);
847   char expected_warning[128];
848   sprintf(expected_warning, "LargeFunction.*asan_test.*:%d", failing_line);
849   EXPECT_DEATH(LargeFunction(true), expected_warning);
850 }
851 
852 // Check that we unwind and symbolize correctly.
TEST(AddressSanitizer,DISABLED_MallocFreeUnwindAndSymbolizeTest)853 TEST(AddressSanitizer, DISABLED_MallocFreeUnwindAndSymbolizeTest) {
854   int *a = (int*)malloc_aaa(sizeof(int));
855   *a = 1;
856   free_aaa(a);
857   EXPECT_DEATH(*a = 1, "free_ccc.*free_bbb.*free_aaa.*"
858                "malloc_fff.*malloc_eee.*malloc_ddd");
859 }
860 
TryToSetThreadName(const char * name)861 static bool TryToSetThreadName(const char *name) {
862 #if defined(__linux__) && defined(PR_SET_NAME)
863   return 0 == prctl(PR_SET_NAME, (unsigned long)name, 0, 0, 0);
864 #else
865   return false;
866 #endif
867 }
868 
ThreadedTestAlloc(void * a)869 void *ThreadedTestAlloc(void *a) {
870   EXPECT_EQ(true, TryToSetThreadName("AllocThr"));
871   int **p = (int**)a;
872   *p = new int;
873   return 0;
874 }
875 
ThreadedTestFree(void * a)876 void *ThreadedTestFree(void *a) {
877   EXPECT_EQ(true, TryToSetThreadName("FreeThr"));
878   int **p = (int**)a;
879   delete *p;
880   return 0;
881 }
882 
ThreadedTestUse(void * a)883 void *ThreadedTestUse(void *a) {
884   EXPECT_EQ(true, TryToSetThreadName("UseThr"));
885   int **p = (int**)a;
886   **p = 1;
887   return 0;
888 }
889 
ThreadedTestSpawn()890 void ThreadedTestSpawn() {
891   pthread_t t;
892   int *x;
893   PTHREAD_CREATE(&t, 0, ThreadedTestAlloc, &x);
894   PTHREAD_JOIN(t, 0);
895   PTHREAD_CREATE(&t, 0, ThreadedTestFree, &x);
896   PTHREAD_JOIN(t, 0);
897   PTHREAD_CREATE(&t, 0, ThreadedTestUse, &x);
898   PTHREAD_JOIN(t, 0);
899 }
900 
901 #if !defined(_WIN32)  // FIXME: This should be a lit test.
TEST(AddressSanitizer,ThreadedTest)902 TEST(AddressSanitizer, ThreadedTest) {
903   EXPECT_DEATH(ThreadedTestSpawn(),
904                ASAN_PCRE_DOTALL
905                "Thread T.*created"
906                ".*Thread T.*created"
907                ".*Thread T.*created");
908 }
909 #endif
910 
ThreadedTestFunc(void * unused)911 void *ThreadedTestFunc(void *unused) {
912   // Check if prctl(PR_SET_NAME) is supported. Return if not.
913   if (!TryToSetThreadName("TestFunc"))
914     return 0;
915   EXPECT_DEATH(ThreadedTestSpawn(),
916                ASAN_PCRE_DOTALL
917                "WRITE .*thread T. .UseThr."
918                ".*freed by thread T. .FreeThr. here:"
919                ".*previously allocated by thread T. .AllocThr. here:"
920                ".*Thread T. .UseThr. created by T.*TestFunc"
921                ".*Thread T. .FreeThr. created by T"
922                ".*Thread T. .AllocThr. created by T"
923                "");
924   return 0;
925 }
926 
TEST(AddressSanitizer,ThreadNamesTest)927 TEST(AddressSanitizer, ThreadNamesTest) {
928   // Run ThreadedTestFunc in a separate thread because it tries to set a
929   // thread name and we don't want to change the main thread's name.
930   pthread_t t;
931   PTHREAD_CREATE(&t, 0, ThreadedTestFunc, 0);
932   PTHREAD_JOIN(t, 0);
933 }
934 
935 #if ASAN_NEEDS_SEGV
TEST(AddressSanitizer,ShadowGapTest)936 TEST(AddressSanitizer, ShadowGapTest) {
937 #if SANITIZER_WORDSIZE == 32
938   char *addr = (char*)0x22000000;
939 #else
940 # if defined(__powerpc64__)
941   char *addr = (char*)0x024000800000;
942 # elif defined(__s390x__)
943   char *addr = (char*)0x11000000000000;
944 # else
945   char *addr = (char*)0x0000100000080000;
946 # endif
947 #endif
948   EXPECT_DEATH(*addr = 1, "AddressSanitizer: SEGV on unknown");
949 }
950 #endif  // ASAN_NEEDS_SEGV
951 
952 extern "C" {
UseThenFreeThenUse()953 NOINLINE static void UseThenFreeThenUse() {
954   char *x = Ident((char*)malloc(8));
955   *x = 1;
956   free_aaa(x);
957   *x = 2;
958 }
959 }
960 
TEST(AddressSanitizer,UseThenFreeThenUseTest)961 TEST(AddressSanitizer, UseThenFreeThenUseTest) {
962   EXPECT_DEATH(UseThenFreeThenUse(), "freed by thread");
963 }
964 
TEST(AddressSanitizer,StrDupTest)965 TEST(AddressSanitizer, StrDupTest) {
966   free(strdup(Ident("123")));
967 }
968 
969 // Currently we create and poison redzone at right of global variables.
970 static char static110[110];
971 const char ConstGlob[7] = {1, 2, 3, 4, 5, 6, 7};
972 static const char StaticConstGlob[3] = {9, 8, 7};
973 
TEST(AddressSanitizer,GlobalTest)974 TEST(AddressSanitizer, GlobalTest) {
975   static char func_static15[15];
976 
977   static char fs1[10];
978   static char fs2[10];
979   static char fs3[10];
980 
981   glob5[Ident(0)] = 0;
982   glob5[Ident(1)] = 0;
983   glob5[Ident(2)] = 0;
984   glob5[Ident(3)] = 0;
985   glob5[Ident(4)] = 0;
986 
987   EXPECT_DEATH(glob5[Ident(5)] = 0,
988                "0 bytes to the right of global variable.*glob5.* size 5");
989   EXPECT_DEATH(glob5[Ident(5+6)] = 0,
990                "6 bytes to the right of global variable.*glob5.* size 5");
991   Ident(static110);  // avoid optimizations
992   static110[Ident(0)] = 0;
993   static110[Ident(109)] = 0;
994   EXPECT_DEATH(static110[Ident(110)] = 0,
995                "0 bytes to the right of global variable");
996   EXPECT_DEATH(static110[Ident(110+7)] = 0,
997                "7 bytes to the right of global variable");
998 
999   Ident(func_static15);  // avoid optimizations
1000   func_static15[Ident(0)] = 0;
1001   EXPECT_DEATH(func_static15[Ident(15)] = 0,
1002                "0 bytes to the right of global variable");
1003   EXPECT_DEATH(func_static15[Ident(15 + 9)] = 0,
1004                "9 bytes to the right of global variable");
1005 
1006   Ident(fs1);
1007   Ident(fs2);
1008   Ident(fs3);
1009 
1010   // We don't create left redzones, so this is not 100% guaranteed to fail.
1011   // But most likely will.
1012   EXPECT_DEATH(fs2[Ident(-1)] = 0, "is located.*of global variable");
1013 
1014   EXPECT_DEATH(Ident(Ident(ConstGlob)[8]),
1015                "is located 1 bytes to the right of .*ConstGlob");
1016   EXPECT_DEATH(Ident(Ident(StaticConstGlob)[5]),
1017                "is located 2 bytes to the right of .*StaticConstGlob");
1018 
1019   // call stuff from another file.
1020   GlobalsTest(0);
1021 }
1022 
TEST(AddressSanitizer,GlobalStringConstTest)1023 TEST(AddressSanitizer, GlobalStringConstTest) {
1024   static const char *zoo = "FOOBAR123";
1025   const char *p = Ident(zoo);
1026   EXPECT_DEATH(Ident(p[15]), "is ascii string 'FOOBAR123'");
1027 }
1028 
TEST(AddressSanitizer,FileNameInGlobalReportTest)1029 TEST(AddressSanitizer, FileNameInGlobalReportTest) {
1030   static char zoo[10];
1031   const char *p = Ident(zoo);
1032   // The file name should be present in the report.
1033   EXPECT_DEATH(Ident(p[15]), "zoo.*asan_test.");
1034 }
1035 
ReturnsPointerToALocalObject()1036 int *ReturnsPointerToALocalObject() {
1037   int a = 0;
1038   return Ident(&a);
1039 }
1040 
1041 #if ASAN_UAR == 1
TEST(AddressSanitizer,LocalReferenceReturnTest)1042 TEST(AddressSanitizer, LocalReferenceReturnTest) {
1043   int *(*f)() = Ident(ReturnsPointerToALocalObject);
1044   int *p = f();
1045   // Call 'f' a few more times, 'p' should still be poisoned.
1046   for (int i = 0; i < 32; i++)
1047     f();
1048   EXPECT_DEATH(*p = 1, "AddressSanitizer: stack-use-after-return");
1049   EXPECT_DEATH(*p = 1, "is located.*in frame .*ReturnsPointerToALocal");
1050 }
1051 #endif
1052 
1053 template <int kSize>
FuncWithStack()1054 NOINLINE static void FuncWithStack() {
1055   char x[kSize];
1056   Ident(x)[0] = 0;
1057   Ident(x)[kSize-1] = 0;
1058 }
1059 
LotsOfStackReuse()1060 static void LotsOfStackReuse() {
1061   int LargeStack[10000];
1062   Ident(LargeStack)[0] = 0;
1063   for (int i = 0; i < 10000; i++) {
1064     FuncWithStack<128 * 1>();
1065     FuncWithStack<128 * 2>();
1066     FuncWithStack<128 * 4>();
1067     FuncWithStack<128 * 8>();
1068     FuncWithStack<128 * 16>();
1069     FuncWithStack<128 * 32>();
1070     FuncWithStack<128 * 64>();
1071     FuncWithStack<128 * 128>();
1072     FuncWithStack<128 * 256>();
1073     FuncWithStack<128 * 512>();
1074     Ident(LargeStack)[0] = 0;
1075   }
1076 }
1077 
TEST(AddressSanitizer,StressStackReuseTest)1078 TEST(AddressSanitizer, StressStackReuseTest) {
1079   LotsOfStackReuse();
1080 }
1081 
TEST(AddressSanitizer,ThreadedStressStackReuseTest)1082 TEST(AddressSanitizer, ThreadedStressStackReuseTest) {
1083   const int kNumThreads = 20;
1084   pthread_t t[kNumThreads];
1085   for (int i = 0; i < kNumThreads; i++) {
1086     PTHREAD_CREATE(&t[i], 0, (void* (*)(void *x))LotsOfStackReuse, 0);
1087   }
1088   for (int i = 0; i < kNumThreads; i++) {
1089     PTHREAD_JOIN(t[i], 0);
1090   }
1091 }
1092 
PthreadExit(void * a)1093 static void *PthreadExit(void *a) {
1094   pthread_exit(0);
1095   return 0;
1096 }
1097 
TEST(AddressSanitizer,PthreadExitTest)1098 TEST(AddressSanitizer, PthreadExitTest) {
1099   pthread_t t;
1100   for (int i = 0; i < 1000; i++) {
1101     PTHREAD_CREATE(&t, 0, PthreadExit, 0);
1102     PTHREAD_JOIN(t, 0);
1103   }
1104 }
1105 
1106 // FIXME: Why does clang-cl define __EXCEPTIONS?
1107 #if defined(__EXCEPTIONS) && !defined(_WIN32)
StackReuseAndException()1108 NOINLINE static void StackReuseAndException() {
1109   int large_stack[1000];
1110   Ident(large_stack);
1111   ASAN_THROW(1);
1112 }
1113 
1114 // TODO(kcc): support exceptions with use-after-return.
TEST(AddressSanitizer,DISABLED_StressStackReuseAndExceptionsTest)1115 TEST(AddressSanitizer, DISABLED_StressStackReuseAndExceptionsTest) {
1116   for (int i = 0; i < 10000; i++) {
1117     try {
1118     StackReuseAndException();
1119     } catch(...) {
1120     }
1121   }
1122 }
1123 #endif
1124 
1125 #if !defined(_WIN32)
TEST(AddressSanitizer,MlockTest)1126 TEST(AddressSanitizer, MlockTest) {
1127   EXPECT_EQ(0, mlockall(MCL_CURRENT));
1128   EXPECT_EQ(0, mlock((void*)0x12345, 0x5678));
1129   EXPECT_EQ(0, munlockall());
1130   EXPECT_EQ(0, munlock((void*)0x987, 0x654));
1131 }
1132 #endif
1133 
1134 struct LargeStruct {
1135   int foo[100];
1136 };
1137 
1138 // Test for bug http://llvm.org/bugs/show_bug.cgi?id=11763.
1139 // Struct copy should not cause asan warning even if lhs == rhs.
TEST(AddressSanitizer,LargeStructCopyTest)1140 TEST(AddressSanitizer, LargeStructCopyTest) {
1141   LargeStruct a;
1142   *Ident(&a) = *Ident(&a);
1143 }
1144 
1145 ATTRIBUTE_NO_SANITIZE_ADDRESS
NoSanitizeAddress()1146 static void NoSanitizeAddress() {
1147   char *foo = new char[10];
1148   Ident(foo)[10] = 0;
1149   delete [] foo;
1150 }
1151 
TEST(AddressSanitizer,AttributeNoSanitizeAddressTest)1152 TEST(AddressSanitizer, AttributeNoSanitizeAddressTest) {
1153   Ident(NoSanitizeAddress)();
1154 }
1155 
1156 // The new/delete/etc mismatch checks don't work on Android,
1157 //   as calls to new/delete go through malloc/free.
1158 // OS X support is tracked here:
1159 //   https://github.com/google/sanitizers/issues/131
1160 // Windows support is tracked here:
1161 //   https://github.com/google/sanitizers/issues/309
1162 #if !defined(__ANDROID__) && \
1163     !defined(__APPLE__) && \
1164     !defined(_WIN32)
MismatchStr(const string & str)1165 static string MismatchStr(const string &str) {
1166   return string("AddressSanitizer: alloc-dealloc-mismatch \\(") + str;
1167 }
1168 
MismatchOrNewDeleteTypeStr(const string & mismatch_str)1169 static string MismatchOrNewDeleteTypeStr(const string &mismatch_str) {
1170   return "(" + MismatchStr(mismatch_str) +
1171          ")|(AddressSanitizer: new-delete-type-mismatch)";
1172 }
1173 
TEST(AddressSanitizer,AllocDeallocMismatch)1174 TEST(AddressSanitizer, AllocDeallocMismatch) {
1175   EXPECT_DEATH(free(Ident(new int)),
1176                MismatchStr("operator new vs free"));
1177   EXPECT_DEATH(free(Ident(new int[2])),
1178                MismatchStr("operator new \\[\\] vs free"));
1179   EXPECT_DEATH(
1180       delete (Ident(new int[2])),
1181       MismatchOrNewDeleteTypeStr("operator new \\[\\] vs operator delete"));
1182   EXPECT_DEATH(delete (Ident((int *)malloc(2 * sizeof(int)))),
1183                MismatchOrNewDeleteTypeStr("malloc vs operator delete"));
1184   EXPECT_DEATH(delete [] (Ident(new int)),
1185                MismatchStr("operator new vs operator delete \\[\\]"));
1186   EXPECT_DEATH(delete [] (Ident((int*)malloc(2 * sizeof(int)))),
1187                MismatchStr("malloc vs operator delete \\[\\]"));
1188 }
1189 #endif
1190 
1191 // ------------------ demo tests; run each one-by-one -------------
1192 // e.g. --gtest_filter=*DemoOOBLeftHigh --gtest_also_run_disabled_tests
TEST(AddressSanitizer,DISABLED_DemoThreadedTest)1193 TEST(AddressSanitizer, DISABLED_DemoThreadedTest) {
1194   ThreadedTestSpawn();
1195 }
1196 
SimpleBugOnSTack(void * x=0)1197 void *SimpleBugOnSTack(void *x = 0) {
1198   char a[20];
1199   Ident(a)[20] = 0;
1200   return 0;
1201 }
1202 
TEST(AddressSanitizer,DISABLED_DemoStackTest)1203 TEST(AddressSanitizer, DISABLED_DemoStackTest) {
1204   SimpleBugOnSTack();
1205 }
1206 
TEST(AddressSanitizer,DISABLED_DemoThreadStackTest)1207 TEST(AddressSanitizer, DISABLED_DemoThreadStackTest) {
1208   pthread_t t;
1209   PTHREAD_CREATE(&t, 0, SimpleBugOnSTack, 0);
1210   PTHREAD_JOIN(t, 0);
1211 }
1212 
TEST(AddressSanitizer,DISABLED_DemoUAFLowIn)1213 TEST(AddressSanitizer, DISABLED_DemoUAFLowIn) {
1214   uaf_test<U1>(10, 0);
1215 }
TEST(AddressSanitizer,DISABLED_DemoUAFLowLeft)1216 TEST(AddressSanitizer, DISABLED_DemoUAFLowLeft) {
1217   uaf_test<U1>(10, -2);
1218 }
TEST(AddressSanitizer,DISABLED_DemoUAFLowRight)1219 TEST(AddressSanitizer, DISABLED_DemoUAFLowRight) {
1220   uaf_test<U1>(10, 10);
1221 }
1222 
TEST(AddressSanitizer,DISABLED_DemoUAFHigh)1223 TEST(AddressSanitizer, DISABLED_DemoUAFHigh) {
1224   uaf_test<U1>(kLargeMalloc, 0);
1225 }
1226 
TEST(AddressSanitizer,DISABLED_DemoOOM)1227 TEST(AddressSanitizer, DISABLED_DemoOOM) {
1228   size_t size = SANITIZER_WORDSIZE == 64 ? (size_t)(1ULL << 40) : (0xf0000000);
1229   printf("%p\n", malloc(size));
1230 }
1231 
TEST(AddressSanitizer,DISABLED_DemoDoubleFreeTest)1232 TEST(AddressSanitizer, DISABLED_DemoDoubleFreeTest) {
1233   DoubleFree();
1234 }
1235 
TEST(AddressSanitizer,DISABLED_DemoNullDerefTest)1236 TEST(AddressSanitizer, DISABLED_DemoNullDerefTest) {
1237   int *a = 0;
1238   Ident(a)[10] = 0;
1239 }
1240 
TEST(AddressSanitizer,DISABLED_DemoFunctionStaticTest)1241 TEST(AddressSanitizer, DISABLED_DemoFunctionStaticTest) {
1242   static char a[100];
1243   static char b[100];
1244   static char c[100];
1245   Ident(a);
1246   Ident(b);
1247   Ident(c);
1248   Ident(a)[5] = 0;
1249   Ident(b)[105] = 0;
1250   Ident(a)[5] = 0;
1251 }
1252 
TEST(AddressSanitizer,DISABLED_DemoTooMuchMemoryTest)1253 TEST(AddressSanitizer, DISABLED_DemoTooMuchMemoryTest) {
1254   const size_t kAllocSize = (1 << 28) - 1024;
1255   size_t total_size = 0;
1256   while (true) {
1257     void *x = malloc(kAllocSize);
1258     memset(x, 0, kAllocSize);
1259     total_size += kAllocSize;
1260     fprintf(stderr, "total: %ldM %p\n", (long)total_size >> 20, x);
1261   }
1262 }
1263 
1264 // https://github.com/google/sanitizers/issues/66
TEST(AddressSanitizer,BufferOverflowAfterManyFrees)1265 TEST(AddressSanitizer, BufferOverflowAfterManyFrees) {
1266   for (int i = 0; i < 1000000; i++) {
1267     delete [] (Ident(new char [8644]));
1268   }
1269   char *x = new char[8192];
1270   EXPECT_DEATH(x[Ident(8192)] = 0, "AddressSanitizer: heap-buffer-overflow");
1271   delete [] Ident(x);
1272 }
1273 
1274 
1275 // Test that instrumentation of stack allocations takes into account
1276 // AllocSize of a type, and not its StoreSize (16 vs 10 bytes for long double).
1277 // See http://llvm.org/bugs/show_bug.cgi?id=12047 for more details.
TEST(AddressSanitizer,LongDoubleNegativeTest)1278 TEST(AddressSanitizer, LongDoubleNegativeTest) {
1279   long double a, b;
1280   static long double c;
1281   memcpy(Ident(&a), Ident(&b), sizeof(long double));
1282   memcpy(Ident(&c), Ident(&b), sizeof(long double));
1283 }
1284 
1285 #if !defined(_WIN32)
TEST(AddressSanitizer,pthread_getschedparam)1286 TEST(AddressSanitizer, pthread_getschedparam) {
1287   int policy;
1288   struct sched_param param;
1289   EXPECT_DEATH(
1290       pthread_getschedparam(pthread_self(), &policy, Ident(&param) + 2),
1291       "AddressSanitizer: stack-buffer-.*flow");
1292   EXPECT_DEATH(
1293       pthread_getschedparam(pthread_self(), Ident(&policy) - 1, &param),
1294       "AddressSanitizer: stack-buffer-.*flow");
1295   int res = pthread_getschedparam(pthread_self(), &policy, &param);
1296   ASSERT_EQ(0, res);
1297 }
1298 #endif
1299 
1300 #if SANITIZER_TEST_HAS_PRINTF_L
vsnprintf_l_wrapper(char * s,size_t n,locale_t l,const char * format,...)1301 static int vsnprintf_l_wrapper(char *s, size_t n,
1302                                locale_t l, const char *format, ...) {
1303   va_list va;
1304   va_start(va, format);
1305   int res = vsnprintf_l(s, n , l, format, va);
1306   va_end(va);
1307   return res;
1308 }
1309 
TEST(AddressSanitizer,snprintf_l)1310 TEST(AddressSanitizer, snprintf_l) {
1311   char buff[5];
1312   // Check that snprintf_l() works fine with Asan.
1313   int res = snprintf_l(buff, 5,
1314                        _LIBCPP_GET_C_LOCALE, "%s", "snprintf_l()");
1315   EXPECT_EQ(12, res);
1316   // Check that vsnprintf_l() works fine with Asan.
1317   res = vsnprintf_l_wrapper(buff, 5,
1318                             _LIBCPP_GET_C_LOCALE, "%s", "vsnprintf_l()");
1319   EXPECT_EQ(13, res);
1320 
1321   EXPECT_DEATH(snprintf_l(buff, 10,
1322                           _LIBCPP_GET_C_LOCALE, "%s", "snprintf_l()"),
1323                 "AddressSanitizer: stack-buffer-overflow");
1324   EXPECT_DEATH(vsnprintf_l_wrapper(buff, 10,
1325                                   _LIBCPP_GET_C_LOCALE, "%s", "vsnprintf_l()"),
1326                 "AddressSanitizer: stack-buffer-overflow");
1327 }
1328 #endif
1329