1 // RUN: %clang_dfsan -fno-sanitize=dataflow -O2 -fPIE -DCALLBACKS -c %s -o %t-callbacks.o
2 // RUN: %clang_dfsan -fsanitize-ignorelist=%S/Inputs/flags_abilist.txt -O2 -mllvm -dfsan-conditional-callbacks %s %t-callbacks.o -o %t
3 // RUN: %run %t FooBarBaz 2>&1 | FileCheck %s
4 //
5 // REQUIRES: x86_64-target-arch
6
7 #include <assert.h>
8 #include <sanitizer/dfsan_interface.h>
9 #include <signal.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14
15 #ifdef CALLBACKS
16 // Compile this code without DFSan to avoid recursive instrumentation.
17
my_dfsan_conditional_callback(dfsan_label Label,dfsan_origin Origin)18 void my_dfsan_conditional_callback(dfsan_label Label, dfsan_origin Origin) {
19 assert(Label != 0);
20 assert(Origin == 0);
21
22 static int Count = 0;
23 switch (Count++) {
24 case 0:
25 assert(Label == 1);
26 break;
27 case 1:
28 assert(Label == 4);
29 break;
30 default:
31 break;
32 }
33
34 fprintf(stderr, "Label %u used as condition\n", Label);
35 }
36
37 #else
38 // Compile this code with DFSan and -dfsan-conditional-callbacks to insert the
39 // callbacks.
40
41 extern void my_dfsan_conditional_callback(dfsan_label Label,
42 dfsan_origin Origin);
43
44 volatile int x = 0;
45 volatile int y = 1;
46 volatile int z = 0;
47
SignalHandler(int signo)48 void SignalHandler(int signo) {
49 assert(dfsan_get_label(x) == 0);
50 assert(dfsan_get_label(y) != 0);
51 assert(dfsan_get_label(z) != 0);
52 // Running the conditional callback from a signal handler is risky,
53 // because the code must be written with signal handler context in mind.
54 // Instead dfsan_get_labels_in_signal_conditional() will indicate labels
55 // used in conditions inside signal handlers.
56 // CHECK-NOT: Label 8 used as condition
57 if (z != 0) {
58 x = y;
59 }
60 }
61
main(int Argc,char * Argv[])62 int main(int Argc, char *Argv[]) {
63 assert(Argc >= 1);
64 int unknown = (Argv[0][0] != 0) ? 1 : 0;
65 dfsan_set_label(1, &unknown, sizeof(unknown));
66
67 dfsan_set_conditional_callback(my_dfsan_conditional_callback);
68
69 // CHECK: Label 1 used as condition
70 if (unknown) {
71 z = 42;
72 }
73
74 assert(dfsan_get_labels_in_signal_conditional() == 0);
75 dfsan_set_label(4, (void *)&y, sizeof(y));
76 dfsan_set_label(8, (void *)&z, sizeof(z));
77
78 struct sigaction sa = {};
79 sa.sa_handler = SignalHandler;
80 int r = sigaction(SIGHUP, &sa, NULL);
81 assert(dfsan_get_label(r) == 0);
82
83 kill(getpid(), SIGHUP);
84 signal(SIGHUP, SIG_DFL);
85
86 assert(dfsan_get_labels_in_signal_conditional() == 8);
87 assert(x == 1);
88 // CHECK: Label 4 used as condition
89 if (x != 0) {
90 z = 123;
91 }
92 // Flush should clear the conditional signals seen.
93 dfsan_flush();
94 assert(dfsan_get_labels_in_signal_conditional() == 0);
95 return 0;
96 }
97
98 #endif // #ifdef CALLBACKS
99