xref: /llvm-project/compiler-rt/test/sanitizer_common/TestCases/onprint.cpp (revision a871c34e8d400e83f60320b51f19f0cb33eb7ade)
1 // Checks that the __sanitizer_on_print hook gets the exact same sanitizer
2 // report as what is printed to stderr.
3 //
4 // RUN: %clangxx %s -o %t
5 // RUN: %run %t %t-onprint.txt 2>%t-stderr.txt || true
6 // RUN: diff %t-onprint.txt %t-stderr.txt
7 //
8 // UNSUPPORTED: android
9 
10 #include <cassert>
11 #include <cstdlib>
12 #include <fcntl.h>
13 #include <string.h>
14 #include <sys/stat.h>
15 #include <sys/types.h>
16 #include <unistd.h>
17 
18 int f;
19 volatile void *buf;
20 volatile char sink;
21 
22 __attribute__((disable_sanitizer_instrumentation)) extern "C" void
__sanitizer_on_print(const char * str)23 __sanitizer_on_print(const char *str) {
24   write(f, str, strlen(str));
25 }
26 
main(int argc,char * argv[])27 int main(int argc, char *argv[]) {
28   assert(argc >= 2);
29   f = open(argv[1], O_CREAT | O_TRUNC | O_WRONLY, 0666);
30 
31   // Use-after-free to trigger ASan/TSan reports.
32   void *ptr = malloc(1);
33   buf = ptr;
34   free(ptr);
35   sink = *static_cast<char *>(ptr);
36   return 0;
37 }
38