1// RUN: %clangxx_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s
2// UNSUPPORTED: darwin
3#include <pthread.h>
4#include <stdio.h>
5#include <stdlib.h>
6#include <signal.h>
7#include <sys/types.h>
8#include <sys/time.h>
9#include <unistd.h>
10#include <errno.h>
11
12// Test synchronization in signal handled within IgnoreSync region.
13
14extern "C" void AnnotateIgnoreSyncBegin(const char *f, int l);
15extern "C" void AnnotateIgnoreSyncEnd(const char *f, int l);
16
17const int kSignalCount = 500;
18
19__thread int process_signals;
20int signals_handled;
21int done;
22int ready[kSignalCount];
23long long data[kSignalCount];
24
25static void handler(int sig) {
26 if (!__atomic_load_n(&process_signals, __ATOMIC_RELAXED))
27 return;
28 int pos = signals_handled++;
29 if (pos >= kSignalCount)
30 return;
31 data[pos] = pos;
32 __atomic_store_n(&ready[pos], 1, __ATOMIC_RELEASE);
33}
34
35static void* thr(void *p) {
36 AnnotateIgnoreSyncBegin(__FILE__, __LINE__);
37 __atomic_store_n(&process_signals, 1, __ATOMIC_RELAXED);
38 while (!__atomic_load_n(&done, __ATOMIC_RELAXED)) {
39 }
40 AnnotateIgnoreSyncEnd(__FILE__, __LINE__);
41 return 0;
42}
43
44int main() {
45 struct sigaction act = {};
46 act.sa_handler = handler;
47 if (sigaction(SIGPROF, &act, 0)) {
48 perror("sigaction");
49 exit(1);
50 }
51 itimerval t;
52 t.it_value.tv_sec = 0;
53 t.it_value.tv_usec = 10;
54 t.it_interval = t.it_value;
55 if (setitimer(ITIMER_PROF, &t, 0)) {
56 perror("setitimer");
57 exit(1);
58 }
59
60 pthread_t th;
61 pthread_create(&th, 0, thr, 0);
62 for (int pos = 0; pos < kSignalCount; pos++) {
63 while (__atomic_load_n(&ready[pos], __ATOMIC_ACQUIRE) == 0) {
64 }
65 if (data[pos] != pos) {
66 printf("at pos %d, expect %d, got %lld\n", pos, pos, data[pos]);
67 exit(1);
68 }
69 }
70 __atomic_store_n(&done, 1, __ATOMIC_RELAXED);
71 pthread_join(th, 0);
72 fprintf(stderr, "DONE\n");
73 return 0;
74}
75
76// CHECK-NOT: WARNING: ThreadSanitizer:
77// CHECK: DONE
78