1 // Stress test recovery mode with many threads.
2 //
3 // RUN: %clangxx_asan -fsanitize-recover=address -pthread %s -o %t
4 //
5 // RUN: %env_asan_opts=halt_on_error=false:suppress_equal_pcs=false %run %t 1 10 >%t.log 2>&1
6 // RUN: grep 'ERROR: AddressSanitizer: use-after-poison' %t.log | count 10
7 // RUN: FileCheck %s <%t.log
8 //
9 // RUN: %env_asan_opts=halt_on_error=false:suppress_equal_pcs=false:exitcode=0 %run %t 10 20 >%t.log 2>&1
10 // RUN: grep 'ERROR: AddressSanitizer: use-after-poison' %t.log | count 200
11 // RUN: FileCheck %s <%t.log
12 //
13 // RUN: %env_asan_opts=halt_on_error=false:exitcode=0 %run %t 10 20 >%t.log 2>&1
14 // RUN: grep 'ERROR: AddressSanitizer: use-after-poison' %t.log | count 1
15 // RUN: FileCheck %s <%t.log
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <pthread.h>
20 #include <time.h>
21
22 #include <sanitizer/asan_interface.h>
23
24 size_t nthreads = 10;
25 size_t niter = 10;
26
random_delay(unsigned * seed)27 void random_delay(unsigned *seed) {
28 *seed = 1664525 * *seed + 1013904223;
29 struct timespec delay = { 0, static_cast<long>((*seed % 1000) * 1000) };
30 nanosleep(&delay, 0);
31 }
32
run(void * arg)33 void *run(void *arg) {
34 unsigned seed = (unsigned)(size_t)arg;
35
36 volatile char tmp[2];
37 __asan_poison_memory_region(&tmp, sizeof(tmp));
38
39 for (size_t i = 0; i < niter; ++i) {
40 random_delay(&seed);
41 // CHECK: ERROR: AddressSanitizer: use-after-poison
42 volatile int idx = 0;
43 tmp[idx] = 0;
44 }
45
46 return 0;
47 }
48
main(int argc,char ** argv)49 int main(int argc, char **argv) {
50 if (argc != 3) {
51 fprintf(stderr, "Syntax: %s nthreads niter\n", argv[0]);
52 exit(1);
53 }
54
55 nthreads = (size_t)strtoul(argv[1], 0, 0);
56 niter = (size_t)strtoul(argv[2], 0, 0);
57
58 pthread_t *tids = new pthread_t[nthreads];
59
60 for (size_t i = 0; i < nthreads; ++i) {
61 if (0 != pthread_create(&tids[i], 0, run, (void *)i)) {
62 fprintf(stderr, "Failed to create thread\n");
63 exit(1);
64 }
65 }
66
67 for (size_t i = 0; i < nthreads; ++i) {
68 if (0 != pthread_join(tids[i], 0)) {
69 fprintf(stderr, "Failed to join thread\n");
70 exit(1);
71 }
72 }
73
74 // CHECK: All threads terminated
75 printf("All threads terminated\n");
76
77 delete [] tids;
78
79 return 0;
80 }
81