blob: d2bc5cb1b2827691e0f5447200cb11481a6a3bcc [file] [log] [blame]
Stephen Hines86277eb2015-03-23 12:06:32 -07001// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2#include "test.h"
3
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -08004// Test case https://github.com/google/sanitizers/issues/494
Stephen Hines86277eb2015-03-23 12:06:32 -07005// 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
19long global;
20long *syncp;
21long *addr;
22long sink;
23
24void *Thread(void *x) {
25 while (__atomic_load_n(&syncp, __ATOMIC_ACQUIRE) == 0)
26 usleep(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
33void __attribute__((noinline)) foobar() {
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080034 __attribute__((aligned(64))) long s;
35
Stephen Hines86277eb2015-03-23 12:06:32 -070036 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(1000); // spin wait
41}
42
43void __attribute__((noinline)) barfoo() {
Pirama Arumuga Nainar799172d2016-03-03 15:50:30 -080044 __attribute__((aligned(64))) long s;
45
Stephen Hines86277eb2015-03-23 12:06:32 -070046 if (addr != &s) {
47 printf("address mismatch addr=%p &s=%p\n", addr, &s);
48 exit(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
56int main() {
57 pthread_t t;
58 pthread_create(&t, 0, Thread, 0);
59 foobar();
60 barfoo();
61 pthread_join(t, 0);
62 if (sink != 0)
63 exit(1);
64 fprintf(stderr, "DONE\n");
65 return 0;
66}
67