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