PR rtl-optimization/82913
[official-gcc.git] / gcc / gcov.c
blob846a232619647defb78bde94e2ce546e47f0d474
1 /* Gcov.c: prepend line execution counts and branch probabilities to a
2 source file.
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)
11 any later version.
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. */
33 #include "config.h"
34 #define INCLUDE_ALGORITHM
35 #define INCLUDE_VECTOR
36 #define INCLUDE_STRING
37 #define INCLUDE_MAP
38 #define INCLUDE_SET
39 #include "system.h"
40 #include "coretypes.h"
41 #include "tm.h"
42 #include "intl.h"
43 #include "diagnostic.h"
44 #include "version.h"
45 #include "demangle.h"
46 #include "color-macros.h"
48 #include <getopt.h>
50 #include "md5.h"
52 using namespace std;
54 #define IN_GCOV 1
55 #include "gcov-io.h"
56 #include "gcov-io.c"
58 /* The gcno file is generated by -ftest-coverage option. The gcda file is
59 generated by a program compiled with -fprofile-arcs. Their formats
60 are documented in gcov-io.h. */
62 /* The functions in this file for creating and solution program flow graphs
63 are very similar to functions in the gcc source file profile.c. In
64 some places we make use of the knowledge of how profile.c works to
65 select particular algorithms here. */
67 /* The code validates that the profile information read in corresponds
68 to the code currently being compiled. Rather than checking for
69 identical files, the code below compares a checksum on the CFG
70 (based on the order of basic blocks and the arcs in the CFG). If
71 the CFG checksum in the gcda file match the CFG checksum in the
72 gcno file, the profile data will be used. */
74 /* This is the size of the buffer used to read in source file lines. */
76 struct function_info;
77 struct block_info;
78 struct source_info;
80 /* Describes an arc between two basic blocks. */
82 typedef struct arc_info
84 /* source and destination blocks. */
85 struct block_info *src;
86 struct block_info *dst;
88 /* transition counts. */
89 gcov_type count;
90 /* used in cycle search, so that we do not clobber original counts. */
91 gcov_type cs_count;
93 unsigned int count_valid : 1;
94 unsigned int on_tree : 1;
95 unsigned int fake : 1;
96 unsigned int fall_through : 1;
98 /* Arc to a catch handler. */
99 unsigned int is_throw : 1;
101 /* Arc is for a function that abnormally returns. */
102 unsigned int is_call_non_return : 1;
104 /* Arc is for catch/setjmp. */
105 unsigned int is_nonlocal_return : 1;
107 /* Is an unconditional branch. */
108 unsigned int is_unconditional : 1;
110 /* Loop making arc. */
111 unsigned int cycle : 1;
113 /* Links to next arc on src and dst lists. */
114 struct arc_info *succ_next;
115 struct arc_info *pred_next;
116 } arc_t;
118 /* Describes which locations (lines and files) are associated with
119 a basic block. */
121 struct block_location_info
123 block_location_info (unsigned _source_file_idx):
124 source_file_idx (_source_file_idx)
127 unsigned source_file_idx;
128 vector<unsigned> lines;
131 /* Describes a basic block. Contains lists of arcs to successor and
132 predecessor blocks. */
134 typedef struct block_info
136 /* Constructor. */
137 block_info ();
139 /* Chain of exit and entry arcs. */
140 arc_t *succ;
141 arc_t *pred;
143 /* Number of unprocessed exit and entry arcs. */
144 gcov_type num_succ;
145 gcov_type num_pred;
147 unsigned id;
149 /* Block execution count. */
150 gcov_type count;
151 unsigned count_valid : 1;
152 unsigned valid_chain : 1;
153 unsigned invalid_chain : 1;
154 unsigned exceptional : 1;
156 /* Block is a call instrumenting site. */
157 unsigned is_call_site : 1; /* Does the call. */
158 unsigned is_call_return : 1; /* Is the return. */
160 /* Block is a landing pad for longjmp or throw. */
161 unsigned is_nonlocal_return : 1;
163 vector<block_location_info> locations;
165 struct
167 /* Single line graph cycle workspace. Used for all-blocks
168 mode. */
169 arc_t *arc;
170 unsigned ident;
171 } cycle; /* Used in all-blocks mode, after blocks are linked onto
172 lines. */
174 /* Temporary chain for solving graph, and for chaining blocks on one
175 line. */
176 struct block_info *chain;
178 } block_t;
180 block_info::block_info (): succ (NULL), pred (NULL), num_succ (0), num_pred (0),
181 id (0), count (0), count_valid (0), valid_chain (0), invalid_chain (0),
182 exceptional (0), is_call_site (0), is_call_return (0), is_nonlocal_return (0),
183 locations (), chain (NULL)
185 cycle.arc = NULL;
188 /* Describes a single line of source. Contains a chain of basic blocks
189 with code on it. */
191 struct line_info
193 /* Default constructor. */
194 line_info ();
196 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
197 bool has_block (block_t *needle);
199 /* Execution count. */
200 gcov_type count;
202 /* Branches from blocks that end on this line. */
203 vector<arc_t *> branches;
205 /* blocks which start on this line. Used in all-blocks mode. */
206 vector<block_t *> blocks;
208 unsigned exists : 1;
209 unsigned unexceptional : 1;
210 unsigned has_unexecuted_block : 1;
213 line_info::line_info (): count (0), branches (), blocks (), exists (false),
214 unexceptional (0), has_unexecuted_block (0)
218 bool
219 line_info::has_block (block_t *needle)
221 return std::find (blocks.begin (), blocks.end (), needle) != blocks.end ();
224 /* Describes a single function. Contains an array of basic blocks. */
226 typedef struct function_info
228 function_info ();
229 ~function_info ();
231 /* Return true when line N belongs to the function in source file SRC_IDX.
232 The line must be defined in body of the function, can't be inlined. */
233 bool group_line_p (unsigned n, unsigned src_idx);
235 /* Name of function. */
236 char *name;
237 char *demangled_name;
238 unsigned ident;
239 unsigned lineno_checksum;
240 unsigned cfg_checksum;
242 /* The graph contains at least one fake incoming edge. */
243 unsigned has_catch : 1;
245 /* True when the function is artificial and does not exist
246 in a source file. */
247 unsigned artificial : 1;
249 /* True when multiple functions start at a line in a source file. */
250 unsigned is_group : 1;
252 /* Array of basic blocks. Like in GCC, the entry block is
253 at blocks[0] and the exit block is at blocks[1]. */
254 #define ENTRY_BLOCK (0)
255 #define EXIT_BLOCK (1)
256 vector<block_t> blocks;
257 unsigned blocks_executed;
259 /* Raw arc coverage counts. */
260 gcov_type *counts;
261 unsigned num_counts;
263 /* First line number. */
264 unsigned start_line;
266 /* First line column. */
267 unsigned start_column;
269 /* Last line number. */
270 unsigned end_line;
272 /* Index of source file where the function is defined. */
273 unsigned src;
275 /* Vector of line information. */
276 vector<line_info> lines;
278 /* Next function. */
279 struct function_info *next;
280 } function_t;
282 /* Function info comparer that will sort functions according to starting
283 line. */
285 struct function_line_start_cmp
287 inline bool operator() (const function_info *lhs,
288 const function_info *rhs)
290 return (lhs->start_line == rhs->start_line
291 ? lhs->start_column < rhs->start_column
292 : lhs->start_line < rhs->start_line);
296 /* Describes coverage of a file or function. */
298 typedef struct coverage_info
300 int lines;
301 int lines_executed;
303 int branches;
304 int branches_executed;
305 int branches_taken;
307 int calls;
308 int calls_executed;
310 char *name;
311 } coverage_t;
313 /* Describes a file mentioned in the block graph. Contains an array
314 of line info. */
316 struct source_info
318 /* Default constructor. */
319 source_info ();
321 vector<function_t *> get_functions_at_location (unsigned line_num) const;
323 /* Index of the source_info in sources vector. */
324 unsigned index;
326 /* Canonical name of source file. */
327 char *name;
328 time_t file_time;
330 /* Vector of line information. */
331 vector<line_info> lines;
333 coverage_t coverage;
335 /* Functions in this source file. These are in ascending line
336 number order. */
337 vector <function_t *> functions;
340 source_info::source_info (): index (0), name (NULL), file_time (),
341 lines (), coverage (), functions ()
345 vector<function_t *>
346 source_info::get_functions_at_location (unsigned line_num) const
348 vector<function_t *> r;
350 for (vector<function_t *>::const_iterator it = functions.begin ();
351 it != functions.end (); it++)
353 if ((*it)->start_line == line_num && (*it)->src == index)
354 r.push_back (*it);
357 std::sort (r.begin (), r.end (), function_line_start_cmp ());
359 return r;
362 class name_map
364 public:
365 name_map ()
369 name_map (char *_name, unsigned _src): name (_name), src (_src)
373 bool operator== (const name_map &rhs) const
375 #if HAVE_DOS_BASED_FILE_SYSTEM
376 return strcasecmp (this->name, rhs.name) == 0;
377 #else
378 return strcmp (this->name, rhs.name) == 0;
379 #endif
382 bool operator< (const name_map &rhs) const
384 #if HAVE_DOS_BASED_FILE_SYSTEM
385 return strcasecmp (this->name, rhs.name) < 0;
386 #else
387 return strcmp (this->name, rhs.name) < 0;
388 #endif
391 const char *name; /* Source file name */
392 unsigned src; /* Source file */
395 /* Holds a list of function basic block graphs. */
397 static function_t *functions;
398 static function_t **fn_end = &functions;
400 /* Vector of source files. */
401 static vector<source_info> sources;
403 /* Mapping of file names to sources */
404 static vector<name_map> names;
406 /* This holds data summary information. */
408 static unsigned object_runs;
409 static unsigned program_count;
411 static unsigned total_lines;
412 static unsigned total_executed;
414 /* Modification time of graph file. */
416 static time_t bbg_file_time;
418 /* Name of the notes (gcno) output file. The "bbg" prefix is for
419 historical reasons, when the notes file contained only the
420 basic block graph notes. */
422 static char *bbg_file_name;
424 /* Stamp of the bbg file */
425 static unsigned bbg_stamp;
427 /* Name and file pointer of the input file for the count data (gcda). */
429 static char *da_file_name;
431 /* Data file is missing. */
433 static int no_data_file;
435 /* If there is several input files, compute and display results after
436 reading all data files. This way if two or more gcda file refer to
437 the same source file (eg inline subprograms in a .h file), the
438 counts are added. */
440 static int multiple_files = 0;
442 /* Output branch probabilities. */
444 static int flag_branches = 0;
446 /* Show unconditional branches too. */
447 static int flag_unconditional = 0;
449 /* Output a gcov file if this is true. This is on by default, and can
450 be turned off by the -n option. */
452 static int flag_gcov_file = 1;
454 /* Output progress indication if this is true. This is off by default
455 and can be turned on by the -d option. */
457 static int flag_display_progress = 0;
459 /* Output *.gcov file in intermediate format used by 'lcov'. */
461 static int flag_intermediate_format = 0;
463 /* Output demangled function names. */
465 static int flag_demangled_names = 0;
467 /* For included files, make the gcov output file name include the name
468 of the input source file. For example, if x.h is included in a.c,
469 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
471 static int flag_long_names = 0;
473 /* For situations when a long name can potentially hit filesystem path limit,
474 let's calculate md5sum of the path and append it to a file name. */
476 static int flag_hash_filenames = 0;
478 /* Print verbose informations. */
480 static int flag_verbose = 0;
482 /* Print colored output. */
484 static int flag_use_colors = 0;
486 /* Output count information for every basic block, not merely those
487 that contain line number information. */
489 static int flag_all_blocks = 0;
491 /* Output human readable numbers. */
493 static int flag_human_readable_numbers = 0;
495 /* Output summary info for each function. */
497 static int flag_function_summary = 0;
499 /* Object directory file prefix. This is the directory/file where the
500 graph and data files are looked for, if nonzero. */
502 static char *object_directory = 0;
504 /* Source directory prefix. This is removed from source pathnames
505 that match, when generating the output file name. */
507 static char *source_prefix = 0;
508 static size_t source_length = 0;
510 /* Only show data for sources with relative pathnames. Absolute ones
511 usually indicate a system header file, which although it may
512 contain inline functions, is usually uninteresting. */
513 static int flag_relative_only = 0;
515 /* Preserve all pathname components. Needed when object files and
516 source files are in subdirectories. '/' is mangled as '#', '.' is
517 elided and '..' mangled to '^'. */
519 static int flag_preserve_paths = 0;
521 /* Output the number of times a branch was taken as opposed to the percentage
522 of times it was taken. */
524 static int flag_counts = 0;
526 /* Forward declarations. */
527 static int process_args (int, char **);
528 static void print_usage (int) ATTRIBUTE_NORETURN;
529 static void print_version (void) ATTRIBUTE_NORETURN;
530 static void process_file (const char *);
531 static void generate_results (const char *);
532 static void create_file_names (const char *);
533 static char *canonicalize_name (const char *);
534 static unsigned find_source (const char *);
535 static function_t *read_graph_file (void);
536 static int read_count_file (function_t *);
537 static void solve_flow_graph (function_t *);
538 static void find_exception_blocks (function_t *);
539 static void add_branch_counts (coverage_t *, const arc_t *);
540 static void add_line_counts (coverage_t *, function_t *);
541 static void executed_summary (unsigned, unsigned);
542 static void function_summary (const coverage_t *, const char *);
543 static const char *format_gcov (gcov_type, gcov_type, int);
544 static void accumulate_line_counts (source_info *);
545 static void output_gcov_file (const char *, source_info *);
546 static int output_branch_count (FILE *, int, const arc_t *);
547 static void output_lines (FILE *, const source_info *);
548 static char *make_gcov_file_name (const char *, const char *);
549 static char *mangle_name (const char *, char *);
550 static void release_structures (void);
551 extern int main (int, char **);
553 function_info::function_info (): name (NULL), demangled_name (NULL),
554 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
555 artificial (0), is_group (0),
556 blocks (), blocks_executed (0), counts (NULL), num_counts (0),
557 start_line (0), start_column (0), end_line (0), src (0), lines (), next (NULL)
561 function_info::~function_info ()
563 for (int i = blocks.size () - 1; i >= 0; i--)
565 arc_t *arc, *arc_n;
567 for (arc = blocks[i].succ; arc; arc = arc_n)
569 arc_n = arc->succ_next;
570 free (arc);
573 free (counts);
574 if (flag_demangled_names && demangled_name != name)
575 free (demangled_name);
576 free (name);
579 bool function_info::group_line_p (unsigned n, unsigned src_idx)
581 return is_group && src == src_idx && start_line <= n && n <= end_line;
584 /* Cycle detection!
585 There are a bajillion algorithms that do this. Boost's function is named
586 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
587 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
588 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
590 The basic algorithm is simple: effectively, we're finding all simple paths
591 in a subgraph (that shrinks every iteration). Duplicates are filtered by
592 "blocking" a path when a node is added to the path (this also prevents non-
593 simple paths)--the node is unblocked only when it participates in a cycle.
596 typedef vector<arc_t *> arc_vector_t;
597 typedef vector<const block_t *> block_vector_t;
599 /* Enum with types of loop in CFG. */
601 enum loop_type
603 NO_LOOP = 0,
604 LOOP = 1,
605 NEGATIVE_LOOP = 3
608 /* Loop_type operator that merges two values: A and B. */
610 inline loop_type& operator |= (loop_type& a, loop_type b)
612 return a = static_cast<loop_type> (a | b);
615 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
616 and subtract the value from all counts. The subtracted value is added
617 to COUNT. Returns type of loop. */
619 static loop_type
620 handle_cycle (const arc_vector_t &edges, int64_t &count)
622 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
623 that amount. */
624 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
625 for (unsigned i = 0; i < edges.size (); i++)
627 int64_t ecount = edges[i]->cs_count;
628 if (cycle_count > ecount)
629 cycle_count = ecount;
631 count += cycle_count;
632 for (unsigned i = 0; i < edges.size (); i++)
633 edges[i]->cs_count -= cycle_count;
635 return cycle_count < 0 ? NEGATIVE_LOOP : LOOP;
638 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
639 blocked by U in BLOCK_LISTS. */
641 static void
642 unblock (const block_t *u, block_vector_t &blocked,
643 vector<block_vector_t > &block_lists)
645 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
646 if (it == blocked.end ())
647 return;
649 unsigned index = it - blocked.begin ();
650 blocked.erase (it);
652 block_vector_t to_unblock (block_lists[index]);
654 block_lists.erase (block_lists.begin () + index);
656 for (block_vector_t::iterator it = to_unblock.begin ();
657 it != to_unblock.end (); it++)
658 unblock (*it, blocked, block_lists);
661 /* Find circuit going to block V, PATH is provisional seen cycle.
662 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
663 blocked by a block. COUNT is accumulated count of the current LINE.
664 Returns what type of loop it contains. */
666 static loop_type
667 circuit (block_t *v, arc_vector_t &path, block_t *start,
668 block_vector_t &blocked, vector<block_vector_t> &block_lists,
669 line_info &linfo, int64_t &count)
671 loop_type result = NO_LOOP;
673 /* Add v to the block list. */
674 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
675 blocked.push_back (v);
676 block_lists.push_back (block_vector_t ());
678 for (arc_t *arc = v->succ; arc; arc = arc->succ_next)
680 block_t *w = arc->dst;
681 if (w < start || !linfo.has_block (w))
682 continue;
684 path.push_back (arc);
685 if (w == start)
686 /* Cycle has been found. */
687 result |= handle_cycle (path, count);
688 else if (find (blocked.begin (), blocked.end (), w) == blocked.end ())
689 result |= circuit (w, path, start, blocked, block_lists, linfo, count);
691 path.pop_back ();
694 if (result != NO_LOOP)
695 unblock (v, blocked, block_lists);
696 else
697 for (arc_t *arc = v->succ; arc; arc = arc->succ_next)
699 block_t *w = arc->dst;
700 if (w < start || !linfo.has_block (w))
701 continue;
703 size_t index
704 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
705 gcc_assert (index < blocked.size ());
706 block_vector_t &list = block_lists[index];
707 if (find (list.begin (), list.end (), v) == list.end ())
708 list.push_back (v);
711 return result;
714 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
715 contains a negative loop, then perform the same function once again. */
717 static gcov_type
718 get_cycles_count (line_info &linfo, bool handle_negative_cycles = true)
720 /* Note that this algorithm works even if blocks aren't in sorted order.
721 Each iteration of the circuit detection is completely independent
722 (except for reducing counts, but that shouldn't matter anyways).
723 Therefore, operating on a permuted order (i.e., non-sorted) only
724 has the effect of permuting the output cycles. */
726 loop_type result = NO_LOOP;
727 gcov_type count = 0;
728 for (vector<block_t *>::iterator it = linfo.blocks.begin ();
729 it != linfo.blocks.end (); it++)
731 arc_vector_t path;
732 block_vector_t blocked;
733 vector<block_vector_t > block_lists;
734 result |= circuit (*it, path, *it, blocked, block_lists, linfo,
735 count);
738 /* If we have a negative cycle, repeat the find_cycles routine. */
739 if (result == NEGATIVE_LOOP && handle_negative_cycles)
740 count += get_cycles_count (linfo, false);
742 return count;
746 main (int argc, char **argv)
748 int argno;
749 int first_arg;
750 const char *p;
752 p = argv[0] + strlen (argv[0]);
753 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
754 --p;
755 progname = p;
757 xmalloc_set_program_name (progname);
759 /* Unlock the stdio streams. */
760 unlock_std_streams ();
762 gcc_init_libintl ();
764 diagnostic_initialize (global_dc, 0);
766 /* Handle response files. */
767 expandargv (&argc, &argv);
769 argno = process_args (argc, argv);
770 if (optind == argc)
771 print_usage (true);
773 if (argc - argno > 1)
774 multiple_files = 1;
776 first_arg = argno;
778 for (; argno != argc; argno++)
780 if (flag_display_progress)
781 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
782 argc - first_arg);
783 process_file (argv[argno]);
786 generate_results (multiple_files ? NULL : argv[argc - 1]);
788 release_structures ();
790 return 0;
793 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
794 otherwise the output of --help. */
796 static void
797 print_usage (int error_p)
799 FILE *file = error_p ? stderr : stdout;
800 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
802 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
803 fnotice (file, "Print code coverage information.\n\n");
804 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
805 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
806 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
807 rather than percentages\n");
808 fnotice (file, " -d, --display-progress Display progress information\n");
809 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
810 fnotice (file, " -h, --help Print this help, then exit\n");
811 fnotice (file, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
812 fnotice (file, " -j, --human-readable Output human readable numbers\n");
813 fnotice (file, " -k, --use-colors Emit colored output\n");
814 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
815 source files\n");
816 fnotice (file, " -m, --demangled-names Output demangled function names\n");
817 fnotice (file, " -n, --no-output Do not create an output file\n");
818 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
819 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
820 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
821 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
822 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
823 fnotice (file, " -v, --version Print version number, then exit\n");
824 fnotice (file, " -w, --verbose Print verbose informations\n");
825 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
826 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
827 bug_report_url);
828 exit (status);
831 /* Print version information and exit. */
833 static void
834 print_version (void)
836 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
837 fprintf (stdout, "Copyright %s 2017 Free Software Foundation, Inc.\n",
838 _("(C)"));
839 fnotice (stdout,
840 _("This is free software; see the source for copying conditions.\n"
841 "There is NO warranty; not even for MERCHANTABILITY or \n"
842 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
843 exit (SUCCESS_EXIT_CODE);
846 static const struct option options[] =
848 { "help", no_argument, NULL, 'h' },
849 { "version", no_argument, NULL, 'v' },
850 { "verbose", no_argument, NULL, 'w' },
851 { "all-blocks", no_argument, NULL, 'a' },
852 { "branch-probabilities", no_argument, NULL, 'b' },
853 { "branch-counts", no_argument, NULL, 'c' },
854 { "intermediate-format", no_argument, NULL, 'i' },
855 { "human-readable", no_argument, NULL, 'j' },
856 { "no-output", no_argument, NULL, 'n' },
857 { "long-file-names", no_argument, NULL, 'l' },
858 { "function-summaries", no_argument, NULL, 'f' },
859 { "demangled-names", no_argument, NULL, 'm' },
860 { "preserve-paths", no_argument, NULL, 'p' },
861 { "relative-only", no_argument, NULL, 'r' },
862 { "object-directory", required_argument, NULL, 'o' },
863 { "object-file", required_argument, NULL, 'o' },
864 { "source-prefix", required_argument, NULL, 's' },
865 { "unconditional-branches", no_argument, NULL, 'u' },
866 { "display-progress", no_argument, NULL, 'd' },
867 { "hash-filenames", no_argument, NULL, 'x' },
868 { "use-colors", no_argument, NULL, 'k' },
869 { 0, 0, 0, 0 }
872 /* Process args, return index to first non-arg. */
874 static int
875 process_args (int argc, char **argv)
877 int opt;
879 const char *opts = "abcdfhijklmno:prs:uvwx";
880 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
882 switch (opt)
884 case 'a':
885 flag_all_blocks = 1;
886 break;
887 case 'b':
888 flag_branches = 1;
889 break;
890 case 'c':
891 flag_counts = 1;
892 break;
893 case 'f':
894 flag_function_summary = 1;
895 break;
896 case 'h':
897 print_usage (false);
898 /* print_usage will exit. */
899 case 'l':
900 flag_long_names = 1;
901 break;
902 case 'j':
903 flag_human_readable_numbers = 1;
904 break;
905 case 'k':
906 flag_use_colors = 1;
907 break;
908 case 'm':
909 flag_demangled_names = 1;
910 break;
911 case 'n':
912 flag_gcov_file = 0;
913 break;
914 case 'o':
915 object_directory = optarg;
916 break;
917 case 's':
918 source_prefix = optarg;
919 source_length = strlen (source_prefix);
920 break;
921 case 'r':
922 flag_relative_only = 1;
923 break;
924 case 'p':
925 flag_preserve_paths = 1;
926 break;
927 case 'u':
928 flag_unconditional = 1;
929 break;
930 case 'i':
931 flag_intermediate_format = 1;
932 flag_gcov_file = 1;
933 break;
934 case 'd':
935 flag_display_progress = 1;
936 break;
937 case 'x':
938 flag_hash_filenames = 1;
939 break;
940 case 'w':
941 flag_verbose = 1;
942 break;
943 case 'v':
944 print_version ();
945 /* print_version will exit. */
946 default:
947 print_usage (true);
948 /* print_usage will exit. */
952 return optind;
955 /* Output intermediate LINE sitting on LINE_NUM to output file F. */
957 static void
958 output_intermediate_line (FILE *f, line_info *line, unsigned line_num)
960 if (!line->exists)
961 return;
963 fprintf (f, "lcount:%u,%s,%d\n", line_num,
964 format_gcov (line->count, 0, -1),
965 line->has_unexecuted_block);
967 vector<arc_t *>::const_iterator it;
968 if (flag_branches)
969 for (it = line->branches.begin (); it != line->branches.end ();
970 it++)
972 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
974 const char *branch_type;
975 /* branch:<line_num>,<branch_coverage_type>
976 branch_coverage_type
977 : notexec (Branch not executed)
978 : taken (Branch executed and taken)
979 : nottaken (Branch executed, but not taken)
981 if ((*it)->src->count)
982 branch_type
983 = ((*it)->count > 0) ? "taken" : "nottaken";
984 else
985 branch_type = "notexec";
986 fprintf (f, "branch:%d,%s\n", line_num, branch_type);
991 /* Output the result in intermediate format used by 'lcov'.
993 The intermediate format contains a single file named 'foo.cc.gcov',
994 with no source code included.
996 The default gcov outputs multiple files: 'foo.cc.gcov',
997 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
998 included. Instead the intermediate format here outputs only a single
999 file 'foo.cc.gcov' similar to the above example. */
1001 static void
1002 output_intermediate_file (FILE *gcov_file, source_info *src)
1004 fprintf (gcov_file, "file:%s\n", src->name); /* source file name */
1006 std::sort (src->functions.begin (), src->functions.end (),
1007 function_line_start_cmp ());
1008 for (vector<function_t *>::iterator it = src->functions.begin ();
1009 it != src->functions.end (); it++)
1011 /* function:<name>,<line_number>,<execution_count> */
1012 fprintf (gcov_file, "function:%d,%d,%s,%s\n", (*it)->start_line,
1013 (*it)->end_line, format_gcov ((*it)->blocks[0].count, 0, -1),
1014 flag_demangled_names ? (*it)->demangled_name : (*it)->name);
1017 for (unsigned line_num = 0; line_num <= src->lines.size (); line_num++)
1019 vector<function_t *> fns = src->get_functions_at_location (line_num);
1021 /* Print first group functions that begin on the line. */
1022 for (vector<function_t *>::iterator it2 = fns.begin ();
1023 it2 != fns.end (); it2++)
1025 vector<line_info> &lines = (*it2)->lines;
1026 for (unsigned i = 0; i < lines.size (); i++)
1028 line_info *line = &lines[i];
1029 output_intermediate_line (gcov_file, line, line_num + i);
1033 /* Follow with lines associated with the source file. */
1034 output_intermediate_line (gcov_file, &src->lines[line_num], line_num);
1038 /* Function start pair. */
1039 struct function_start
1041 unsigned source_file_idx;
1042 unsigned start_line;
1045 /* Traits class for function start hash maps below. */
1047 struct function_start_pair_hash : typed_noop_remove <function_start>
1049 typedef function_start value_type;
1050 typedef function_start compare_type;
1052 static hashval_t
1053 hash (const function_start &ref)
1055 inchash::hash hstate (0);
1056 hstate.add_int (ref.source_file_idx);
1057 hstate.add_int (ref.start_line);
1058 return hstate.end ();
1061 static bool
1062 equal (const function_start &ref1, const function_start &ref2)
1064 return (ref1.source_file_idx == ref2.source_file_idx
1065 && ref1.start_line == ref2.start_line);
1068 static void
1069 mark_deleted (function_start &ref)
1071 ref.start_line = ~1U;
1074 static void
1075 mark_empty (function_start &ref)
1077 ref.start_line = ~2U;
1080 static bool
1081 is_deleted (const function_start &ref)
1083 return ref.start_line == ~1U;
1086 static bool
1087 is_empty (const function_start &ref)
1089 return ref.start_line == ~2U;
1093 /* Process a single input file. */
1095 static void
1096 process_file (const char *file_name)
1098 function_t *fns;
1100 create_file_names (file_name);
1101 fns = read_graph_file ();
1102 if (!fns)
1103 return;
1105 read_count_file (fns);
1107 hash_map<function_start_pair_hash, function_t *> fn_map;
1109 /* Identify group functions. */
1110 for (function_t *f = fns; f; f = f->next)
1111 if (!f->artificial)
1113 function_start needle;
1114 needle.source_file_idx = f->src;
1115 needle.start_line = f->start_line;
1117 function_t **slot = fn_map.get (needle);
1118 if (slot)
1120 gcc_assert ((*slot)->end_line == f->end_line);
1121 (*slot)->is_group = 1;
1122 f->is_group = 1;
1124 else
1125 fn_map.put (needle, f);
1128 while (fns)
1130 function_t *fn = fns;
1132 fns = fn->next;
1133 fn->next = NULL;
1134 if (fn->counts || no_data_file)
1136 unsigned src = fn->src;
1137 unsigned block_no;
1139 /* Process only non-artificial functions. */
1140 if (!fn->artificial)
1142 source_info *s = &sources[src];
1143 s->functions.push_back (fn);
1145 /* Mark last line in files touched by function. */
1146 for (block_no = 0; block_no != fn->blocks.size (); block_no++)
1148 block_t *block = &fn->blocks[block_no];
1149 for (unsigned i = 0; i < block->locations.size (); i++)
1151 /* Sort lines of locations. */
1152 sort (block->locations[i].lines.begin (),
1153 block->locations[i].lines.end ());
1155 if (!block->locations[i].lines.empty ())
1157 s = &sources[block->locations[i].source_file_idx];
1158 unsigned last_line
1159 = block->locations[i].lines.back ();
1161 /* Record new lines for the function. */
1162 if (last_line >= s->lines.size ())
1164 /* Record new lines for a source file. */
1165 s->lines.resize (last_line + 1);
1170 /* Allocate lines for group function, following start_line
1171 and end_line information of the function. */
1172 if (fn->is_group)
1173 fn->lines.resize (fn->end_line - fn->start_line + 1);
1176 solve_flow_graph (fn);
1177 if (fn->has_catch)
1178 find_exception_blocks (fn);
1181 *fn_end = fn;
1182 fn_end = &fn->next;
1184 else
1185 /* The function was not in the executable -- some other
1186 instance must have been selected. */
1187 delete fn;
1191 static void
1192 output_gcov_file (const char *file_name, source_info *src)
1194 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1196 if (src->coverage.lines)
1198 FILE *gcov_file = fopen (gcov_file_name, "w");
1199 if (gcov_file)
1201 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1203 if (flag_intermediate_format)
1204 output_intermediate_file (gcov_file, src);
1205 else
1206 output_lines (gcov_file, src);
1207 if (ferror (gcov_file))
1208 fnotice (stderr, "Error writing output file '%s'\n", gcov_file_name);
1209 fclose (gcov_file);
1211 else
1212 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1214 else
1216 unlink (gcov_file_name);
1217 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1219 free (gcov_file_name);
1222 static void
1223 generate_results (const char *file_name)
1225 function_t *fn;
1227 for (fn = functions; fn; fn = fn->next)
1229 coverage_t coverage;
1230 if (fn->artificial)
1231 continue;
1233 memset (&coverage, 0, sizeof (coverage));
1234 coverage.name = flag_demangled_names ? fn->demangled_name : fn->name;
1235 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1236 if (flag_function_summary)
1238 function_summary (&coverage, "Function");
1239 fnotice (stdout, "\n");
1243 name_map needle;
1245 if (file_name)
1247 needle.name = file_name;
1248 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1249 needle);
1250 if (it != names.end ())
1251 file_name = sources[it->src].coverage.name;
1252 else
1253 file_name = canonicalize_name (file_name);
1256 for (vector<source_info>::iterator it = sources.begin ();
1257 it != sources.end (); it++)
1259 source_info *src = &(*it);
1260 if (flag_relative_only)
1262 /* Ignore this source, if it is an absolute path (after
1263 source prefix removal). */
1264 char first = src->coverage.name[0];
1266 #if HAVE_DOS_BASED_FILE_SYSTEM
1267 if (first && src->coverage.name[1] == ':')
1268 first = src->coverage.name[2];
1269 #endif
1270 if (IS_DIR_SEPARATOR (first))
1271 continue;
1274 accumulate_line_counts (src);
1275 function_summary (&src->coverage, "File");
1276 total_lines += src->coverage.lines;
1277 total_executed += src->coverage.lines_executed;
1278 if (flag_gcov_file)
1280 output_gcov_file (file_name, src);
1281 fnotice (stdout, "\n");
1285 if (!file_name)
1286 executed_summary (total_lines, total_executed);
1289 /* Release all memory used. */
1291 static void
1292 release_structures (void)
1294 function_t *fn;
1296 while ((fn = functions))
1298 functions = fn->next;
1299 delete fn;
1303 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1304 is not specified, these are named from FILE_NAME sans extension. If
1305 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1306 directory, but named from the basename of the FILE_NAME, sans extension.
1307 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1308 and the data files are named from that. */
1310 static void
1311 create_file_names (const char *file_name)
1313 char *cptr;
1314 char *name;
1315 int length = strlen (file_name);
1316 int base;
1318 /* Free previous file names. */
1319 free (bbg_file_name);
1320 free (da_file_name);
1321 da_file_name = bbg_file_name = NULL;
1322 bbg_file_time = 0;
1323 bbg_stamp = 0;
1325 if (object_directory && object_directory[0])
1327 struct stat status;
1329 length += strlen (object_directory) + 2;
1330 name = XNEWVEC (char, length);
1331 name[0] = 0;
1333 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1334 strcat (name, object_directory);
1335 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1336 strcat (name, "/");
1338 else
1340 name = XNEWVEC (char, length + 1);
1341 strcpy (name, file_name);
1342 base = 0;
1345 if (base)
1347 /* Append source file name. */
1348 const char *cptr = lbasename (file_name);
1349 strcat (name, cptr ? cptr : file_name);
1352 /* Remove the extension. */
1353 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1354 if (cptr)
1355 *cptr = 0;
1357 length = strlen (name);
1359 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1360 strcpy (bbg_file_name, name);
1361 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1363 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1364 strcpy (da_file_name, name);
1365 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1367 free (name);
1368 return;
1371 /* Find or create a source file structure for FILE_NAME. Copies
1372 FILE_NAME on creation */
1374 static unsigned
1375 find_source (const char *file_name)
1377 char *canon;
1378 unsigned idx;
1379 struct stat status;
1381 if (!file_name)
1382 file_name = "<unknown>";
1384 name_map needle;
1385 needle.name = file_name;
1387 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1388 needle);
1389 if (it != names.end ())
1391 idx = it->src;
1392 goto check_date;
1395 /* Not found, try the canonical name. */
1396 canon = canonicalize_name (file_name);
1397 needle.name = canon;
1398 it = std::find (names.begin (), names.end (), needle);
1399 if (it == names.end ())
1401 /* Not found with canonical name, create a new source. */
1402 source_info *src;
1404 idx = sources.size ();
1405 needle = name_map (canon, idx);
1406 names.push_back (needle);
1408 sources.push_back (source_info ());
1409 src = &sources.back ();
1410 src->name = canon;
1411 src->coverage.name = src->name;
1412 src->index = idx;
1413 if (source_length
1414 #if HAVE_DOS_BASED_FILE_SYSTEM
1415 /* You lose if separators don't match exactly in the
1416 prefix. */
1417 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1418 #else
1419 && !strncmp (source_prefix, src->coverage.name, source_length)
1420 #endif
1421 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1422 src->coverage.name += source_length + 1;
1423 if (!stat (src->name, &status))
1424 src->file_time = status.st_mtime;
1426 else
1427 idx = it->src;
1429 needle.name = file_name;
1430 if (std::find (names.begin (), names.end (), needle) == names.end ())
1432 /* Append the non-canonical name. */
1433 names.push_back (name_map (xstrdup (file_name), idx));
1436 /* Resort the name map. */
1437 std::sort (names.begin (), names.end ());
1439 check_date:
1440 if (sources[idx].file_time > bbg_file_time)
1442 static int info_emitted;
1444 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1445 file_name, bbg_file_name);
1446 if (!info_emitted)
1448 fnotice (stderr,
1449 "(the message is displayed only once per source file)\n");
1450 info_emitted = 1;
1452 sources[idx].file_time = 0;
1455 return idx;
1458 /* Read the notes file. Return list of functions read -- in reverse order. */
1460 static function_t *
1461 read_graph_file (void)
1463 unsigned version;
1464 unsigned current_tag = 0;
1465 function_t *fn = NULL;
1466 function_t *fns = NULL;
1467 function_t **fns_end = &fns;
1468 unsigned tag;
1470 if (!gcov_open (bbg_file_name, 1))
1472 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1473 return fns;
1475 bbg_file_time = gcov_time ();
1476 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1478 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1479 gcov_close ();
1480 return fns;
1483 version = gcov_read_unsigned ();
1484 if (version != GCOV_VERSION)
1486 char v[4], e[4];
1488 GCOV_UNSIGNED2STRING (v, version);
1489 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1491 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1492 bbg_file_name, v, e);
1494 bbg_stamp = gcov_read_unsigned ();
1496 while ((tag = gcov_read_unsigned ()))
1498 unsigned length = gcov_read_unsigned ();
1499 gcov_position_t base = gcov_position ();
1501 if (tag == GCOV_TAG_FUNCTION)
1503 char *function_name;
1504 unsigned ident;
1505 unsigned lineno_checksum, cfg_checksum;
1507 ident = gcov_read_unsigned ();
1508 lineno_checksum = gcov_read_unsigned ();
1509 cfg_checksum = gcov_read_unsigned ();
1510 function_name = xstrdup (gcov_read_string ());
1511 unsigned artificial = gcov_read_unsigned ();
1512 unsigned src_idx = find_source (gcov_read_string ());
1513 unsigned start_line = gcov_read_unsigned ();
1514 unsigned start_column = gcov_read_unsigned ();
1515 unsigned end_line = gcov_read_unsigned ();
1517 fn = new function_t;
1518 fn->name = function_name;
1519 if (flag_demangled_names)
1521 fn->demangled_name = cplus_demangle (fn->name, DMGL_PARAMS);
1522 if (!fn->demangled_name)
1523 fn->demangled_name = fn->name;
1525 fn->ident = ident;
1526 fn->lineno_checksum = lineno_checksum;
1527 fn->cfg_checksum = cfg_checksum;
1528 fn->src = src_idx;
1529 fn->start_line = start_line;
1530 fn->start_column = start_column;
1531 fn->end_line = end_line;
1532 fn->artificial = artificial;
1534 fn->next = NULL;
1535 *fns_end = fn;
1536 fns_end = &fn->next;
1537 current_tag = tag;
1539 else if (fn && tag == GCOV_TAG_BLOCKS)
1541 if (!fn->blocks.empty ())
1542 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1543 bbg_file_name, fn->name);
1544 else
1545 fn->blocks.resize (gcov_read_unsigned ());
1547 else if (fn && tag == GCOV_TAG_ARCS)
1549 unsigned src = gcov_read_unsigned ();
1550 fn->blocks[src].id = src;
1551 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1552 block_t *src_blk = &fn->blocks[src];
1553 unsigned mark_catches = 0;
1554 struct arc_info *arc;
1556 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1557 goto corrupt;
1559 while (num_dests--)
1561 unsigned dest = gcov_read_unsigned ();
1562 unsigned flags = gcov_read_unsigned ();
1564 if (dest >= fn->blocks.size ())
1565 goto corrupt;
1566 arc = XCNEW (arc_t);
1568 arc->dst = &fn->blocks[dest];
1569 arc->src = src_blk;
1571 arc->count = 0;
1572 arc->count_valid = 0;
1573 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1574 arc->fake = !!(flags & GCOV_ARC_FAKE);
1575 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1577 arc->succ_next = src_blk->succ;
1578 src_blk->succ = arc;
1579 src_blk->num_succ++;
1581 arc->pred_next = fn->blocks[dest].pred;
1582 fn->blocks[dest].pred = arc;
1583 fn->blocks[dest].num_pred++;
1585 if (arc->fake)
1587 if (src)
1589 /* Exceptional exit from this function, the
1590 source block must be a call. */
1591 fn->blocks[src].is_call_site = 1;
1592 arc->is_call_non_return = 1;
1593 mark_catches = 1;
1595 else
1597 /* Non-local return from a callee of this
1598 function. The destination block is a setjmp. */
1599 arc->is_nonlocal_return = 1;
1600 fn->blocks[dest].is_nonlocal_return = 1;
1604 if (!arc->on_tree)
1605 fn->num_counts++;
1608 if (mark_catches)
1610 /* We have a fake exit from this block. The other
1611 non-fall through exits must be to catch handlers.
1612 Mark them as catch arcs. */
1614 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1615 if (!arc->fake && !arc->fall_through)
1617 arc->is_throw = 1;
1618 fn->has_catch = 1;
1622 else if (fn && tag == GCOV_TAG_LINES)
1624 unsigned blockno = gcov_read_unsigned ();
1625 block_t *block = &fn->blocks[blockno];
1627 if (blockno >= fn->blocks.size ())
1628 goto corrupt;
1630 while (true)
1632 unsigned lineno = gcov_read_unsigned ();
1634 if (lineno)
1635 block->locations.back ().lines.push_back (lineno);
1636 else
1638 const char *file_name = gcov_read_string ();
1640 if (!file_name)
1641 break;
1642 block->locations.push_back (block_location_info
1643 (find_source (file_name)));
1647 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1649 fn = NULL;
1650 current_tag = 0;
1652 gcov_sync (base, length);
1653 if (gcov_is_error ())
1655 corrupt:;
1656 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1657 break;
1660 gcov_close ();
1662 if (!fns)
1663 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1665 return fns;
1668 /* Reads profiles from the count file and attach to each
1669 function. Return nonzero if fatal error. */
1671 static int
1672 read_count_file (function_t *fns)
1674 unsigned ix;
1675 unsigned version;
1676 unsigned tag;
1677 function_t *fn = NULL;
1678 int error = 0;
1680 if (!gcov_open (da_file_name, 1))
1682 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1683 da_file_name);
1684 no_data_file = 1;
1685 return 0;
1687 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1689 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1690 cleanup:;
1691 gcov_close ();
1692 return 1;
1694 version = gcov_read_unsigned ();
1695 if (version != GCOV_VERSION)
1697 char v[4], e[4];
1699 GCOV_UNSIGNED2STRING (v, version);
1700 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1702 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1703 da_file_name, v, e);
1705 tag = gcov_read_unsigned ();
1706 if (tag != bbg_stamp)
1708 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1709 goto cleanup;
1712 while ((tag = gcov_read_unsigned ()))
1714 unsigned length = gcov_read_unsigned ();
1715 unsigned long base = gcov_position ();
1717 if (tag == GCOV_TAG_PROGRAM_SUMMARY)
1719 struct gcov_summary summary;
1720 gcov_read_summary (&summary);
1721 object_runs += summary.ctrs[GCOV_COUNTER_ARCS].runs;
1722 program_count++;
1724 else if (tag == GCOV_TAG_FUNCTION && !length)
1725 ; /* placeholder */
1726 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1728 unsigned ident;
1729 struct function_info *fn_n;
1731 /* Try to find the function in the list. To speed up the
1732 search, first start from the last function found. */
1733 ident = gcov_read_unsigned ();
1734 fn_n = fns;
1735 for (fn = fn ? fn->next : NULL; ; fn = fn->next)
1737 if (fn)
1739 else if ((fn = fn_n))
1740 fn_n = NULL;
1741 else
1743 fnotice (stderr, "%s:unknown function '%u'\n",
1744 da_file_name, ident);
1745 break;
1747 if (fn->ident == ident)
1748 break;
1751 if (!fn)
1753 else if (gcov_read_unsigned () != fn->lineno_checksum
1754 || gcov_read_unsigned () != fn->cfg_checksum)
1756 mismatch:;
1757 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1758 da_file_name, fn->name);
1759 goto cleanup;
1762 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1764 if (length != GCOV_TAG_COUNTER_LENGTH (fn->num_counts))
1765 goto mismatch;
1767 if (!fn->counts)
1768 fn->counts = XCNEWVEC (gcov_type, fn->num_counts);
1770 for (ix = 0; ix != fn->num_counts; ix++)
1771 fn->counts[ix] += gcov_read_counter ();
1773 gcov_sync (base, length);
1774 if ((error = gcov_is_error ()))
1776 fnotice (stderr,
1777 error < 0
1778 ? N_("%s:overflowed\n")
1779 : N_("%s:corrupted\n"),
1780 da_file_name);
1781 goto cleanup;
1785 gcov_close ();
1786 return 0;
1789 /* Solve the flow graph. Propagate counts from the instrumented arcs
1790 to the blocks and the uninstrumented arcs. */
1792 static void
1793 solve_flow_graph (function_t *fn)
1795 unsigned ix;
1796 arc_t *arc;
1797 gcov_type *count_ptr = fn->counts;
1798 block_t *blk;
1799 block_t *valid_blocks = NULL; /* valid, but unpropagated blocks. */
1800 block_t *invalid_blocks = NULL; /* invalid, but inferable blocks. */
1802 /* The arcs were built in reverse order. Fix that now. */
1803 for (ix = fn->blocks.size (); ix--;)
1805 arc_t *arc_p, *arc_n;
1807 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
1808 arc_p = arc, arc = arc_n)
1810 arc_n = arc->succ_next;
1811 arc->succ_next = arc_p;
1813 fn->blocks[ix].succ = arc_p;
1815 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
1816 arc_p = arc, arc = arc_n)
1818 arc_n = arc->pred_next;
1819 arc->pred_next = arc_p;
1821 fn->blocks[ix].pred = arc_p;
1824 if (fn->blocks.size () < 2)
1825 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
1826 bbg_file_name, fn->name);
1827 else
1829 if (fn->blocks[ENTRY_BLOCK].num_pred)
1830 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
1831 bbg_file_name, fn->name);
1832 else
1833 /* We can't deduce the entry block counts from the lack of
1834 predecessors. */
1835 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
1837 if (fn->blocks[EXIT_BLOCK].num_succ)
1838 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
1839 bbg_file_name, fn->name);
1840 else
1841 /* Likewise, we can't deduce exit block counts from the lack
1842 of its successors. */
1843 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
1846 /* Propagate the measured counts, this must be done in the same
1847 order as the code in profile.c */
1848 for (unsigned i = 0; i < fn->blocks.size (); i++)
1850 blk = &fn->blocks[i];
1851 block_t const *prev_dst = NULL;
1852 int out_of_order = 0;
1853 int non_fake_succ = 0;
1855 for (arc = blk->succ; arc; arc = arc->succ_next)
1857 if (!arc->fake)
1858 non_fake_succ++;
1860 if (!arc->on_tree)
1862 if (count_ptr)
1863 arc->count = *count_ptr++;
1864 arc->count_valid = 1;
1865 blk->num_succ--;
1866 arc->dst->num_pred--;
1868 if (prev_dst && prev_dst > arc->dst)
1869 out_of_order = 1;
1870 prev_dst = arc->dst;
1872 if (non_fake_succ == 1)
1874 /* If there is only one non-fake exit, it is an
1875 unconditional branch. */
1876 for (arc = blk->succ; arc; arc = arc->succ_next)
1877 if (!arc->fake)
1879 arc->is_unconditional = 1;
1880 /* If this block is instrumenting a call, it might be
1881 an artificial block. It is not artificial if it has
1882 a non-fallthrough exit, or the destination of this
1883 arc has more than one entry. Mark the destination
1884 block as a return site, if none of those conditions
1885 hold. */
1886 if (blk->is_call_site && arc->fall_through
1887 && arc->dst->pred == arc && !arc->pred_next)
1888 arc->dst->is_call_return = 1;
1892 /* Sort the successor arcs into ascending dst order. profile.c
1893 normally produces arcs in the right order, but sometimes with
1894 one or two out of order. We're not using a particularly
1895 smart sort. */
1896 if (out_of_order)
1898 arc_t *start = blk->succ;
1899 unsigned changes = 1;
1901 while (changes)
1903 arc_t *arc, *arc_p, *arc_n;
1905 changes = 0;
1906 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
1908 if (arc->dst > arc_n->dst)
1910 changes = 1;
1911 if (arc_p)
1912 arc_p->succ_next = arc_n;
1913 else
1914 start = arc_n;
1915 arc->succ_next = arc_n->succ_next;
1916 arc_n->succ_next = arc;
1917 arc_p = arc_n;
1919 else
1921 arc_p = arc;
1922 arc = arc_n;
1926 blk->succ = start;
1929 /* Place it on the invalid chain, it will be ignored if that's
1930 wrong. */
1931 blk->invalid_chain = 1;
1932 blk->chain = invalid_blocks;
1933 invalid_blocks = blk;
1936 while (invalid_blocks || valid_blocks)
1938 while ((blk = invalid_blocks))
1940 gcov_type total = 0;
1941 const arc_t *arc;
1943 invalid_blocks = blk->chain;
1944 blk->invalid_chain = 0;
1945 if (!blk->num_succ)
1946 for (arc = blk->succ; arc; arc = arc->succ_next)
1947 total += arc->count;
1948 else if (!blk->num_pred)
1949 for (arc = blk->pred; arc; arc = arc->pred_next)
1950 total += arc->count;
1951 else
1952 continue;
1954 blk->count = total;
1955 blk->count_valid = 1;
1956 blk->chain = valid_blocks;
1957 blk->valid_chain = 1;
1958 valid_blocks = blk;
1960 while ((blk = valid_blocks))
1962 gcov_type total;
1963 arc_t *arc, *inv_arc;
1965 valid_blocks = blk->chain;
1966 blk->valid_chain = 0;
1967 if (blk->num_succ == 1)
1969 block_t *dst;
1971 total = blk->count;
1972 inv_arc = NULL;
1973 for (arc = blk->succ; arc; arc = arc->succ_next)
1975 total -= arc->count;
1976 if (!arc->count_valid)
1977 inv_arc = arc;
1979 dst = inv_arc->dst;
1980 inv_arc->count_valid = 1;
1981 inv_arc->count = total;
1982 blk->num_succ--;
1983 dst->num_pred--;
1984 if (dst->count_valid)
1986 if (dst->num_pred == 1 && !dst->valid_chain)
1988 dst->chain = valid_blocks;
1989 dst->valid_chain = 1;
1990 valid_blocks = dst;
1993 else
1995 if (!dst->num_pred && !dst->invalid_chain)
1997 dst->chain = invalid_blocks;
1998 dst->invalid_chain = 1;
1999 invalid_blocks = dst;
2003 if (blk->num_pred == 1)
2005 block_t *src;
2007 total = blk->count;
2008 inv_arc = NULL;
2009 for (arc = blk->pred; arc; arc = arc->pred_next)
2011 total -= arc->count;
2012 if (!arc->count_valid)
2013 inv_arc = arc;
2015 src = inv_arc->src;
2016 inv_arc->count_valid = 1;
2017 inv_arc->count = total;
2018 blk->num_pred--;
2019 src->num_succ--;
2020 if (src->count_valid)
2022 if (src->num_succ == 1 && !src->valid_chain)
2024 src->chain = valid_blocks;
2025 src->valid_chain = 1;
2026 valid_blocks = src;
2029 else
2031 if (!src->num_succ && !src->invalid_chain)
2033 src->chain = invalid_blocks;
2034 src->invalid_chain = 1;
2035 invalid_blocks = src;
2042 /* If the graph has been correctly solved, every block will have a
2043 valid count. */
2044 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2045 if (!fn->blocks[i].count_valid)
2047 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2048 bbg_file_name, fn->name);
2049 break;
2053 /* Mark all the blocks only reachable via an incoming catch. */
2055 static void
2056 find_exception_blocks (function_t *fn)
2058 unsigned ix;
2059 block_t **queue = XALLOCAVEC (block_t *, fn->blocks.size ());
2061 /* First mark all blocks as exceptional. */
2062 for (ix = fn->blocks.size (); ix--;)
2063 fn->blocks[ix].exceptional = 1;
2065 /* Now mark all the blocks reachable via non-fake edges */
2066 queue[0] = &fn->blocks[0];
2067 queue[0]->exceptional = 0;
2068 for (ix = 1; ix;)
2070 block_t *block = queue[--ix];
2071 const arc_t *arc;
2073 for (arc = block->succ; arc; arc = arc->succ_next)
2074 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2076 arc->dst->exceptional = 0;
2077 queue[ix++] = arc->dst;
2083 /* Increment totals in COVERAGE according to arc ARC. */
2085 static void
2086 add_branch_counts (coverage_t *coverage, const arc_t *arc)
2088 if (arc->is_call_non_return)
2090 coverage->calls++;
2091 if (arc->src->count)
2092 coverage->calls_executed++;
2094 else if (!arc->is_unconditional)
2096 coverage->branches++;
2097 if (arc->src->count)
2098 coverage->branches_executed++;
2099 if (arc->count)
2100 coverage->branches_taken++;
2104 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2105 readable format. */
2107 static char const *
2108 format_count (gcov_type count)
2110 static char buffer[64];
2111 const char *units = " kMGTPEZY";
2113 if (count < 1000 || !flag_human_readable_numbers)
2115 sprintf (buffer, "%" PRId64, count);
2116 return buffer;
2119 unsigned i;
2120 gcov_type divisor = 1;
2121 for (i = 0; units[i+1]; i++, divisor *= 1000)
2123 if (count + divisor / 2 < 1000 * divisor)
2124 break;
2126 gcov_type r = (count + divisor / 2) / divisor;
2127 sprintf (buffer, "%" PRId64 "%c", r, units[i]);
2128 return buffer;
2131 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2132 count. If dp >= 0, format TOP/BOTTOM * 100 to DP decimal places.
2133 If DP is zero, no decimal point is printed. Only print 100% when
2134 TOP==BOTTOM and only print 0% when TOP=0. If dp < 0, then simply
2135 format TOP. Return pointer to a static string. */
2137 static char const *
2138 format_gcov (gcov_type top, gcov_type bottom, int dp)
2140 static char buffer[20];
2142 /* Handle invalid values that would result in a misleading value. */
2143 if (bottom != 0 && top > bottom && dp >= 0)
2145 sprintf (buffer, "NAN %%");
2146 return buffer;
2149 if (dp >= 0)
2151 float ratio = bottom ? (float)top / bottom : 0;
2152 int ix;
2153 unsigned limit = 100;
2154 unsigned percent;
2156 for (ix = dp; ix--; )
2157 limit *= 10;
2159 percent = (unsigned) (ratio * limit + (float)0.5);
2160 if (percent <= 0 && top)
2161 percent = 1;
2162 else if (percent >= limit && top != bottom)
2163 percent = limit - 1;
2164 ix = sprintf (buffer, "%.*u%%", dp + 1, percent);
2165 if (dp)
2167 dp++;
2170 buffer[ix+1] = buffer[ix];
2171 ix--;
2173 while (dp--);
2174 buffer[ix + 1] = '.';
2177 else
2178 return format_count (top);
2180 return buffer;
2183 /* Summary of execution */
2185 static void
2186 executed_summary (unsigned lines, unsigned executed)
2188 if (lines)
2189 fnotice (stdout, "Lines executed:%s of %d\n",
2190 format_gcov (executed, lines, 2), lines);
2191 else
2192 fnotice (stdout, "No executable lines\n");
2195 /* Output summary info for a function or file. */
2197 static void
2198 function_summary (const coverage_t *coverage, const char *title)
2200 fnotice (stdout, "%s '%s'\n", title, coverage->name);
2201 executed_summary (coverage->lines, coverage->lines_executed);
2203 if (flag_branches)
2205 if (coverage->branches)
2207 fnotice (stdout, "Branches executed:%s of %d\n",
2208 format_gcov (coverage->branches_executed,
2209 coverage->branches, 2),
2210 coverage->branches);
2211 fnotice (stdout, "Taken at least once:%s of %d\n",
2212 format_gcov (coverage->branches_taken,
2213 coverage->branches, 2),
2214 coverage->branches);
2216 else
2217 fnotice (stdout, "No branches\n");
2218 if (coverage->calls)
2219 fnotice (stdout, "Calls executed:%s of %d\n",
2220 format_gcov (coverage->calls_executed, coverage->calls, 2),
2221 coverage->calls);
2222 else
2223 fnotice (stdout, "No calls\n");
2227 /* Canonicalize the filename NAME by canonicalizing directory
2228 separators, eliding . components and resolving .. components
2229 appropriately. Always returns a unique string. */
2231 static char *
2232 canonicalize_name (const char *name)
2234 /* The canonical name cannot be longer than the incoming name. */
2235 char *result = XNEWVEC (char, strlen (name) + 1);
2236 const char *base = name, *probe;
2237 char *ptr = result;
2238 char *dd_base;
2239 int slash = 0;
2241 #if HAVE_DOS_BASED_FILE_SYSTEM
2242 if (base[0] && base[1] == ':')
2244 result[0] = base[0];
2245 result[1] = ':';
2246 base += 2;
2247 ptr += 2;
2249 #endif
2250 for (dd_base = ptr; *base; base = probe)
2252 size_t len;
2254 for (probe = base; *probe; probe++)
2255 if (IS_DIR_SEPARATOR (*probe))
2256 break;
2258 len = probe - base;
2259 if (len == 1 && base[0] == '.')
2260 /* Elide a '.' directory */
2262 else if (len == 2 && base[0] == '.' && base[1] == '.')
2264 /* '..', we can only elide it and the previous directory, if
2265 we're not a symlink. */
2266 struct stat ATTRIBUTE_UNUSED buf;
2268 *ptr = 0;
2269 if (dd_base == ptr
2270 #if defined (S_ISLNK)
2271 /* S_ISLNK is not POSIX.1-1996. */
2272 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2273 #endif
2276 /* Cannot elide, or unreadable or a symlink. */
2277 dd_base = ptr + 2 + slash;
2278 goto regular;
2280 while (ptr != dd_base && *ptr != '/')
2281 ptr--;
2282 slash = ptr != result;
2284 else
2286 regular:
2287 /* Regular pathname component. */
2288 if (slash)
2289 *ptr++ = '/';
2290 memcpy (ptr, base, len);
2291 ptr += len;
2292 slash = 1;
2295 for (; IS_DIR_SEPARATOR (*probe); probe++)
2296 continue;
2298 *ptr = 0;
2300 return result;
2303 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2305 static void
2306 md5sum_to_hex (const char *sum, char *buffer)
2308 for (unsigned i = 0; i < 16; i++)
2309 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2312 /* Generate an output file name. INPUT_NAME is the canonicalized main
2313 input file and SRC_NAME is the canonicalized file name.
2314 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2315 long_output_names we prepend the processed name of the input file
2316 to each output name (except when the current source file is the
2317 input file, so you don't get a double concatenation). The two
2318 components are separated by '##'. With preserve_paths we create a
2319 filename from all path components of the source file, replacing '/'
2320 with '#', and .. with '^', without it we simply take the basename
2321 component. (Remember, the canonicalized name will already have
2322 elided '.' components and converted \\ separators.) */
2324 static char *
2325 make_gcov_file_name (const char *input_name, const char *src_name)
2327 char *ptr;
2328 char *result;
2330 if (flag_long_names && input_name && strcmp (src_name, input_name))
2332 /* Generate the input filename part. */
2333 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2335 ptr = result;
2336 ptr = mangle_name (input_name, ptr);
2337 ptr[0] = ptr[1] = '#';
2338 ptr += 2;
2340 else
2342 result = XNEWVEC (char, strlen (src_name) + 10);
2343 ptr = result;
2346 ptr = mangle_name (src_name, ptr);
2347 strcpy (ptr, ".gcov");
2349 /* When hashing filenames, we shorten them by only using the filename
2350 component and appending a hash of the full (mangled) pathname. */
2351 if (flag_hash_filenames)
2353 md5_ctx ctx;
2354 char md5sum[16];
2355 char md5sum_hex[33];
2357 md5_init_ctx (&ctx);
2358 md5_process_bytes (src_name, strlen (src_name), &ctx);
2359 md5_finish_ctx (&ctx, md5sum);
2360 md5sum_to_hex (md5sum, md5sum_hex);
2361 free (result);
2363 result = XNEWVEC (char, strlen (src_name) + 50);
2364 ptr = result;
2365 ptr = mangle_name (src_name, ptr);
2366 ptr[0] = ptr[1] = '#';
2367 ptr += 2;
2368 memcpy (ptr, md5sum_hex, 32);
2369 ptr += 32;
2370 strcpy (ptr, ".gcov");
2373 return result;
2376 static char *
2377 mangle_name (char const *base, char *ptr)
2379 size_t len;
2381 /* Generate the source filename part. */
2382 if (!flag_preserve_paths)
2384 base = lbasename (base);
2385 len = strlen (base);
2386 memcpy (ptr, base, len);
2387 ptr += len;
2389 else
2391 /* Convert '/' to '#', convert '..' to '^',
2392 convert ':' to '~' on DOS based file system. */
2393 const char *probe;
2395 #if HAVE_DOS_BASED_FILE_SYSTEM
2396 if (base[0] && base[1] == ':')
2398 ptr[0] = base[0];
2399 ptr[1] = '~';
2400 ptr += 2;
2401 base += 2;
2403 #endif
2404 for (; *base; base = probe)
2406 size_t len;
2408 for (probe = base; *probe; probe++)
2409 if (*probe == '/')
2410 break;
2411 len = probe - base;
2412 if (len == 2 && base[0] == '.' && base[1] == '.')
2413 *ptr++ = '^';
2414 else
2416 memcpy (ptr, base, len);
2417 ptr += len;
2419 if (*probe)
2421 *ptr++ = '#';
2422 probe++;
2427 return ptr;
2430 /* Scan through the bb_data for each line in the block, increment
2431 the line number execution count indicated by the execution count of
2432 the appropriate basic block. */
2434 static void
2435 add_line_counts (coverage_t *coverage, function_t *fn)
2437 bool has_any_line = false;
2438 /* Scan each basic block. */
2439 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2441 line_info *line = NULL;
2442 block_t *block = &fn->blocks[ix];
2443 if (block->count && ix && ix + 1 != fn->blocks.size ())
2444 fn->blocks_executed++;
2445 for (unsigned i = 0; i < block->locations.size (); i++)
2447 unsigned src_idx = block->locations[i].source_file_idx;
2448 vector<unsigned> &lines = block->locations[i].lines;
2450 block->cycle.arc = NULL;
2451 block->cycle.ident = ~0U;
2453 for (unsigned j = 0; j < lines.size (); j++)
2455 unsigned ln = lines[j];
2457 /* Line belongs to a function that is in a group. */
2458 if (fn->group_line_p (ln, src_idx))
2460 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2461 line = &(fn->lines[lines[j] - fn->start_line]);
2462 line->exists = 1;
2463 if (!block->exceptional)
2465 line->unexceptional = 1;
2466 if (block->count == 0)
2467 line->has_unexecuted_block = 1;
2469 line->count += block->count;
2471 else
2473 gcc_assert (ln < sources[src_idx].lines.size ());
2474 line = &(sources[src_idx].lines[ln]);
2475 if (coverage)
2477 if (!line->exists)
2478 coverage->lines++;
2479 if (!line->count && block->count)
2480 coverage->lines_executed++;
2482 line->exists = 1;
2483 if (!block->exceptional)
2485 line->unexceptional = 1;
2486 if (block->count == 0)
2487 line->has_unexecuted_block = 1;
2489 line->count += block->count;
2493 has_any_line = true;
2495 if (!ix || ix + 1 == fn->blocks.size ())
2496 /* Entry or exit block. */;
2497 else if (line != NULL)
2499 line->blocks.push_back (block);
2501 if (flag_branches)
2503 arc_t *arc;
2505 for (arc = block->succ; arc; arc = arc->succ_next)
2506 line->branches.push_back (arc);
2512 if (!has_any_line)
2513 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name, fn->name);
2516 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2517 is set to true, update source file summary. */
2519 static void accumulate_line_info (line_info *line, source_info *src,
2520 bool add_coverage)
2522 if (add_coverage)
2523 for (vector<arc_info *>::iterator it = line->branches.begin ();
2524 it != line->branches.end (); it++)
2525 add_branch_counts (&src->coverage, *it);
2527 if (!line->blocks.empty ())
2529 /* The user expects the line count to be the number of times
2530 a line has been executed. Simply summing the block count
2531 will give an artificially high number. The Right Thing
2532 is to sum the entry counts to the graph of blocks on this
2533 line, then find the elementary cycles of the local graph
2534 and add the transition counts of those cycles. */
2535 gcov_type count = 0;
2537 /* Cycle detection. */
2538 for (vector<block_t *>::iterator it = line->blocks.begin ();
2539 it != line->blocks.end (); it++)
2541 for (arc_t *arc = (*it)->pred; arc; arc = arc->pred_next)
2542 if (!line->has_block (arc->src))
2543 count += arc->count;
2544 for (arc_t *arc = (*it)->succ; arc; arc = arc->succ_next)
2545 arc->cs_count = arc->count;
2548 /* Now, add the count of loops entirely on this line. */
2549 count += get_cycles_count (*line);
2550 line->count = count;
2553 if (line->exists && add_coverage)
2555 src->coverage.lines++;
2556 if (line->count)
2557 src->coverage.lines_executed++;
2561 /* Accumulate the line counts of a file. */
2563 static void
2564 accumulate_line_counts (source_info *src)
2566 /* First work on group functions. */
2567 for (vector<function_t *>::iterator it = src->functions.begin ();
2568 it != src->functions.end (); it++)
2570 function_info *fn = *it;
2572 if (fn->src != src->index || !fn->is_group)
2573 continue;
2575 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2576 it2 != fn->lines.end (); it2++)
2578 line_info *line = &(*it2);
2579 accumulate_line_info (line, src, false);
2583 /* Work on global lines that line in source file SRC. */
2584 for (vector<line_info>::iterator it = src->lines.begin ();
2585 it != src->lines.end (); it++)
2586 accumulate_line_info (&(*it), src, true);
2588 /* If not using intermediate mode, sum lines of group functions and
2589 add them to lines that live in a source file. */
2590 if (!flag_intermediate_format)
2591 for (vector<function_t *>::iterator it = src->functions.begin ();
2592 it != src->functions.end (); it++)
2594 function_info *fn = *it;
2596 if (fn->src != src->index || !fn->is_group)
2597 continue;
2599 for (unsigned i = 0; i < fn->lines.size (); i++)
2601 line_info *fn_line = &fn->lines[i];
2602 if (fn_line->exists)
2604 unsigned ln = fn->start_line + i;
2605 line_info *src_line = &src->lines[ln];
2607 if (!src_line->exists)
2608 src->coverage.lines++;
2609 if (!src_line->count && fn_line->count)
2610 src->coverage.lines_executed++;
2612 src_line->count += fn_line->count;
2613 src_line->exists = 1;
2615 if (fn_line->has_unexecuted_block)
2616 src_line->has_unexecuted_block = 1;
2618 if (fn_line->unexceptional)
2619 src_line->unexceptional = 1;
2625 /* Output information about ARC number IX. Returns nonzero if
2626 anything is output. */
2628 static int
2629 output_branch_count (FILE *gcov_file, int ix, const arc_t *arc)
2631 if (arc->is_call_non_return)
2633 if (arc->src->count)
2635 fnotice (gcov_file, "call %2d returned %s\n", ix,
2636 format_gcov (arc->src->count - arc->count,
2637 arc->src->count, -flag_counts));
2639 else
2640 fnotice (gcov_file, "call %2d never executed\n", ix);
2642 else if (!arc->is_unconditional)
2644 if (arc->src->count)
2645 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2646 format_gcov (arc->count, arc->src->count, -flag_counts),
2647 arc->fall_through ? " (fallthrough)"
2648 : arc->is_throw ? " (throw)" : "");
2649 else
2650 fnotice (gcov_file, "branch %2d never executed", ix);
2652 if (flag_verbose)
2653 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2655 fnotice (gcov_file, "\n");
2657 else if (flag_unconditional && !arc->dst->is_call_return)
2659 if (arc->src->count)
2660 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2661 format_gcov (arc->count, arc->src->count, -flag_counts));
2662 else
2663 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2665 else
2666 return 0;
2667 return 1;
2670 static const char *
2671 read_line (FILE *file)
2673 static char *string;
2674 static size_t string_len;
2675 size_t pos = 0;
2676 char *ptr;
2678 if (!string_len)
2680 string_len = 200;
2681 string = XNEWVEC (char, string_len);
2684 while ((ptr = fgets (string + pos, string_len - pos, file)))
2686 size_t len = strlen (string + pos);
2688 if (len && string[pos + len - 1] == '\n')
2690 string[pos + len - 1] = 0;
2691 return string;
2693 pos += len;
2694 /* If the file contains NUL characters or an incomplete
2695 last line, which can happen more than once in one run,
2696 we have to avoid doubling the STRING_LEN unnecessarily. */
2697 if (pos > string_len / 2)
2699 string_len *= 2;
2700 string = XRESIZEVEC (char, string, string_len);
2704 return pos ? string : NULL;
2707 /* Pad string S with spaces from left to have total width equal to 9. */
2709 static void
2710 pad_count_string (string &s)
2712 if (s.size () < 9)
2713 s.insert (0, 9 - s.size (), ' ');
2716 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2717 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2718 an exceptional statement. The output is printed for LINE_NUM of given
2719 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2720 used to indicate non-executed blocks. */
2722 static void
2723 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2724 bool has_unexecuted_block,
2725 gcov_type count, unsigned line_num,
2726 const char *exceptional_string,
2727 const char *unexceptional_string)
2729 string s;
2730 if (exists)
2732 if (count > 0)
2734 s = format_gcov (count, 0, -1);
2735 if (has_unexecuted_block)
2737 if (flag_use_colors)
2739 pad_count_string (s);
2740 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2741 COLOR_SEPARATOR COLOR_FG_WHITE));
2742 s += SGR_RESET;
2744 else
2745 s += "*";
2747 pad_count_string (s);
2749 else
2751 if (flag_use_colors)
2753 s = "0";
2754 pad_count_string (s);
2755 if (unexceptional)
2756 s.insert (0, SGR_SEQ (COLOR_BG_RED
2757 COLOR_SEPARATOR COLOR_FG_WHITE));
2758 else
2759 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2760 COLOR_SEPARATOR COLOR_FG_WHITE));
2761 s += SGR_RESET;
2763 else
2765 s = unexceptional ? unexceptional_string : exceptional_string;
2766 pad_count_string (s);
2770 else
2772 s = "-";
2773 pad_count_string (s);
2776 fprintf (f, "%s:%5u", s.c_str (), line_num);
2779 static void
2780 print_source_line (FILE *f, const vector<const char *> &source_lines,
2781 unsigned line)
2783 gcc_assert (line >= 1);
2784 gcc_assert (line <= source_lines.size ());
2786 fprintf (f, ":%s\n", source_lines[line - 1]);
2789 /* Output line details for LINE and print it to F file. LINE lives on
2790 LINE_NUM. */
2792 static void
2793 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2795 if (flag_all_blocks)
2797 arc_t *arc;
2798 int ix, jx;
2800 ix = jx = 0;
2801 for (vector<block_t *>::const_iterator it = line->blocks.begin ();
2802 it != line->blocks.end (); it++)
2804 if (!(*it)->is_call_return)
2806 output_line_beginning (f, line->exists,
2807 (*it)->exceptional, false,
2808 (*it)->count, line_num,
2809 "%%%%%", "$$$$$");
2810 fprintf (f, "-block %2d", ix++);
2811 if (flag_verbose)
2812 fprintf (f, " (BB %u)", (*it)->id);
2813 fprintf (f, "\n");
2815 if (flag_branches)
2816 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2817 jx += output_branch_count (f, jx, arc);
2820 else if (flag_branches)
2822 int ix;
2824 ix = 0;
2825 for (vector<arc_t *>::const_iterator it = line->branches.begin ();
2826 it != line->branches.end (); it++)
2827 ix += output_branch_count (f, ix, (*it));
2831 /* Output detail statistics about function FN to file F. */
2833 static void
2834 output_function_details (FILE *f, const function_info *fn)
2836 if (!flag_branches)
2837 return;
2839 arc_t *arc = fn->blocks[EXIT_BLOCK].pred;
2840 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
2841 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
2843 for (; arc; arc = arc->pred_next)
2844 if (arc->fake)
2845 return_count -= arc->count;
2847 fprintf (f, "function %s",
2848 flag_demangled_names ? fn->demangled_name : fn->name);
2849 fprintf (f, " called %s",
2850 format_gcov (called_count, 0, -1));
2851 fprintf (f, " returned %s",
2852 format_gcov (return_count, called_count, 0));
2853 fprintf (f, " blocks executed %s",
2854 format_gcov (fn->blocks_executed, fn->blocks.size () - 2,
2855 0));
2856 fprintf (f, "\n");
2859 /* Read in the source file one line at a time, and output that line to
2860 the gcov file preceded by its execution count and other
2861 information. */
2863 static void
2864 output_lines (FILE *gcov_file, const source_info *src)
2866 #define DEFAULT_LINE_START " -: 0:"
2867 #define FN_SEPARATOR "------------------\n"
2869 FILE *source_file;
2870 const char *retval;
2872 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
2873 if (!multiple_files)
2875 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
2876 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
2877 no_data_file ? "-" : da_file_name);
2878 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
2880 fprintf (gcov_file, DEFAULT_LINE_START "Programs:%u\n", program_count);
2882 source_file = fopen (src->name, "r");
2883 if (!source_file)
2884 fnotice (stderr, "Cannot open source file %s\n", src->name);
2885 else if (src->file_time == 0)
2886 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
2888 vector<const char *> source_lines;
2889 if (source_file)
2890 while ((retval = read_line (source_file)) != NULL)
2891 source_lines.push_back (xstrdup (retval));
2893 unsigned line_start_group = 0;
2894 vector<function_t *> fns;
2896 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
2898 if (line_num >= src->lines.size ())
2900 fprintf (gcov_file, "%9s:%5u", "-", line_num);
2901 print_source_line (gcov_file, source_lines, line_num);
2902 continue;
2905 const line_info *line = &src->lines[line_num];
2907 if (line_start_group == 0)
2909 fns = src->get_functions_at_location (line_num);
2910 if (fns.size () > 1)
2911 line_start_group = fns[0]->end_line;
2912 else if (fns.size () == 1)
2914 function_t *fn = fns[0];
2915 output_function_details (gcov_file, fn);
2919 /* For lines which don't exist in the .bb file, print '-' before
2920 the source line. For lines which exist but were never
2921 executed, print '#####' or '=====' before the source line.
2922 Otherwise, print the execution count before the source line.
2923 There are 16 spaces of indentation added before the source
2924 line so that tabs won't be messed up. */
2925 output_line_beginning (gcov_file, line->exists, line->unexceptional,
2926 line->has_unexecuted_block, line->count,
2927 line_num, "=====", "#####");
2929 print_source_line (gcov_file, source_lines, line_num);
2930 output_line_details (gcov_file, line, line_num);
2932 if (line_start_group == line_num)
2934 for (vector<function_t *>::iterator it = fns.begin ();
2935 it != fns.end (); it++)
2937 function_info *fn = *it;
2938 vector<line_info> &lines = fn->lines;
2940 fprintf (gcov_file, FN_SEPARATOR);
2942 string fn_name
2943 = flag_demangled_names ? fn->demangled_name : fn->name;
2945 if (flag_use_colors)
2947 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
2948 fn_name += SGR_RESET;
2951 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
2953 output_function_details (gcov_file, fn);
2955 /* Print all lines covered by the function. */
2956 for (unsigned i = 0; i < lines.size (); i++)
2958 line_info *line = &lines[i];
2959 unsigned l = fn->start_line + i;
2961 /* For lines which don't exist in the .bb file, print '-'
2962 before the source line. For lines which exist but
2963 were never executed, print '#####' or '=====' before
2964 the source line. Otherwise, print the execution count
2965 before the source line.
2966 There are 16 spaces of indentation added before the source
2967 line so that tabs won't be messed up. */
2968 output_line_beginning (gcov_file, line->exists,
2969 line->unexceptional,
2970 line->has_unexecuted_block,
2971 line->count,
2972 l, "=====", "#####");
2974 print_source_line (gcov_file, source_lines, l);
2975 output_line_details (gcov_file, line, l);
2979 fprintf (gcov_file, FN_SEPARATOR);
2980 line_start_group = 0;
2984 if (source_file)
2985 fclose (source_file);