1 /* Gcov.c: prepend line execution counts and branch probabilities to a
3 Copyright (C) 1990-2017 Free Software Foundation, Inc.
4 Contributed by James E. Wilson of Cygnus Support.
5 Mangled by Bob Manson of Cygnus Support.
6 Mangled further by Nathan Sidwell <nathan@codesourcery.com>
8 Gcov is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 3, or (at your option)
13 Gcov is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with Gcov; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 /* ??? Print a list of the ten blocks with the highest execution counts,
23 and list the line numbers corresponding to those blocks. Also, perhaps
24 list the line numbers with the highest execution counts, only printing
25 the first if there are several which are all listed in the same block. */
27 /* ??? Should have an option to print the number of basic blocks, and the
28 percent of them that are covered. */
30 /* Need an option to show individual block counts, and show
31 probabilities of fall through arcs. */
34 #define INCLUDE_ALGORITHM
35 #define INCLUDE_VECTOR
36 #define INCLUDE_STRING
38 #include "coretypes.h"
41 #include "diagnostic.h"
44 #include "color-macros.h"
56 /* The gcno file is generated by -ftest-coverage option. The gcda file is
57 generated by a program compiled with -fprofile-arcs. Their formats
58 are documented in gcov-io.h. */
60 /* The functions in this file for creating and solution program flow graphs
61 are very similar to functions in the gcc source file profile.c. In
62 some places we make use of the knowledge of how profile.c works to
63 select particular algorithms here. */
65 /* The code validates that the profile information read in corresponds
66 to the code currently being compiled. Rather than checking for
67 identical files, the code below compares a checksum on the CFG
68 (based on the order of basic blocks and the arcs in the CFG). If
69 the CFG checksum in the gcda file match the CFG checksum in the
70 gcno file, the profile data will be used. */
72 /* This is the size of the buffer used to read in source file lines. */
78 /* Describes an arc between two basic blocks. */
80 typedef struct arc_info
82 /* source and destination blocks. */
83 struct block_info
*src
;
84 struct block_info
*dst
;
86 /* transition counts. */
88 /* used in cycle search, so that we do not clobber original counts. */
91 unsigned int count_valid
: 1;
92 unsigned int on_tree
: 1;
93 unsigned int fake
: 1;
94 unsigned int fall_through
: 1;
96 /* Arc to a catch handler. */
97 unsigned int is_throw
: 1;
99 /* Arc is for a function that abnormally returns. */
100 unsigned int is_call_non_return
: 1;
102 /* Arc is for catch/setjmp. */
103 unsigned int is_nonlocal_return
: 1;
105 /* Is an unconditional branch. */
106 unsigned int is_unconditional
: 1;
108 /* Loop making arc. */
109 unsigned int cycle
: 1;
111 /* Links to next arc on src and dst lists. */
112 struct arc_info
*succ_next
;
113 struct arc_info
*pred_next
;
116 /* Describes which locations (lines and files) are associated with
119 struct block_location_info
121 block_location_info (unsigned _source_file_idx
):
122 source_file_idx (_source_file_idx
)
125 unsigned source_file_idx
;
126 vector
<unsigned> lines
;
129 /* Describes a basic block. Contains lists of arcs to successor and
130 predecessor blocks. */
132 typedef struct block_info
137 /* Chain of exit and entry arcs. */
141 /* Number of unprocessed exit and entry arcs. */
147 /* Block execution count. */
149 unsigned count_valid
: 1;
150 unsigned valid_chain
: 1;
151 unsigned invalid_chain
: 1;
152 unsigned exceptional
: 1;
154 /* Block is a call instrumenting site. */
155 unsigned is_call_site
: 1; /* Does the call. */
156 unsigned is_call_return
: 1; /* Is the return. */
158 /* Block is a landing pad for longjmp or throw. */
159 unsigned is_nonlocal_return
: 1;
161 vector
<block_location_info
> locations
;
165 /* Single line graph cycle workspace. Used for all-blocks
169 } cycle
; /* Used in all-blocks mode, after blocks are linked onto
172 /* Temporary chain for solving graph, and for chaining blocks on one
174 struct block_info
*chain
;
178 block_info::block_info (): succ (NULL
), pred (NULL
), num_succ (0), num_pred (0),
179 id (0), count (0), count_valid (0), valid_chain (0), invalid_chain (0),
180 exceptional (0), is_call_site (0), is_call_return (0), is_nonlocal_return (0),
181 locations (), chain (NULL
)
186 /* Describes a single function. Contains an array of basic blocks. */
188 typedef struct function_info
193 /* Name of function. */
195 char *demangled_name
;
197 unsigned lineno_checksum
;
198 unsigned cfg_checksum
;
200 /* The graph contains at least one fake incoming edge. */
201 unsigned has_catch
: 1;
203 /* Array of basic blocks. Like in GCC, the entry block is
204 at blocks[0] and the exit block is at blocks[1]. */
205 #define ENTRY_BLOCK (0)
206 #define EXIT_BLOCK (1)
207 vector
<block_t
> blocks
;
208 unsigned blocks_executed
;
210 /* Raw arc coverage counts. */
214 /* First line number & file. */
218 /* Next function in same source file. */
219 struct function_info
*next_file_fn
;
222 struct function_info
*next
;
225 /* Describes coverage of a file or function. */
227 typedef struct coverage_info
233 int branches_executed
;
242 /* Describes a single line of source. Contains a chain of basic blocks
247 /* Default constructor. */
250 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
251 bool has_block (block_t
*needle
);
253 /* Execution count. */
256 /* Branches from blocks that end on this line. */
257 vector
<arc_t
*> branches
;
259 /* blocks which start on this line. Used in all-blocks mode. */
260 vector
<block_t
*> blocks
;
263 unsigned unexceptional
: 1;
264 unsigned has_unexecuted_block
: 1;
267 line_info::line_info (): count (0), branches (), blocks (), exists (false),
268 unexceptional (0), has_unexecuted_block (0)
273 line_info::has_block (block_t
*needle
)
275 return std::find (blocks
.begin (), blocks
.end (), needle
) != blocks
.end ();
278 /* Describes a file mentioned in the block graph. Contains an array
283 /* Default constructor. */
286 /* Canonical name of source file. */
290 /* Vector of line information. */
291 vector
<line_info
> lines
;
295 /* Functions in this source file. These are in ascending line
297 function_t
*functions
;
300 source_info::source_info (): name (NULL
), file_time (), lines (),
301 coverage (), functions (NULL
)
312 name_map (char *_name
, unsigned _src
): name (_name
), src (_src
)
316 bool operator== (const name_map
&rhs
) const
318 #if HAVE_DOS_BASED_FILE_SYSTEM
319 return strcasecmp (this->name
, rhs
.name
) == 0;
321 return strcmp (this->name
, rhs
.name
) == 0;
325 bool operator< (const name_map
&rhs
) const
327 #if HAVE_DOS_BASED_FILE_SYSTEM
328 return strcasecmp (this->name
, rhs
.name
) < 0;
330 return strcmp (this->name
, rhs
.name
) < 0;
334 const char *name
; /* Source file name */
335 unsigned src
; /* Source file */
338 /* Holds a list of function basic block graphs. */
340 static function_t
*functions
;
341 static function_t
**fn_end
= &functions
;
343 /* Vector of source files. */
344 static vector
<source_info
> sources
;
346 /* Mapping of file names to sources */
347 static vector
<name_map
> names
;
349 /* This holds data summary information. */
351 static unsigned object_runs
;
352 static unsigned program_count
;
354 static unsigned total_lines
;
355 static unsigned total_executed
;
357 /* Modification time of graph file. */
359 static time_t bbg_file_time
;
361 /* Name of the notes (gcno) output file. The "bbg" prefix is for
362 historical reasons, when the notes file contained only the
363 basic block graph notes. */
365 static char *bbg_file_name
;
367 /* Stamp of the bbg file */
368 static unsigned bbg_stamp
;
370 /* Name and file pointer of the input file for the count data (gcda). */
372 static char *da_file_name
;
374 /* Data file is missing. */
376 static int no_data_file
;
378 /* If there is several input files, compute and display results after
379 reading all data files. This way if two or more gcda file refer to
380 the same source file (eg inline subprograms in a .h file), the
383 static int multiple_files
= 0;
385 /* Output branch probabilities. */
387 static int flag_branches
= 0;
389 /* Show unconditional branches too. */
390 static int flag_unconditional
= 0;
392 /* Output a gcov file if this is true. This is on by default, and can
393 be turned off by the -n option. */
395 static int flag_gcov_file
= 1;
397 /* Output progress indication if this is true. This is off by default
398 and can be turned on by the -d option. */
400 static int flag_display_progress
= 0;
402 /* Output *.gcov file in intermediate format used by 'lcov'. */
404 static int flag_intermediate_format
= 0;
406 /* Output demangled function names. */
408 static int flag_demangled_names
= 0;
410 /* For included files, make the gcov output file name include the name
411 of the input source file. For example, if x.h is included in a.c,
412 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
414 static int flag_long_names
= 0;
416 /* For situations when a long name can potentially hit filesystem path limit,
417 let's calculate md5sum of the path and append it to a file name. */
419 static int flag_hash_filenames
= 0;
421 /* Print verbose informations. */
423 static int flag_verbose
= 0;
425 /* Print colored output. */
427 static int flag_use_colors
= 0;
429 /* Output count information for every basic block, not merely those
430 that contain line number information. */
432 static int flag_all_blocks
= 0;
434 /* Output human readable numbers. */
436 static int flag_human_readable_numbers
= 0;
438 /* Output summary info for each function. */
440 static int flag_function_summary
= 0;
442 /* Object directory file prefix. This is the directory/file where the
443 graph and data files are looked for, if nonzero. */
445 static char *object_directory
= 0;
447 /* Source directory prefix. This is removed from source pathnames
448 that match, when generating the output file name. */
450 static char *source_prefix
= 0;
451 static size_t source_length
= 0;
453 /* Only show data for sources with relative pathnames. Absolute ones
454 usually indicate a system header file, which although it may
455 contain inline functions, is usually uninteresting. */
456 static int flag_relative_only
= 0;
458 /* Preserve all pathname components. Needed when object files and
459 source files are in subdirectories. '/' is mangled as '#', '.' is
460 elided and '..' mangled to '^'. */
462 static int flag_preserve_paths
= 0;
464 /* Output the number of times a branch was taken as opposed to the percentage
465 of times it was taken. */
467 static int flag_counts
= 0;
469 /* Forward declarations. */
470 static int process_args (int, char **);
471 static void print_usage (int) ATTRIBUTE_NORETURN
;
472 static void print_version (void) ATTRIBUTE_NORETURN
;
473 static void process_file (const char *);
474 static void generate_results (const char *);
475 static void create_file_names (const char *);
476 static char *canonicalize_name (const char *);
477 static unsigned find_source (const char *);
478 static function_t
*read_graph_file (void);
479 static int read_count_file (function_t
*);
480 static void solve_flow_graph (function_t
*);
481 static void find_exception_blocks (function_t
*);
482 static void add_branch_counts (coverage_t
*, const arc_t
*);
483 static void add_line_counts (coverage_t
*, function_t
*);
484 static void executed_summary (unsigned, unsigned);
485 static void function_summary (const coverage_t
*, const char *);
486 static const char *format_gcov (gcov_type
, gcov_type
, int);
487 static void accumulate_line_counts (source_info
*);
488 static void output_gcov_file (const char *, source_info
*);
489 static int output_branch_count (FILE *, int, const arc_t
*);
490 static void output_lines (FILE *, const source_info
*);
491 static char *make_gcov_file_name (const char *, const char *);
492 static char *mangle_name (const char *, char *);
493 static void release_structures (void);
494 extern int main (int, char **);
496 function_info::function_info (): name (NULL
), demangled_name (NULL
),
497 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
498 blocks (), blocks_executed (0), counts (NULL
), num_counts (0),
499 line (0), src (0), next_file_fn (NULL
), next (NULL
)
503 function_info::~function_info ()
505 for (int i
= blocks
.size () - 1; i
>= 0; i
--)
509 for (arc
= blocks
[i
].succ
; arc
; arc
= arc_n
)
511 arc_n
= arc
->succ_next
;
516 if (flag_demangled_names
&& demangled_name
!= name
)
517 free (demangled_name
);
522 There are a bajillion algorithms that do this. Boost's function is named
523 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
524 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
525 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
527 The basic algorithm is simple: effectively, we're finding all simple paths
528 in a subgraph (that shrinks every iteration). Duplicates are filtered by
529 "blocking" a path when a node is added to the path (this also prevents non-
530 simple paths)--the node is unblocked only when it participates in a cycle.
533 typedef vector
<arc_t
*> arc_vector_t
;
534 typedef vector
<const block_t
*> block_vector_t
;
536 /* Enum with types of loop in CFG. */
545 /* Loop_type operator that merges two values: A and B. */
547 inline loop_type
& operator |= (loop_type
& a
, loop_type b
)
549 return a
= static_cast<loop_type
> (a
| b
);
552 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
553 and subtract the value from all counts. The subtracted value is added
554 to COUNT. Returns type of loop. */
557 handle_cycle (const arc_vector_t
&edges
, int64_t &count
)
559 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
561 int64_t cycle_count
= INTTYPE_MAXIMUM (int64_t);
562 for (unsigned i
= 0; i
< edges
.size (); i
++)
564 int64_t ecount
= edges
[i
]->cs_count
;
565 if (cycle_count
> ecount
)
566 cycle_count
= ecount
;
568 count
+= cycle_count
;
569 for (unsigned i
= 0; i
< edges
.size (); i
++)
570 edges
[i
]->cs_count
-= cycle_count
;
572 return cycle_count
< 0 ? NEGATIVE_LOOP
: LOOP
;
575 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
576 blocked by U in BLOCK_LISTS. */
579 unblock (const block_t
*u
, block_vector_t
&blocked
,
580 vector
<block_vector_t
> &block_lists
)
582 block_vector_t::iterator it
= find (blocked
.begin (), blocked
.end (), u
);
583 if (it
== blocked
.end ())
586 unsigned index
= it
- blocked
.begin ();
589 block_vector_t
to_unblock (block_lists
[index
]);
591 block_lists
.erase (block_lists
.begin () + index
);
593 for (block_vector_t::iterator it
= to_unblock
.begin ();
594 it
!= to_unblock
.end (); it
++)
595 unblock (*it
, blocked
, block_lists
);
598 /* Find circuit going to block V, PATH is provisional seen cycle.
599 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
600 blocked by a block. COUNT is accumulated count of the current LINE.
601 Returns what type of loop it contains. */
604 circuit (block_t
*v
, arc_vector_t
&path
, block_t
*start
,
605 block_vector_t
&blocked
, vector
<block_vector_t
> &block_lists
,
606 line_info
&linfo
, int64_t &count
)
608 loop_type result
= NO_LOOP
;
610 /* Add v to the block list. */
611 gcc_assert (find (blocked
.begin (), blocked
.end (), v
) == blocked
.end ());
612 blocked
.push_back (v
);
613 block_lists
.push_back (block_vector_t ());
615 for (arc_t
*arc
= v
->succ
; arc
; arc
= arc
->succ_next
)
617 block_t
*w
= arc
->dst
;
618 if (w
< start
|| !linfo
.has_block (w
))
621 path
.push_back (arc
);
623 /* Cycle has been found. */
624 result
|= handle_cycle (path
, count
);
625 else if (find (blocked
.begin (), blocked
.end (), w
) == blocked
.end ())
626 result
|= circuit (w
, path
, start
, blocked
, block_lists
, linfo
, count
);
631 if (result
!= NO_LOOP
)
632 unblock (v
, blocked
, block_lists
);
634 for (arc_t
*arc
= v
->succ
; arc
; arc
= arc
->succ_next
)
636 block_t
*w
= arc
->dst
;
637 if (w
< start
|| !linfo
.has_block (w
))
641 = find (blocked
.begin (), blocked
.end (), w
) - blocked
.begin ();
642 gcc_assert (index
< blocked
.size ());
643 block_vector_t
&list
= block_lists
[index
];
644 if (find (list
.begin (), list
.end (), v
) == list
.end ())
651 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
652 contains a negative loop, then perform the same function once again. */
655 get_cycles_count (line_info
&linfo
, bool handle_negative_cycles
= true)
657 /* Note that this algorithm works even if blocks aren't in sorted order.
658 Each iteration of the circuit detection is completely independent
659 (except for reducing counts, but that shouldn't matter anyways).
660 Therefore, operating on a permuted order (i.e., non-sorted) only
661 has the effect of permuting the output cycles. */
663 loop_type result
= NO_LOOP
;
665 for (vector
<block_t
*>::iterator it
= linfo
.blocks
.begin ();
666 it
!= linfo
.blocks
.end (); it
++)
669 block_vector_t blocked
;
670 vector
<block_vector_t
> block_lists
;
671 result
|= circuit (*it
, path
, *it
, blocked
, block_lists
, linfo
,
675 /* If we have a negative cycle, repeat the find_cycles routine. */
676 if (result
== NEGATIVE_LOOP
&& handle_negative_cycles
)
677 count
+= get_cycles_count (linfo
, false);
683 main (int argc
, char **argv
)
689 p
= argv
[0] + strlen (argv
[0]);
690 while (p
!= argv
[0] && !IS_DIR_SEPARATOR (p
[-1]))
694 xmalloc_set_program_name (progname
);
696 /* Unlock the stdio streams. */
697 unlock_std_streams ();
701 diagnostic_initialize (global_dc
, 0);
703 /* Handle response files. */
704 expandargv (&argc
, &argv
);
706 argno
= process_args (argc
, argv
);
710 if (argc
- argno
> 1)
715 for (; argno
!= argc
; argno
++)
717 if (flag_display_progress
)
718 printf ("Processing file %d out of %d\n", argno
- first_arg
+ 1,
720 process_file (argv
[argno
]);
723 generate_results (multiple_files
? NULL
: argv
[argc
- 1]);
725 release_structures ();
730 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
731 otherwise the output of --help. */
734 print_usage (int error_p
)
736 FILE *file
= error_p
? stderr
: stdout
;
737 int status
= error_p
? FATAL_EXIT_CODE
: SUCCESS_EXIT_CODE
;
739 fnotice (file
, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
740 fnotice (file
, "Print code coverage information.\n\n");
741 fnotice (file
, " -a, --all-blocks Show information for every basic block\n");
742 fnotice (file
, " -b, --branch-probabilities Include branch probabilities in output\n");
743 fnotice (file
, " -c, --branch-counts Output counts of branches taken\n\
744 rather than percentages\n");
745 fnotice (file
, " -d, --display-progress Display progress information\n");
746 fnotice (file
, " -f, --function-summaries Output summaries for each function\n");
747 fnotice (file
, " -h, --help Print this help, then exit\n");
748 fnotice (file
, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
749 fnotice (file
, " -j, --human-readable Output human readable numbers\n");
750 fnotice (file
, " -k, --use-colors Emit colored output\n");
751 fnotice (file
, " -l, --long-file-names Use long output file names for included\n\
753 fnotice (file
, " -m, --demangled-names Output demangled function names\n");
754 fnotice (file
, " -n, --no-output Do not create an output file\n");
755 fnotice (file
, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
756 fnotice (file
, " -p, --preserve-paths Preserve all pathname components\n");
757 fnotice (file
, " -r, --relative-only Only show data for relative sources\n");
758 fnotice (file
, " -s, --source-prefix DIR Source prefix to elide\n");
759 fnotice (file
, " -u, --unconditional-branches Show unconditional branch counts too\n");
760 fnotice (file
, " -v, --version Print version number, then exit\n");
761 fnotice (file
, " -w, --verbose Print verbose informations\n");
762 fnotice (file
, " -x, --hash-filenames Hash long pathnames\n");
763 fnotice (file
, "\nFor bug reporting instructions, please see:\n%s.\n",
768 /* Print version information and exit. */
773 fnotice (stdout
, "gcov %s%s\n", pkgversion_string
, version_string
);
774 fprintf (stdout
, "Copyright %s 2017 Free Software Foundation, Inc.\n",
777 _("This is free software; see the source for copying conditions.\n"
778 "There is NO warranty; not even for MERCHANTABILITY or \n"
779 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
780 exit (SUCCESS_EXIT_CODE
);
783 static const struct option options
[] =
785 { "help", no_argument
, NULL
, 'h' },
786 { "version", no_argument
, NULL
, 'v' },
787 { "verbose", no_argument
, NULL
, 'w' },
788 { "all-blocks", no_argument
, NULL
, 'a' },
789 { "branch-probabilities", no_argument
, NULL
, 'b' },
790 { "branch-counts", no_argument
, NULL
, 'c' },
791 { "intermediate-format", no_argument
, NULL
, 'i' },
792 { "human-readable", no_argument
, NULL
, 'j' },
793 { "no-output", no_argument
, NULL
, 'n' },
794 { "long-file-names", no_argument
, NULL
, 'l' },
795 { "function-summaries", no_argument
, NULL
, 'f' },
796 { "demangled-names", no_argument
, NULL
, 'm' },
797 { "preserve-paths", no_argument
, NULL
, 'p' },
798 { "relative-only", no_argument
, NULL
, 'r' },
799 { "object-directory", required_argument
, NULL
, 'o' },
800 { "object-file", required_argument
, NULL
, 'o' },
801 { "source-prefix", required_argument
, NULL
, 's' },
802 { "unconditional-branches", no_argument
, NULL
, 'u' },
803 { "display-progress", no_argument
, NULL
, 'd' },
804 { "hash-filenames", no_argument
, NULL
, 'x' },
805 { "use-colors", no_argument
, NULL
, 'k' },
809 /* Process args, return index to first non-arg. */
812 process_args (int argc
, char **argv
)
816 const char *opts
= "abcdfhijklmno:prs:uvwx";
817 while ((opt
= getopt_long (argc
, argv
, opts
, options
, NULL
)) != -1)
831 flag_function_summary
= 1;
835 /* print_usage will exit. */
840 flag_human_readable_numbers
= 1;
846 flag_demangled_names
= 1;
852 object_directory
= optarg
;
855 source_prefix
= optarg
;
856 source_length
= strlen (source_prefix
);
859 flag_relative_only
= 1;
862 flag_preserve_paths
= 1;
865 flag_unconditional
= 1;
868 flag_intermediate_format
= 1;
872 flag_display_progress
= 1;
875 flag_hash_filenames
= 1;
882 /* print_version will exit. */
885 /* print_usage will exit. */
892 /* Output the result in intermediate format used by 'lcov'.
894 The intermediate format contains a single file named 'foo.cc.gcov',
895 with no source code included.
897 The default gcov outputs multiple files: 'foo.cc.gcov',
898 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
899 included. Instead the intermediate format here outputs only a single
900 file 'foo.cc.gcov' similar to the above example. */
903 output_intermediate_file (FILE *gcov_file
, source_info
*src
)
905 unsigned line_num
; /* current line number. */
906 const line_info
*line
; /* current line info ptr. */
907 function_t
*fn
; /* current function info ptr. */
909 fprintf (gcov_file
, "file:%s\n", src
->name
); /* source file name */
911 for (fn
= src
->functions
; fn
; fn
= fn
->next_file_fn
)
913 /* function:<name>,<line_number>,<execution_count> */
914 fprintf (gcov_file
, "function:%d,%s,%s\n", fn
->line
,
915 format_gcov (fn
->blocks
[0].count
, 0, -1),
916 flag_demangled_names
? fn
->demangled_name
: fn
->name
);
919 for (line_num
= 1, line
= &src
->lines
[line_num
];
920 line_num
< src
->lines
.size ();
924 fprintf (gcov_file
, "lcount:%u,%s,%d\n", line_num
,
925 format_gcov (line
->count
, 0, -1), line
->has_unexecuted_block
);
927 for (vector
<arc_t
*>::const_iterator it
= line
->branches
.begin ();
928 it
!= line
->branches
.end (); it
++)
930 if (!(*it
)->is_unconditional
&& !(*it
)->is_call_non_return
)
932 const char *branch_type
;
933 /* branch:<line_num>,<branch_coverage_type>
935 : notexec (Branch not executed)
936 : taken (Branch executed and taken)
937 : nottaken (Branch executed, but not taken)
939 if ((*it
)->src
->count
)
940 branch_type
= ((*it
)->count
> 0) ? "taken" : "nottaken";
942 branch_type
= "notexec";
943 fprintf (gcov_file
, "branch:%d,%s\n", line_num
, branch_type
);
949 /* Process a single input file. */
952 process_file (const char *file_name
)
956 create_file_names (file_name
);
957 fns
= read_graph_file ();
961 read_count_file (fns
);
964 function_t
*fn
= fns
;
968 if (fn
->counts
|| no_data_file
)
970 unsigned src
= fn
->src
;
971 unsigned line
= fn
->line
;
973 function_t
*probe
, **prev
;
975 /* Now insert it into the source file's list of
976 functions. Normally functions will be encountered in
977 ascending order, so a simple scan is quick. Note we're
978 building this list in reverse order. */
979 for (prev
= &sources
[src
].functions
;
980 (probe
= *prev
); prev
= &probe
->next_file_fn
)
981 if (probe
->line
<= line
)
983 fn
->next_file_fn
= probe
;
986 /* Mark last line in files touched by function. */
987 for (block_no
= 0; block_no
!= fn
->blocks
.size (); block_no
++)
989 block_t
*block
= &fn
->blocks
[block_no
];
990 for (unsigned i
= 0; i
< block
->locations
.size (); i
++)
992 unsigned s
= block
->locations
[i
].source_file_idx
;
994 /* Sort lines of locations. */
995 sort (block
->locations
[i
].lines
.begin (),
996 block
->locations
[i
].lines
.end ());
998 if (!block
->locations
[i
].lines
.empty ())
1001 = block
->locations
[i
].lines
.back () + 1;
1002 if (last_line
> sources
[s
].lines
.size ())
1003 sources
[s
].lines
.resize (last_line
);
1008 solve_flow_graph (fn
);
1010 find_exception_blocks (fn
);
1015 /* The function was not in the executable -- some other
1016 instance must have been selected. */
1022 output_gcov_file (const char *file_name
, source_info
*src
)
1024 char *gcov_file_name
= make_gcov_file_name (file_name
, src
->coverage
.name
);
1026 if (src
->coverage
.lines
)
1028 FILE *gcov_file
= fopen (gcov_file_name
, "w");
1031 fnotice (stdout
, "Creating '%s'\n", gcov_file_name
);
1033 if (flag_intermediate_format
)
1034 output_intermediate_file (gcov_file
, src
);
1036 output_lines (gcov_file
, src
);
1037 if (ferror (gcov_file
))
1038 fnotice (stderr
, "Error writing output file '%s'\n", gcov_file_name
);
1042 fnotice (stderr
, "Could not open output file '%s'\n", gcov_file_name
);
1046 unlink (gcov_file_name
);
1047 fnotice (stdout
, "Removing '%s'\n", gcov_file_name
);
1049 free (gcov_file_name
);
1053 generate_results (const char *file_name
)
1057 for (fn
= functions
; fn
; fn
= fn
->next
)
1059 coverage_t coverage
;
1061 memset (&coverage
, 0, sizeof (coverage
));
1062 coverage
.name
= flag_demangled_names
? fn
->demangled_name
: fn
->name
;
1063 add_line_counts (flag_function_summary
? &coverage
: NULL
, fn
);
1064 if (flag_function_summary
)
1066 function_summary (&coverage
, "Function");
1067 fnotice (stdout
, "\n");
1075 needle
.name
= file_name
;
1076 vector
<name_map
>::iterator it
= std::find (names
.begin (), names
.end (),
1078 if (it
!= names
.end ())
1079 file_name
= sources
[it
->src
].coverage
.name
;
1081 file_name
= canonicalize_name (file_name
);
1084 for (vector
<source_info
>::iterator it
= sources
.begin ();
1085 it
!= sources
.end (); it
++)
1087 source_info
*src
= &(*it
);
1088 if (flag_relative_only
)
1090 /* Ignore this source, if it is an absolute path (after
1091 source prefix removal). */
1092 char first
= src
->coverage
.name
[0];
1094 #if HAVE_DOS_BASED_FILE_SYSTEM
1095 if (first
&& src
->coverage
.name
[1] == ':')
1096 first
= src
->coverage
.name
[2];
1098 if (IS_DIR_SEPARATOR (first
))
1102 accumulate_line_counts (src
);
1103 function_summary (&src
->coverage
, "File");
1104 total_lines
+= src
->coverage
.lines
;
1105 total_executed
+= src
->coverage
.lines_executed
;
1108 output_gcov_file (file_name
, src
);
1109 fnotice (stdout
, "\n");
1114 executed_summary (total_lines
, total_executed
);
1117 /* Release all memory used. */
1120 release_structures (void)
1124 while ((fn
= functions
))
1126 functions
= fn
->next
;
1131 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1132 is not specified, these are named from FILE_NAME sans extension. If
1133 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1134 directory, but named from the basename of the FILE_NAME, sans extension.
1135 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1136 and the data files are named from that. */
1139 create_file_names (const char *file_name
)
1143 int length
= strlen (file_name
);
1146 /* Free previous file names. */
1147 free (bbg_file_name
);
1148 free (da_file_name
);
1149 da_file_name
= bbg_file_name
= NULL
;
1153 if (object_directory
&& object_directory
[0])
1157 length
+= strlen (object_directory
) + 2;
1158 name
= XNEWVEC (char, length
);
1161 base
= !stat (object_directory
, &status
) && S_ISDIR (status
.st_mode
);
1162 strcat (name
, object_directory
);
1163 if (base
&& (!IS_DIR_SEPARATOR (name
[strlen (name
) - 1])))
1168 name
= XNEWVEC (char, length
+ 1);
1169 strcpy (name
, file_name
);
1175 /* Append source file name. */
1176 const char *cptr
= lbasename (file_name
);
1177 strcat (name
, cptr
? cptr
: file_name
);
1180 /* Remove the extension. */
1181 cptr
= strrchr (CONST_CAST (char *, lbasename (name
)), '.');
1185 length
= strlen (name
);
1187 bbg_file_name
= XNEWVEC (char, length
+ strlen (GCOV_NOTE_SUFFIX
) + 1);
1188 strcpy (bbg_file_name
, name
);
1189 strcpy (bbg_file_name
+ length
, GCOV_NOTE_SUFFIX
);
1191 da_file_name
= XNEWVEC (char, length
+ strlen (GCOV_DATA_SUFFIX
) + 1);
1192 strcpy (da_file_name
, name
);
1193 strcpy (da_file_name
+ length
, GCOV_DATA_SUFFIX
);
1199 /* Find or create a source file structure for FILE_NAME. Copies
1200 FILE_NAME on creation */
1203 find_source (const char *file_name
)
1210 file_name
= "<unknown>";
1213 needle
.name
= file_name
;
1215 vector
<name_map
>::iterator it
= std::find (names
.begin (), names
.end (),
1217 if (it
!= names
.end ())
1223 /* Not found, try the canonical name. */
1224 canon
= canonicalize_name (file_name
);
1225 needle
.name
= canon
;
1226 it
= std::find (names
.begin (), names
.end (), needle
);
1227 if (it
== names
.end ())
1229 /* Not found with canonical name, create a new source. */
1232 idx
= sources
.size ();
1233 needle
= name_map (canon
, idx
);
1234 names
.push_back (needle
);
1236 sources
.push_back (source_info ());
1237 src
= &sources
.back ();
1239 src
->coverage
.name
= src
->name
;
1241 #if HAVE_DOS_BASED_FILE_SYSTEM
1242 /* You lose if separators don't match exactly in the
1244 && !strncasecmp (source_prefix
, src
->coverage
.name
, source_length
)
1246 && !strncmp (source_prefix
, src
->coverage
.name
, source_length
)
1248 && IS_DIR_SEPARATOR (src
->coverage
.name
[source_length
]))
1249 src
->coverage
.name
+= source_length
+ 1;
1250 if (!stat (src
->name
, &status
))
1251 src
->file_time
= status
.st_mtime
;
1256 needle
.name
= file_name
;
1257 if (std::find (names
.begin (), names
.end (), needle
) == names
.end ())
1259 /* Append the non-canonical name. */
1260 names
.push_back (name_map (xstrdup (file_name
), idx
));
1263 /* Resort the name map. */
1264 std::sort (names
.begin (), names
.end ());
1267 if (sources
[idx
].file_time
> bbg_file_time
)
1269 static int info_emitted
;
1271 fnotice (stderr
, "%s:source file is newer than notes file '%s'\n",
1272 file_name
, bbg_file_name
);
1276 "(the message is displayed only once per source file)\n");
1279 sources
[idx
].file_time
= 0;
1285 /* Read the notes file. Return list of functions read -- in reverse order. */
1288 read_graph_file (void)
1291 unsigned current_tag
= 0;
1292 function_t
*fn
= NULL
;
1293 function_t
*fns
= NULL
;
1294 function_t
**fns_end
= &fns
;
1297 if (!gcov_open (bbg_file_name
, 1))
1299 fnotice (stderr
, "%s:cannot open notes file\n", bbg_file_name
);
1302 bbg_file_time
= gcov_time ();
1303 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC
))
1305 fnotice (stderr
, "%s:not a gcov notes file\n", bbg_file_name
);
1310 version
= gcov_read_unsigned ();
1311 if (version
!= GCOV_VERSION
)
1315 GCOV_UNSIGNED2STRING (v
, version
);
1316 GCOV_UNSIGNED2STRING (e
, GCOV_VERSION
);
1318 fnotice (stderr
, "%s:version '%.4s', prefer '%.4s'\n",
1319 bbg_file_name
, v
, e
);
1321 bbg_stamp
= gcov_read_unsigned ();
1323 while ((tag
= gcov_read_unsigned ()))
1325 unsigned length
= gcov_read_unsigned ();
1326 gcov_position_t base
= gcov_position ();
1328 if (tag
== GCOV_TAG_FUNCTION
)
1330 char *function_name
;
1331 unsigned ident
, lineno
;
1332 unsigned lineno_checksum
, cfg_checksum
;
1334 ident
= gcov_read_unsigned ();
1335 lineno_checksum
= gcov_read_unsigned ();
1336 cfg_checksum
= gcov_read_unsigned ();
1337 function_name
= xstrdup (gcov_read_string ());
1338 unsigned src_idx
= find_source (gcov_read_string ());
1339 lineno
= gcov_read_unsigned ();
1341 fn
= new function_t
;
1342 fn
->name
= function_name
;
1343 if (flag_demangled_names
)
1345 fn
->demangled_name
= cplus_demangle (fn
->name
, DMGL_PARAMS
);
1346 if (!fn
->demangled_name
)
1347 fn
->demangled_name
= fn
->name
;
1350 fn
->lineno_checksum
= lineno_checksum
;
1351 fn
->cfg_checksum
= cfg_checksum
;
1355 fn
->next_file_fn
= NULL
;
1358 fns_end
= &fn
->next
;
1361 else if (fn
&& tag
== GCOV_TAG_BLOCKS
)
1363 if (!fn
->blocks
.empty ())
1364 fnotice (stderr
, "%s:already seen blocks for '%s'\n",
1365 bbg_file_name
, fn
->name
);
1367 fn
->blocks
.resize (gcov_read_unsigned ());
1369 else if (fn
&& tag
== GCOV_TAG_ARCS
)
1371 unsigned src
= gcov_read_unsigned ();
1372 fn
->blocks
[src
].id
= src
;
1373 unsigned num_dests
= GCOV_TAG_ARCS_NUM (length
);
1374 block_t
*src_blk
= &fn
->blocks
[src
];
1375 unsigned mark_catches
= 0;
1376 struct arc_info
*arc
;
1378 if (src
>= fn
->blocks
.size () || fn
->blocks
[src
].succ
)
1383 unsigned dest
= gcov_read_unsigned ();
1384 unsigned flags
= gcov_read_unsigned ();
1386 if (dest
>= fn
->blocks
.size ())
1388 arc
= XCNEW (arc_t
);
1390 arc
->dst
= &fn
->blocks
[dest
];
1394 arc
->count_valid
= 0;
1395 arc
->on_tree
= !!(flags
& GCOV_ARC_ON_TREE
);
1396 arc
->fake
= !!(flags
& GCOV_ARC_FAKE
);
1397 arc
->fall_through
= !!(flags
& GCOV_ARC_FALLTHROUGH
);
1399 arc
->succ_next
= src_blk
->succ
;
1400 src_blk
->succ
= arc
;
1401 src_blk
->num_succ
++;
1403 arc
->pred_next
= fn
->blocks
[dest
].pred
;
1404 fn
->blocks
[dest
].pred
= arc
;
1405 fn
->blocks
[dest
].num_pred
++;
1411 /* Exceptional exit from this function, the
1412 source block must be a call. */
1413 fn
->blocks
[src
].is_call_site
= 1;
1414 arc
->is_call_non_return
= 1;
1419 /* Non-local return from a callee of this
1420 function. The destination block is a setjmp. */
1421 arc
->is_nonlocal_return
= 1;
1422 fn
->blocks
[dest
].is_nonlocal_return
= 1;
1432 /* We have a fake exit from this block. The other
1433 non-fall through exits must be to catch handlers.
1434 Mark them as catch arcs. */
1436 for (arc
= src_blk
->succ
; arc
; arc
= arc
->succ_next
)
1437 if (!arc
->fake
&& !arc
->fall_through
)
1444 else if (fn
&& tag
== GCOV_TAG_LINES
)
1446 unsigned blockno
= gcov_read_unsigned ();
1447 block_t
*block
= &fn
->blocks
[blockno
];
1449 if (blockno
>= fn
->blocks
.size ())
1454 unsigned lineno
= gcov_read_unsigned ();
1457 block
->locations
.back ().lines
.push_back (lineno
);
1460 const char *file_name
= gcov_read_string ();
1464 block
->locations
.push_back (block_location_info
1465 (find_source (file_name
)));
1469 else if (current_tag
&& !GCOV_TAG_IS_SUBTAG (current_tag
, tag
))
1474 gcov_sync (base
, length
);
1475 if (gcov_is_error ())
1478 fnotice (stderr
, "%s:corrupted\n", bbg_file_name
);
1485 fnotice (stderr
, "%s:no functions found\n", bbg_file_name
);
1490 /* Reads profiles from the count file and attach to each
1491 function. Return nonzero if fatal error. */
1494 read_count_file (function_t
*fns
)
1499 function_t
*fn
= NULL
;
1502 if (!gcov_open (da_file_name
, 1))
1504 fnotice (stderr
, "%s:cannot open data file, assuming not executed\n",
1509 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC
))
1511 fnotice (stderr
, "%s:not a gcov data file\n", da_file_name
);
1516 version
= gcov_read_unsigned ();
1517 if (version
!= GCOV_VERSION
)
1521 GCOV_UNSIGNED2STRING (v
, version
);
1522 GCOV_UNSIGNED2STRING (e
, GCOV_VERSION
);
1524 fnotice (stderr
, "%s:version '%.4s', prefer version '%.4s'\n",
1525 da_file_name
, v
, e
);
1527 tag
= gcov_read_unsigned ();
1528 if (tag
!= bbg_stamp
)
1530 fnotice (stderr
, "%s:stamp mismatch with notes file\n", da_file_name
);
1534 while ((tag
= gcov_read_unsigned ()))
1536 unsigned length
= gcov_read_unsigned ();
1537 unsigned long base
= gcov_position ();
1539 if (tag
== GCOV_TAG_PROGRAM_SUMMARY
)
1541 struct gcov_summary summary
;
1542 gcov_read_summary (&summary
);
1543 object_runs
+= summary
.ctrs
[GCOV_COUNTER_ARCS
].runs
;
1546 else if (tag
== GCOV_TAG_FUNCTION
&& !length
)
1548 else if (tag
== GCOV_TAG_FUNCTION
&& length
== GCOV_TAG_FUNCTION_LENGTH
)
1551 struct function_info
*fn_n
;
1553 /* Try to find the function in the list. To speed up the
1554 search, first start from the last function found. */
1555 ident
= gcov_read_unsigned ();
1557 for (fn
= fn
? fn
->next
: NULL
; ; fn
= fn
->next
)
1561 else if ((fn
= fn_n
))
1565 fnotice (stderr
, "%s:unknown function '%u'\n",
1566 da_file_name
, ident
);
1569 if (fn
->ident
== ident
)
1575 else if (gcov_read_unsigned () != fn
->lineno_checksum
1576 || gcov_read_unsigned () != fn
->cfg_checksum
)
1579 fnotice (stderr
, "%s:profile mismatch for '%s'\n",
1580 da_file_name
, fn
->name
);
1584 else if (tag
== GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS
) && fn
)
1586 if (length
!= GCOV_TAG_COUNTER_LENGTH (fn
->num_counts
))
1590 fn
->counts
= XCNEWVEC (gcov_type
, fn
->num_counts
);
1592 for (ix
= 0; ix
!= fn
->num_counts
; ix
++)
1593 fn
->counts
[ix
] += gcov_read_counter ();
1595 gcov_sync (base
, length
);
1596 if ((error
= gcov_is_error ()))
1600 ? N_("%s:overflowed\n")
1601 : N_("%s:corrupted\n"),
1611 /* Solve the flow graph. Propagate counts from the instrumented arcs
1612 to the blocks and the uninstrumented arcs. */
1615 solve_flow_graph (function_t
*fn
)
1619 gcov_type
*count_ptr
= fn
->counts
;
1621 block_t
*valid_blocks
= NULL
; /* valid, but unpropagated blocks. */
1622 block_t
*invalid_blocks
= NULL
; /* invalid, but inferable blocks. */
1624 /* The arcs were built in reverse order. Fix that now. */
1625 for (ix
= fn
->blocks
.size (); ix
--;)
1627 arc_t
*arc_p
, *arc_n
;
1629 for (arc_p
= NULL
, arc
= fn
->blocks
[ix
].succ
; arc
;
1630 arc_p
= arc
, arc
= arc_n
)
1632 arc_n
= arc
->succ_next
;
1633 arc
->succ_next
= arc_p
;
1635 fn
->blocks
[ix
].succ
= arc_p
;
1637 for (arc_p
= NULL
, arc
= fn
->blocks
[ix
].pred
; arc
;
1638 arc_p
= arc
, arc
= arc_n
)
1640 arc_n
= arc
->pred_next
;
1641 arc
->pred_next
= arc_p
;
1643 fn
->blocks
[ix
].pred
= arc_p
;
1646 if (fn
->blocks
.size () < 2)
1647 fnotice (stderr
, "%s:'%s' lacks entry and/or exit blocks\n",
1648 bbg_file_name
, fn
->name
);
1651 if (fn
->blocks
[ENTRY_BLOCK
].num_pred
)
1652 fnotice (stderr
, "%s:'%s' has arcs to entry block\n",
1653 bbg_file_name
, fn
->name
);
1655 /* We can't deduce the entry block counts from the lack of
1657 fn
->blocks
[ENTRY_BLOCK
].num_pred
= ~(unsigned)0;
1659 if (fn
->blocks
[EXIT_BLOCK
].num_succ
)
1660 fnotice (stderr
, "%s:'%s' has arcs from exit block\n",
1661 bbg_file_name
, fn
->name
);
1663 /* Likewise, we can't deduce exit block counts from the lack
1664 of its successors. */
1665 fn
->blocks
[EXIT_BLOCK
].num_succ
= ~(unsigned)0;
1668 /* Propagate the measured counts, this must be done in the same
1669 order as the code in profile.c */
1670 for (unsigned i
= 0; i
< fn
->blocks
.size (); i
++)
1672 blk
= &fn
->blocks
[i
];
1673 block_t
const *prev_dst
= NULL
;
1674 int out_of_order
= 0;
1675 int non_fake_succ
= 0;
1677 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1685 arc
->count
= *count_ptr
++;
1686 arc
->count_valid
= 1;
1688 arc
->dst
->num_pred
--;
1690 if (prev_dst
&& prev_dst
> arc
->dst
)
1692 prev_dst
= arc
->dst
;
1694 if (non_fake_succ
== 1)
1696 /* If there is only one non-fake exit, it is an
1697 unconditional branch. */
1698 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1701 arc
->is_unconditional
= 1;
1702 /* If this block is instrumenting a call, it might be
1703 an artificial block. It is not artificial if it has
1704 a non-fallthrough exit, or the destination of this
1705 arc has more than one entry. Mark the destination
1706 block as a return site, if none of those conditions
1708 if (blk
->is_call_site
&& arc
->fall_through
1709 && arc
->dst
->pred
== arc
&& !arc
->pred_next
)
1710 arc
->dst
->is_call_return
= 1;
1714 /* Sort the successor arcs into ascending dst order. profile.c
1715 normally produces arcs in the right order, but sometimes with
1716 one or two out of order. We're not using a particularly
1720 arc_t
*start
= blk
->succ
;
1721 unsigned changes
= 1;
1725 arc_t
*arc
, *arc_p
, *arc_n
;
1728 for (arc_p
= NULL
, arc
= start
; (arc_n
= arc
->succ_next
);)
1730 if (arc
->dst
> arc_n
->dst
)
1734 arc_p
->succ_next
= arc_n
;
1737 arc
->succ_next
= arc_n
->succ_next
;
1738 arc_n
->succ_next
= arc
;
1751 /* Place it on the invalid chain, it will be ignored if that's
1753 blk
->invalid_chain
= 1;
1754 blk
->chain
= invalid_blocks
;
1755 invalid_blocks
= blk
;
1758 while (invalid_blocks
|| valid_blocks
)
1760 while ((blk
= invalid_blocks
))
1762 gcov_type total
= 0;
1765 invalid_blocks
= blk
->chain
;
1766 blk
->invalid_chain
= 0;
1768 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1769 total
+= arc
->count
;
1770 else if (!blk
->num_pred
)
1771 for (arc
= blk
->pred
; arc
; arc
= arc
->pred_next
)
1772 total
+= arc
->count
;
1777 blk
->count_valid
= 1;
1778 blk
->chain
= valid_blocks
;
1779 blk
->valid_chain
= 1;
1782 while ((blk
= valid_blocks
))
1785 arc_t
*arc
, *inv_arc
;
1787 valid_blocks
= blk
->chain
;
1788 blk
->valid_chain
= 0;
1789 if (blk
->num_succ
== 1)
1795 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1797 total
-= arc
->count
;
1798 if (!arc
->count_valid
)
1802 inv_arc
->count_valid
= 1;
1803 inv_arc
->count
= total
;
1806 if (dst
->count_valid
)
1808 if (dst
->num_pred
== 1 && !dst
->valid_chain
)
1810 dst
->chain
= valid_blocks
;
1811 dst
->valid_chain
= 1;
1817 if (!dst
->num_pred
&& !dst
->invalid_chain
)
1819 dst
->chain
= invalid_blocks
;
1820 dst
->invalid_chain
= 1;
1821 invalid_blocks
= dst
;
1825 if (blk
->num_pred
== 1)
1831 for (arc
= blk
->pred
; arc
; arc
= arc
->pred_next
)
1833 total
-= arc
->count
;
1834 if (!arc
->count_valid
)
1838 inv_arc
->count_valid
= 1;
1839 inv_arc
->count
= total
;
1842 if (src
->count_valid
)
1844 if (src
->num_succ
== 1 && !src
->valid_chain
)
1846 src
->chain
= valid_blocks
;
1847 src
->valid_chain
= 1;
1853 if (!src
->num_succ
&& !src
->invalid_chain
)
1855 src
->chain
= invalid_blocks
;
1856 src
->invalid_chain
= 1;
1857 invalid_blocks
= src
;
1864 /* If the graph has been correctly solved, every block will have a
1866 for (unsigned i
= 0; ix
< fn
->blocks
.size (); i
++)
1867 if (!fn
->blocks
[i
].count_valid
)
1869 fnotice (stderr
, "%s:graph is unsolvable for '%s'\n",
1870 bbg_file_name
, fn
->name
);
1875 /* Mark all the blocks only reachable via an incoming catch. */
1878 find_exception_blocks (function_t
*fn
)
1881 block_t
**queue
= XALLOCAVEC (block_t
*, fn
->blocks
.size ());
1883 /* First mark all blocks as exceptional. */
1884 for (ix
= fn
->blocks
.size (); ix
--;)
1885 fn
->blocks
[ix
].exceptional
= 1;
1887 /* Now mark all the blocks reachable via non-fake edges */
1888 queue
[0] = &fn
->blocks
[0];
1889 queue
[0]->exceptional
= 0;
1892 block_t
*block
= queue
[--ix
];
1895 for (arc
= block
->succ
; arc
; arc
= arc
->succ_next
)
1896 if (!arc
->fake
&& !arc
->is_throw
&& arc
->dst
->exceptional
)
1898 arc
->dst
->exceptional
= 0;
1899 queue
[ix
++] = arc
->dst
;
1905 /* Increment totals in COVERAGE according to arc ARC. */
1908 add_branch_counts (coverage_t
*coverage
, const arc_t
*arc
)
1910 if (arc
->is_call_non_return
)
1913 if (arc
->src
->count
)
1914 coverage
->calls_executed
++;
1916 else if (!arc
->is_unconditional
)
1918 coverage
->branches
++;
1919 if (arc
->src
->count
)
1920 coverage
->branches_executed
++;
1922 coverage
->branches_taken
++;
1926 /* Format COUNT, if flag_human_readable_numbers is set, return it human
1930 format_count (gcov_type count
)
1932 static char buffer
[64];
1933 const char *units
= " kMGTPEZY";
1935 if (count
< 1000 || !flag_human_readable_numbers
)
1937 sprintf (buffer
, "%" PRId64
, count
);
1942 gcov_type divisor
= 1;
1943 for (i
= 0; units
[i
+1]; i
++, divisor
*= 1000)
1945 if (count
+ divisor
/ 2 < 1000 * divisor
)
1948 gcov_type r
= (count
+ divisor
/ 2) / divisor
;
1949 sprintf (buffer
, "%" PRId64
"%c", r
, units
[i
]);
1953 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
1954 count. If dp >= 0, format TOP/BOTTOM * 100 to DP decimal places.
1955 If DP is zero, no decimal point is printed. Only print 100% when
1956 TOP==BOTTOM and only print 0% when TOP=0. If dp < 0, then simply
1957 format TOP. Return pointer to a static string. */
1960 format_gcov (gcov_type top
, gcov_type bottom
, int dp
)
1962 static char buffer
[20];
1964 /* Handle invalid values that would result in a misleading value. */
1965 if (bottom
!= 0 && top
> bottom
&& dp
>= 0)
1967 sprintf (buffer
, "NAN %%");
1973 float ratio
= bottom
? (float)top
/ bottom
: 0;
1975 unsigned limit
= 100;
1978 for (ix
= dp
; ix
--; )
1981 percent
= (unsigned) (ratio
* limit
+ (float)0.5);
1982 if (percent
<= 0 && top
)
1984 else if (percent
>= limit
&& top
!= bottom
)
1985 percent
= limit
- 1;
1986 ix
= sprintf (buffer
, "%.*u%%", dp
+ 1, percent
);
1992 buffer
[ix
+1] = buffer
[ix
];
1996 buffer
[ix
+ 1] = '.';
2000 return format_count (top
);
2005 /* Summary of execution */
2008 executed_summary (unsigned lines
, unsigned executed
)
2011 fnotice (stdout
, "Lines executed:%s of %d\n",
2012 format_gcov (executed
, lines
, 2), lines
);
2014 fnotice (stdout
, "No executable lines\n");
2017 /* Output summary info for a function or file. */
2020 function_summary (const coverage_t
*coverage
, const char *title
)
2022 fnotice (stdout
, "%s '%s'\n", title
, coverage
->name
);
2023 executed_summary (coverage
->lines
, coverage
->lines_executed
);
2027 if (coverage
->branches
)
2029 fnotice (stdout
, "Branches executed:%s of %d\n",
2030 format_gcov (coverage
->branches_executed
,
2031 coverage
->branches
, 2),
2032 coverage
->branches
);
2033 fnotice (stdout
, "Taken at least once:%s of %d\n",
2034 format_gcov (coverage
->branches_taken
,
2035 coverage
->branches
, 2),
2036 coverage
->branches
);
2039 fnotice (stdout
, "No branches\n");
2040 if (coverage
->calls
)
2041 fnotice (stdout
, "Calls executed:%s of %d\n",
2042 format_gcov (coverage
->calls_executed
, coverage
->calls
, 2),
2045 fnotice (stdout
, "No calls\n");
2049 /* Canonicalize the filename NAME by canonicalizing directory
2050 separators, eliding . components and resolving .. components
2051 appropriately. Always returns a unique string. */
2054 canonicalize_name (const char *name
)
2056 /* The canonical name cannot be longer than the incoming name. */
2057 char *result
= XNEWVEC (char, strlen (name
) + 1);
2058 const char *base
= name
, *probe
;
2063 #if HAVE_DOS_BASED_FILE_SYSTEM
2064 if (base
[0] && base
[1] == ':')
2066 result
[0] = base
[0];
2072 for (dd_base
= ptr
; *base
; base
= probe
)
2076 for (probe
= base
; *probe
; probe
++)
2077 if (IS_DIR_SEPARATOR (*probe
))
2081 if (len
== 1 && base
[0] == '.')
2082 /* Elide a '.' directory */
2084 else if (len
== 2 && base
[0] == '.' && base
[1] == '.')
2086 /* '..', we can only elide it and the previous directory, if
2087 we're not a symlink. */
2088 struct stat ATTRIBUTE_UNUSED buf
;
2092 #if defined (S_ISLNK)
2093 /* S_ISLNK is not POSIX.1-1996. */
2094 || stat (result
, &buf
) || S_ISLNK (buf
.st_mode
)
2098 /* Cannot elide, or unreadable or a symlink. */
2099 dd_base
= ptr
+ 2 + slash
;
2102 while (ptr
!= dd_base
&& *ptr
!= '/')
2104 slash
= ptr
!= result
;
2109 /* Regular pathname component. */
2112 memcpy (ptr
, base
, len
);
2117 for (; IS_DIR_SEPARATOR (*probe
); probe
++)
2125 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2128 md5sum_to_hex (const char *sum
, char *buffer
)
2130 for (unsigned i
= 0; i
< 16; i
++)
2131 sprintf (buffer
+ (2 * i
), "%02x", (unsigned char)sum
[i
]);
2134 /* Generate an output file name. INPUT_NAME is the canonicalized main
2135 input file and SRC_NAME is the canonicalized file name.
2136 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2137 long_output_names we prepend the processed name of the input file
2138 to each output name (except when the current source file is the
2139 input file, so you don't get a double concatenation). The two
2140 components are separated by '##'. With preserve_paths we create a
2141 filename from all path components of the source file, replacing '/'
2142 with '#', and .. with '^', without it we simply take the basename
2143 component. (Remember, the canonicalized name will already have
2144 elided '.' components and converted \\ separators.) */
2147 make_gcov_file_name (const char *input_name
, const char *src_name
)
2152 if (flag_long_names
&& input_name
&& strcmp (src_name
, input_name
))
2154 /* Generate the input filename part. */
2155 result
= XNEWVEC (char, strlen (input_name
) + strlen (src_name
) + 10);
2158 ptr
= mangle_name (input_name
, ptr
);
2159 ptr
[0] = ptr
[1] = '#';
2164 result
= XNEWVEC (char, strlen (src_name
) + 10);
2168 ptr
= mangle_name (src_name
, ptr
);
2169 strcpy (ptr
, ".gcov");
2171 /* When hashing filenames, we shorten them by only using the filename
2172 component and appending a hash of the full (mangled) pathname. */
2173 if (flag_hash_filenames
)
2177 char md5sum_hex
[33];
2179 md5_init_ctx (&ctx
);
2180 md5_process_bytes (src_name
, strlen (src_name
), &ctx
);
2181 md5_finish_ctx (&ctx
, md5sum
);
2182 md5sum_to_hex (md5sum
, md5sum_hex
);
2185 result
= XNEWVEC (char, strlen (src_name
) + 50);
2187 ptr
= mangle_name (src_name
, ptr
);
2188 ptr
[0] = ptr
[1] = '#';
2190 memcpy (ptr
, md5sum_hex
, 32);
2192 strcpy (ptr
, ".gcov");
2199 mangle_name (char const *base
, char *ptr
)
2203 /* Generate the source filename part. */
2204 if (!flag_preserve_paths
)
2206 base
= lbasename (base
);
2207 len
= strlen (base
);
2208 memcpy (ptr
, base
, len
);
2213 /* Convert '/' to '#', convert '..' to '^',
2214 convert ':' to '~' on DOS based file system. */
2217 #if HAVE_DOS_BASED_FILE_SYSTEM
2218 if (base
[0] && base
[1] == ':')
2226 for (; *base
; base
= probe
)
2230 for (probe
= base
; *probe
; probe
++)
2234 if (len
== 2 && base
[0] == '.' && base
[1] == '.')
2238 memcpy (ptr
, base
, len
);
2252 /* Scan through the bb_data for each line in the block, increment
2253 the line number execution count indicated by the execution count of
2254 the appropriate basic block. */
2257 add_line_counts (coverage_t
*coverage
, function_t
*fn
)
2259 bool has_any_line
= false;
2260 /* Scan each basic block. */
2261 for (unsigned ix
= 0; ix
!= fn
->blocks
.size (); ix
++)
2263 line_info
*line
= NULL
;
2264 block_t
*block
= &fn
->blocks
[ix
];
2265 if (block
->count
&& ix
&& ix
+ 1 != fn
->blocks
.size ())
2266 fn
->blocks_executed
++;
2267 for (unsigned i
= 0; i
< block
->locations
.size (); i
++)
2269 source_info
*src
= &sources
[block
->locations
[i
].source_file_idx
];
2271 vector
<unsigned> &lines
= block
->locations
[i
].lines
;
2272 for (unsigned j
= 0; j
< lines
.size (); j
++)
2274 line
= &src
->lines
[lines
[j
]];
2279 if (!line
->count
&& block
->count
)
2280 coverage
->lines_executed
++;
2283 if (!block
->exceptional
)
2285 line
->unexceptional
= 1;
2286 if (block
->count
== 0)
2287 line
->has_unexecuted_block
= 1;
2289 line
->count
+= block
->count
;
2292 block
->cycle
.arc
= NULL
;
2293 block
->cycle
.ident
= ~0U;
2294 has_any_line
= true;
2296 if (!ix
|| ix
+ 1 == fn
->blocks
.size ())
2297 /* Entry or exit block */;
2298 else if (line
!= NULL
)
2300 line
->blocks
.push_back (block
);
2306 for (arc
= block
->succ
; arc
; arc
= arc
->succ_next
)
2308 line
->branches
.push_back (arc
);
2309 if (coverage
&& !arc
->is_unconditional
)
2310 add_branch_counts (coverage
, arc
);
2317 fnotice (stderr
, "%s:no lines for '%s'\n", bbg_file_name
, fn
->name
);
2320 /* Accumulate the line counts of a file. */
2323 accumulate_line_counts (source_info
*src
)
2325 function_t
*fn
, *fn_p
, *fn_n
;
2328 /* Reverse the function order. */
2329 for (fn
= src
->functions
, fn_p
= NULL
; fn
; fn_p
= fn
, fn
= fn_n
)
2331 fn_n
= fn
->next_file_fn
;
2332 fn
->next_file_fn
= fn_p
;
2334 src
->functions
= fn_p
;
2336 for (vector
<line_info
>::reverse_iterator it
= src
->lines
.rbegin ();
2337 it
!= src
->lines
.rend (); it
++)
2339 line_info
*line
= &(*it
);
2340 if (!line
->blocks
.empty ())
2342 /* The user expects the line count to be the number of times
2343 a line has been executed. Simply summing the block count
2344 will give an artificially high number. The Right Thing
2345 is to sum the entry counts to the graph of blocks on this
2346 line, then find the elementary cycles of the local graph
2347 and add the transition counts of those cycles. */
2348 gcov_type count
= 0;
2350 /* Sum the entry arcs. */
2351 for (vector
<block_t
*>::iterator it
= line
->blocks
.begin ();
2352 it
!= line
->blocks
.end (); it
++)
2356 for (arc
= (*it
)->pred
; arc
; arc
= arc
->pred_next
)
2358 add_branch_counts (&src
->coverage
, arc
);
2361 /* Cycle detection. */
2362 for (vector
<block_t
*>::iterator it
= line
->blocks
.begin ();
2363 it
!= line
->blocks
.end (); it
++)
2365 for (arc_t
*arc
= (*it
)->pred
; arc
; arc
= arc
->pred_next
)
2366 if (!line
->has_block (arc
->src
))
2367 count
+= arc
->count
;
2368 for (arc_t
*arc
= (*it
)->succ
; arc
; arc
= arc
->succ_next
)
2369 arc
->cs_count
= arc
->count
;
2372 /* Now, add the count of loops entirely on this line. */
2373 count
+= get_cycles_count (*line
);
2374 line
->count
= count
;
2379 src
->coverage
.lines
++;
2381 src
->coverage
.lines_executed
++;
2388 /* Output information about ARC number IX. Returns nonzero if
2389 anything is output. */
2392 output_branch_count (FILE *gcov_file
, int ix
, const arc_t
*arc
)
2394 if (arc
->is_call_non_return
)
2396 if (arc
->src
->count
)
2398 fnotice (gcov_file
, "call %2d returned %s\n", ix
,
2399 format_gcov (arc
->src
->count
- arc
->count
,
2400 arc
->src
->count
, -flag_counts
));
2403 fnotice (gcov_file
, "call %2d never executed\n", ix
);
2405 else if (!arc
->is_unconditional
)
2407 if (arc
->src
->count
)
2408 fnotice (gcov_file
, "branch %2d taken %s%s", ix
,
2409 format_gcov (arc
->count
, arc
->src
->count
, -flag_counts
),
2410 arc
->fall_through
? " (fallthrough)"
2411 : arc
->is_throw
? " (throw)" : "");
2413 fnotice (gcov_file
, "branch %2d never executed", ix
);
2416 fnotice (gcov_file
, " (BB %d)", arc
->dst
->id
);
2418 fnotice (gcov_file
, "\n");
2420 else if (flag_unconditional
&& !arc
->dst
->is_call_return
)
2422 if (arc
->src
->count
)
2423 fnotice (gcov_file
, "unconditional %2d taken %s\n", ix
,
2424 format_gcov (arc
->count
, arc
->src
->count
, -flag_counts
));
2426 fnotice (gcov_file
, "unconditional %2d never executed\n", ix
);
2434 read_line (FILE *file
)
2436 static char *string
;
2437 static size_t string_len
;
2444 string
= XNEWVEC (char, string_len
);
2447 while ((ptr
= fgets (string
+ pos
, string_len
- pos
, file
)))
2449 size_t len
= strlen (string
+ pos
);
2451 if (len
&& string
[pos
+ len
- 1] == '\n')
2453 string
[pos
+ len
- 1] = 0;
2457 /* If the file contains NUL characters or an incomplete
2458 last line, which can happen more than once in one run,
2459 we have to avoid doubling the STRING_LEN unnecessarily. */
2460 if (pos
> string_len
/ 2)
2463 string
= XRESIZEVEC (char, string
, string_len
);
2467 return pos
? string
: NULL
;
2470 /* Pad string S with spaces from left to have total width equal to 9. */
2473 pad_count_string (string
&s
)
2476 s
.insert (0, 9 - s
.size (), ' ');
2479 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2480 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2481 an exceptional statement. The output is printed for LINE_NUM of given
2482 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2483 used to indicate non-executed blocks. */
2486 output_line_beginning (FILE *f
, bool exists
, bool unexceptional
,
2487 bool has_unexecuted_block
,
2488 gcov_type count
, unsigned line_num
,
2489 const char *exceptional_string
,
2490 const char *unexceptional_string
)
2497 s
= format_gcov (count
, 0, -1);
2498 if (has_unexecuted_block
)
2500 if (flag_use_colors
)
2502 pad_count_string (s
);
2503 s
= SGR_SEQ (COLOR_BG_MAGENTA COLOR_SEPARATOR COLOR_FG_WHITE
);
2509 pad_count_string (s
);
2513 if (flag_use_colors
)
2516 pad_count_string (s
);
2518 s
.insert (0, SGR_SEQ (COLOR_BG_RED
2519 COLOR_SEPARATOR COLOR_FG_WHITE
));
2521 s
.insert (0, SGR_SEQ (COLOR_BG_CYAN
2522 COLOR_SEPARATOR COLOR_FG_WHITE
));
2527 s
= unexceptional
? unexceptional_string
: exceptional_string
;
2528 pad_count_string (s
);
2535 pad_count_string (s
);
2538 fprintf (f
, "%s:%5u", s
.c_str (), line_num
);
2541 /* Read in the source file one line at a time, and output that line to
2542 the gcov file preceded by its execution count and other
2546 output_lines (FILE *gcov_file
, const source_info
*src
)
2548 #define DEFAULT_LINE_START " -: 0:"
2551 unsigned line_num
; /* current line number. */
2552 const line_info
*line
; /* current line info ptr. */
2553 const char *retval
= ""; /* status of source file reading. */
2554 function_t
*fn
= NULL
;
2556 fprintf (gcov_file
, DEFAULT_LINE_START
"Source:%s\n", src
->coverage
.name
);
2557 if (!multiple_files
)
2559 fprintf (gcov_file
, DEFAULT_LINE_START
"Graph:%s\n", bbg_file_name
);
2560 fprintf (gcov_file
, DEFAULT_LINE_START
"Data:%s\n",
2561 no_data_file
? "-" : da_file_name
);
2562 fprintf (gcov_file
, DEFAULT_LINE_START
"Runs:%u\n", object_runs
);
2564 fprintf (gcov_file
, DEFAULT_LINE_START
"Programs:%u\n", program_count
);
2566 source_file
= fopen (src
->name
, "r");
2569 fnotice (stderr
, "Cannot open source file %s\n", src
->name
);
2572 else if (src
->file_time
== 0)
2573 fprintf (gcov_file
, DEFAULT_LINE_START
"Source is newer than graph\n");
2576 fn
= src
->functions
;
2578 for (line_num
= 1, line
= &src
->lines
[line_num
];
2579 line_num
< src
->lines
.size (); line_num
++, line
++)
2581 for (; fn
&& fn
->line
== line_num
; fn
= fn
->next_file_fn
)
2583 arc_t
*arc
= fn
->blocks
[EXIT_BLOCK
].pred
;
2584 gcov_type return_count
= fn
->blocks
[EXIT_BLOCK
].count
;
2585 gcov_type called_count
= fn
->blocks
[ENTRY_BLOCK
].count
;
2587 for (; arc
; arc
= arc
->pred_next
)
2589 return_count
-= arc
->count
;
2591 fprintf (gcov_file
, "function %s", flag_demangled_names
?
2592 fn
->demangled_name
: fn
->name
);
2593 fprintf (gcov_file
, " called %s",
2594 format_gcov (called_count
, 0, -1));
2595 fprintf (gcov_file
, " returned %s",
2596 format_gcov (return_count
, called_count
, 0));
2597 fprintf (gcov_file
, " blocks executed %s",
2598 format_gcov (fn
->blocks_executed
, fn
->blocks
.size () - 2,
2600 fprintf (gcov_file
, "\n");
2604 retval
= read_line (source_file
);
2606 /* For lines which don't exist in the .bb file, print '-' before
2607 the source line. For lines which exist but were never
2608 executed, print '#####' or '=====' before the source line.
2609 Otherwise, print the execution count before the source line.
2610 There are 16 spaces of indentation added before the source
2611 line so that tabs won't be messed up. */
2612 output_line_beginning (gcov_file
, line
->exists
, line
->unexceptional
,
2613 line
->has_unexecuted_block
, line
->count
, line_num
,
2615 fprintf (gcov_file
, ":%s\n", retval
? retval
: "/*EOF*/");
2617 if (flag_all_blocks
)
2623 for (vector
<block_t
*>::const_iterator it
= line
->blocks
.begin ();
2624 it
!= line
->blocks
.end (); it
++)
2626 if (!(*it
)->is_call_return
)
2628 output_line_beginning (gcov_file
, line
->exists
,
2629 (*it
)->exceptional
, false,
2630 (*it
)->count
, line_num
,
2632 fprintf (gcov_file
, "-block %2d", ix
++);
2634 fprintf (gcov_file
, " (BB %u)", (*it
)->id
);
2635 fprintf (gcov_file
, "\n");
2638 for (arc
= (*it
)->succ
; arc
; arc
= arc
->succ_next
)
2639 jx
+= output_branch_count (gcov_file
, jx
, arc
);
2642 else if (flag_branches
)
2647 for (vector
<arc_t
*>::const_iterator it
= line
->branches
.begin ();
2648 it
!= line
->branches
.end (); it
++)
2649 ix
+= output_branch_count (gcov_file
, ix
, (*it
));
2653 /* Handle all remaining source lines. There may be lines after the
2654 last line of code. */
2657 for (; (retval
= read_line (source_file
)); line_num
++)
2658 fprintf (gcov_file
, "%9s:%5u:%s\n", "-", line_num
, retval
);
2662 fclose (source_file
);