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