1// RUN: %clang_tsan -O1 %s -o %t && %env_tsan_opts=report_atomic_races=0 %run %t 2>&1 | FileCheck %s
2// This test exposed non-atomicity in mmap interceptor
3// which made shadow for the region temporarily unmapped.
4// This resulted in crashes in the Accesser thread.
5#include "test.h"
6#include <errno.h>
7#include <sys/mman.h>
8
9// The size needs to be large enough to trigger
10// large region optimization in the runtime.
11const size_t kMmapSize = 16 << 20;
12
13void *Remapper(void *arg) {
14 for (;;) {
15 void *p = mmap(addr: arg, len: kMmapSize, PROT_READ | PROT_WRITE,
16 MAP_FIXED | MAP_PRIVATE | MAP_ANON, fd: -1, offset: 0);
17 if (p == MAP_FAILED)
18 exit(status: printf(format: "mmap failed: %d\n", errno));
19 }
20 return 0;
21}
22
23void *Accesser(void *arg) {
24 unsigned rnd = time(timer: 0);
25 for (;;) {
26 int index = rand_r(seed: &rnd) % kMmapSize;
27 char *p = &((char *)arg)[index];
28 __atomic_fetch_add(p, 1, __ATOMIC_ACQ_REL);
29 }
30 return 0;
31}
32
33int main() {
34 void *p = mmap(addr: 0, len: kMmapSize, PROT_READ | PROT_WRITE,
35 MAP_PRIVATE | MAP_ANON, fd: -1, offset: 0);
36 if (p == MAP_FAILED)
37 exit(status: printf(format: "mmap failed: %d\n", errno));
38 pthread_attr_t attr;
39 pthread_attr_init(attr: &attr);
40 pthread_attr_setdetachstate(attr: &attr, PTHREAD_CREATE_DETACHED);
41 pthread_t th[2];
42 if (pthread_create(newthread: &th[0], attr: &attr, start_routine: Remapper, arg: p))
43 exit(status: printf(format: "pthread_create failed: %d\n", errno));
44 if (pthread_create(newthread: &th[1], attr: &attr, start_routine: Accesser, arg: p))
45 exit(status: printf(format: "pthread_create failed: %d\n", errno));
46 pthread_attr_destroy(attr: &attr);
47 sleep(seconds: 3);
48 fprintf(stderr, format: "DONE\n");
49}
50
51// CHECK: DONE
52

source code of compiler-rt/test/tsan/mmap_stress2.cpp