Run DCE after a LoopFlatten test to reduce spurious output [nfc]
[llvm-project.git] / compiler-rt / test / tsan / signal_thread_sigctx_race.cpp
bloba3a206f9ab386636df69b2807aeb2fd7a70bfe77
1 // RUN: %clangxx_tsan %s -o %t && %run %t 2>&1 | FileCheck %s
2 // UNSUPPORTED: darwin
4 #include <errno.h>
5 #include <limits.h>
6 #include <pthread.h>
7 #include <signal.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/select.h>
11 #include <sys/time.h>
12 #include <sys/types.h>
13 #include <unistd.h>
15 // This attempts to exercise a race condition where both a thread and its signal
16 // handler allocate the SigCtx. If the race is allowed, it leads to a leak and
17 // the first signal being dropped.
18 // Spawn threads in a loop and send it SIGUSR1 concurrently with the thread
19 // doing a bogus kill() call. The signal handler writes to a self-pipe which the
20 // thread detects and then exits. A dropped signal results in a timeout.
21 int pipes[2];
22 static void handler(int sig) { write(pipes[1], "x", 1); }
24 static int do_select() {
25 struct timeval tvs {
26 0, 1000
28 fd_set fds;
29 FD_ZERO(&fds);
30 FD_SET(pipes[0], &fds);
31 return select(pipes[0] + 1, &fds, 0, 0, &tvs);
34 static void *thr(void *p) {
35 // This kill() is expected to fail; it exists only to trigger a call to SigCtx
36 // outside of the signal handler.
37 kill(INT_MIN, 0);
38 int success = 0;
39 for (int i = 0; i < 1024; i++) {
40 if (do_select() > 0) {
41 success = 1;
42 break;
45 if (success) {
46 char c;
47 read(pipes[0], &c, 1);
48 } else {
49 fprintf(stderr, "Failed to receive signal\n");
50 exit(1);
52 return p;
55 int main() {
56 if (pipe(pipes)) {
57 perror("pipe");
58 exit(1);
61 struct sigaction act = {};
62 act.sa_handler = &handler;
63 if (sigaction(SIGUSR1, &act, 0)) {
64 perror("sigaction");
65 exit(1);
68 for (int i = 0; i < (1 << 10); i++) {
69 pthread_t th{};
70 if (pthread_create(&th, 0, thr, 0)) {
71 perror("pthread_create");
72 exit(1);
74 pthread_kill(th, SIGUSR1);
75 pthread_join(th, 0);
78 fprintf(stderr, "DONE\n");
79 return 0;
82 // CHECK-NOT: WARNING: ThreadSanitizer:
83 // CHECK: DONE
84 // CHECK-NOT: WARNING: ThreadSanitizer: