Code coverage-Use of gcov lcov

Source: Internet
Author: User
Tags gcov network function perl script

1.Gcov viewing arm-Linux code coverage

I. About the gcov Tool

Gcov is released with GCC. Add the-fprofile-arcs-ftest-coverage parameter to the GCC compilation to generate a binary program, and execute the test case to generate code coverage information.
1. How to Use gcov

The-fprofile-arcs-ftest-coverage option is added during GCC compilation, and the link is also added.
The fprofile-arcs parameter allows GCC to create a program flow chart, and then find the appropriate spanning tree. Only the arcs that are not in the spanning tree are manipulated (instrumented): GCC adds code to count the number of times these arcs are executed. When this arc is the only exit or entry of a block, the instrumentation code will be added to the block. Otherwise, a basic block will be created to contain the code of the control tool.

Gcov mainly uses two files:. gcno and. gcda.
. Gcno is generated by-ftest-coverage. It contains information about rebuilding the basic block graph and the source code of the corresponding block.
. Gcda is generated by running the compiled file with the-fprofile-arcs compilation parameter added, it contains the number of arc hops and other summary information (gcda can only be generated after the program runs successfully ).
Gcov overwrites execution functions, statement overwrites, and branch overwrites.

For example, the program code consists of the Main. C and TMP. c files, which compile, link, and run the program.
Compile: gcc-fprofile-arcs-ftest-coverage-O MyApp main. c TMP. c
Command: gcov main. C, gcov TMP. c

At this time, the current directory has a new file main. C. gcov, and TMP. C. gcov.
To save the coverage file, modify the preceding command:
Command: gcov main. c> yourfilename, gcov TMP. c> yourfilename

At this time, Main. C. gcov and TMP. C. gcov contain information about the number of function and code executions. We can view the result:
-: 65: /*************************************** **************************************** ********
-: 66: * Name: Main
-: 67: * return: 0 OK
-: 68: * Other Error
-: 69: * History: 2006-06-13
-: 70: **************************************** **************************************** ********/
-: 71: int main (INT argc, char * argv [])/* the entrance for program

Function main called 4 returned 100% blocks executed 81%
4: 72 :{
4: 73: int loop = 0;
4: 74: int ret = OK;
4: 75: int empty_line = 0;
4: 76: int code_line = 0;
4: 77: int annotation_line = 0;
4: 78: struct stat file_stat;/* use for file state */
4: 79: Char recu_name [1, 256];
4: 80: char * Pwd = NULL;
4: 81: char * TMP = NULL;
-: 82:
4: 83: If (argc = max_file) {/* file size larger than Max size */
#####: 98: printf ("file [% s] size is over 64 K! /Ncontinue.../N ", argv [loop]);
#####: 99: continue;
-: 100 :}

##### This indicates that it is not running

The parameters are as follows:
Gcov [-B] [-C] [-V] [-N] [-L] [-F] [-O Directory] sourcefile
Write branch frequencies to the output file, and write branch summary info to the standard output. This option allows you

See how often each branch in your program was taken.
// B (ranch), branch Test
Write branch frequencies as the number of branches taken, rather than the percentage of branches taken.

Display the gcov version number (on the standard error stream ).
// It's too simple. I used it.
Do not create the gcov output file.
Create long file names for encoded source files. For example, if the header file 'x. H' contains code, and was encoded in

File 'a. c', then running gcov on the file 'a. c 'will produce an output file called 'a. c. x. h. gcov 'instead of 'X. h. gcov '. this can

Be useful if 'x. H' is supported in multiple source files.
Output summaries for each function in addition to the file level summary.
The directory where the object files live. gcov will search for '. BB','. bbg', and '. da' files in this directory.

That's what the new version says.
-O directory │ File
-- Object-directory
-- Object-file File
Specify either the directory containing the gcov data files, or
Object Path Name. The. gcno, And. gcda data files are searched
Using this option. If a directory is specified, the data files are
In that directory and named after the source file name, without its
Extension. If a file is specified here, the data files are named
After that file, without its extension. If this option is not sup-
Plied, It defaults to the current directory.
Others have the new version-u,
-- Unconditional-branches
When branch counts are given, include those of unconditional
Branches. Unconditional branches are normally not interesting.
-- Preserve-paths
Preserve complete path information in the names of generated. gcov
Files. Without this option, just the filename component is used.
With this option, all directories are used, with '/' characters
Translated to '# 'characters,'. 'directory components removed and
'.. 'Components renamed to' ^ '. This is useful if sourcefiles are
In several different directories. It also affects the-L option.

Ii. About lcov

Lcov is a front-end of gcov result display. It can convert the coverage information into HTML display.

1. example of how to access user space application code to overwrite data
Prerequisites: Use GCC to compile the program with the-fprofile-arcs and-ftest-coverage options. Assume that the compiling directory is named "/root/test/code_cover/", and then execute:

Take fork. C under one of my instances/root/test/code_cover/as an example to check the code coverage rate:

First, go to the/root/test/code_cover/directory.

A) reset the counter

Lcov -- directory. -- zerocounters

B) Collect the current code to overwrite a file (this command can work normally after the application starts and stops at least once)

Lcov -- directory. -- capture -- output-file

Capturing coverage data from.
Found gcov version: 3.4.6
Scanning. For. gcda files...
Found 1 data files in.
Processing./testquery. gcda
Finished. Info-File Creation

C) obtain HTML output

Genhtml-O results

"-O results" indicates the location where the result is stored.

Reading data file
Found 18 entries.
Found common filename prefix "/home/search/isearch_yb/src"
Writing. CSS and. PNG files.
Generating output.
Processing file CPP/CORE/basis/globaldef. h
Processing file CPP/CORE/search/querycache. h
Writing directory view page.
Overall coverage rate: 117 of 514 lines (22.8%)

Open the index.html file in a web browser to view the code coverage result.


Iii. Linux kernel coverage test:

Copy the final gcov kernel module file to the system wide modules directory or the directory where the Perl script is located. Run the following command as root:

Gcov: gcov can also be used for code coverage tests on Linux kernel programs, but a patch must be provided for the kernel. Gcov Kernel Patch: Download the gcov kernel patch (wget, unzip the patch, and then patch a kernel (patch



After the configuration is complete, re-compile the kernel, copy the compiled gcov kernel module/home/linux-v3.4-mem/kernel/gcov/gcov-proc.ko to the Network File System, this module is loaded after ARM Linux is started.

(1)/insmod gcov-proc.ko

Then run another test program and run it for a while. You will find various gcov statistical files under the/proc/gcov directory:

/Proc/gcov # ls

Arch crypto init kernel Security vmlinux

Block drivers IPC net sound

Copy the entire directory to a directory under the fedora virtual machine. I copied it to the/nfs/kernel_test/gcov directory, and then

(2) collect the current Code overwrite status to a file

Lcov -- directory. -- output-file

(3) Obtain HTML output


Open the index.html file in a web browser to view the code coverage result.


The above describes how to obtain the coverage rate of the kernel Running code.

But what should we do if we only want to get the kernel code coverage for a program running ???

Here are some features of the gcov-Proc module:

(1) module attributes:

We found the parameters folder under/sys/module/gcov_proc. We found two Property Files:

/Sys/module/gcov_proc/parameters # ls

Gcov_link gcov_persist

What are these two attributes under control ??? Look at the official statement:

-Gcov_link = 0/1 (default is 1): When set to non-zero, symbolic links

Source and gcov graph files are created in/proc/gcov along with the data


-Gcov_persist = 0/1 (default is 0): When set to non-zero, gcov data

Kernel modules is kept even after those modules are unloaded so that

Coverage measurements can be extended to module cleanup code. To clear

This persistent data, write to/proc/vmlinux.

(2) restart the data collected by kernel coverage

To reset coverage data for a specific file, simply write to the associated data

File in the/proc/gcov hierarchy:


Echo 0>/proc/gcov/kernel/signal. Da


To reset all coverage data, write to the extra File '/proc/gcov/vmlinux ':


Echo 0>/proc/gcov/vmlinux


4. Obtain kernel coverage during running hours

My method is to run the application (here is the timetest application under my/nfs/memtest/timetest) first use the "Echo 0>/proc/gcov/vmlinux" command to clear all the statistics under our/proc/gcov and let it count again, the following describes our methods and steps:

1. first obtain a kernel and gcov-proc.ko that indicates gcov information, which has been said above;

2. Start the Linux kernel, and then install the gcov-proc.ko

/Memtest # insmod gcov-proc.ko

Gcov-Proc: initializing proc module: persist = 0 link = 1 format = GCC 3.4

Gcov-Proc: init done

/Memtest # cd timetest/

/Memtest/timetest # ls

20100106. Log fp2 timetest. c timetest. gcno

20100111. Log results timetest-lcov timetest. gcda

3. Run the "Echo 0>/proc/gcov/vmlinux" command to clear gcov, run timetest, and

Copy/proc/gcov to/tmp to prevent a large number of network function calls and increase the statistical error.

/Memtest/timetest # Echo 0>/proc/gcov/vmlinux &./timetest & CP-r/proc/gcov/tmp

Game Over count1 is 0xc9413e40, count2 is 0x0, count3 is 0x3c8b1e45, count4 is 0x0

/Memtest/timetest # ls/tmp


4. The current statistical data is stored under/TP/gcov. We need to copy the data to the VM on the host computer for analysis, because our lcov can only run in the VM.

/Memtest/timetest # cp-R/tmp/gcov /./

/Memtest/timetest #

5. Now we need to go to the virtual machine and run lcov to generate the final HTML page.

[Root @ localhost timetest] # cd gcov/

[Root @ localhost gcov] # lcov -- directory. -- capture -- output-file

[Root @ localhost gcov] # genhtml-O results

In this way, the kernel code coverage rate that is basically only run in the timetest period is generated.


2. gcov instance

1. Instructions for use

Pay attention to the following when using gcov for code coverage rate statistics:

1) do not add optimization options during compilation, because the code changes after the compilation options are added, so you cannot find the hotspot code you have written.

2) if complex macros are used in the Code, such as loops or other control structures after the macro is expanded, gcov only reports the row that appears in macro calls, if a complex macro looks like a function, it can be replaced by an inline function.

3) when writing code, you should note that each line should have only one statement.

4) gcov and lcov can be used to test Linux kernel coverage. For details, refer


Here we only discuss application coverage.

2. Use instances

There are three steps:

1) compilation phase: add the compilation option gcc-O hello-fprofile-arcs-ftest-coverage hello to generate the program flowchart and other information.

2) data collection and extraction stage:./Hello., generate specific running information

The data generated in this phase is automatically saved. The directory where the o file is located, that is, if/usr/build/Hello. O exists,/usr/build/Hello. gcda is generated, but if the front-edge directory does not exist, an error will occur.

3) generate a Data Report: gcov hello. c

The following describes how gcov applies NMAP to C ++ projects.

NMAP is a powerful port scanning program, and NMAP is also a tool on which Nessus is a famous security tool. There are more than 30 thousand lines of code.


  1. Cxxflags = "-fprofile-arcs-ftest-coverage" libs =-lgcov./configure è makefile
  2. Each source file generates a. gcno file.
  3. ./NMAP. Each source file generates a. gcda file.
  4. Each source file generates a. gcov file.

Step 1:Detection code

Compile and run the code according to the README document of the Nmap project to ensure code correctness.

Step 2:Added the gcov compilation options:-fprofile-arcs-ftest-coverage, and the link options-lgcov or-coverage.

You can directly add the compilation option for manually written makefile code.

For some automatically generated makefile files, run. /configure-H: Check the method for adding the makefile compilation connection option, add the compilation option:-fprofile-arcs-ftest-coverage, and set it through some environment variables, for example, this program is set to cxxflags = "-fprofile-arcs-ftest-coverage" libs =-lgcov. /configure


Step 3:Compile the connection

After modifying the MAKEFILE file, execute make to generate the. gcno file for each source file.

Step 4:Test

Run a single test case or test case group to generate the. gcda file. Run./NMAP as follows:

Step 5:Run gcov to generate coverage test information

Analyze the test coverage of a source file and its associated files as follows. By default, sourefilename is generated. c. gcov file. You can add the-L and-P options to generate a specific directory and long file name. The coverage rate of Main. CC and output. CC is calculated as follows. Here, we can view the row coverage rate. You can also add-B and-F to provide the branch coverage rate. For details, see man gcov.

The following figure shows the row coverage rate:

Main. CC

Output. CC

Step 6:View the. gcov File

Shows the execution of the source code, as shown in the following figure. CC execution. The following are output. cc. the header and part of the gcov file. The red box indicates the number of executions of the Code in the row.-indicates the code line that has not been inserted.

Is the branch coverage information:

The overall information is provided before the function starts:

Some branches:

Step 7:Use lcov to view overall code coverage

Clear coverage data before using lcov, lcov-z-D ./

Run lcov-B in the source code path. /-D. /-c-o,-B indicates to use the current directory as the relative path,-D indicates to overwrite the data file in the statistics directory instead of the kernel data, and save the generated information to the file shown in-o. For details about the parameters, see lcov-H.

Finally, you can merge multiple coverage information with the-A option.

Lcov-add-tracefile. Out/ .info

Step 8: Use genhtml to view the overall view and webpage View

As shown in the following figure, we can see that there are nearly 20 thousand rows in the number of successfully overwritten instrument lines, but there are only more than three thousand rows in the number of executed lines. We can repeatedly add test cases to improve the coverage test rate. The overall coverage and coverage of each source file are provided respectively.

3. Common Errors

1. gcda file directory error. The directory to be created cannot be found. This is mainly used for cross-platform scenarios.

This is because the generation of the. gcda file is saved to the directory where. O is located by default, but if the directory where. o does not exist, an error will occur.

Setting environment variables can solve this problem.

Set gcov_prefix =/target/run' with gcov_prefix_strip = 1

The generated. gcda file is saved to/target/run/build/Foo. gcda.

2. The gcov message "merge mismatch for summaries"

You can set. gcda deletes all or compiles the entire file, instead of a single changed file. This is caused by the mismatch between gcda and gcno, because there is a timestamp between the two to record whether it is the same.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.