1 @c Copyright (C) 1996-2023 Free Software Foundation, Inc.
2 @c This is part of the GCC manual.
3 @c For copying conditions, see the file gcc.texi.
7 Copyright @copyright{} 1996-2023 Free Software Foundation, Inc.
9 Permission is granted to copy, distribute and/or modify this document
10 under the terms of the GNU Free Documentation License, Version 1.3 or
11 any later version published by the Free Software Foundation; with the
12 Invariant Sections being ``GNU General Public License'' and ``Funding
13 Free Software'', the Front-Cover texts being (a) (see below), and with
14 the Back-Cover Texts being (b) (see below). A copy of the license is
15 included in the gfdl(7) man page.
17 (a) The FSF's Front-Cover Text is:
21 (b) The FSF's Back-Cover Text is:
23 You have freedom to copy and modify this GNU Manual, like GNU
24 software. Copies published by the Free Software Foundation raise
25 funds for GNU development.
27 @c Set file name and title for the man page.
29 @settitle coverage testing tool
33 @chapter @command{gcov}---a Test Coverage Program
35 @command{gcov} is a tool you can use in conjunction with GCC to
36 test code coverage in your programs.
39 * Gcov Intro:: Introduction to gcov.
40 * Invoking Gcov:: How to use gcov.
41 * Gcov and Optimization:: Using gcov with GCC optimization.
42 * Gcov Data Files:: The files used by gcov.
43 * Cross-profiling:: Data file relocation.
44 * Freestanding Environments:: How to use profiling and test
45 coverage in freestanding environments.
49 @section Introduction to @command{gcov}
50 @c man begin DESCRIPTION
52 @command{gcov} is a test coverage program. Use it in concert with GCC
53 to analyze your programs to help create more efficient, faster running
54 code and to discover untested parts of your program. You can use
55 @command{gcov} as a profiling tool to help discover where your
56 optimization efforts will best affect your code. You can also use
57 @command{gcov} along with the other profiling tool, @command{gprof}, to
58 assess which parts of your code use the greatest amount of computing
61 Profiling tools help you analyze your code's performance. Using a
62 profiler such as @command{gcov} or @command{gprof}, you can find out some
63 basic performance statistics, such as:
67 how often each line of code executes
70 what lines of code are actually executed
73 how much computing time each section of code uses
76 Once you know these things about how your code works when compiled, you
77 can look at each module to see which modules should be optimized.
78 @command{gcov} helps you determine where to work on optimization.
80 Software developers also use coverage testing in concert with
81 testsuites, to make sure software is actually good enough for a release.
82 Testsuites can verify that a program works as expected; a coverage
83 program tests to see how much of the program is exercised by the
84 testsuite. Developers can then determine what kinds of test cases need
85 to be added to the testsuites to create both better testing and a better
88 You should compile your code without optimization if you plan to use
89 @command{gcov} because the optimization, by combining some lines of code
90 into one function, may not give you as much information as you need to
91 look for `hot spots' where the code is using a great deal of computer
92 time. Likewise, because @command{gcov} accumulates statistics by line (at
93 the lowest resolution), it works best with a programming style that
94 places only one statement on each line. If you use complicated macros
95 that expand to loops or to other control structures, the statistics are
96 less helpful---they only report on the line where the macro call
97 appears. If your complex macros behave like functions, you can replace
98 them with inline functions to solve this problem.
100 @command{gcov} creates a logfile called @file{@var{sourcefile}.gcov} which
101 indicates how many times each line of a source file @file{@var{sourcefile}.c}
102 has executed. You can use these logfiles along with @command{gprof} to aid
103 in fine-tuning the performance of your programs. @command{gprof} gives
104 timing information you can use along with the information you get from
107 @command{gcov} works only on code compiled with GCC@. It is not
108 compatible with any other profiling or test coverage mechanism.
113 @section Invoking @command{gcov}
116 gcov @r{[}@var{options}@r{]} @var{files}
119 @command{gcov} accepts the following options:
122 @c man begin SYNOPSIS
123 gcov [@option{-v}|@option{--version}] [@option{-h}|@option{--help}]
124 [@option{-a}|@option{--all-blocks}]
125 [@option{-b}|@option{--branch-probabilities}]
126 [@option{-c}|@option{--branch-counts}]
127 [@option{-d}|@option{--display-progress}]
128 [@option{-f}|@option{--function-summaries}]
129 [@option{-j}|@option{--json-format}]
130 [@option{-H}|@option{--human-readable}]
131 [@option{-k}|@option{--use-colors}]
132 [@option{-l}|@option{--long-file-names}]
133 [@option{-m}|@option{--demangled-names}]
134 [@option{-n}|@option{--no-output}]
135 [@option{-o}|@option{--object-directory} @var{directory|file}]
136 [@option{-p}|@option{--preserve-paths}]
137 [@option{-q}|@option{--use-hotness-colors}]
138 [@option{-r}|@option{--relative-only}]
139 [@option{-s}|@option{--source-prefix} @var{directory}]
140 [@option{-t}|@option{--stdout}]
141 [@option{-u}|@option{--unconditional-branches}]
142 [@option{-x}|@option{--hash-filenames}]
146 gpl(7), gfdl(7), fsf-funding(7), gcc(1) and the Info entry for @file{gcc}.
155 Write individual execution counts for every basic block. Normally gcov
156 outputs execution counts only for the main blocks of a line. With this
157 option you can determine if blocks within a single line are not being
161 @itemx --branch-probabilities
162 Write branch frequencies to the output file, and write branch summary
163 info to the standard output. This option allows you to see how often
164 each branch in your program was taken. Unconditional branches will not
165 be shown, unless the @option{-u} option is given.
168 @itemx --branch-counts
169 Write branch frequencies as the number of branches taken, rather than
170 the percentage of branches taken.
173 @itemx --display-progress
174 Display the progress on the standard output.
177 @itemx --function-summaries
178 Output summaries for each function in addition to the file level summary.
182 Display help about using @command{gcov} (on the standard output), and
183 exit without doing any further processing.
187 Output gcov file in an easy-to-parse JSON intermediate format
188 which does not require source code for generation. The JSON
189 file is compressed with gzip compression algorithm
190 and the files have @file{.gcov.json.gz} extension.
192 Structure of the JSON is following:
196 "current_working_directory": "foo/bar",
197 "data_file": "a.out",
198 "format_version": "1",
199 "gcc_version": "11.1.1 20210510"
204 Fields of the root element have following semantics:
208 @var{current_working_directory}: working directory where
209 a compilation unit was compiled
212 @var{data_file}: name of the data file (GCDA)
215 @var{format_version}: semantic version of the format
218 @var{gcc_version}: version of the GCC compiler
221 Each @var{file} has the following form:
226 "functions": ["$function"],
231 Fields of the @var{file} element have following semantics:
235 @var{file_name}: name of the source file
238 Each @var{function} has the following form:
243 "blocks_executed": 2,
244 "demangled_name": "foo",
247 "execution_count": 1,
254 Fields of the @var{function} element have following semantics:
258 @var{blocks}: number of blocks that are in the function
261 @var{blocks_executed}: number of executed blocks of the function
264 @var{demangled_name}: demangled name of the function
267 @var{end_column}: column in the source file where the function ends
270 @var{end_line}: line in the source file where the function ends
273 @var{execution_count}: number of executions of the function
276 @var{name}: name of the function
279 @var{start_column}: column in the source file where the function begins
282 @var{start_line}: line in the source file where the function begins
285 Note that line numbers and column numbers number from 1. In the current
286 implementation, @var{start_line} and @var{start_column} do not include
287 any template parameters and the leading return type but that
288 this is likely to be fixed in the future.
290 Each @var{line} has the following form:
294 "branches": ["$branch"],
297 "unexecuted_block": false,
298 "function_name": "foo",
302 Branches are present only with @var{-b} option.
303 Fields of the @var{line} element have following semantics:
307 @var{count}: number of executions of the line
310 @var{line_number}: line number
313 @var{unexecuted_block}: flag whether the line contains an unexecuted block
314 (not all statements on the line are executed)
317 @var{function_name}: a name of a function this @var{line} belongs to
318 (for a line with an inlined statements can be not set)
321 Each @var{branch} has the following form:
331 Fields of the @var{branch} element have following semantics:
335 @var{count}: number of executions of the branch
338 @var{fallthrough}: true when the branch is a fall through branch
341 @var{throw}: true when the branch is an exceptional branch
345 @itemx --human-readable
346 Write counts in human readable format (like 24.6k).
351 Use colors for lines of code that have zero coverage. We use red color for
352 non-exceptional lines and cyan for exceptional. Same colors are used for
353 basic blocks with @option{-a} option.
356 @itemx --long-file-names
357 Create long file names for included source files. For example, if the
358 header file @file{x.h} contains code, and was included in the file
359 @file{a.c}, then running @command{gcov} on the file @file{a.c} will
360 produce an output file called @file{a.c##x.h.gcov} instead of
361 @file{x.h.gcov}. This can be useful if @file{x.h} is included in
362 multiple source files and you want to see the individual
363 contributions. If you use the @samp{-p} option, both the including
364 and included file names will be complete path names.
367 @itemx --demangled-names
368 Display demangled function names in output. The default is to show
369 mangled function names.
373 Do not create the @command{gcov} output file.
375 @item -o @var{directory|file}
376 @itemx --object-directory @var{directory}
377 @itemx --object-file @var{file}
378 Specify either the directory containing the gcov data files, or the
379 object path name. The @file{.gcno}, and
380 @file{.gcda} data files are searched for using this option. If a directory
381 is specified, the data files are in that directory and named after the
382 input file name, without its extension. If a file is specified here,
383 the data files are named after that file, without its extension.
386 @itemx --preserve-paths
387 Preserve complete path information in the names of generated
388 @file{.gcov} files. Without this option, just the filename component is
389 used. With this option, all directories are used, with @samp{/} characters
390 translated to @samp{#} characters, @file{.} directory components
391 removed and unremoveable @file{..}
392 components renamed to @samp{^}. This is useful if sourcefiles are in several
393 different directories.
396 @itemx --use-hotness-colors
398 Emit perf-like colored output for hot lines. Legend of the color scale
399 is printed at the very beginning of the output file.
402 @itemx --relative-only
403 Only output information about source files with a relative pathname
404 (after source prefix elision). Absolute paths are usually system
405 header files and coverage of any inline functions therein is normally
408 @item -s @var{directory}
409 @itemx --source-prefix @var{directory}
410 A prefix for source file names to remove when generating the output
411 coverage files. This option is useful when building in a separate
412 directory, and the pathname to the source directory is not wanted when
413 determining the output file names. Note that this prefix detection is
414 applied before determining whether the source file is absolute.
418 Output to standard output instead of output files.
421 @itemx --unconditional-branches
422 When branch probabilities are given, include those of unconditional branches.
423 Unconditional branches are normally not interesting.
427 Display the @command{gcov} version number (on the standard output),
428 and exit without doing any further processing.
432 Print verbose informations related to basic blocks and arcs.
435 @itemx --hash-filenames
436 When using @var{--preserve-paths},
437 gcov uses the full pathname of the source files to create
438 an output filename. This can lead to long filenames that can overflow
439 filesystem limits. This option creates names of the form
440 @file{@var{source-file}##@var{md5}.gcov},
441 where the @var{source-file} component is the final filename part and
442 the @var{md5} component is calculated from the full mangled name that
443 would have been used otherwise. The option is an alternative
444 to the @var{--preserve-paths} on systems which have a filesystem limit.
448 @command{gcov} should be run with the current directory the same as that
449 when you invoked the compiler. Otherwise it will not be able to locate
450 the source files. @command{gcov} produces files called
451 @file{@var{mangledname}.gcov} in the current directory. These contain
452 the coverage information of the source file they correspond to.
453 One @file{.gcov} file is produced for each source (or header) file
455 which was compiled to produce the data files. The @var{mangledname} part
456 of the output file name is usually simply the source file name, but can
457 be something more complicated if the @samp{-l} or @samp{-p} options are
458 given. Refer to those options for details.
460 If you invoke @command{gcov} with multiple input files, the
461 contributions from each input file are summed. Typically you would
462 invoke it with the same list of files as the final link of your executable.
464 The @file{.gcov} files contain the @samp{:} separated fields along with
465 program source code. The format is
468 @var{execution_count}:@var{line_number}:@var{source line text}
471 Additional block information may succeed each line, when requested by
472 command line option. The @var{execution_count} is @samp{-} for lines
473 containing no code. Unexecuted lines are marked @samp{#####} or
474 @samp{=====}, depending on whether they are reachable by
475 non-exceptional paths or only exceptional paths such as C++ exception
476 handlers, respectively. Given the @samp{-a} option, unexecuted blocks are
477 marked @samp{$$$$$} or @samp{%%%%%}, depending on whether a basic block
478 is reachable via non-exceptional or exceptional paths.
479 Executed basic blocks having a statement with zero @var{execution_count}
480 end with @samp{*} character and are colored with magenta color with
481 the @option{-k} option. This functionality is not supported in Ada.
483 Note that GCC can completely remove the bodies of functions that are
484 not needed -- for instance if they are inlined everywhere. Such functions
485 are marked with @samp{-}, which can be confusing.
486 Use the @option{-fkeep-inline-functions} and @option{-fkeep-static-functions}
487 options to retain these functions and
488 allow gcov to properly show their @var{execution_count}.
490 Some lines of information at the start have @var{line_number} of zero.
491 These preamble lines are of the form
494 -:0:@var{tag}:@var{value}
497 The ordering and number of these preamble lines will be augmented as
498 @command{gcov} development progresses --- do not rely on them remaining
499 unchanged. Use @var{tag} to locate a particular preamble line.
501 The additional block information is of the form
504 @var{tag} @var{information}
507 The @var{information} is human readable, but designed to be simple
508 enough for machine parsing too.
510 When printing percentages, 0% and 100% are only printed when the values
511 are @emph{exactly} 0% and 100% respectively. Other values which would
512 conventionally be rounded to 0% or 100% are instead printed as the
513 nearest non-boundary value.
515 When using @command{gcov}, you must first compile your program
516 with a special GCC option @samp{--coverage}.
517 This tells the compiler to generate additional information needed by
518 gcov (basically a flow graph of the program) and also includes
519 additional code in the object files for generating the extra profiling
520 information needed by gcov. These additional files are placed in the
521 directory where the object file is located.
523 Running the program will cause profile output to be generated. For each
524 source file compiled with @option{-fprofile-arcs}, an accompanying
525 @file{.gcda} file will be placed in the object file directory.
527 Running @command{gcov} with your program's source file names as arguments
528 will now produce a listing of the code along with frequency of execution
529 for each line. For example, if your program is called @file{tmp.cpp}, this
530 is what you see when you use the basic @command{gcov} facility:
533 $ g++ --coverage tmp.cpp -c
534 $ g++ --coverage tmp.o
538 Lines executed:92.86% of 14
539 Creating 'tmp.cpp.gcov'
542 The file @file{tmp.cpp.gcov} contains output from @command{gcov}.
547 -: 0:Working directory:/home/gcc/testcase
552 -: 1:#include <stdio.h>
554 -: 3:template<class T>
558 1*: 7: Foo(): b (1000) @{@}
561 #####: 7: Foo(): b (1000) @{@}
564 1: 7: Foo(): b (1000) @{@}
566 2*: 8: void inc () @{ b++; @}
569 #####: 8: void inc () @{ b++; @}
572 2: 8: void inc () @{ b++; @}
579 -: 14:template class Foo<int>;
580 -: 15:template class Foo<char>;
586 1: 21: Foo<int> counter;
588 1: 23: counter.inc();
589 1: 24: counter.inc();
592 11: 27: for (i = 0; i < 10; i++)
595 1*: 30: int v = total > 100 ? 1 : 2;
597 1: 32: if (total != 45)
598 #####: 33: printf ("Failure\n");
600 1: 35: printf ("Success\n");
605 Note that line 7 is shown in the report multiple times. First occurrence
606 presents total number of execution of the line and the next two belong
607 to instances of class Foo constructors. As you can also see, line 30 contains
608 some unexecuted basic blocks and thus execution count has asterisk symbol.
610 When you use the @option{-a} option, you will get individual block
611 counts, and the output looks like this:
615 -: 0:Working directory:/home/gcc/testcase
620 -: 1:#include <stdio.h>
622 -: 3:template<class T>
626 1*: 7: Foo(): b (1000) @{@}
629 #####: 7: Foo(): b (1000) @{@}
632 1: 7: Foo(): b (1000) @{@}
634 2*: 8: void inc () @{ b++; @}
637 #####: 8: void inc () @{ b++; @}
640 2: 8: void inc () @{ b++; @}
647 -: 14:template class Foo<int>;
648 -: 15:template class Foo<char>;
654 1: 21: Foo<int> counter;
657 1: 23: counter.inc();
659 1: 24: counter.inc();
663 11: 27: for (i = 0; i < 10; i++)
669 1*: 30: int v = total > 100 ? 1 : 2;
674 1: 32: if (total != 45)
676 #####: 33: printf ("Failure\n");
679 1: 35: printf ("Success\n");
686 In this mode, each basic block is only shown on one line -- the last
687 line of the block. A multi-line block will only contribute to the
688 execution count of that last line, and other lines will not be shown
689 to contain code, unless previous blocks end on those lines.
690 The total execution count of a line is shown and subsequent lines show
691 the execution counts for individual blocks that end on that line. After each
692 block, the branch and call counts of the block will be shown, if the
693 @option{-b} option is given.
695 Because of the way GCC instruments calls, a call count can be shown
696 after a line with no individual blocks.
697 As you can see, line 33 contains a basic block that was not executed.
700 When you use the @option{-b} option, your output looks like this:
704 -: 0:Working directory:/home/gcc/testcase
709 -: 1:#include <stdio.h>
711 -: 3:template<class T>
715 1*: 7: Foo(): b (1000) @{@}
718 function Foo<char>::Foo() called 0 returned 0% blocks executed 0%
719 #####: 7: Foo(): b (1000) @{@}
722 function Foo<int>::Foo() called 1 returned 100% blocks executed 100%
723 1: 7: Foo(): b (1000) @{@}
725 2*: 8: void inc () @{ b++; @}
728 function Foo<char>::inc() called 0 returned 0% blocks executed 0%
729 #####: 8: void inc () @{ b++; @}
732 function Foo<int>::inc() called 2 returned 100% blocks executed 100%
733 2: 8: void inc () @{ b++; @}
740 -: 14:template class Foo<int>;
741 -: 15:template class Foo<char>;
744 function main called 1 returned 100% blocks executed 81%
748 1: 21: Foo<int> counter;
750 branch 1 taken 100% (fallthrough)
751 branch 2 taken 0% (throw)
753 1: 23: counter.inc();
755 branch 1 taken 100% (fallthrough)
756 branch 2 taken 0% (throw)
757 1: 24: counter.inc();
759 branch 1 taken 100% (fallthrough)
760 branch 2 taken 0% (throw)
763 11: 27: for (i = 0; i < 10; i++)
764 branch 0 taken 91% (fallthrough)
768 1*: 30: int v = total > 100 ? 1 : 2;
769 branch 0 taken 0% (fallthrough)
772 1: 32: if (total != 45)
773 branch 0 taken 0% (fallthrough)
775 #####: 33: printf ("Failure\n");
776 call 0 never executed
777 branch 1 never executed
778 branch 2 never executed
780 1: 35: printf ("Success\n");
782 branch 1 taken 100% (fallthrough)
783 branch 2 taken 0% (throw)
788 For each function, a line is printed showing how many times the function
789 is called, how many times it returns and what percentage of the
790 function's blocks were executed.
792 For each basic block, a line is printed after the last line of the basic
793 block describing the branch or call that ends the basic block. There can
794 be multiple branches and calls listed for a single source line if there
795 are multiple basic blocks that end on that line. In this case, the
796 branches and calls are each given a number. There is no simple way to map
797 these branches and calls back to source constructs. In general, though,
798 the lowest numbered branch or call will correspond to the leftmost construct
801 For a branch, if it was executed at least once, then a percentage
802 indicating the number of times the branch was taken divided by the
803 number of times the branch was executed will be printed. Otherwise, the
804 message ``never executed'' is printed.
806 For a call, if it was executed at least once, then a percentage
807 indicating the number of times the call returned divided by the number
808 of times the call was executed will be printed. This will usually be
809 100%, but may be less for functions that call @code{exit} or @code{longjmp},
810 and thus may not return every time they are called.
812 The execution counts are cumulative. If the example program were
813 executed again without removing the @file{.gcda} file, the count for the
814 number of times each line in the source was executed would be added to
815 the results of the previous run(s). This is potentially useful in
816 several ways. For example, it could be used to accumulate data over a
817 number of program runs as part of a test verification suite, or to
818 provide more accurate long-term information over a large number of
821 The data in the @file{.gcda} files is saved immediately before the program
822 exits. For each source file compiled with @option{-fprofile-arcs}, the
823 profiling code first attempts to read in an existing @file{.gcda} file; if
824 the file doesn't match the executable (differing number of basic block
825 counts) it will ignore the contents of the file. It then adds in the
826 new execution counts and finally writes the data to the file.
828 @node Gcov and Optimization
829 @section Using @command{gcov} with GCC Optimization
831 If you plan to use @command{gcov} to help optimize your code, you must
832 first compile your program with a special GCC option
833 @samp{--coverage}. Aside from that, you can use any
834 other GCC options; but if you want to prove that every single line
835 in your program was executed, you should not compile with optimization
836 at the same time. On some machines the optimizer can eliminate some
837 simple code lines by combining them with other lines. For example, code
848 can be compiled into one instruction on some machines. In this case,
849 there is no way for @command{gcov} to calculate separate execution counts
850 for each line because there isn't separate code for each line. Hence
851 the @command{gcov} output looks like this if you compiled the program with
861 The output shows that this block of code, combined by optimization,
862 executed 100 times. In one sense this result is correct, because there
863 was only one instruction representing all four of these lines. However,
864 the output does not indicate how many times the result was 0 and how
865 many times the result was 1.
867 Inlineable functions can create unexpected line counts. Line counts are
868 shown for the source code of the inlineable function, but what is shown
869 depends on where the function is inlined, or if it is not inlined at all.
871 If the function is not inlined, the compiler must emit an out of line
872 copy of the function, in any object file that needs it. If
873 @file{fileA.o} and @file{fileB.o} both contain out of line bodies of a
874 particular inlineable function, they will also both contain coverage
875 counts for that function. When @file{fileA.o} and @file{fileB.o} are
876 linked together, the linker will, on many systems, select one of those
877 out of line bodies for all calls to that function, and remove or ignore
878 the other. Unfortunately, it will not remove the coverage counters for
879 the unused function body. Hence when instrumented, all but one use of
880 that function will show zero counts.
882 If the function is inlined in several places, the block structure in
883 each location might not be the same. For instance, a condition might
884 now be calculable at compile time in some instances. Because the
885 coverage of all the uses of the inline function will be shown for the
886 same source lines, the line counts themselves might seem inconsistent.
888 Long-running applications can use the @code{__gcov_reset} and @code{__gcov_dump}
889 facilities to restrict profile collection to the program region of
890 interest. Calling @code{__gcov_reset(void)} will clear all run-time profile
891 counters to zero, and calling @code{__gcov_dump(void)} will cause the profile
892 information collected at that point to be dumped to @file{.gcda} output files.
893 Instrumented applications use a static destructor with priority 99
894 to invoke the @code{__gcov_dump} function. Thus @code{__gcov_dump}
895 is executed after all user defined static destructors,
896 as well as handlers registered with @code{atexit}.
898 If an executable loads a dynamic shared object via dlopen functionality,
899 @option{-Wl,--dynamic-list-data} is needed to dump all profile data.
901 Profiling run-time library reports various errors related to profile
902 manipulation and profile saving. Errors are printed into standard error output
903 or @samp{GCOV_ERROR_FILE} file, if environment variable is used.
904 In order to terminate immediately after an errors occurs
905 set @samp{GCOV_EXIT_AT_ERROR} environment variable.
906 That can help users to find profile clashing which leads
907 to a misleading profile.
911 @node Gcov Data Files
912 @section Brief Description of @command{gcov} Data Files
914 @command{gcov} uses two files for profiling. The names of these files
915 are derived from the original @emph{object} file by substituting the
916 file suffix with either @file{.gcno}, or @file{.gcda}. The files
917 contain coverage and profile data stored in a platform-independent format.
918 The @file{.gcno} files are placed in the same directory as the object
919 file. By default, the @file{.gcda} files are also stored in the same
920 directory as the object file, but the GCC @option{-fprofile-dir} option
921 may be used to store the @file{.gcda} files in a separate directory.
923 The @file{.gcno} notes file is generated when the source file is compiled
924 with the GCC @option{-ftest-coverage} option. It contains information to
925 reconstruct the basic block graphs and assign source line numbers to
928 The @file{.gcda} count data file is generated when a program containing
929 object files built with the GCC @option{-fprofile-arcs} option is executed.
930 A separate @file{.gcda} file is created for each object file compiled with
931 this option. It contains arc transition counts, value profile counts, and
932 some summary information.
934 It is not recommended to access the coverage files directly.
935 Consumers should use the intermediate format that is provided
936 by @command{gcov} tool via @option{--json-format} option.
938 @node Cross-profiling
939 @section Data File Relocation to Support Cross-Profiling
941 Running the program will cause profile output to be generated. For each
942 source file compiled with @option{-fprofile-arcs}, an accompanying @file{.gcda}
943 file will be placed in the object file directory. That implicitly requires
944 running the program on the same system as it was built or having the same
945 absolute directory structure on the target system. The program will try
946 to create the needed directory structure, if it is not already present.
948 To support cross-profiling, a program compiled with @option{-fprofile-arcs}
949 can relocate the data files based on two environment variables:
953 GCOV_PREFIX contains the prefix to add to the absolute paths
954 in the object file. Prefix can be absolute, or relative. The
955 default is no prefix.
958 GCOV_PREFIX_STRIP indicates the how many initial directory names to strip off
959 the hardwired absolute paths. Default value is 0.
961 @emph{Note:} If GCOV_PREFIX_STRIP is set without GCOV_PREFIX is undefined,
962 then a relative path is made out of the hardwired absolute paths.
965 For example, if the object file @file{/user/build/foo.o} was built with
966 @option{-fprofile-arcs}, the final executable will try to create the data file
967 @file{/user/build/foo.gcda} when running on the target system. This will
968 fail if the corresponding directory does not exist and it is unable to create
969 it. This can be overcome by, for example, setting the environment as
970 @samp{GCOV_PREFIX=/target/run} and @samp{GCOV_PREFIX_STRIP=1}. Such a
971 setting will name the data file @file{/target/run/build/foo.gcda}.
973 You must move the data files to the expected directory tree in order to
974 use them for profile directed optimizations (@option{-fprofile-use}), or to
975 use the @command{gcov} tool.
977 @node Freestanding Environments
978 @section Profiling and Test Coverage in Freestanding Environments
980 In case your application runs in a hosted environment such as GNU/Linux, then
981 this section is likely not relevant to you. This section is intended for
982 application developers targeting freestanding environments (for example
983 embedded systems) with limited resources. In particular, systems or test cases
984 which do not support constructors/destructors or the C library file I/O. In
985 this section, the @dfn{target system} runs your application instrumented for
986 profiling or test coverage. You develop and analyze your application on the
987 @dfn{host system}. We now provide an overview how profiling and test coverage
988 can be obtained in this scenario followed by a tutorial which can be exercised
989 on the host system. Finally, some system initialization caveats are listed.
993 For an application instrumented for profiling or test coverage, the compiler
994 generates some global data structures which are updated by instrumentation code
995 while the application runs. These data structures are called the @dfn{gcov
996 information}. Normally, when the application exits, the gcov information is
997 stored to @file{.gcda} files. There is one file per translation unit
998 instrumented for profiling or test coverage. The function
999 @code{__gcov_exit()}, which stores the gcov information to a file, is called by
1000 a global destructor function for each translation unit instrumented for
1001 profiling or test coverage. It runs at process exit. In a global constructor
1002 function, the @code{__gcov_init()} function is called to register the gcov
1003 information of a translation unit in a global list. In some situations, this
1004 procedure does not work. Firstly, if you want to profile the global
1005 constructor or exit processing of an operating system, the compiler generated
1006 functions may conflict with the test objectives. Secondly, you may want to
1007 test early parts of the system initialization or abnormal program behaviour
1008 which do not allow a global constructor or exit processing. Thirdly, you need
1009 a filesystem to store the files.
1011 The @option{-fprofile-info-section} GCC option enables you to use profiling and
1012 test coverage in freestanding environments. This option disables the use of
1013 global constructors and destructors for the gcov information. Instead, a
1014 pointer to the gcov information is stored in a special linker input section for
1015 each translation unit which is compiled with this option. By default, the
1016 section name is @code{.gcov_info}. The gcov information is statically
1017 initialized. The pointers to the gcov information from all translation units
1018 of an executable can be collected by the linker in a contiguous memory block.
1019 For the GNU linker, the below linker script output section definition can be
1020 used to achieve this:
1025 PROVIDE (__gcov_info_start = .);
1026 KEEP (*(.gcov_info))
1027 PROVIDE (__gcov_info_end = .);
1031 The linker will provide two global symbols, @code{__gcov_info_start} and
1032 @code{__gcov_info_end}, which define the start and end of the array of pointers
1033 to gcov information blocks, respectively. The @code{KEEP ()} directive is
1034 required to prevent a garbage collection of the pointers. They are not
1035 directly referenced by anything in the executable. The section may be placed
1036 in a read-only memory area.
1038 In order to transfer the profiling and test coverage data from the target to
1039 the host system, the application has to provide a function to produce a
1040 reliable in order byte stream from the target to the host. The byte stream may
1041 be compressed and encoded using error detection and correction codes to meet
1042 application-specific requirements. The GCC provided @file{libgcov} target
1043 library provides two functions, @code{__gcov_info_to_gcda()} and
1044 @code{__gcov_filename_to_gcfn()}, to generate a byte stream from a gcov
1045 information bock. The functions are declared in @code{#include <gcov.h>}. The
1046 byte stream can be deserialized by the @command{merge-stream} subcommand of the
1047 @command{gcov-tool} to create or update @file{.gcda} files in the host
1048 filesystem for the instrumented application.
1050 @subsection Tutorial
1052 This tutorial should be exercised on the host system. We will build a program
1053 instrumented for test coverage. The program runs an application and dumps the
1054 gcov information to @file{stderr} encoded as a printable character stream. The
1055 application simply decodes such character streams from @file{stdin} and writes
1056 the decoded character stream to @file{stdout} (warning: this is binary data).
1057 The decoded character stream is consumed by the @command{merge-stream}
1058 subcommand of the @command{gcov-tool} to create or update the @file{.gcda}
1061 To get started, create an empty directory. Change into the new directory.
1062 Then you will create the following three files in this directory
1066 @file{app.h} - a header file included by @file{app.c} and @file{main.c},
1069 @file{app.c} - a source file which contains an example application, and
1072 @file{main.c} - a source file which contains the program main function and code
1073 to dump the gcov information.
1076 Firstly, create the header file @file{app.h} with the following content:
1079 static const unsigned char a = 'a';
1081 static inline unsigned char *
1082 encode (unsigned char c, unsigned char buf[2])
1084 buf[0] = c % 16 + a;
1085 buf[1] = (c / 16) % 16 + a;
1089 extern void application (void);
1092 Secondly, create the source file @file{app.c} with the following content:
1099 /* The application reads a character stream encoded by encode() from stdin,
1100 decodes it, and writes the decoded characters to stdout. Characters other
1101 than the 16 characters 'a' to 'p' are ignored. */
1103 static int can_decode (unsigned char c)
1105 return (unsigned char)(c - a) < 16;
1115 while ((i = fgetc (stdin)) != EOF)
1117 unsigned char x = (unsigned char)i;
1124 fputc (c + 16 * (x - a), stdout);
1133 Thirdly, create the source file @file{main.c} with the following content:
1142 /* The start and end symbols are provided by the linker script. We use the
1143 array notation to avoid issues with a potential small-data area. */
1145 extern const struct gcov_info *const __gcov_info_start[];
1146 extern const struct gcov_info *const __gcov_info_end[];
1148 /* This function shall produce a reliable in order byte stream to transfer the
1149 gcov information from the target to the host system. */
1152 dump (const void *d, unsigned n, void *arg)
1155 const unsigned char *c = d;
1156 unsigned char buf[2];
1158 for (unsigned i = 0; i < n; ++i)
1159 fwrite (encode (c[i], buf), sizeof (buf), 1, stderr);
1162 /* The filename is serialized to a gcfn data stream by the
1163 __gcov_filename_to_gcfn() function. The gcfn data is used by the
1164 "merge-stream" subcommand of the "gcov-tool" to figure out the filename
1165 associated with the gcov information. */
1168 filename (const char *f, void *arg)
1170 __gcov_filename_to_gcfn (f, dump, arg);
1173 /* The __gcov_info_to_gcda() function may have to allocate memory under
1174 certain conditions. Simply try it out if it is needed for your application
1178 allocate (unsigned length, void *arg)
1181 return malloc (length);
1184 /* Dump the gcov information of all translation units. */
1187 dump_gcov_info (void)
1189 const struct gcov_info *const *info = __gcov_info_start;
1190 const struct gcov_info *const *end = __gcov_info_end;
1192 /* Obfuscate variable to prevent compiler optimizations. */
1193 __asm__ ("" : "+r" (info));
1198 __gcov_info_to_gcda (*info, filename, dump, allocate, arg);
1199 fputc ('\n', stderr);
1204 /* The main() function just runs the application and then dumps the gcov
1205 information to stderr. */
1216 If we compile @file{app.c} with test coverage and no extra profiling options,
1217 then a global constructor (@code{_sub_I_00100_0} here, it may have a different
1218 name in your environment) and destructor (@code{_sub_D_00100_1}) is used to
1219 register and dump the gcov information, respectively. We also see undefined
1220 references to @code{__gcov_init} and @code{__gcov_exit}:
1223 $ gcc --coverage -c app.c
1225 0000000000000000 r a
1226 0000000000000030 T application
1227 0000000000000000 t can_decode
1230 0000000000000000 b __gcov0.application
1231 0000000000000038 b __gcov0.can_decode
1232 0000000000000000 d __gcov_.application
1233 00000000000000c0 d __gcov_.can_decode
1239 0000000000000161 t _sub_D_00100_1
1240 0000000000000151 t _sub_I_00100_0
1243 Compile @file{app.c} and @file{main.c} with test coverage and
1244 @option{-fprofile-info-section}. Now, a read-only pointer size object is
1245 present in the @code{.gcov_info} section and there are no undefined references
1246 to @code{__gcov_init} and @code{__gcov_exit}:
1249 $ gcc --coverage -fprofile-info-section -c main.c
1250 $ gcc --coverage -fprofile-info-section -c app.c
1253 app.o: file format elf64-x86-64
1256 Idx Name Size VMA LMA File off Algn
1257 0 .text 00000151 0000000000000000 0000000000000000 00000040 2**0
1258 CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
1259 1 .data 00000100 0000000000000000 0000000000000000 000001a0 2**5
1260 CONTENTS, ALLOC, LOAD, RELOC, DATA
1261 2 .bss 00000040 0000000000000000 0000000000000000 000002a0 2**5
1263 3 .rodata 0000003c 0000000000000000 0000000000000000 000002a0 2**3
1264 CONTENTS, ALLOC, LOAD, READONLY, DATA
1265 4 .gcov_info 00000008 0000000000000000 0000000000000000 000002e0 2**3
1266 CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
1267 5 .comment 0000004e 0000000000000000 0000000000000000 000002e8 2**0
1269 6 .note.GNU-stack 00000000 0000000000000000 0000000000000000 00000336 2**0
1271 7 .eh_frame 00000058 0000000000000000 0000000000000000 00000338 2**3
1272 CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
1275 We have to customize the program link procedure so that all the
1276 @code{.gcov_info} linker input sections are placed in a contiguous memory block
1277 with a begin and end symbol. Firstly, get the default linker script using the
1278 following commands (we assume a GNU linker):
1281 $ ld --verbose | sed '1,/^===/d' | sed '/^===/d' > linkcmds
1284 Secondly, open the file @file{linkcmds} with a text editor and place the linker
1285 output section definition from the overview after the @code{.rodata} section
1286 definition. Link the program executable using the customized linker script:
1289 $ gcc --coverage main.o app.o -T linkcmds -Wl,-Map,app.map
1292 In the linker map file @file{app.map}, we see that the linker placed the
1293 read-only pointer size objects of our objects files @file{main.o} and
1294 @file{app.o} into a contiguous memory block and provided the symbols
1295 @code{__gcov_info_start} and @code{__gcov_info_end}:
1298 $ grep -C 1 "\.gcov_info" app.map
1300 .gcov_info 0x0000000000403ac0 0x10
1301 0x0000000000403ac0 PROVIDE (__gcov_info_start = .)
1303 .gcov_info 0x0000000000403ac0 0x8 main.o
1304 .gcov_info 0x0000000000403ac8 0x8 app.o
1305 0x0000000000403ad0 PROVIDE (__gcov_info_end = .)
1308 Make sure no @file{.gcda} files are present. Run the program with nothing to
1309 decode and dump @file{stderr} to the file @file{gcda-0.txt} (first run). Run
1310 the program to decode @file{gcda-0.txt} and send it to the @command{gcov-tool}
1311 using the @command{merge-stream} subcommand to create the @file{.gcda} files
1312 (second run). Run @command{gcov} to produce a report for @file{app.c}. We see
1313 that the first run with nothing to decode results in a partially covered
1317 $ rm -f app.gcda main.gcda
1318 $ echo "" | ./a.out 2>gcda-0.txt
1319 $ ./a.out <gcda-0.txt 2>gcda-1.txt | gcov-tool merge-stream
1322 Lines executed:69.23% of 13
1323 Branches executed:66.67% of 6
1324 Taken at least once:50.00% of 6
1325 Calls executed:66.67% of 3
1326 Creating 'app.c.gcov'
1328 Lines executed:69.23% of 13
1331 Run the program to decode @file{gcda-1.txt} and send it to the
1332 @command{gcov-tool} using the @command{merge-stream} subcommand to update the
1333 @file{.gcda} files. Run @command{gcov} to produce a report for @file{app.c}.
1334 Since the second run decoded the gcov information of the first run, we have now
1335 a fully covered application:
1338 $ ./a.out <gcda-1.txt 2>gcda-2.txt | gcov-tool merge-stream
1341 Lines executed:100.00% of 13
1342 Branches executed:100.00% of 6
1343 Taken at least once:100.00% of 6
1344 Calls executed:100.00% of 3
1345 Creating 'app.c.gcov'
1347 Lines executed:100.00% of 13
1350 @subsection System Initialization Caveats
1352 The gcov information of a translation unit consists of several global data
1353 structures. For example, the instrumented code may update program flow graph
1354 edge counters in a zero-initialized data structure. It is safe to run
1355 instrumented code before the zero-initialized data is cleared to zero. The
1356 coverage information obtained before the zero-initialized data is cleared to
1357 zero is unusable. Dumping the gcov information using
1358 @code{__gcov_info_to_gcda()} before the zero-initialized data is cleared to
1359 zero or the initialized data is loaded, is undefined behaviour. Clearing the
1360 zero-initialized data to zero through a function instrumented for profiling or
1361 test coverage is undefined behaviour, since it may produce inconsistent program
1362 flow graph edge counters for example.