1 // RUN: %clangxx_tsan %s -o %t
2 // RUN: %deflake %run %t 2>&1 | FileCheck %s
3 
4 #include <thread>
5 
6 #import "../test.h"
7 
8 
9 extern "C" {
10 int __tsan_get_report_data(void *report, const char **description, int *count,
11                            int *stack_count, int *mop_count, int *loc_count,
12                            int *mutex_count, int *thread_count,
13                            int *unique_tid_count, void **sleep_trace,
14                            unsigned long trace_size);
15 int __tsan_get_report_tag(void *report, unsigned long *tag);
16 }
17 
18 __attribute__((no_sanitize("thread"), noinline))
ExternalWrite(void * addr)19 void ExternalWrite(void *addr) {
20   void *kSwiftAccessRaceTag = (void *)0x1;
21   __tsan_external_write(addr, nullptr, kSwiftAccessRaceTag);
22 }
23 
main(int argc,char * argv[])24 int main(int argc, char *argv[]) {
25   barrier_init(&barrier, 2);
26   fprintf(stderr, "Start.\n");
27   // CHECK: Start.
28 
29   void *opaque_object = malloc(16);
30   std::thread t1([opaque_object] {
31     ExternalWrite(opaque_object);
32     barrier_wait(&barrier);
33   });
34   std::thread t2([opaque_object] {
35     barrier_wait(&barrier);
36     ExternalWrite(opaque_object);
37   });
38   // CHECK: WARNING: ThreadSanitizer: Swift access race
39   // CHECK: Modifying access of Swift variable at {{.*}} by thread {{.*}}
40   // CHECK: Previous modifying access of Swift variable at {{.*}} by thread {{.*}}
41   // CHECK: SUMMARY: ThreadSanitizer: Swift access race
42   t1.join();
43   t2.join();
44 
45   fprintf(stderr, "Done.\n");
46 }
47 
48 extern "C"
__tsan_on_report(void * report)49 void __tsan_on_report(void *report) {
50   const char *description;
51   int count;
52   int stack_count, mop_count, loc_count, mutex_count, thread_count,
53       unique_tid_count;
54   void *sleep_trace[16] = {0};
55   __tsan_get_report_data(report, &description, &count, &stack_count, &mop_count,
56                          &loc_count, &mutex_count, &thread_count,
57                          &unique_tid_count, sleep_trace, 16);
58   fprintf(stderr, "report type = '%s', count = %d\n", description, count);
59   // CHECK: report type = 'external-race', count = 0
60 
61   unsigned long tag;
62   __tsan_get_report_tag(report, &tag);
63   fprintf(stderr, "tag = %ld\n", tag);
64   // CHECK: tag = 1
65 }
66 
67 // CHECK: Done.
68 // CHECK: ThreadSanitizer: reported 1 warnings
69