SanitizerCoverage.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. =================
  2. SanitizerCoverage
  3. =================
  4. .. contents::
  5. :local:
  6. Introduction
  7. ============
  8. LLVM has a simple code coverage instrumentation built in (SanitizerCoverage).
  9. It inserts calls to user-defined functions on function-, basic-block-, and edge- levels.
  10. Default implementations of those callbacks are provided and implement
  11. simple coverage reporting and visualization,
  12. however if you need *just* coverage visualization you may want to use
  13. :doc:`SourceBasedCodeCoverage <SourceBasedCodeCoverage>` instead.
  14. Tracing PCs with guards
  15. =======================
  16. With ``-fsanitize-coverage=trace-pc-guard`` the compiler will insert the following code
  17. on every edge:
  18. .. code-block:: none
  19. __sanitizer_cov_trace_pc_guard(&guard_variable)
  20. Every edge will have its own `guard_variable` (uint32_t).
  21. The compler will also insert calls to a module constructor:
  22. .. code-block:: c++
  23. // The guards are [start, stop).
  24. // This function will be called at least once per DSO and may be called
  25. // more than once with the same values of start/stop.
  26. __sanitizer_cov_trace_pc_guard_init(uint32_t *start, uint32_t *stop);
  27. With an additional ``...=trace-pc,indirect-calls`` flag
  28. ``__sanitizer_cov_trace_pc_indirect(void *callee)`` will be inserted on every indirect call.
  29. The functions `__sanitizer_cov_trace_pc_*` should be defined by the user.
  30. Example:
  31. .. code-block:: c++
  32. // trace-pc-guard-cb.cc
  33. #include <stdint.h>
  34. #include <stdio.h>
  35. #include <sanitizer/coverage_interface.h>
  36. // This callback is inserted by the compiler as a module constructor
  37. // into every DSO. 'start' and 'stop' correspond to the
  38. // beginning and end of the section with the guards for the entire
  39. // binary (executable or DSO). The callback will be called at least
  40. // once per DSO and may be called multiple times with the same parameters.
  41. extern "C" void __sanitizer_cov_trace_pc_guard_init(uint32_t *start,
  42. uint32_t *stop) {
  43. static uint64_t N; // Counter for the guards.
  44. if (start == stop || *start) return; // Initialize only once.
  45. printf("INIT: %p %p\n", start, stop);
  46. for (uint32_t *x = start; x < stop; x++)
  47. *x = ++N; // Guards should start from 1.
  48. }
  49. // This callback is inserted by the compiler on every edge in the
  50. // control flow (some optimizations apply).
  51. // Typically, the compiler will emit the code like this:
  52. // if(*guard)
  53. // __sanitizer_cov_trace_pc_guard(guard);
  54. // But for large functions it will emit a simple call:
  55. // __sanitizer_cov_trace_pc_guard(guard);
  56. extern "C" void __sanitizer_cov_trace_pc_guard(uint32_t *guard) {
  57. if (!*guard) return; // Duplicate the guard check.
  58. // If you set *guard to 0 this code will not be called again for this edge.
  59. // Now you can get the PC and do whatever you want:
  60. // store it somewhere or symbolize it and print right away.
  61. // The values of `*guard` are as you set them in
  62. // __sanitizer_cov_trace_pc_guard_init and so you can make them consecutive
  63. // and use them to dereference an array or a bit vector.
  64. void *PC = __builtin_return_address(0);
  65. char PcDescr[1024];
  66. // This function is a part of the sanitizer run-time.
  67. // To use it, link with AddressSanitizer or other sanitizer.
  68. __sanitizer_symbolize_pc(PC, "%p %F %L", PcDescr, sizeof(PcDescr));
  69. printf("guard: %p %x PC %s\n", guard, *guard, PcDescr);
  70. }
  71. .. code-block:: c++
  72. // trace-pc-guard-example.cc
  73. void foo() { }
  74. int main(int argc, char **argv) {
  75. if (argc > 1) foo();
  76. }
  77. .. code-block:: console
  78. clang++ -g -fsanitize-coverage=trace-pc-guard trace-pc-guard-example.cc -c
  79. clang++ trace-pc-guard-cb.cc trace-pc-guard-example.o -fsanitize=address
  80. ASAN_OPTIONS=strip_path_prefix=`pwd`/ ./a.out
  81. .. code-block:: console
  82. INIT: 0x71bcd0 0x71bce0
  83. guard: 0x71bcd4 2 PC 0x4ecd5b in main trace-pc-guard-example.cc:2
  84. guard: 0x71bcd8 3 PC 0x4ecd9e in main trace-pc-guard-example.cc:3:7
  85. .. code-block:: console
  86. ASAN_OPTIONS=strip_path_prefix=`pwd`/ ./a.out with-foo
  87. .. code-block:: console
  88. INIT: 0x71bcd0 0x71bce0
  89. guard: 0x71bcd4 2 PC 0x4ecd5b in main trace-pc-guard-example.cc:3
  90. guard: 0x71bcdc 4 PC 0x4ecdc7 in main trace-pc-guard-example.cc:4:17
  91. guard: 0x71bcd0 1 PC 0x4ecd20 in foo() trace-pc-guard-example.cc:2:14
  92. Inline 8bit-counters
  93. ====================
  94. **Experimental, may change or disappear in future**
  95. With ``-fsanitize-coverage=inline-8bit-counters`` the compiler will insert
  96. inline counter increments on every edge.
  97. This is similar to ``-fsanitize-coverage=trace-pc-guard`` but instead of a
  98. callback the instrumentation simply increments a counter.
  99. Users need to implement a single function to capture the counters at startup.
  100. .. code-block:: c++
  101. extern "C"
  102. void __sanitizer_cov_8bit_counters_init(char *start, char *end) {
  103. // [start,end) is the array of 8-bit counters created for the current DSO.
  104. // Capture this array in order to read/modify the counters.
  105. }
  106. PC-Table
  107. ========
  108. **Experimental, may change or disappear in future**
  109. **Note:** this instrumentation might be incompatible with dead code stripping
  110. (``-Wl,-gc-sections``) for linkers other than LLD, thus resulting in a
  111. significant binary size overhead. For more information, see
  112. `Bug 34636 <https://bugs.llvm.org/show_bug.cgi?id=34636>`_.
  113. With ``-fsanitize-coverage=pc-table`` the compiler will create a table of
  114. instrumented PCs. Requires either ``-fsanitize-coverage=inline-8bit-counters`` or
  115. ``-fsanitize-coverage=trace-pc-guard``.
  116. Users need to implement a single function to capture the PC table at startup:
  117. .. code-block:: c++
  118. extern "C"
  119. void __sanitizer_cov_pcs_init(const uintptr_t *pcs_beg,
  120. const uintptr_t *pcs_end) {
  121. // [pcs_beg,pcs_end) is the array of ptr-sized integers representing
  122. // pairs [PC,PCFlags] for every instrumented block in the current DSO.
  123. // Capture this array in order to read the PCs and their Flags.
  124. // The number of PCs and PCFlags for a given DSO is the same as the number
  125. // of 8-bit counters (-fsanitize-coverage=inline-8bit-counters) or
  126. // trace_pc_guard callbacks (-fsanitize-coverage=trace-pc-guard)
  127. // A PCFlags describes the basic block:
  128. // * bit0: 1 if the block is the function entry block, 0 otherwise.
  129. }
  130. Tracing PCs
  131. ===========
  132. With ``-fsanitize-coverage=trace-pc`` the compiler will insert
  133. ``__sanitizer_cov_trace_pc()`` on every edge.
  134. With an additional ``...=trace-pc,indirect-calls`` flag
  135. ``__sanitizer_cov_trace_pc_indirect(void *callee)`` will be inserted on every indirect call.
  136. These callbacks are not implemented in the Sanitizer run-time and should be defined
  137. by the user.
  138. This mechanism is used for fuzzing the Linux kernel
  139. (https://github.com/google/syzkaller).
  140. Instrumentation points
  141. ======================
  142. Sanitizer Coverage offers different levels of instrumentation.
  143. * ``edge`` (default): edges are instrumented (see below).
  144. * ``bb``: basic blocks are instrumented.
  145. * ``func``: only the entry block of every function will be instrumented.
  146. Use these flags together with ``trace-pc-guard`` or ``trace-pc``,
  147. like this: ``-fsanitize-coverage=func,trace-pc-guard``.
  148. When ``edge`` or ``bb`` is used, some of the edges/blocks may still be left
  149. uninstrumented (pruned) if such instrumentation is considered redundant.
  150. Use ``no-prune`` (e.g. ``-fsanitize-coverage=bb,no-prune,trace-pc-guard``)
  151. to disable pruning. This could be useful for better coverage visualization.
  152. Edge coverage
  153. -------------
  154. Consider this code:
  155. .. code-block:: c++
  156. void foo(int *a) {
  157. if (a)
  158. *a = 0;
  159. }
  160. It contains 3 basic blocks, let's name them A, B, C:
  161. .. code-block:: none
  162. A
  163. |\
  164. | \
  165. | B
  166. | /
  167. |/
  168. C
  169. If blocks A, B, and C are all covered we know for certain that the edges A=>B
  170. and B=>C were executed, but we still don't know if the edge A=>C was executed.
  171. Such edges of control flow graph are called
  172. `critical <https://en.wikipedia.org/wiki/Control_flow_graph#Special_edges>`_.
  173. The edge-level coverage simply splits all critical edges by introducing new
  174. dummy blocks and then instruments those blocks:
  175. .. code-block:: none
  176. A
  177. |\
  178. | \
  179. D B
  180. | /
  181. |/
  182. C
  183. Tracing data flow
  184. =================
  185. Support for data-flow-guided fuzzing.
  186. With ``-fsanitize-coverage=trace-cmp`` the compiler will insert extra instrumentation
  187. around comparison instructions and switch statements.
  188. Similarly, with ``-fsanitize-coverage=trace-div`` the compiler will instrument
  189. integer division instructions (to capture the right argument of division)
  190. and with ``-fsanitize-coverage=trace-gep`` --
  191. the `LLVM GEP instructions <https://llvm.org/docs/GetElementPtr.html>`_
  192. (to capture array indices).
  193. Unless ``no-prune`` option is provided, some of the comparison instructions
  194. will not be instrumented.
  195. .. code-block:: c++
  196. // Called before a comparison instruction.
  197. // Arg1 and Arg2 are arguments of the comparison.
  198. void __sanitizer_cov_trace_cmp1(uint8_t Arg1, uint8_t Arg2);
  199. void __sanitizer_cov_trace_cmp2(uint16_t Arg1, uint16_t Arg2);
  200. void __sanitizer_cov_trace_cmp4(uint32_t Arg1, uint32_t Arg2);
  201. void __sanitizer_cov_trace_cmp8(uint64_t Arg1, uint64_t Arg2);
  202. // Called before a comparison instruction if exactly one of the arguments is constant.
  203. // Arg1 and Arg2 are arguments of the comparison, Arg1 is a compile-time constant.
  204. // These callbacks are emitted by -fsanitize-coverage=trace-cmp since 2017-08-11
  205. void __sanitizer_cov_trace_const_cmp1(uint8_t Arg1, uint8_t Arg2);
  206. void __sanitizer_cov_trace_const_cmp2(uint16_t Arg1, uint16_t Arg2);
  207. void __sanitizer_cov_trace_const_cmp4(uint32_t Arg1, uint32_t Arg2);
  208. void __sanitizer_cov_trace_const_cmp8(uint64_t Arg1, uint64_t Arg2);
  209. // Called before a switch statement.
  210. // Val is the switch operand.
  211. // Cases[0] is the number of case constants.
  212. // Cases[1] is the size of Val in bits.
  213. // Cases[2:] are the case constants.
  214. void __sanitizer_cov_trace_switch(uint64_t Val, uint64_t *Cases);
  215. // Called before a division statement.
  216. // Val is the second argument of division.
  217. void __sanitizer_cov_trace_div4(uint32_t Val);
  218. void __sanitizer_cov_trace_div8(uint64_t Val);
  219. // Called before a GetElemementPtr (GEP) instruction
  220. // for every non-constant array index.
  221. void __sanitizer_cov_trace_gep(uintptr_t Idx);
  222. Default implementation
  223. ======================
  224. The sanitizer run-time (AddressSanitizer, MemorySanitizer, etc) provide a
  225. default implementations of some of the coverage callbacks.
  226. You may use this implementation to dump the coverage on disk at the process
  227. exit.
  228. Example:
  229. .. code-block:: console
  230. % cat -n cov.cc
  231. 1 #include <stdio.h>
  232. 2 __attribute__((noinline))
  233. 3 void foo() { printf("foo\n"); }
  234. 4
  235. 5 int main(int argc, char **argv) {
  236. 6 if (argc == 2)
  237. 7 foo();
  238. 8 printf("main\n");
  239. 9 }
  240. % clang++ -g cov.cc -fsanitize=address -fsanitize-coverage=trace-pc-guard
  241. % ASAN_OPTIONS=coverage=1 ./a.out; wc -c *.sancov
  242. main
  243. SanitizerCoverage: ./a.out.7312.sancov 2 PCs written
  244. 24 a.out.7312.sancov
  245. % ASAN_OPTIONS=coverage=1 ./a.out foo ; wc -c *.sancov
  246. foo
  247. main
  248. SanitizerCoverage: ./a.out.7316.sancov 3 PCs written
  249. 24 a.out.7312.sancov
  250. 32 a.out.7316.sancov
  251. Every time you run an executable instrumented with SanitizerCoverage
  252. one ``*.sancov`` file is created during the process shutdown.
  253. If the executable is dynamically linked against instrumented DSOs,
  254. one ``*.sancov`` file will be also created for every DSO.
  255. Sancov data format
  256. ------------------
  257. The format of ``*.sancov`` files is very simple: the first 8 bytes is the magic,
  258. one of ``0xC0BFFFFFFFFFFF64`` and ``0xC0BFFFFFFFFFFF32``. The last byte of the
  259. magic defines the size of the following offsets. The rest of the data is the
  260. offsets in the corresponding binary/DSO that were executed during the run.
  261. Sancov Tool
  262. -----------
  263. An simple ``sancov`` tool is provided to process coverage files.
  264. The tool is part of LLVM project and is currently supported only on Linux.
  265. It can handle symbolization tasks autonomously without any extra support
  266. from the environment. You need to pass .sancov files (named
  267. ``<module_name>.<pid>.sancov`` and paths to all corresponding binary elf files.
  268. Sancov matches these files using module names and binaries file names.
  269. .. code-block:: console
  270. USAGE: sancov [options] <action> (<binary file>|<.sancov file>)...
  271. Action (required)
  272. -print - Print coverage addresses
  273. -covered-functions - Print all covered functions.
  274. -not-covered-functions - Print all not covered functions.
  275. -symbolize - Symbolizes the report.
  276. Options
  277. -blacklist=<string> - Blacklist file (sanitizer blacklist format).
  278. -demangle - Print demangled function name.
  279. -strip_path_prefix=<string> - Strip this prefix from file paths in reports
  280. Coverage Reports
  281. ----------------
  282. **Experimental**
  283. ``.sancov`` files do not contain enough information to generate a source-level
  284. coverage report. The missing information is contained
  285. in debug info of the binary. Thus the ``.sancov`` has to be symbolized
  286. to produce a ``.symcov`` file first:
  287. .. code-block:: console
  288. sancov -symbolize my_program.123.sancov my_program > my_program.123.symcov
  289. The ``.symcov`` file can be browsed overlayed over the source code by
  290. running ``tools/sancov/coverage-report-server.py`` script that will start
  291. an HTTP server.
  292. Output directory
  293. ----------------
  294. By default, .sancov files are created in the current working directory.
  295. This can be changed with ``ASAN_OPTIONS=coverage_dir=/path``:
  296. .. code-block:: console
  297. % ASAN_OPTIONS="coverage=1:coverage_dir=/tmp/cov" ./a.out foo
  298. % ls -l /tmp/cov/*sancov
  299. -rw-r----- 1 kcc eng 4 Nov 27 12:21 a.out.22673.sancov
  300. -rw-r----- 1 kcc eng 8 Nov 27 12:21 a.out.22679.sancov