]> git.lizzy.rs Git - rust.git/blob - src/doc/unstable-book/src/compiler-flags/source-based-code-coverage.md
Combination of commits
[rust.git] / src / doc / unstable-book / src / compiler-flags / source-based-code-coverage.md
1 # `source-based-code-coverage`
2
3 The tracking issue for this feature is: [#79121].
4
5 ------------------------
6
7 ## Introduction
8
9 The Rust compiler includes two code coverage implementations:
10
11 * A GCC-compatible, gcov-based coverage implementation, enabled with [`-Zprofile`], which operates on DebugInfo.
12 * A source-based code coverage implementation, enabled with `-Zinstrument-coverage`, which uses LLVM's native coverage instrumentation to generate very precise coverage data.
13
14 This document describes how to enable and use the LLVM instrumentation-based coverage, via the `-Zinstrument-coverage` compiler flag.
15
16 ## How it works
17
18 When `-Zinstrument-coverage` is enabled, the Rust compiler enhances rust-based libraries and binaries by:
19
20 * Automatically injecting calls to an LLVM intrinsic ([`llvm.instrprof.increment`]), at functions and branches in compiled code, to increment counters when conditional sections of code are executed.
21 * Embedding additional information in the data section of each library and binary (using the [LLVM Code Coverage Mapping Format] _Version 4_, supported _only_ in LLVM 11 and up), to define the code regions (start and end positions in the source code) being counted.
22
23 When running a coverage-instrumented program, the counter values are written to a `profraw` file at program termination. LLVM bundles tools that read the counter results, combine those results with the coverage map (embedded in the program binary), and generate coverage reports in multiple formats.
24
25 ## Enable coverage profiling in the Rust compiler
26
27 Rust's source-based code coverage requires the Rust "profiler runtime". Without it, compiling with `-Zinstrument-coverage` generates an error that the profiler runtime is missing.
28
29 The Rust `nightly` distribution channel should include the profiler runtime, by default.
30
31 *IMPORTANT:* If you are building the Rust compiler from the source distribution, the profiler runtime is *not* enabled in the default `config.toml.example`. Edit your `config.toml` file and ensure the `profiler` feature is set it to `true`:
32
33 ```toml
34 # Build the profiler runtime (required when compiling with options that depend
35 # on this runtime, such as `-C profile-generate` or `-Z instrument-coverage`).
36 profiler = true
37 ```
38
39 If changed, rebuild the Rust compiler (see [rustc-dev-guide-how-to-build-and-run]).
40
41 ### Building the demangler
42
43 LLVM coverage reporting tools generate results that can include function names and other symbol references, and the raw coverage results report symbols using the compiler's "mangled" version of the symbol names, which can be difficult to interpret. To work around this issue, LLVM coverage tools also support a user-specified symbol name demangler.
44
45 One option for a Rust demangler is [`rustfilt`], which can be installed with:
46
47 ```shell
48 cargo install rustfilt
49 ```
50
51 Another option, if you are building from the Rust compiler source distribution, is to use the `rust-demangler` tool included in the Rust source distribution, which can be built with:
52
53 ```shell
54 $ ./x.py build rust-demangler
55 ```
56
57 ## Compiling with coverage enabled
58
59 Set the `-Zinstrument-coverage` compiler flag in order to enable LLVM source-based code coverage profiling.
60
61 With `cargo`, you can instrument your program binary *and* dependencies at the same time.
62
63 For example (if your project's Cargo.toml builds a binary by default):
64
65 ```shell
66 $ cd your-project
67 $ cargo clean
68 $ RUSTFLAGS="-Zinstrument-coverage" cargo build
69 ```
70
71 If `cargo` is not configured to use your `profiler`-enabled version of `rustc`, set the path explicitly via the `RUSTC` environment variable. Here is another example, using a `stage1` build of `rustc` to compile an `example` binary (from the [`json5format`] crate):
72
73 ```shell
74 $ RUSTC=$HOME/rust/build/x86_64-unknown-linux-gnu/stage1/bin/rustc \
75     RUSTFLAGS="-Zinstrument-coverage" \
76     cargo build --example formatjson5
77 ```
78
79 ## Running the instrumented binary to generate raw coverage profiling data
80
81 In the previous example, `cargo` generated the coverage-instrumented binary `formatjson5`:
82
83 ```shell
84 $ echo "{some: 'thing'}" | target/debug/examples/formatjson5 -
85 ```
86 ```json5
87 {
88     some: 'thing',
89 }
90 ```
91
92 After running this program, a new file, `default.profraw`, should be in the current working directory. It's often preferable to set a specific file name or path. You can change the output file using the environment variable `LLVM_PROFILE_FILE`:
93
94
95 ```shell
96 $ echo "{some: 'thing'}" \
97     | LLVM_PROFILE_FILE="formatjson5.profraw" target/debug/examples/formatjson5 -
98 ...
99 $ ls formatjson5.profraw
100 formatjson5.profraw
101 ```
102
103 If `LLVM_PROFILE_FILE` contains a path to a non-existent directory, the missing directory structure will be created. Additionally, the following special pattern strings are rewritten:
104
105 * `%p` - The process ID.
106 * `%h` - The hostname of the machine running the program.
107 * `%t` - The value of the TMPDIR environment variable.
108 * `%Nm` - the instrumented binary’s signature: The runtime creates a pool of N raw profiles, used for on-line profile merging. The runtime takes care of selecting a raw profile from the pool, locking it, and updating it before the program exits. `N` must be between `1` and `9`, and defaults to `1` if omitted (with simply `%m`).
109 * `%c` - Does not add anything to the filename, but enables a mode (on some platforms, including Darwin) in which profile counter updates are continuously synced to a file. This means that if the instrumented program crashes, or is killed by a signal, perfect coverage information can still be recovered.
110
111 ## Installing LLVM coverage tools
112
113 LLVM's supplies two tools—`llvm-profdata` and `llvm-cov`—that process coverage data and generate reports. There are several ways to find and/or install these tools, but note that the coverage mapping data generated by the Rust compiler requires LLVM version 11 or higher. (`llvm-cov --version` typically shows the tool's LLVM version number.):
114
115 * The LLVM tools may be installed (or installable) directly to your OS (such as via `apt-get`, for Linux).
116 * If you are building the Rust compiler from source, you can optionally use the bundled LLVM tools, built from source. Those tool binaries can typically be found in your build platform directory at something like: `rust/build/x86_64-unknown-linux-gnu/llvm/bin/llvm-*`.
117 * You can install compatible versions of these tools via `rustup`.
118
119 The `rustup` option is guaranteed to install a compatible version of the LLVM tools, but they can be hard to find. We recommend [`cargo-bintools`], which installs Rust-specific wrappers around these and other LLVM tools, so you can invoke them via `cargo` commands!
120
121 ```shell
122 $ rustup component add llvm-tools-preview
123 $ cargo install cargo-binutils
124 $ cargo profdata -- --help  # note the additional "--" preceeding the tool-specific arguments
125 ```
126
127 ## Creating coverage reports
128
129 Raw profiles have to be indexed before they can be used to generate coverage reports. This is done using [`llvm-profdata merge`] (or `cargo cov -- merge`), which can combine multiple raw profiles and index them at the same time:
130
131 ```shell
132 $ llvm-profdata merge -sparse formatjson5.profraw -o formatjson5.profdata
133 ```
134
135 Finally, the `.profdata` file is used, in combination with the coverage map (from the program binary) to generate coverage reports using [`llvm-cov report`] (or `cargo cov -- report`), for a coverage summaries; and [`llvm-cov show`] (or `cargo cov -- show`), to see detailed coverage of lines and regions (character ranges) overlaid on the original source code.
136
137 These commands have several display and filtering options. For example:
138
139 ```shell
140 $ llvm-cov show -Xdemangler=rustfilt target/debug/examples/formatjson5 \
141     -instr-profile=formatjson5.profdata \
142     -show-line-counts-or-regions \
143     -show-instantiations \
144     -name=add_quoted_string
145 ```
146
147 <img alt="Screenshot of sample `llvm-cov show` result, for function add_quoted_string" src="img/llvm-cov-show-01.png" class="center"/>
148 <br/>
149 <br/>
150
151 Some of the more notable options in this example include:
152
153 * `--Xdemangler=rustfilt` - the command name or path used to demangle Rust symbols (`rustfilt` in the example, but this could also be a path to the `rust-demangler` tool)
154 * `target/debug/examples/formatjson5` - the instrumented binary (from which to extract the coverage map)
155 * `--instr-profile=<path-to-file>.profdata` - the location of the `.profdata` file created by `llvm-profdata merge` (from the `.profraw` file generated by the instrumented binary)
156 * `--name=<exact-function-name>` - to show coverage for a specific function (or, consider using another filter option, such as `--name-regex=<pattern>`)
157
158 ## Interpreting reports
159
160 There are four statistics tracked in a coverage summary:
161
162 * Function coverage is the percentage of functions that have been executed at least once. A function is considered to be executed if any of its instantiations are executed.
163 * Instantiation coverage is the percentage of function instantiations that have been executed at least once. Generic functions and functions generated from macros are two kinds of functions that may have multiple instantiations.
164 * Line coverage is the percentage of code lines that have been executed at least once. Only executable lines within function bodies are considered to be code lines.
165 * Region coverage is the percentage of code regions that have been executed at least once. A code region may span multiple lines: for example, in a large function body with no control flow. In other cases, a single line can contain multiple code regions: `return x || (y && z)` has countable code regions for `x` (which may resolve the expression, if `x` is `true`), `|| (y && z)` (executed only if `x` was `false`), and `return` (executed in either situation).
166
167 Of these four statistics, function coverage is usually the least granular while region coverage is the most granular. The project-wide totals for each statistic are listed in the summary.
168
169 ## Test coverage
170
171 A typical use case for coverage analysis is test coverage. Rust's source-based coverage tools can both measure your tests' code coverage as percentage, and pinpoint functions and branches not tested.
172
173 The following example (using the [`json5format`] crate, for demonstration purposes) show how to generate and analyze coverage results for all tests in a crate.
174
175 Since `cargo test` both builds and runs the tests, we set both the additional `RUSTFLAGS`, to add the `-Zinstrument-coverage` flag, and `LLVM_PROFILE_FILE`, to set a custom filename for the raw profiling data generated during the test runs. Since there may be more than one test binary, apply `%m` in the filename pattern. This generates unique names for each test binary. (Otherwise, each executed test binary would overwrite the coverage results from the previous binary.)
176
177 ```shell
178 $ RUSTFLAGS="-Zinstrument-coverage" \
179     LLVM_PROFILE_FILE="json5format-%m.profraw" \
180     cargo test --tests
181 ```
182
183 Make note of the test binary file paths, displayed after the word "`Running`" in the test output:
184
185 ```text
186    ...
187    Compiling json5format v0.1.3 ($HOME/json5format)
188     Finished test [unoptimized + debuginfo] target(s) in 14.60s
189
190      Running target/debug/deps/json5format-fececd4653271682
191 running 25 tests
192 ...
193 test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
194
195      Running target/debug/deps/lib-30768f9c53506dc5
196 running 31 tests
197 ...
198 test result: ok. 31 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
199 ```
200
201 You should have one ore more `.profraw` files now, one for each test binary. Run the `profdata` tool to merge them:
202
203 ```shell
204 $ cargo profdata -- merge \
205     -sparse json5format-*.profraw -o json5format.profdata
206 ```
207
208 Then run the `cov` tool, with the `profdata` file and all test binaries:
209
210 ```shell
211 $ cargo cov -- report \
212     --use-color --ignore-filename-regex='/.cargo/registry' \
213     --instr-profile=json5format.profdata \
214     target/debug/deps/lib-30768f9c53506dc5 \
215     target/debug/deps/json5format-fececd4653271682
216 $ cargo cov -- show \
217     --use-color --ignore-filename-regex='/.cargo/registry' \
218     --instr-profile=json5format.profdata \
219     target/debug/deps/lib-30768f9c53506dc5 \
220     target/debug/deps/json5format-fececd4653271682 \
221     --show-instantiations --show-line-counts-or-regions \
222     --Xdemangler=rustfilt | less -R
223 ```
224
225 _Note the command line option `--ignore-filename-regex=/.cargo/registry`, which excludes the sources for dependencies from the coverage results._
226
227 ## Other references
228
229 Rust's implementation and workflow for source-based code coverage is based on the same library and tools used to implement [source-based code coverage in Clang]. (This document is partially based on the Clang guide.)
230
231 [#79121]: https://github.com/rust-lang/rust/issues/79121
232 [`-Zprofile`]: profile.md
233 [`llvm.instrprof.increment`]: https://llvm.org/docs/LangRef.html#llvm-instrprof-increment-intrinsic
234 [LLVM Code Coverage Mapping Format]: https://llvm.org/docs/CoverageMappingFormat.html
235 [rustc-dev-guide-how-to-build-and-run]: https://rustc-dev-guide.rust-lang.org/building/how-to-build-and-run.html
236 [`rustfilt`]: https://crates.io/crates/rustfilt
237 [`json5format`]: https://crates.io/crates/json5format
238 [`cargo-bintools`]: https://crates.io/crates/cargo-bintools
239 [`llvm-profdata merge`]: https://llvm.org/docs/CommandGuide/llvm-profdata.html#profdata-merge
240 [`llvm-cov report`]: https://llvm.org/docs/CommandGuide/llvm-cov.html#llvm-cov-report
241 [`llvm-cov show`]: https://llvm.org/docs/CommandGuide/llvm-cov.html#llvm-cov-show
242 [source-based code coverage in Clang]: https://clang.llvm.org/docs/SourceBasedCodeCoverage.html