52 lines · cpp
1// RUN: %clang_tsan -O1 %s -o %t && %env_tsan_opts=report_atomic_races=0 %run %t 2>&1 | FileCheck %s2// This test exposed non-atomicity in mmap interceptor3// 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 trigger10// large region optimization in the runtime.11const size_t kMmapSize = 16 << 20;12 13void *Remapper(void *arg) {14 for (;;) {15 void *p = mmap(arg, kMmapSize, PROT_READ | PROT_WRITE,16 MAP_FIXED | MAP_PRIVATE | MAP_ANON, -1, 0);17 if (p == MAP_FAILED)18 exit(printf("mmap failed: %d\n", errno));19 }20 return 0;21}22 23void *Accesser(void *arg) {24 unsigned rnd = time(0);25 for (;;) {26 int index = rand_r(&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(0, kMmapSize, PROT_READ | PROT_WRITE,35 MAP_PRIVATE | MAP_ANON, -1, 0);36 if (p == MAP_FAILED)37 exit(printf("mmap failed: %d\n", errno));38 pthread_attr_t attr;39 pthread_attr_init(&attr);40 pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);41 pthread_t th[2];42 if (pthread_create(&th[0], &attr, Remapper, p))43 exit(printf("pthread_create failed: %d\n", errno));44 if (pthread_create(&th[1], &attr, Accesser, p))45 exit(printf("pthread_create failed: %d\n", errno));46 pthread_attr_destroy(&attr);47 sleep(3);48 fprintf(stderr, "DONE\n");49}50 51// CHECK: DONE52