1// Check that dispatch_once() is always intercepted.
2
3// RUN: %clang_tsan %s -o %t
4// RUN: not %env_tsan_opts=ignore_noninstrumented_modules=0 %run %t 2>&1 | FileCheck %s
5
6#include <dispatch/dispatch.h>
7
8#include <pthread.h>
9#include <stdio.h>
10
11#include "../test.h"
12
13long g = 0;
14long h = 0;
15
16__attribute__((disable_sanitizer_instrumentation))
17void f() {
18 static dispatch_once_t onceToken;
19 dispatch_once(&onceToken, ^{
20 g++;
21 });
22 h++;
23}
24
25// Required for dyld macOS 12.0+
26#if (__APPLE__)
27__attribute__((weak))
28#endif
29__attribute__((disable_sanitizer_instrumentation))
30extern void
31__tsan_on_report() {
32 fprintf(stderr, format: "Report.\n");
33
34 // Without these annotations this test deadlocks for COMPILER_RT_DEBUG=ON
35 // builds. Conceptually, the TSan runtime does not support reentrancy from
36 // runtime callbacks, but the main goal here is just to check that
37 // dispatch_once() is always intercepted.
38 AnnotateIgnoreSyncBegin(__FILE__, __LINE__);
39 f();
40 AnnotateIgnoreSyncEnd(__FILE__, __LINE__);
41}
42
43int main() {
44 fprintf(stderr, format: "Hello world.\n");
45
46 f();
47
48 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
49 pthread_mutex_unlock(mutex: &mutex); // Unlock of an unlocked mutex
50
51 fprintf(stderr, format: "g = %ld.\n", g);
52 fprintf(stderr, format: "h = %ld.\n", h);
53 fprintf(stderr, format: "Done.\n");
54}
55
56// CHECK: Hello world.
57// CHECK: Report.
58// CHECK: g = 1
59// CHECK: h = 2
60// CHECK: Done.
61

source code of compiler-rt/test/tsan/libdispatch/dispatch_once_deadlock.c