| 1 | // RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s |
| 2 | #include "test.h" |
| 3 | |
| 4 | // Test case https://github.com/google/sanitizers/issues/494 |
| 5 | // Tsan sees false HB edge on address pointed to by syncp variable. |
| 6 | // It is false because when acquire is done syncp points to a var in one frame, |
| 7 | // and during release it points to a var in a different frame. |
| 8 | // The code is somewhat tricky because it prevents compiler from optimizing |
| 9 | // our accesses away, structured to not introduce other data races and |
| 10 | // not introduce other synchronization, and to arrange the vars in different |
| 11 | // frames to occupy the same address. |
| 12 | |
| 13 | // The data race CHECK-NOT below actually must be CHECK, because the program |
| 14 | // does contain the data race on global. |
| 15 | |
| 16 | // CHECK-NOT: WARNING: ThreadSanitizer: data race |
| 17 | // CHECK: DONE |
| 18 | |
| 19 | long global; |
| 20 | long *syncp; |
| 21 | long *addr; |
| 22 | long sink; |
| 23 | |
| 24 | void *Thread(void *x) { |
| 25 | while (__atomic_load_n(&syncp, __ATOMIC_ACQUIRE) == 0) |
| 26 | usleep(useconds: 1000); // spin wait |
| 27 | global = 42; |
| 28 | __atomic_store_n(syncp, 1, __ATOMIC_RELEASE); |
| 29 | __atomic_store_n(&syncp, 0, __ATOMIC_RELAXED); |
| 30 | return NULL; |
| 31 | } |
| 32 | |
| 33 | void __attribute__((noinline)) foobar() { |
| 34 | __attribute__((aligned(64))) long s; |
| 35 | |
| 36 | addr = &s; |
| 37 | __atomic_store_n(&s, 0, __ATOMIC_RELAXED); |
| 38 | __atomic_store_n(&syncp, &s, __ATOMIC_RELEASE); |
| 39 | while (__atomic_load_n(&syncp, __ATOMIC_RELAXED) != 0) |
| 40 | usleep(useconds: 1000); // spin wait |
| 41 | } |
| 42 | |
| 43 | void __attribute__((noinline)) barfoo() { |
| 44 | __attribute__((aligned(64))) long s; |
| 45 | |
| 46 | if (addr != &s) { |
| 47 | printf(format: "address mismatch addr=%p &s=%p\n" , addr, &s); |
| 48 | exit(status: 1); |
| 49 | } |
| 50 | __atomic_store_n(&addr, &s, __ATOMIC_RELAXED); |
| 51 | __atomic_store_n(&s, 0, __ATOMIC_RELAXED); |
| 52 | sink = __atomic_load_n(&s, __ATOMIC_ACQUIRE); |
| 53 | global = 43; |
| 54 | } |
| 55 | |
| 56 | int main() { |
| 57 | pthread_t t; |
| 58 | pthread_create(newthread: &t, attr: 0, start_routine: Thread, arg: 0); |
| 59 | foobar(); |
| 60 | barfoo(); |
| 61 | pthread_join(th: t, thread_return: 0); |
| 62 | if (sink != 0) |
| 63 | exit(status: 1); |
| 64 | fprintf(stderr, format: "DONE\n" ); |
| 65 | return 0; |
| 66 | } |
| 67 | |
| 68 | |