• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // trace-pc-guard-cb.cc
2 #include <stdint.h>
3 #include <stdio.h>
4 #include <sanitizer/coverage_interface.h>
5 
6 // This callback is inserted by the compiler as a module constructor
7 // into every DSO. 'start' and 'stop' correspond to the
8 // beginning and end of the section with the guards for the entire
9 // binary (executable or DSO). The callback will be called at least
10 // once per DSO and may be called multiple times with the same parameters.
__sanitizer_cov_trace_pc_guard_init(uint32_t * start,uint32_t * stop)11 extern "C" void __sanitizer_cov_trace_pc_guard_init(uint32_t *start,
12                                                     uint32_t *stop) {
13   static uint64_t N;  // Counter for the guards.
14   if (start == stop || *start) return;  // Initialize only once.
15   printf("INIT: %p %p\n", start, stop);
16   for (uint32_t *x = start; x < stop; x++)
17     *x = ++N;  // Guards should start from 1.
18 }
19 
20 // This callback is inserted by the compiler on every edge in the
21 // control flow (some optimizations apply).
22 // Typically, the compiler will emit the code like this:
23 //    if(*guard)
24 //      __sanitizer_cov_trace_pc_guard(guard);
25 // But for large functions it will emit a simple call:
26 //    __sanitizer_cov_trace_pc_guard(guard);
__sanitizer_cov_trace_pc_guard(uint32_t * guard)27 extern "C" void __sanitizer_cov_trace_pc_guard(uint32_t *guard) {
28   if (!*guard) return;  // Duplicate the guard check.
29   // If you set *guard to 0 this code will not be called again for this edge.
30   // Now you can get the PC and do whatever you want:
31   //   store it somewhere or symbolize it and print right away.
32   // The values of `*guard` are as you set them in
33   // __sanitizer_cov_trace_pc_guard_init and so you can make them consecutive
34   // and use them to dereference an array or a bit vector.
35   void *PC = __builtin_return_address(0);
36   char PcDescr[1024];
37   // This function is a part of the sanitizer run-time.
38   // To use it, link with AddressSanitizer or other sanitizer.
39   __sanitizer_symbolize_pc(PC, "%p %F %L", PcDescr, sizeof(PcDescr));
40   printf("guard: %p %x PC %s\n", guard, *guard, PcDescr);
41 }
42 
main()43 int main(){}