File: atomic.cpp

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (59 lines) | stat: -rw-r--r-- 1,680 bytes parent folder | download | duplicates (20)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// RUN: %clangxx_dfsan %s -fno-exceptions -o %t && %run %t
// RUN: %clangxx_dfsan -DORIGIN_TRACKING -mllvm -dfsan-track-origins=1 %s -fno-exceptions -o %t && %run %t
//
// Use -fno-exceptions to turn off exceptions to avoid instrumenting
// __cxa_begin_catch, std::terminate and __gxx_personality_v0.
//
// TODO: Support builtin atomics. For example, https://gcc.gnu.org/onlinedocs/gcc/_005f_005fatomic-Builtins.html
// DFSan instrumentation pass cannot identify builtin callsites yet.

#include <sanitizer/dfsan_interface.h>

#include <assert.h>
#include <atomic>
#include <pthread.h>

std::atomic<int> atomic_i{0};

struct arg_struct {
  size_t index;
  dfsan_origin origin;
};

static void *ThreadFn(void *arg) {
  if (((arg_struct *)arg)->index % 2) {
    int i = 10;
    dfsan_set_label(8, (void *)&i, sizeof(i));
    atomic_i.store(i, std::memory_order_relaxed);
    return 0;
  }
  int j = atomic_i.load();
  assert(dfsan_get_label(j) == 0 || dfsan_get_label(j) == 2);
#ifdef ORIGIN_TRACKING
  if (dfsan_get_label(j) == 2)
    assert(dfsan_get_init_origin(&j) == ((arg_struct *)arg)->origin);
#endif
  return 0;
}

int main(void) {
  int i = 10;
  dfsan_set_label(2, (void *)&i, sizeof(i));
#ifdef ORIGIN_TRACKING
  dfsan_origin origin = dfsan_get_origin(i);
#endif
  atomic_i.store(i, std::memory_order_relaxed);
  const int kNumThreads = 24;
  pthread_t t[kNumThreads];
  arg_struct args[kNumThreads];
  for (int i = 0; i < kNumThreads; ++i) {
    args[i].index = i;
#ifdef ORIGIN_TRACKING
    args[i].origin = origin;
#endif
    pthread_create(&t[i], 0, ThreadFn, (void *)(args + i));
  }
  for (int i = 0; i < kNumThreads; ++i)
    pthread_join(t[i], 0);
  return 0;
}