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 summary info for each function. */
436 static int flag_function_summary
= 0;
438 /* Object directory file prefix. This is the directory/file where the
439 graph and data files are looked for, if nonzero. */
441 static char *object_directory
= 0;
443 /* Source directory prefix. This is removed from source pathnames
444 that match, when generating the output file name. */
446 static char *source_prefix
= 0;
447 static size_t source_length
= 0;
449 /* Only show data for sources with relative pathnames. Absolute ones
450 usually indicate a system header file, which although it may
451 contain inline functions, is usually uninteresting. */
452 static int flag_relative_only
= 0;
454 /* Preserve all pathname components. Needed when object files and
455 source files are in subdirectories. '/' is mangled as '#', '.' is
456 elided and '..' mangled to '^'. */
458 static int flag_preserve_paths
= 0;
460 /* Output the number of times a branch was taken as opposed to the percentage
461 of times it was taken. */
463 static int flag_counts
= 0;
465 /* Forward declarations. */
466 static int process_args (int, char **);
467 static void print_usage (int) ATTRIBUTE_NORETURN
;
468 static void print_version (void) ATTRIBUTE_NORETURN
;
469 static void process_file (const char *);
470 static void generate_results (const char *);
471 static void create_file_names (const char *);
472 static char *canonicalize_name (const char *);
473 static unsigned find_source (const char *);
474 static function_t
*read_graph_file (void);
475 static int read_count_file (function_t
*);
476 static void solve_flow_graph (function_t
*);
477 static void find_exception_blocks (function_t
*);
478 static void add_branch_counts (coverage_t
*, const arc_t
*);
479 static void add_line_counts (coverage_t
*, function_t
*);
480 static void executed_summary (unsigned, unsigned);
481 static void function_summary (const coverage_t
*, const char *);
482 static const char *format_gcov (gcov_type
, gcov_type
, int);
483 static void accumulate_line_counts (source_info
*);
484 static void output_gcov_file (const char *, source_info
*);
485 static int output_branch_count (FILE *, int, const arc_t
*);
486 static void output_lines (FILE *, const source_info
*);
487 static char *make_gcov_file_name (const char *, const char *);
488 static char *mangle_name (const char *, char *);
489 static void release_structures (void);
490 extern int main (int, char **);
492 function_info::function_info (): name (NULL
), demangled_name (NULL
),
493 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
494 blocks (), blocks_executed (0), counts (NULL
), num_counts (0),
495 line (0), src (0), next_file_fn (NULL
), next (NULL
)
499 function_info::~function_info ()
501 for (int i
= blocks
.size () - 1; i
>= 0; i
--)
505 for (arc
= blocks
[i
].succ
; arc
; arc
= arc_n
)
507 arc_n
= arc
->succ_next
;
512 if (flag_demangled_names
&& demangled_name
!= name
)
513 free (demangled_name
);
518 There are a bajillion algorithms that do this. Boost's function is named
519 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
520 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
521 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
523 The basic algorithm is simple: effectively, we're finding all simple paths
524 in a subgraph (that shrinks every iteration). Duplicates are filtered by
525 "blocking" a path when a node is added to the path (this also prevents non-
526 simple paths)--the node is unblocked only when it participates in a cycle.
529 typedef vector
<arc_t
*> arc_vector_t
;
530 typedef vector
<const block_t
*> block_vector_t
;
532 /* Enum with types of loop in CFG. */
541 /* Loop_type operator that merges two values: A and B. */
543 inline loop_type
& operator |= (loop_type
& a
, loop_type b
)
545 return a
= static_cast<loop_type
> (a
| b
);
548 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
549 and subtract the value from all counts. The subtracted value is added
550 to COUNT. Returns type of loop. */
553 handle_cycle (const arc_vector_t
&edges
, int64_t &count
)
555 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
557 int64_t cycle_count
= INTTYPE_MAXIMUM (int64_t);
558 for (unsigned i
= 0; i
< edges
.size (); i
++)
560 int64_t ecount
= edges
[i
]->cs_count
;
561 if (cycle_count
> ecount
)
562 cycle_count
= ecount
;
564 count
+= cycle_count
;
565 for (unsigned i
= 0; i
< edges
.size (); i
++)
566 edges
[i
]->cs_count
-= cycle_count
;
568 return cycle_count
< 0 ? NEGATIVE_LOOP
: LOOP
;
571 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
572 blocked by U in BLOCK_LISTS. */
575 unblock (const block_t
*u
, block_vector_t
&blocked
,
576 vector
<block_vector_t
> &block_lists
)
578 block_vector_t::iterator it
= find (blocked
.begin (), blocked
.end (), u
);
579 if (it
== blocked
.end ())
582 unsigned index
= it
- blocked
.begin ();
585 block_vector_t
to_unblock (block_lists
[index
]);
587 block_lists
.erase (block_lists
.begin () + index
);
589 for (block_vector_t::iterator it
= to_unblock
.begin ();
590 it
!= to_unblock
.end (); it
++)
591 unblock (*it
, blocked
, block_lists
);
594 /* Find circuit going to block V, PATH is provisional seen cycle.
595 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
596 blocked by a block. COUNT is accumulated count of the current LINE.
597 Returns what type of loop it contains. */
600 circuit (block_t
*v
, arc_vector_t
&path
, block_t
*start
,
601 block_vector_t
&blocked
, vector
<block_vector_t
> &block_lists
,
602 line_info
&linfo
, int64_t &count
)
604 loop_type result
= NO_LOOP
;
606 /* Add v to the block list. */
607 gcc_assert (find (blocked
.begin (), blocked
.end (), v
) == blocked
.end ());
608 blocked
.push_back (v
);
609 block_lists
.push_back (block_vector_t ());
611 for (arc_t
*arc
= v
->succ
; arc
; arc
= arc
->succ_next
)
613 block_t
*w
= arc
->dst
;
614 if (w
< start
|| !linfo
.has_block (w
))
617 path
.push_back (arc
);
619 /* Cycle has been found. */
620 result
|= handle_cycle (path
, count
);
621 else if (find (blocked
.begin (), blocked
.end (), w
) == blocked
.end ())
622 result
|= circuit (w
, path
, start
, blocked
, block_lists
, linfo
, count
);
627 if (result
!= NO_LOOP
)
628 unblock (v
, blocked
, block_lists
);
630 for (arc_t
*arc
= v
->succ
; arc
; arc
= arc
->succ_next
)
632 block_t
*w
= arc
->dst
;
633 if (w
< start
|| !linfo
.has_block (w
))
637 = find (blocked
.begin (), blocked
.end (), w
) - blocked
.begin ();
638 gcc_assert (index
< blocked
.size ());
639 block_vector_t
&list
= block_lists
[index
];
640 if (find (list
.begin (), list
.end (), v
) == list
.end ())
647 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
648 contains a negative loop, then perform the same function once again. */
651 get_cycles_count (line_info
&linfo
, bool handle_negative_cycles
= true)
653 /* Note that this algorithm works even if blocks aren't in sorted order.
654 Each iteration of the circuit detection is completely independent
655 (except for reducing counts, but that shouldn't matter anyways).
656 Therefore, operating on a permuted order (i.e., non-sorted) only
657 has the effect of permuting the output cycles. */
659 loop_type result
= NO_LOOP
;
661 for (vector
<block_t
*>::iterator it
= linfo
.blocks
.begin ();
662 it
!= linfo
.blocks
.end (); it
++)
665 block_vector_t blocked
;
666 vector
<block_vector_t
> block_lists
;
667 result
|= circuit (*it
, path
, *it
, blocked
, block_lists
, linfo
,
671 /* If we have a negative cycle, repeat the find_cycles routine. */
672 if (result
== NEGATIVE_LOOP
&& handle_negative_cycles
)
673 count
+= get_cycles_count (linfo
, false);
679 main (int argc
, char **argv
)
685 p
= argv
[0] + strlen (argv
[0]);
686 while (p
!= argv
[0] && !IS_DIR_SEPARATOR (p
[-1]))
690 xmalloc_set_program_name (progname
);
692 /* Unlock the stdio streams. */
693 unlock_std_streams ();
697 diagnostic_initialize (global_dc
, 0);
699 /* Handle response files. */
700 expandargv (&argc
, &argv
);
702 argno
= process_args (argc
, argv
);
706 if (argc
- argno
> 1)
711 for (; argno
!= argc
; argno
++)
713 if (flag_display_progress
)
714 printf ("Processing file %d out of %d\n", argno
- first_arg
+ 1,
716 process_file (argv
[argno
]);
719 generate_results (multiple_files
? NULL
: argv
[argc
- 1]);
721 release_structures ();
726 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
727 otherwise the output of --help. */
730 print_usage (int error_p
)
732 FILE *file
= error_p
? stderr
: stdout
;
733 int status
= error_p
? FATAL_EXIT_CODE
: SUCCESS_EXIT_CODE
;
735 fnotice (file
, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
736 fnotice (file
, "Print code coverage information.\n\n");
737 fnotice (file
, " -a, --all-blocks Show information for every basic block\n");
738 fnotice (file
, " -b, --branch-probabilities Include branch probabilities in output\n");
739 fnotice (file
, " -c, --branch-counts Output counts of branches taken\n\
740 rather than percentages\n");
741 fnotice (file
, " -d, --display-progress Display progress information\n");
742 fnotice (file
, " -f, --function-summaries Output summaries for each function\n");
743 fnotice (file
, " -h, --help Print this help, then exit\n");
744 fnotice (file
, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
745 fnotice (file
, " -k, --use-colors Emit colored output\n");
746 fnotice (file
, " -l, --long-file-names Use long output file names for included\n\
748 fnotice (file
, " -m, --demangled-names Output demangled function names\n");
749 fnotice (file
, " -n, --no-output Do not create an output file\n");
750 fnotice (file
, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
751 fnotice (file
, " -p, --preserve-paths Preserve all pathname components\n");
752 fnotice (file
, " -r, --relative-only Only show data for relative sources\n");
753 fnotice (file
, " -s, --source-prefix DIR Source prefix to elide\n");
754 fnotice (file
, " -u, --unconditional-branches Show unconditional branch counts too\n");
755 fnotice (file
, " -v, --version Print version number, then exit\n");
756 fnotice (file
, " -w, --verbose Print verbose informations\n");
757 fnotice (file
, " -x, --hash-filenames Hash long pathnames\n");
758 fnotice (file
, "\nFor bug reporting instructions, please see:\n%s.\n",
763 /* Print version information and exit. */
768 fnotice (stdout
, "gcov %s%s\n", pkgversion_string
, version_string
);
769 fprintf (stdout
, "Copyright %s 2017 Free Software Foundation, Inc.\n",
772 _("This is free software; see the source for copying conditions.\n"
773 "There is NO warranty; not even for MERCHANTABILITY or \n"
774 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
775 exit (SUCCESS_EXIT_CODE
);
778 static const struct option options
[] =
780 { "help", no_argument
, NULL
, 'h' },
781 { "version", no_argument
, NULL
, 'v' },
782 { "verbose", no_argument
, NULL
, 'w' },
783 { "all-blocks", no_argument
, NULL
, 'a' },
784 { "branch-probabilities", no_argument
, NULL
, 'b' },
785 { "branch-counts", no_argument
, NULL
, 'c' },
786 { "intermediate-format", no_argument
, NULL
, 'i' },
787 { "no-output", no_argument
, NULL
, 'n' },
788 { "long-file-names", no_argument
, NULL
, 'l' },
789 { "function-summaries", no_argument
, NULL
, 'f' },
790 { "demangled-names", no_argument
, NULL
, 'm' },
791 { "preserve-paths", no_argument
, NULL
, 'p' },
792 { "relative-only", no_argument
, NULL
, 'r' },
793 { "object-directory", required_argument
, NULL
, 'o' },
794 { "object-file", required_argument
, NULL
, 'o' },
795 { "source-prefix", required_argument
, NULL
, 's' },
796 { "unconditional-branches", no_argument
, NULL
, 'u' },
797 { "display-progress", no_argument
, NULL
, 'd' },
798 { "hash-filenames", no_argument
, NULL
, 'x' },
799 { "use-colors", no_argument
, NULL
, 'k' },
803 /* Process args, return index to first non-arg. */
806 process_args (int argc
, char **argv
)
810 const char *opts
= "abcdfhiklmno:prs:uvwx";
811 while ((opt
= getopt_long (argc
, argv
, opts
, options
, NULL
)) != -1)
825 flag_function_summary
= 1;
829 /* print_usage will exit. */
837 flag_demangled_names
= 1;
843 object_directory
= optarg
;
846 source_prefix
= optarg
;
847 source_length
= strlen (source_prefix
);
850 flag_relative_only
= 1;
853 flag_preserve_paths
= 1;
856 flag_unconditional
= 1;
859 flag_intermediate_format
= 1;
863 flag_display_progress
= 1;
866 flag_hash_filenames
= 1;
873 /* print_version will exit. */
876 /* print_usage will exit. */
883 /* Output the result in intermediate format used by 'lcov'.
885 The intermediate format contains a single file named 'foo.cc.gcov',
886 with no source code included.
888 The default gcov outputs multiple files: 'foo.cc.gcov',
889 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
890 included. Instead the intermediate format here outputs only a single
891 file 'foo.cc.gcov' similar to the above example. */
894 output_intermediate_file (FILE *gcov_file
, source_info
*src
)
896 unsigned line_num
; /* current line number. */
897 const line_info
*line
; /* current line info ptr. */
898 function_t
*fn
; /* current function info ptr. */
900 fprintf (gcov_file
, "file:%s\n", src
->name
); /* source file name */
902 for (fn
= src
->functions
; fn
; fn
= fn
->next_file_fn
)
904 /* function:<name>,<line_number>,<execution_count> */
905 fprintf (gcov_file
, "function:%d,%s,%s\n", fn
->line
,
906 format_gcov (fn
->blocks
[0].count
, 0, -1),
907 flag_demangled_names
? fn
->demangled_name
: fn
->name
);
910 for (line_num
= 1, line
= &src
->lines
[line_num
];
911 line_num
< src
->lines
.size ();
915 fprintf (gcov_file
, "lcount:%u,%s,%d\n", line_num
,
916 format_gcov (line
->count
, 0, -1), line
->has_unexecuted_block
);
918 for (vector
<arc_t
*>::const_iterator it
= line
->branches
.begin ();
919 it
!= line
->branches
.end (); it
++)
921 if (!(*it
)->is_unconditional
&& !(*it
)->is_call_non_return
)
923 const char *branch_type
;
924 /* branch:<line_num>,<branch_coverage_type>
926 : notexec (Branch not executed)
927 : taken (Branch executed and taken)
928 : nottaken (Branch executed, but not taken)
930 if ((*it
)->src
->count
)
931 branch_type
= ((*it
)->count
> 0) ? "taken" : "nottaken";
933 branch_type
= "notexec";
934 fprintf (gcov_file
, "branch:%d,%s\n", line_num
, branch_type
);
940 /* Process a single input file. */
943 process_file (const char *file_name
)
947 create_file_names (file_name
);
948 fns
= read_graph_file ();
952 read_count_file (fns
);
955 function_t
*fn
= fns
;
959 if (fn
->counts
|| no_data_file
)
961 unsigned src
= fn
->src
;
962 unsigned line
= fn
->line
;
964 function_t
*probe
, **prev
;
966 /* Now insert it into the source file's list of
967 functions. Normally functions will be encountered in
968 ascending order, so a simple scan is quick. Note we're
969 building this list in reverse order. */
970 for (prev
= &sources
[src
].functions
;
971 (probe
= *prev
); prev
= &probe
->next_file_fn
)
972 if (probe
->line
<= line
)
974 fn
->next_file_fn
= probe
;
977 /* Mark last line in files touched by function. */
978 for (block_no
= 0; block_no
!= fn
->blocks
.size (); block_no
++)
980 block_t
*block
= &fn
->blocks
[block_no
];
981 for (unsigned i
= 0; i
< block
->locations
.size (); i
++)
983 unsigned s
= block
->locations
[i
].source_file_idx
;
985 /* Sort lines of locations. */
986 sort (block
->locations
[i
].lines
.begin (),
987 block
->locations
[i
].lines
.end ());
989 if (!block
->locations
[i
].lines
.empty ())
992 = block
->locations
[i
].lines
.back () + 1;
993 if (last_line
> sources
[s
].lines
.size ())
994 sources
[s
].lines
.resize (last_line
);
999 solve_flow_graph (fn
);
1001 find_exception_blocks (fn
);
1006 /* The function was not in the executable -- some other
1007 instance must have been selected. */
1013 output_gcov_file (const char *file_name
, source_info
*src
)
1015 char *gcov_file_name
= make_gcov_file_name (file_name
, src
->coverage
.name
);
1017 if (src
->coverage
.lines
)
1019 FILE *gcov_file
= fopen (gcov_file_name
, "w");
1022 fnotice (stdout
, "Creating '%s'\n", gcov_file_name
);
1024 if (flag_intermediate_format
)
1025 output_intermediate_file (gcov_file
, src
);
1027 output_lines (gcov_file
, src
);
1028 if (ferror (gcov_file
))
1029 fnotice (stderr
, "Error writing output file '%s'\n", gcov_file_name
);
1033 fnotice (stderr
, "Could not open output file '%s'\n", gcov_file_name
);
1037 unlink (gcov_file_name
);
1038 fnotice (stdout
, "Removing '%s'\n", gcov_file_name
);
1040 free (gcov_file_name
);
1044 generate_results (const char *file_name
)
1048 for (fn
= functions
; fn
; fn
= fn
->next
)
1050 coverage_t coverage
;
1052 memset (&coverage
, 0, sizeof (coverage
));
1053 coverage
.name
= flag_demangled_names
? fn
->demangled_name
: fn
->name
;
1054 add_line_counts (flag_function_summary
? &coverage
: NULL
, fn
);
1055 if (flag_function_summary
)
1057 function_summary (&coverage
, "Function");
1058 fnotice (stdout
, "\n");
1066 needle
.name
= file_name
;
1067 vector
<name_map
>::iterator it
= std::find (names
.begin (), names
.end (),
1069 if (it
!= names
.end ())
1070 file_name
= sources
[it
->src
].coverage
.name
;
1072 file_name
= canonicalize_name (file_name
);
1075 for (vector
<source_info
>::iterator it
= sources
.begin ();
1076 it
!= sources
.end (); it
++)
1078 source_info
*src
= &(*it
);
1079 if (flag_relative_only
)
1081 /* Ignore this source, if it is an absolute path (after
1082 source prefix removal). */
1083 char first
= src
->coverage
.name
[0];
1085 #if HAVE_DOS_BASED_FILE_SYSTEM
1086 if (first
&& src
->coverage
.name
[1] == ':')
1087 first
= src
->coverage
.name
[2];
1089 if (IS_DIR_SEPARATOR (first
))
1093 accumulate_line_counts (src
);
1094 function_summary (&src
->coverage
, "File");
1095 total_lines
+= src
->coverage
.lines
;
1096 total_executed
+= src
->coverage
.lines_executed
;
1099 output_gcov_file (file_name
, src
);
1100 fnotice (stdout
, "\n");
1105 executed_summary (total_lines
, total_executed
);
1108 /* Release all memory used. */
1111 release_structures (void)
1115 while ((fn
= functions
))
1117 functions
= fn
->next
;
1122 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1123 is not specified, these are named from FILE_NAME sans extension. If
1124 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1125 directory, but named from the basename of the FILE_NAME, sans extension.
1126 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1127 and the data files are named from that. */
1130 create_file_names (const char *file_name
)
1134 int length
= strlen (file_name
);
1137 /* Free previous file names. */
1138 free (bbg_file_name
);
1139 free (da_file_name
);
1140 da_file_name
= bbg_file_name
= NULL
;
1144 if (object_directory
&& object_directory
[0])
1148 length
+= strlen (object_directory
) + 2;
1149 name
= XNEWVEC (char, length
);
1152 base
= !stat (object_directory
, &status
) && S_ISDIR (status
.st_mode
);
1153 strcat (name
, object_directory
);
1154 if (base
&& (!IS_DIR_SEPARATOR (name
[strlen (name
) - 1])))
1159 name
= XNEWVEC (char, length
+ 1);
1160 strcpy (name
, file_name
);
1166 /* Append source file name. */
1167 const char *cptr
= lbasename (file_name
);
1168 strcat (name
, cptr
? cptr
: file_name
);
1171 /* Remove the extension. */
1172 cptr
= strrchr (CONST_CAST (char *, lbasename (name
)), '.');
1176 length
= strlen (name
);
1178 bbg_file_name
= XNEWVEC (char, length
+ strlen (GCOV_NOTE_SUFFIX
) + 1);
1179 strcpy (bbg_file_name
, name
);
1180 strcpy (bbg_file_name
+ length
, GCOV_NOTE_SUFFIX
);
1182 da_file_name
= XNEWVEC (char, length
+ strlen (GCOV_DATA_SUFFIX
) + 1);
1183 strcpy (da_file_name
, name
);
1184 strcpy (da_file_name
+ length
, GCOV_DATA_SUFFIX
);
1190 /* Find or create a source file structure for FILE_NAME. Copies
1191 FILE_NAME on creation */
1194 find_source (const char *file_name
)
1201 file_name
= "<unknown>";
1204 needle
.name
= file_name
;
1206 vector
<name_map
>::iterator it
= std::find (names
.begin (), names
.end (),
1208 if (it
!= names
.end ())
1214 /* Not found, try the canonical name. */
1215 canon
= canonicalize_name (file_name
);
1216 needle
.name
= canon
;
1217 it
= std::find (names
.begin (), names
.end (), needle
);
1218 if (it
== names
.end ())
1220 /* Not found with canonical name, create a new source. */
1223 idx
= sources
.size ();
1224 needle
= name_map (canon
, idx
);
1225 names
.push_back (needle
);
1227 sources
.push_back (source_info ());
1228 src
= &sources
.back ();
1230 src
->coverage
.name
= src
->name
;
1232 #if HAVE_DOS_BASED_FILE_SYSTEM
1233 /* You lose if separators don't match exactly in the
1235 && !strncasecmp (source_prefix
, src
->coverage
.name
, source_length
)
1237 && !strncmp (source_prefix
, src
->coverage
.name
, source_length
)
1239 && IS_DIR_SEPARATOR (src
->coverage
.name
[source_length
]))
1240 src
->coverage
.name
+= source_length
+ 1;
1241 if (!stat (src
->name
, &status
))
1242 src
->file_time
= status
.st_mtime
;
1247 needle
.name
= file_name
;
1248 if (std::find (names
.begin (), names
.end (), needle
) == names
.end ())
1250 /* Append the non-canonical name. */
1251 names
.push_back (name_map (xstrdup (file_name
), idx
));
1254 /* Resort the name map. */
1255 std::sort (names
.begin (), names
.end ());
1258 if (sources
[idx
].file_time
> bbg_file_time
)
1260 static int info_emitted
;
1262 fnotice (stderr
, "%s:source file is newer than notes file '%s'\n",
1263 file_name
, bbg_file_name
);
1267 "(the message is displayed only once per source file)\n");
1270 sources
[idx
].file_time
= 0;
1276 /* Read the notes file. Return list of functions read -- in reverse order. */
1279 read_graph_file (void)
1282 unsigned current_tag
= 0;
1283 function_t
*fn
= NULL
;
1284 function_t
*fns
= NULL
;
1285 function_t
**fns_end
= &fns
;
1288 if (!gcov_open (bbg_file_name
, 1))
1290 fnotice (stderr
, "%s:cannot open notes file\n", bbg_file_name
);
1293 bbg_file_time
= gcov_time ();
1294 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC
))
1296 fnotice (stderr
, "%s:not a gcov notes file\n", bbg_file_name
);
1301 version
= gcov_read_unsigned ();
1302 if (version
!= GCOV_VERSION
)
1306 GCOV_UNSIGNED2STRING (v
, version
);
1307 GCOV_UNSIGNED2STRING (e
, GCOV_VERSION
);
1309 fnotice (stderr
, "%s:version '%.4s', prefer '%.4s'\n",
1310 bbg_file_name
, v
, e
);
1312 bbg_stamp
= gcov_read_unsigned ();
1314 while ((tag
= gcov_read_unsigned ()))
1316 unsigned length
= gcov_read_unsigned ();
1317 gcov_position_t base
= gcov_position ();
1319 if (tag
== GCOV_TAG_FUNCTION
)
1321 char *function_name
;
1322 unsigned ident
, lineno
;
1323 unsigned lineno_checksum
, cfg_checksum
;
1325 ident
= gcov_read_unsigned ();
1326 lineno_checksum
= gcov_read_unsigned ();
1327 cfg_checksum
= gcov_read_unsigned ();
1328 function_name
= xstrdup (gcov_read_string ());
1329 unsigned src_idx
= find_source (gcov_read_string ());
1330 lineno
= gcov_read_unsigned ();
1332 fn
= new function_t
;
1333 fn
->name
= function_name
;
1334 if (flag_demangled_names
)
1336 fn
->demangled_name
= cplus_demangle (fn
->name
, DMGL_PARAMS
);
1337 if (!fn
->demangled_name
)
1338 fn
->demangled_name
= fn
->name
;
1341 fn
->lineno_checksum
= lineno_checksum
;
1342 fn
->cfg_checksum
= cfg_checksum
;
1346 fn
->next_file_fn
= NULL
;
1349 fns_end
= &fn
->next
;
1352 else if (fn
&& tag
== GCOV_TAG_BLOCKS
)
1354 if (!fn
->blocks
.empty ())
1355 fnotice (stderr
, "%s:already seen blocks for '%s'\n",
1356 bbg_file_name
, fn
->name
);
1358 fn
->blocks
.resize (gcov_read_unsigned ());
1360 else if (fn
&& tag
== GCOV_TAG_ARCS
)
1362 unsigned src
= gcov_read_unsigned ();
1363 fn
->blocks
[src
].id
= src
;
1364 unsigned num_dests
= GCOV_TAG_ARCS_NUM (length
);
1365 block_t
*src_blk
= &fn
->blocks
[src
];
1366 unsigned mark_catches
= 0;
1367 struct arc_info
*arc
;
1369 if (src
>= fn
->blocks
.size () || fn
->blocks
[src
].succ
)
1374 unsigned dest
= gcov_read_unsigned ();
1375 unsigned flags
= gcov_read_unsigned ();
1377 if (dest
>= fn
->blocks
.size ())
1379 arc
= XCNEW (arc_t
);
1381 arc
->dst
= &fn
->blocks
[dest
];
1385 arc
->count_valid
= 0;
1386 arc
->on_tree
= !!(flags
& GCOV_ARC_ON_TREE
);
1387 arc
->fake
= !!(flags
& GCOV_ARC_FAKE
);
1388 arc
->fall_through
= !!(flags
& GCOV_ARC_FALLTHROUGH
);
1390 arc
->succ_next
= src_blk
->succ
;
1391 src_blk
->succ
= arc
;
1392 src_blk
->num_succ
++;
1394 arc
->pred_next
= fn
->blocks
[dest
].pred
;
1395 fn
->blocks
[dest
].pred
= arc
;
1396 fn
->blocks
[dest
].num_pred
++;
1402 /* Exceptional exit from this function, the
1403 source block must be a call. */
1404 fn
->blocks
[src
].is_call_site
= 1;
1405 arc
->is_call_non_return
= 1;
1410 /* Non-local return from a callee of this
1411 function. The destination block is a setjmp. */
1412 arc
->is_nonlocal_return
= 1;
1413 fn
->blocks
[dest
].is_nonlocal_return
= 1;
1423 /* We have a fake exit from this block. The other
1424 non-fall through exits must be to catch handlers.
1425 Mark them as catch arcs. */
1427 for (arc
= src_blk
->succ
; arc
; arc
= arc
->succ_next
)
1428 if (!arc
->fake
&& !arc
->fall_through
)
1435 else if (fn
&& tag
== GCOV_TAG_LINES
)
1437 unsigned blockno
= gcov_read_unsigned ();
1438 block_t
*block
= &fn
->blocks
[blockno
];
1440 if (blockno
>= fn
->blocks
.size ())
1445 unsigned lineno
= gcov_read_unsigned ();
1448 block
->locations
.back ().lines
.push_back (lineno
);
1451 const char *file_name
= gcov_read_string ();
1455 block
->locations
.push_back (block_location_info
1456 (find_source (file_name
)));
1460 else if (current_tag
&& !GCOV_TAG_IS_SUBTAG (current_tag
, tag
))
1465 gcov_sync (base
, length
);
1466 if (gcov_is_error ())
1469 fnotice (stderr
, "%s:corrupted\n", bbg_file_name
);
1476 fnotice (stderr
, "%s:no functions found\n", bbg_file_name
);
1481 /* Reads profiles from the count file and attach to each
1482 function. Return nonzero if fatal error. */
1485 read_count_file (function_t
*fns
)
1490 function_t
*fn
= NULL
;
1493 if (!gcov_open (da_file_name
, 1))
1495 fnotice (stderr
, "%s:cannot open data file, assuming not executed\n",
1500 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC
))
1502 fnotice (stderr
, "%s:not a gcov data file\n", da_file_name
);
1507 version
= gcov_read_unsigned ();
1508 if (version
!= GCOV_VERSION
)
1512 GCOV_UNSIGNED2STRING (v
, version
);
1513 GCOV_UNSIGNED2STRING (e
, GCOV_VERSION
);
1515 fnotice (stderr
, "%s:version '%.4s', prefer version '%.4s'\n",
1516 da_file_name
, v
, e
);
1518 tag
= gcov_read_unsigned ();
1519 if (tag
!= bbg_stamp
)
1521 fnotice (stderr
, "%s:stamp mismatch with notes file\n", da_file_name
);
1525 while ((tag
= gcov_read_unsigned ()))
1527 unsigned length
= gcov_read_unsigned ();
1528 unsigned long base
= gcov_position ();
1530 if (tag
== GCOV_TAG_PROGRAM_SUMMARY
)
1532 struct gcov_summary summary
;
1533 gcov_read_summary (&summary
);
1534 object_runs
+= summary
.ctrs
[GCOV_COUNTER_ARCS
].runs
;
1537 else if (tag
== GCOV_TAG_FUNCTION
&& !length
)
1539 else if (tag
== GCOV_TAG_FUNCTION
&& length
== GCOV_TAG_FUNCTION_LENGTH
)
1542 struct function_info
*fn_n
;
1544 /* Try to find the function in the list. To speed up the
1545 search, first start from the last function found. */
1546 ident
= gcov_read_unsigned ();
1548 for (fn
= fn
? fn
->next
: NULL
; ; fn
= fn
->next
)
1552 else if ((fn
= fn_n
))
1556 fnotice (stderr
, "%s:unknown function '%u'\n",
1557 da_file_name
, ident
);
1560 if (fn
->ident
== ident
)
1566 else if (gcov_read_unsigned () != fn
->lineno_checksum
1567 || gcov_read_unsigned () != fn
->cfg_checksum
)
1570 fnotice (stderr
, "%s:profile mismatch for '%s'\n",
1571 da_file_name
, fn
->name
);
1575 else if (tag
== GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS
) && fn
)
1577 if (length
!= GCOV_TAG_COUNTER_LENGTH (fn
->num_counts
))
1581 fn
->counts
= XCNEWVEC (gcov_type
, fn
->num_counts
);
1583 for (ix
= 0; ix
!= fn
->num_counts
; ix
++)
1584 fn
->counts
[ix
] += gcov_read_counter ();
1586 gcov_sync (base
, length
);
1587 if ((error
= gcov_is_error ()))
1591 ? N_("%s:overflowed\n")
1592 : N_("%s:corrupted\n"),
1602 /* Solve the flow graph. Propagate counts from the instrumented arcs
1603 to the blocks and the uninstrumented arcs. */
1606 solve_flow_graph (function_t
*fn
)
1610 gcov_type
*count_ptr
= fn
->counts
;
1612 block_t
*valid_blocks
= NULL
; /* valid, but unpropagated blocks. */
1613 block_t
*invalid_blocks
= NULL
; /* invalid, but inferable blocks. */
1615 /* The arcs were built in reverse order. Fix that now. */
1616 for (ix
= fn
->blocks
.size (); ix
--;)
1618 arc_t
*arc_p
, *arc_n
;
1620 for (arc_p
= NULL
, arc
= fn
->blocks
[ix
].succ
; arc
;
1621 arc_p
= arc
, arc
= arc_n
)
1623 arc_n
= arc
->succ_next
;
1624 arc
->succ_next
= arc_p
;
1626 fn
->blocks
[ix
].succ
= arc_p
;
1628 for (arc_p
= NULL
, arc
= fn
->blocks
[ix
].pred
; arc
;
1629 arc_p
= arc
, arc
= arc_n
)
1631 arc_n
= arc
->pred_next
;
1632 arc
->pred_next
= arc_p
;
1634 fn
->blocks
[ix
].pred
= arc_p
;
1637 if (fn
->blocks
.size () < 2)
1638 fnotice (stderr
, "%s:'%s' lacks entry and/or exit blocks\n",
1639 bbg_file_name
, fn
->name
);
1642 if (fn
->blocks
[ENTRY_BLOCK
].num_pred
)
1643 fnotice (stderr
, "%s:'%s' has arcs to entry block\n",
1644 bbg_file_name
, fn
->name
);
1646 /* We can't deduce the entry block counts from the lack of
1648 fn
->blocks
[ENTRY_BLOCK
].num_pred
= ~(unsigned)0;
1650 if (fn
->blocks
[EXIT_BLOCK
].num_succ
)
1651 fnotice (stderr
, "%s:'%s' has arcs from exit block\n",
1652 bbg_file_name
, fn
->name
);
1654 /* Likewise, we can't deduce exit block counts from the lack
1655 of its successors. */
1656 fn
->blocks
[EXIT_BLOCK
].num_succ
= ~(unsigned)0;
1659 /* Propagate the measured counts, this must be done in the same
1660 order as the code in profile.c */
1661 for (unsigned i
= 0; i
< fn
->blocks
.size (); i
++)
1663 blk
= &fn
->blocks
[i
];
1664 block_t
const *prev_dst
= NULL
;
1665 int out_of_order
= 0;
1666 int non_fake_succ
= 0;
1668 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1676 arc
->count
= *count_ptr
++;
1677 arc
->count_valid
= 1;
1679 arc
->dst
->num_pred
--;
1681 if (prev_dst
&& prev_dst
> arc
->dst
)
1683 prev_dst
= arc
->dst
;
1685 if (non_fake_succ
== 1)
1687 /* If there is only one non-fake exit, it is an
1688 unconditional branch. */
1689 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1692 arc
->is_unconditional
= 1;
1693 /* If this block is instrumenting a call, it might be
1694 an artificial block. It is not artificial if it has
1695 a non-fallthrough exit, or the destination of this
1696 arc has more than one entry. Mark the destination
1697 block as a return site, if none of those conditions
1699 if (blk
->is_call_site
&& arc
->fall_through
1700 && arc
->dst
->pred
== arc
&& !arc
->pred_next
)
1701 arc
->dst
->is_call_return
= 1;
1705 /* Sort the successor arcs into ascending dst order. profile.c
1706 normally produces arcs in the right order, but sometimes with
1707 one or two out of order. We're not using a particularly
1711 arc_t
*start
= blk
->succ
;
1712 unsigned changes
= 1;
1716 arc_t
*arc
, *arc_p
, *arc_n
;
1719 for (arc_p
= NULL
, arc
= start
; (arc_n
= arc
->succ_next
);)
1721 if (arc
->dst
> arc_n
->dst
)
1725 arc_p
->succ_next
= arc_n
;
1728 arc
->succ_next
= arc_n
->succ_next
;
1729 arc_n
->succ_next
= arc
;
1742 /* Place it on the invalid chain, it will be ignored if that's
1744 blk
->invalid_chain
= 1;
1745 blk
->chain
= invalid_blocks
;
1746 invalid_blocks
= blk
;
1749 while (invalid_blocks
|| valid_blocks
)
1751 while ((blk
= invalid_blocks
))
1753 gcov_type total
= 0;
1756 invalid_blocks
= blk
->chain
;
1757 blk
->invalid_chain
= 0;
1759 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1760 total
+= arc
->count
;
1761 else if (!blk
->num_pred
)
1762 for (arc
= blk
->pred
; arc
; arc
= arc
->pred_next
)
1763 total
+= arc
->count
;
1768 blk
->count_valid
= 1;
1769 blk
->chain
= valid_blocks
;
1770 blk
->valid_chain
= 1;
1773 while ((blk
= valid_blocks
))
1776 arc_t
*arc
, *inv_arc
;
1778 valid_blocks
= blk
->chain
;
1779 blk
->valid_chain
= 0;
1780 if (blk
->num_succ
== 1)
1786 for (arc
= blk
->succ
; arc
; arc
= arc
->succ_next
)
1788 total
-= arc
->count
;
1789 if (!arc
->count_valid
)
1793 inv_arc
->count_valid
= 1;
1794 inv_arc
->count
= total
;
1797 if (dst
->count_valid
)
1799 if (dst
->num_pred
== 1 && !dst
->valid_chain
)
1801 dst
->chain
= valid_blocks
;
1802 dst
->valid_chain
= 1;
1808 if (!dst
->num_pred
&& !dst
->invalid_chain
)
1810 dst
->chain
= invalid_blocks
;
1811 dst
->invalid_chain
= 1;
1812 invalid_blocks
= dst
;
1816 if (blk
->num_pred
== 1)
1822 for (arc
= blk
->pred
; arc
; arc
= arc
->pred_next
)
1824 total
-= arc
->count
;
1825 if (!arc
->count_valid
)
1829 inv_arc
->count_valid
= 1;
1830 inv_arc
->count
= total
;
1833 if (src
->count_valid
)
1835 if (src
->num_succ
== 1 && !src
->valid_chain
)
1837 src
->chain
= valid_blocks
;
1838 src
->valid_chain
= 1;
1844 if (!src
->num_succ
&& !src
->invalid_chain
)
1846 src
->chain
= invalid_blocks
;
1847 src
->invalid_chain
= 1;
1848 invalid_blocks
= src
;
1855 /* If the graph has been correctly solved, every block will have a
1857 for (unsigned i
= 0; ix
< fn
->blocks
.size (); i
++)
1858 if (!fn
->blocks
[i
].count_valid
)
1860 fnotice (stderr
, "%s:graph is unsolvable for '%s'\n",
1861 bbg_file_name
, fn
->name
);
1866 /* Mark all the blocks only reachable via an incoming catch. */
1869 find_exception_blocks (function_t
*fn
)
1872 block_t
**queue
= XALLOCAVEC (block_t
*, fn
->blocks
.size ());
1874 /* First mark all blocks as exceptional. */
1875 for (ix
= fn
->blocks
.size (); ix
--;)
1876 fn
->blocks
[ix
].exceptional
= 1;
1878 /* Now mark all the blocks reachable via non-fake edges */
1879 queue
[0] = &fn
->blocks
[0];
1880 queue
[0]->exceptional
= 0;
1883 block_t
*block
= queue
[--ix
];
1886 for (arc
= block
->succ
; arc
; arc
= arc
->succ_next
)
1887 if (!arc
->fake
&& !arc
->is_throw
&& arc
->dst
->exceptional
)
1889 arc
->dst
->exceptional
= 0;
1890 queue
[ix
++] = arc
->dst
;
1896 /* Increment totals in COVERAGE according to arc ARC. */
1899 add_branch_counts (coverage_t
*coverage
, const arc_t
*arc
)
1901 if (arc
->is_call_non_return
)
1904 if (arc
->src
->count
)
1905 coverage
->calls_executed
++;
1907 else if (!arc
->is_unconditional
)
1909 coverage
->branches
++;
1910 if (arc
->src
->count
)
1911 coverage
->branches_executed
++;
1913 coverage
->branches_taken
++;
1917 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
1918 count. If dp >= 0, format TOP/BOTTOM * 100 to DP decimal places.
1919 If DP is zero, no decimal point is printed. Only print 100% when
1920 TOP==BOTTOM and only print 0% when TOP=0. If dp < 0, then simply
1921 format TOP. Return pointer to a static string. */
1924 format_gcov (gcov_type top
, gcov_type bottom
, int dp
)
1926 static char buffer
[20];
1928 /* Handle invalid values that would result in a misleading value. */
1929 if (bottom
!= 0 && top
> bottom
&& dp
>= 0)
1931 sprintf (buffer
, "NAN %%");
1937 float ratio
= bottom
? (float)top
/ bottom
: 0;
1939 unsigned limit
= 100;
1942 for (ix
= dp
; ix
--; )
1945 percent
= (unsigned) (ratio
* limit
+ (float)0.5);
1946 if (percent
<= 0 && top
)
1948 else if (percent
>= limit
&& top
!= bottom
)
1949 percent
= limit
- 1;
1950 ix
= sprintf (buffer
, "%.*u%%", dp
+ 1, percent
);
1956 buffer
[ix
+1] = buffer
[ix
];
1960 buffer
[ix
+ 1] = '.';
1964 sprintf (buffer
, "%" PRId64
, (int64_t)top
);
1969 /* Summary of execution */
1972 executed_summary (unsigned lines
, unsigned executed
)
1975 fnotice (stdout
, "Lines executed:%s of %d\n",
1976 format_gcov (executed
, lines
, 2), lines
);
1978 fnotice (stdout
, "No executable lines\n");
1981 /* Output summary info for a function or file. */
1984 function_summary (const coverage_t
*coverage
, const char *title
)
1986 fnotice (stdout
, "%s '%s'\n", title
, coverage
->name
);
1987 executed_summary (coverage
->lines
, coverage
->lines_executed
);
1991 if (coverage
->branches
)
1993 fnotice (stdout
, "Branches executed:%s of %d\n",
1994 format_gcov (coverage
->branches_executed
,
1995 coverage
->branches
, 2),
1996 coverage
->branches
);
1997 fnotice (stdout
, "Taken at least once:%s of %d\n",
1998 format_gcov (coverage
->branches_taken
,
1999 coverage
->branches
, 2),
2000 coverage
->branches
);
2003 fnotice (stdout
, "No branches\n");
2004 if (coverage
->calls
)
2005 fnotice (stdout
, "Calls executed:%s of %d\n",
2006 format_gcov (coverage
->calls_executed
, coverage
->calls
, 2),
2009 fnotice (stdout
, "No calls\n");
2013 /* Canonicalize the filename NAME by canonicalizing directory
2014 separators, eliding . components and resolving .. components
2015 appropriately. Always returns a unique string. */
2018 canonicalize_name (const char *name
)
2020 /* The canonical name cannot be longer than the incoming name. */
2021 char *result
= XNEWVEC (char, strlen (name
) + 1);
2022 const char *base
= name
, *probe
;
2027 #if HAVE_DOS_BASED_FILE_SYSTEM
2028 if (base
[0] && base
[1] == ':')
2030 result
[0] = base
[0];
2036 for (dd_base
= ptr
; *base
; base
= probe
)
2040 for (probe
= base
; *probe
; probe
++)
2041 if (IS_DIR_SEPARATOR (*probe
))
2045 if (len
== 1 && base
[0] == '.')
2046 /* Elide a '.' directory */
2048 else if (len
== 2 && base
[0] == '.' && base
[1] == '.')
2050 /* '..', we can only elide it and the previous directory, if
2051 we're not a symlink. */
2052 struct stat ATTRIBUTE_UNUSED buf
;
2056 #if defined (S_ISLNK)
2057 /* S_ISLNK is not POSIX.1-1996. */
2058 || stat (result
, &buf
) || S_ISLNK (buf
.st_mode
)
2062 /* Cannot elide, or unreadable or a symlink. */
2063 dd_base
= ptr
+ 2 + slash
;
2066 while (ptr
!= dd_base
&& *ptr
!= '/')
2068 slash
= ptr
!= result
;
2073 /* Regular pathname component. */
2076 memcpy (ptr
, base
, len
);
2081 for (; IS_DIR_SEPARATOR (*probe
); probe
++)
2089 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2092 md5sum_to_hex (const char *sum
, char *buffer
)
2094 for (unsigned i
= 0; i
< 16; i
++)
2095 sprintf (buffer
+ (2 * i
), "%02x", (unsigned char)sum
[i
]);
2098 /* Generate an output file name. INPUT_NAME is the canonicalized main
2099 input file and SRC_NAME is the canonicalized file name.
2100 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2101 long_output_names we prepend the processed name of the input file
2102 to each output name (except when the current source file is the
2103 input file, so you don't get a double concatenation). The two
2104 components are separated by '##'. With preserve_paths we create a
2105 filename from all path components of the source file, replacing '/'
2106 with '#', and .. with '^', without it we simply take the basename
2107 component. (Remember, the canonicalized name will already have
2108 elided '.' components and converted \\ separators.) */
2111 make_gcov_file_name (const char *input_name
, const char *src_name
)
2116 if (flag_long_names
&& input_name
&& strcmp (src_name
, input_name
))
2118 /* Generate the input filename part. */
2119 result
= XNEWVEC (char, strlen (input_name
) + strlen (src_name
) + 10);
2122 ptr
= mangle_name (input_name
, ptr
);
2123 ptr
[0] = ptr
[1] = '#';
2128 result
= XNEWVEC (char, strlen (src_name
) + 10);
2132 ptr
= mangle_name (src_name
, ptr
);
2133 strcpy (ptr
, ".gcov");
2135 /* When hashing filenames, we shorten them by only using the filename
2136 component and appending a hash of the full (mangled) pathname. */
2137 if (flag_hash_filenames
)
2141 char md5sum_hex
[33];
2143 md5_init_ctx (&ctx
);
2144 md5_process_bytes (src_name
, strlen (src_name
), &ctx
);
2145 md5_finish_ctx (&ctx
, md5sum
);
2146 md5sum_to_hex (md5sum
, md5sum_hex
);
2149 result
= XNEWVEC (char, strlen (src_name
) + 50);
2151 ptr
= mangle_name (src_name
, ptr
);
2152 ptr
[0] = ptr
[1] = '#';
2154 memcpy (ptr
, md5sum_hex
, 32);
2156 strcpy (ptr
, ".gcov");
2163 mangle_name (char const *base
, char *ptr
)
2167 /* Generate the source filename part. */
2168 if (!flag_preserve_paths
)
2170 base
= lbasename (base
);
2171 len
= strlen (base
);
2172 memcpy (ptr
, base
, len
);
2177 /* Convert '/' to '#', convert '..' to '^',
2178 convert ':' to '~' on DOS based file system. */
2181 #if HAVE_DOS_BASED_FILE_SYSTEM
2182 if (base
[0] && base
[1] == ':')
2190 for (; *base
; base
= probe
)
2194 for (probe
= base
; *probe
; probe
++)
2198 if (len
== 2 && base
[0] == '.' && base
[1] == '.')
2202 memcpy (ptr
, base
, len
);
2216 /* Scan through the bb_data for each line in the block, increment
2217 the line number execution count indicated by the execution count of
2218 the appropriate basic block. */
2221 add_line_counts (coverage_t
*coverage
, function_t
*fn
)
2223 bool has_any_line
= false;
2224 /* Scan each basic block. */
2225 for (unsigned ix
= 0; ix
!= fn
->blocks
.size (); ix
++)
2227 line_info
*line
= NULL
;
2228 block_t
*block
= &fn
->blocks
[ix
];
2229 if (block
->count
&& ix
&& ix
+ 1 != fn
->blocks
.size ())
2230 fn
->blocks_executed
++;
2231 for (unsigned i
= 0; i
< block
->locations
.size (); i
++)
2233 source_info
*src
= &sources
[block
->locations
[i
].source_file_idx
];
2235 vector
<unsigned> &lines
= block
->locations
[i
].lines
;
2236 for (unsigned j
= 0; j
< lines
.size (); j
++)
2238 line
= &src
->lines
[lines
[j
]];
2243 if (!line
->count
&& block
->count
)
2244 coverage
->lines_executed
++;
2247 if (!block
->exceptional
)
2249 line
->unexceptional
= 1;
2250 if (block
->count
== 0)
2251 line
->has_unexecuted_block
= 1;
2253 line
->count
+= block
->count
;
2256 block
->cycle
.arc
= NULL
;
2257 block
->cycle
.ident
= ~0U;
2258 has_any_line
= true;
2260 if (!ix
|| ix
+ 1 == fn
->blocks
.size ())
2261 /* Entry or exit block */;
2262 else if (line
!= NULL
)
2264 line
->blocks
.push_back (block
);
2270 for (arc
= block
->succ
; arc
; arc
= arc
->succ_next
)
2272 line
->branches
.push_back (arc
);
2273 if (coverage
&& !arc
->is_unconditional
)
2274 add_branch_counts (coverage
, arc
);
2281 fnotice (stderr
, "%s:no lines for '%s'\n", bbg_file_name
, fn
->name
);
2284 /* Accumulate the line counts of a file. */
2287 accumulate_line_counts (source_info
*src
)
2289 function_t
*fn
, *fn_p
, *fn_n
;
2292 /* Reverse the function order. */
2293 for (fn
= src
->functions
, fn_p
= NULL
; fn
; fn_p
= fn
, fn
= fn_n
)
2295 fn_n
= fn
->next_file_fn
;
2296 fn
->next_file_fn
= fn_p
;
2298 src
->functions
= fn_p
;
2300 for (vector
<line_info
>::reverse_iterator it
= src
->lines
.rbegin ();
2301 it
!= src
->lines
.rend (); it
++)
2303 line_info
*line
= &(*it
);
2304 if (!line
->blocks
.empty ())
2306 /* The user expects the line count to be the number of times
2307 a line has been executed. Simply summing the block count
2308 will give an artificially high number. The Right Thing
2309 is to sum the entry counts to the graph of blocks on this
2310 line, then find the elementary cycles of the local graph
2311 and add the transition counts of those cycles. */
2312 gcov_type count
= 0;
2314 /* Sum the entry arcs. */
2315 for (vector
<block_t
*>::iterator it
= line
->blocks
.begin ();
2316 it
!= line
->blocks
.end (); it
++)
2320 for (arc
= (*it
)->pred
; arc
; arc
= arc
->pred_next
)
2322 add_branch_counts (&src
->coverage
, arc
);
2325 /* Cycle detection. */
2326 for (vector
<block_t
*>::iterator it
= line
->blocks
.begin ();
2327 it
!= line
->blocks
.end (); it
++)
2329 for (arc_t
*arc
= (*it
)->pred
; arc
; arc
= arc
->pred_next
)
2330 if (!line
->has_block (arc
->src
))
2331 count
+= arc
->count
;
2332 for (arc_t
*arc
= (*it
)->succ
; arc
; arc
= arc
->succ_next
)
2333 arc
->cs_count
= arc
->count
;
2336 /* Now, add the count of loops entirely on this line. */
2337 count
+= get_cycles_count (*line
);
2338 line
->count
= count
;
2343 src
->coverage
.lines
++;
2345 src
->coverage
.lines_executed
++;
2352 /* Output information about ARC number IX. Returns nonzero if
2353 anything is output. */
2356 output_branch_count (FILE *gcov_file
, int ix
, const arc_t
*arc
)
2358 if (arc
->is_call_non_return
)
2360 if (arc
->src
->count
)
2362 fnotice (gcov_file
, "call %2d returned %s\n", ix
,
2363 format_gcov (arc
->src
->count
- arc
->count
,
2364 arc
->src
->count
, -flag_counts
));
2367 fnotice (gcov_file
, "call %2d never executed\n", ix
);
2369 else if (!arc
->is_unconditional
)
2371 if (arc
->src
->count
)
2372 fnotice (gcov_file
, "branch %2d taken %s%s", ix
,
2373 format_gcov (arc
->count
, arc
->src
->count
, -flag_counts
),
2374 arc
->fall_through
? " (fallthrough)"
2375 : arc
->is_throw
? " (throw)" : "");
2377 fnotice (gcov_file
, "branch %2d never executed", ix
);
2380 fnotice (gcov_file
, " (BB %d)", arc
->dst
->id
);
2382 fnotice (gcov_file
, "\n");
2384 else if (flag_unconditional
&& !arc
->dst
->is_call_return
)
2386 if (arc
->src
->count
)
2387 fnotice (gcov_file
, "unconditional %2d taken %s\n", ix
,
2388 format_gcov (arc
->count
, arc
->src
->count
, -flag_counts
));
2390 fnotice (gcov_file
, "unconditional %2d never executed\n", ix
);
2398 read_line (FILE *file
)
2400 static char *string
;
2401 static size_t string_len
;
2408 string
= XNEWVEC (char, string_len
);
2411 while ((ptr
= fgets (string
+ pos
, string_len
- pos
, file
)))
2413 size_t len
= strlen (string
+ pos
);
2415 if (len
&& string
[pos
+ len
- 1] == '\n')
2417 string
[pos
+ len
- 1] = 0;
2421 /* If the file contains NUL characters or an incomplete
2422 last line, which can happen more than once in one run,
2423 we have to avoid doubling the STRING_LEN unnecessarily. */
2424 if (pos
> string_len
/ 2)
2427 string
= XRESIZEVEC (char, string
, string_len
);
2431 return pos
? string
: NULL
;
2434 /* Pad string S with spaces from left to have total width equal to 9. */
2437 pad_count_string (string
&s
)
2440 s
.insert (0, 9 - s
.size (), ' ');
2443 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2444 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2445 an exceptional statement. The output is printed for LINE_NUM of given
2446 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2447 used to indicate non-executed blocks. */
2450 output_line_beginning (FILE *f
, bool exists
, bool unexceptional
,
2451 bool has_unexecuted_block
,
2452 gcov_type count
, unsigned line_num
,
2453 const char *exceptional_string
,
2454 const char *unexceptional_string
)
2461 s
= format_gcov (count
, 0, -1);
2462 if (has_unexecuted_block
)
2464 if (flag_use_colors
)
2466 pad_count_string (s
);
2467 s
= SGR_SEQ (COLOR_BG_MAGENTA COLOR_SEPARATOR COLOR_FG_WHITE
);
2473 pad_count_string (s
);
2477 if (flag_use_colors
)
2480 pad_count_string (s
);
2482 s
.insert (0, SGR_SEQ (COLOR_BG_RED
2483 COLOR_SEPARATOR COLOR_FG_WHITE
));
2485 s
.insert (0, SGR_SEQ (COLOR_BG_CYAN
2486 COLOR_SEPARATOR COLOR_FG_WHITE
));
2491 s
= unexceptional
? unexceptional_string
: exceptional_string
;
2492 pad_count_string (s
);
2499 pad_count_string (s
);
2502 fprintf (f
, "%s:%5u", s
.c_str (), line_num
);
2505 /* Read in the source file one line at a time, and output that line to
2506 the gcov file preceded by its execution count and other
2510 output_lines (FILE *gcov_file
, const source_info
*src
)
2512 #define DEFAULT_LINE_START " -: 0:"
2515 unsigned line_num
; /* current line number. */
2516 const line_info
*line
; /* current line info ptr. */
2517 const char *retval
= ""; /* status of source file reading. */
2518 function_t
*fn
= NULL
;
2520 fprintf (gcov_file
, DEFAULT_LINE_START
"Source:%s\n", src
->coverage
.name
);
2521 if (!multiple_files
)
2523 fprintf (gcov_file
, DEFAULT_LINE_START
"Graph:%s\n", bbg_file_name
);
2524 fprintf (gcov_file
, DEFAULT_LINE_START
"Data:%s\n",
2525 no_data_file
? "-" : da_file_name
);
2526 fprintf (gcov_file
, DEFAULT_LINE_START
"Runs:%u\n", object_runs
);
2528 fprintf (gcov_file
, DEFAULT_LINE_START
"Programs:%u\n", program_count
);
2530 source_file
= fopen (src
->name
, "r");
2533 fnotice (stderr
, "Cannot open source file %s\n", src
->name
);
2536 else if (src
->file_time
== 0)
2537 fprintf (gcov_file
, DEFAULT_LINE_START
"Source is newer than graph\n");
2540 fn
= src
->functions
;
2542 for (line_num
= 1, line
= &src
->lines
[line_num
];
2543 line_num
< src
->lines
.size (); line_num
++, line
++)
2545 for (; fn
&& fn
->line
== line_num
; fn
= fn
->next_file_fn
)
2547 arc_t
*arc
= fn
->blocks
[EXIT_BLOCK
].pred
;
2548 gcov_type return_count
= fn
->blocks
[EXIT_BLOCK
].count
;
2549 gcov_type called_count
= fn
->blocks
[ENTRY_BLOCK
].count
;
2551 for (; arc
; arc
= arc
->pred_next
)
2553 return_count
-= arc
->count
;
2555 fprintf (gcov_file
, "function %s", flag_demangled_names
?
2556 fn
->demangled_name
: fn
->name
);
2557 fprintf (gcov_file
, " called %s",
2558 format_gcov (called_count
, 0, -1));
2559 fprintf (gcov_file
, " returned %s",
2560 format_gcov (return_count
, called_count
, 0));
2561 fprintf (gcov_file
, " blocks executed %s",
2562 format_gcov (fn
->blocks_executed
, fn
->blocks
.size () - 2,
2564 fprintf (gcov_file
, "\n");
2568 retval
= read_line (source_file
);
2570 /* For lines which don't exist in the .bb file, print '-' before
2571 the source line. For lines which exist but were never
2572 executed, print '#####' or '=====' before the source line.
2573 Otherwise, print the execution count before the source line.
2574 There are 16 spaces of indentation added before the source
2575 line so that tabs won't be messed up. */
2576 output_line_beginning (gcov_file
, line
->exists
, line
->unexceptional
,
2577 line
->has_unexecuted_block
, line
->count
, line_num
,
2579 fprintf (gcov_file
, ":%s\n", retval
? retval
: "/*EOF*/");
2581 if (flag_all_blocks
)
2587 for (vector
<block_t
*>::const_iterator it
= line
->blocks
.begin ();
2588 it
!= line
->blocks
.end (); it
++)
2590 if (!(*it
)->is_call_return
)
2592 output_line_beginning (gcov_file
, line
->exists
,
2593 (*it
)->exceptional
, false,
2594 (*it
)->count
, line_num
,
2596 fprintf (gcov_file
, "-block %2d", ix
++);
2598 fprintf (gcov_file
, " (BB %u)", (*it
)->id
);
2599 fprintf (gcov_file
, "\n");
2602 for (arc
= (*it
)->succ
; arc
; arc
= arc
->succ_next
)
2603 jx
+= output_branch_count (gcov_file
, jx
, arc
);
2606 else if (flag_branches
)
2611 for (vector
<arc_t
*>::const_iterator it
= line
->branches
.begin ();
2612 it
!= line
->branches
.end (); it
++)
2613 ix
+= output_branch_count (gcov_file
, ix
, (*it
));
2617 /* Handle all remaining source lines. There may be lines after the
2618 last line of code. */
2621 for (; (retval
= read_line (source_file
)); line_num
++)
2622 fprintf (gcov_file
, "%9s:%5u:%s\n", "-", line_num
, retval
);
2626 fclose (source_file
);