1// RUN: %clangxx_dfsan %s -fno-exceptions -D_GLIBCXX_NO_ASSERTIONS -o %t && %run %t
2// RUN: %clangxx_dfsan -DORIGIN_TRACKING -mllvm -dfsan-track-origins=1 %s -fno-exceptions -D_GLIBCXX_NO_ASSERTIONS -o %t && %run %t
3//
4// Use -fno-exceptions to turn off exceptions to avoid instrumenting
5// __cxa_begin_catch, std::terminate and __gxx_personality_v0.
6//
7// Use -D_GLIBCXX_NO_ASSERTIONS to avoid depending on
8// std::__glibcxx_assert_fail with gcc >= 15.
9//
10// TODO: Support builtin atomics. For example, https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
11// DFSan instrumentation pass cannot identify builtin callsites yet.
12
13#include <sanitizer/dfsan_interface.h>
14
15#include <assert.h>
16#include <atomic>
17#include <pthread.h>
18
19std::atomic<int> atomic_i{0};
20
21struct arg_struct {
22 size_t index;
23 dfsan_origin origin;
24};
25
26static void *ThreadFn(void *arg) {
27 if (((arg_struct *)arg)->index % 2) {
28 int i = 10;
29 dfsan_set_label(label: 8, addr: (void *)&i, size: sizeof(i));
30 atomic_i.store(i, std::memory_order_relaxed);
31 return 0;
32 }
33 int j = atomic_i.load();
34 assert(dfsan_get_label(j) == 0 || dfsan_get_label(j) == 2);
35#ifdef ORIGIN_TRACKING
36 if (dfsan_get_label(j) == 2)
37 assert(dfsan_get_init_origin(&j) == ((arg_struct *)arg)->origin);
38#endif
39 return 0;
40}
41
42int main(void) {
43 int i = 10;
44 dfsan_set_label(label: 2, addr: (void *)&i, size: sizeof(i));
45#ifdef ORIGIN_TRACKING
46 dfsan_origin origin = dfsan_get_origin(i);
47#endif
48 atomic_i.store(i, std::memory_order_relaxed);
49 const int kNumThreads = 24;
50 pthread_t t[kNumThreads];
51 arg_struct args[kNumThreads];
52 for (int i = 0; i < kNumThreads; ++i) {
53 args[i].index = i;
54#ifdef ORIGIN_TRACKING
55 args[i].origin = origin;
56#endif
57 pthread_create(newthread: &t[i], attr: 0, start_routine: ThreadFn, arg: (void *)(args + i));
58 }
59 for (int i = 0; i < kNumThreads; ++i)
60 pthread_join(th: t[i], thread_return: 0);
61 return 0;
62}
63

source code of compiler-rt/test/dfsan/atomic.cpp