[PATCH c++/86881] -Wshadow-local-compatible ICE
[official-gcc.git] / gcc / gcov.c
blobc09d506005388df04163bb4c3fc3b2c95038b190
1 /* Gcov.c: prepend line execution counts and branch probabilities to a
2 source file.
3 Copyright (C) 1990-2018 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 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;
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 struct block_info
136 /* Constructor. */
137 block_info ();
139 /* Chain of exit and entry arcs. */
140 arc_info *succ;
141 arc_info *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_info *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;
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_info *needle);
199 /* Execution count. */
200 gcov_type count;
202 /* Branches from blocks that end on this line. */
203 vector<arc_info *> branches;
205 /* blocks which start on this line. Used in all-blocks mode. */
206 vector<block_info *> 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_info *needle)
221 return std::find (blocks.begin (), blocks.end (), needle) != blocks.end ();
224 /* Describes a single function. Contains an array of basic blocks. */
226 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 /* Function filter based on function_info::artificial variable. */
237 static inline bool
238 is_artificial (function_info *fn)
240 return fn->artificial;
243 /* Name of function. */
244 char *name;
245 char *demangled_name;
246 unsigned ident;
247 unsigned lineno_checksum;
248 unsigned cfg_checksum;
250 /* The graph contains at least one fake incoming edge. */
251 unsigned has_catch : 1;
253 /* True when the function is artificial and does not exist
254 in a source file. */
255 unsigned artificial : 1;
257 /* True when multiple functions start at a line in a source file. */
258 unsigned is_group : 1;
260 /* Array of basic blocks. Like in GCC, the entry block is
261 at blocks[0] and the exit block is at blocks[1]. */
262 #define ENTRY_BLOCK (0)
263 #define EXIT_BLOCK (1)
264 vector<block_info> blocks;
265 unsigned blocks_executed;
267 /* Raw arc coverage counts. */
268 vector<gcov_type> counts;
270 /* First line number. */
271 unsigned start_line;
273 /* First line column. */
274 unsigned start_column;
276 /* Last line number. */
277 unsigned end_line;
279 /* Index of source file where the function is defined. */
280 unsigned src;
282 /* Vector of line information. */
283 vector<line_info> lines;
285 /* Next function. */
286 struct function_info *next;
289 /* Function info comparer that will sort functions according to starting
290 line. */
292 struct function_line_start_cmp
294 inline bool operator() (const function_info *lhs,
295 const function_info *rhs)
297 return (lhs->start_line == rhs->start_line
298 ? lhs->start_column < rhs->start_column
299 : lhs->start_line < rhs->start_line);
303 /* Describes coverage of a file or function. */
305 struct coverage_info
307 int lines;
308 int lines_executed;
310 int branches;
311 int branches_executed;
312 int branches_taken;
314 int calls;
315 int calls_executed;
317 char *name;
320 /* Describes a file mentioned in the block graph. Contains an array
321 of line info. */
323 struct source_info
325 /* Default constructor. */
326 source_info ();
328 vector<function_info *> get_functions_at_location (unsigned line_num) const;
330 /* Index of the source_info in sources vector. */
331 unsigned index;
333 /* Canonical name of source file. */
334 char *name;
335 time_t file_time;
337 /* Vector of line information. */
338 vector<line_info> lines;
340 coverage_info coverage;
342 /* Maximum line count in the source file. */
343 unsigned int maximum_count;
345 /* Functions in this source file. These are in ascending line
346 number order. */
347 vector <function_info *> functions;
350 source_info::source_info (): index (0), name (NULL), file_time (),
351 lines (), coverage (), maximum_count (0), functions ()
355 vector<function_info *>
356 source_info::get_functions_at_location (unsigned line_num) const
358 vector<function_info *> r;
360 for (vector<function_info *>::const_iterator it = functions.begin ();
361 it != functions.end (); it++)
363 if ((*it)->start_line == line_num && (*it)->src == index)
364 r.push_back (*it);
367 std::sort (r.begin (), r.end (), function_line_start_cmp ());
369 return r;
372 class name_map
374 public:
375 name_map ()
379 name_map (char *_name, unsigned _src): name (_name), src (_src)
383 bool operator== (const name_map &rhs) const
385 #if HAVE_DOS_BASED_FILE_SYSTEM
386 return strcasecmp (this->name, rhs.name) == 0;
387 #else
388 return strcmp (this->name, rhs.name) == 0;
389 #endif
392 bool operator< (const name_map &rhs) const
394 #if HAVE_DOS_BASED_FILE_SYSTEM
395 return strcasecmp (this->name, rhs.name) < 0;
396 #else
397 return strcmp (this->name, rhs.name) < 0;
398 #endif
401 const char *name; /* Source file name */
402 unsigned src; /* Source file */
405 /* Vector of all functions. */
406 static vector<function_info *> functions;
408 /* Vector of source files. */
409 static vector<source_info> sources;
411 /* Mapping of file names to sources */
412 static vector<name_map> names;
414 /* Record all processed files in order to warn about
415 a file being read multiple times. */
416 static vector<char *> processed_files;
418 /* This holds data summary information. */
420 static unsigned object_runs;
421 static unsigned program_count;
423 static unsigned total_lines;
424 static unsigned total_executed;
426 /* Modification time of graph file. */
428 static time_t bbg_file_time;
430 /* Name of the notes (gcno) output file. The "bbg" prefix is for
431 historical reasons, when the notes file contained only the
432 basic block graph notes. */
434 static char *bbg_file_name;
436 /* Stamp of the bbg file */
437 static unsigned bbg_stamp;
439 /* Supports has_unexecuted_blocks functionality. */
440 static unsigned bbg_supports_has_unexecuted_blocks;
442 /* Working directory in which a TU was compiled. */
443 static const char *bbg_cwd;
445 /* Name and file pointer of the input file for the count data (gcda). */
447 static char *da_file_name;
449 /* Data file is missing. */
451 static int no_data_file;
453 /* If there is several input files, compute and display results after
454 reading all data files. This way if two or more gcda file refer to
455 the same source file (eg inline subprograms in a .h file), the
456 counts are added. */
458 static int multiple_files = 0;
460 /* Output branch probabilities. */
462 static int flag_branches = 0;
464 /* Show unconditional branches too. */
465 static int flag_unconditional = 0;
467 /* Output a gcov file if this is true. This is on by default, and can
468 be turned off by the -n option. */
470 static int flag_gcov_file = 1;
472 /* Output to stdout instead to a gcov file. */
474 static int flag_use_stdout = 0;
476 /* Output progress indication if this is true. This is off by default
477 and can be turned on by the -d option. */
479 static int flag_display_progress = 0;
481 /* Output *.gcov file in intermediate format used by 'lcov'. */
483 static int flag_intermediate_format = 0;
485 /* Output demangled function names. */
487 static int flag_demangled_names = 0;
489 /* For included files, make the gcov output file name include the name
490 of the input source file. For example, if x.h is included in a.c,
491 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
493 static int flag_long_names = 0;
495 /* For situations when a long name can potentially hit filesystem path limit,
496 let's calculate md5sum of the path and append it to a file name. */
498 static int flag_hash_filenames = 0;
500 /* Print verbose informations. */
502 static int flag_verbose = 0;
504 /* Print colored output. */
506 static int flag_use_colors = 0;
508 /* Use perf-like colors to indicate hot lines. */
510 static int flag_use_hotness_colors = 0;
512 /* Output count information for every basic block, not merely those
513 that contain line number information. */
515 static int flag_all_blocks = 0;
517 /* Output human readable numbers. */
519 static int flag_human_readable_numbers = 0;
521 /* Output summary info for each function. */
523 static int flag_function_summary = 0;
525 /* Object directory file prefix. This is the directory/file where the
526 graph and data files are looked for, if nonzero. */
528 static char *object_directory = 0;
530 /* Source directory prefix. This is removed from source pathnames
531 that match, when generating the output file name. */
533 static char *source_prefix = 0;
534 static size_t source_length = 0;
536 /* Only show data for sources with relative pathnames. Absolute ones
537 usually indicate a system header file, which although it may
538 contain inline functions, is usually uninteresting. */
539 static int flag_relative_only = 0;
541 /* Preserve all pathname components. Needed when object files and
542 source files are in subdirectories. '/' is mangled as '#', '.' is
543 elided and '..' mangled to '^'. */
545 static int flag_preserve_paths = 0;
547 /* Output the number of times a branch was taken as opposed to the percentage
548 of times it was taken. */
550 static int flag_counts = 0;
552 /* Forward declarations. */
553 static int process_args (int, char **);
554 static void print_usage (int) ATTRIBUTE_NORETURN;
555 static void print_version (void) ATTRIBUTE_NORETURN;
556 static void process_file (const char *);
557 static void process_all_functions (void);
558 static void generate_results (const char *);
559 static void create_file_names (const char *);
560 static char *canonicalize_name (const char *);
561 static unsigned find_source (const char *);
562 static void read_graph_file (void);
563 static int read_count_file (void);
564 static void solve_flow_graph (function_info *);
565 static void find_exception_blocks (function_info *);
566 static void add_branch_counts (coverage_info *, const arc_info *);
567 static void add_line_counts (coverage_info *, function_info *);
568 static void executed_summary (unsigned, unsigned);
569 static void function_summary (const coverage_info *, const char *);
570 static const char *format_gcov (gcov_type, gcov_type, int);
571 static void accumulate_line_counts (source_info *);
572 static void output_gcov_file (const char *, source_info *);
573 static int output_branch_count (FILE *, int, const arc_info *);
574 static void output_lines (FILE *, const source_info *);
575 static char *make_gcov_file_name (const char *, const char *);
576 static char *mangle_name (const char *, char *);
577 static void release_structures (void);
578 extern int main (int, char **);
580 function_info::function_info (): name (NULL), demangled_name (NULL),
581 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
582 artificial (0), is_group (0),
583 blocks (), blocks_executed (0), counts (),
584 start_line (0), start_column (), end_line (0), src (0), lines (), next (NULL)
588 function_info::~function_info ()
590 for (int i = blocks.size () - 1; i >= 0; i--)
592 arc_info *arc, *arc_n;
594 for (arc = blocks[i].succ; arc; arc = arc_n)
596 arc_n = arc->succ_next;
597 free (arc);
600 if (flag_demangled_names && demangled_name != name)
601 free (demangled_name);
602 free (name);
605 bool function_info::group_line_p (unsigned n, unsigned src_idx)
607 return is_group && src == src_idx && start_line <= n && n <= end_line;
610 /* Cycle detection!
611 There are a bajillion algorithms that do this. Boost's function is named
612 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
613 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
614 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
616 The basic algorithm is simple: effectively, we're finding all simple paths
617 in a subgraph (that shrinks every iteration). Duplicates are filtered by
618 "blocking" a path when a node is added to the path (this also prevents non-
619 simple paths)--the node is unblocked only when it participates in a cycle.
622 typedef vector<arc_info *> arc_vector_t;
623 typedef vector<const block_info *> block_vector_t;
625 /* Enum with types of loop in CFG. */
627 enum loop_type
629 NO_LOOP = 0,
630 LOOP = 1,
631 NEGATIVE_LOOP = 3
634 /* Loop_type operator that merges two values: A and B. */
636 inline loop_type& operator |= (loop_type& a, loop_type b)
638 return a = static_cast<loop_type> (a | b);
641 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
642 and subtract the value from all counts. The subtracted value is added
643 to COUNT. Returns type of loop. */
645 static loop_type
646 handle_cycle (const arc_vector_t &edges, int64_t &count)
648 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
649 that amount. */
650 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
651 for (unsigned i = 0; i < edges.size (); i++)
653 int64_t ecount = edges[i]->cs_count;
654 if (cycle_count > ecount)
655 cycle_count = ecount;
657 count += cycle_count;
658 for (unsigned i = 0; i < edges.size (); i++)
659 edges[i]->cs_count -= cycle_count;
661 return cycle_count < 0 ? NEGATIVE_LOOP : LOOP;
664 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
665 blocked by U in BLOCK_LISTS. */
667 static void
668 unblock (const block_info *u, block_vector_t &blocked,
669 vector<block_vector_t > &block_lists)
671 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
672 if (it == blocked.end ())
673 return;
675 unsigned index = it - blocked.begin ();
676 blocked.erase (it);
678 block_vector_t to_unblock (block_lists[index]);
680 block_lists.erase (block_lists.begin () + index);
682 for (block_vector_t::iterator it = to_unblock.begin ();
683 it != to_unblock.end (); it++)
684 unblock (*it, blocked, block_lists);
687 /* Find circuit going to block V, PATH is provisional seen cycle.
688 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
689 blocked by a block. COUNT is accumulated count of the current LINE.
690 Returns what type of loop it contains. */
692 static loop_type
693 circuit (block_info *v, arc_vector_t &path, block_info *start,
694 block_vector_t &blocked, vector<block_vector_t> &block_lists,
695 line_info &linfo, int64_t &count)
697 loop_type result = NO_LOOP;
699 /* Add v to the block list. */
700 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
701 blocked.push_back (v);
702 block_lists.push_back (block_vector_t ());
704 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
706 block_info *w = arc->dst;
707 if (w < start || !linfo.has_block (w))
708 continue;
710 path.push_back (arc);
711 if (w == start)
712 /* Cycle has been found. */
713 result |= handle_cycle (path, count);
714 else if (find (blocked.begin (), blocked.end (), w) == blocked.end ())
715 result |= circuit (w, path, start, blocked, block_lists, linfo, count);
717 path.pop_back ();
720 if (result != NO_LOOP)
721 unblock (v, blocked, block_lists);
722 else
723 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
725 block_info *w = arc->dst;
726 if (w < start || !linfo.has_block (w))
727 continue;
729 size_t index
730 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
731 gcc_assert (index < blocked.size ());
732 block_vector_t &list = block_lists[index];
733 if (find (list.begin (), list.end (), v) == list.end ())
734 list.push_back (v);
737 return result;
740 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
741 contains a negative loop, then perform the same function once again. */
743 static gcov_type
744 get_cycles_count (line_info &linfo, bool handle_negative_cycles = true)
746 /* Note that this algorithm works even if blocks aren't in sorted order.
747 Each iteration of the circuit detection is completely independent
748 (except for reducing counts, but that shouldn't matter anyways).
749 Therefore, operating on a permuted order (i.e., non-sorted) only
750 has the effect of permuting the output cycles. */
752 loop_type result = NO_LOOP;
753 gcov_type count = 0;
754 for (vector<block_info *>::iterator it = linfo.blocks.begin ();
755 it != linfo.blocks.end (); it++)
757 arc_vector_t path;
758 block_vector_t blocked;
759 vector<block_vector_t > block_lists;
760 result |= circuit (*it, path, *it, blocked, block_lists, linfo,
761 count);
764 /* If we have a negative cycle, repeat the find_cycles routine. */
765 if (result == NEGATIVE_LOOP && handle_negative_cycles)
766 count += get_cycles_count (linfo, false);
768 return count;
772 main (int argc, char **argv)
774 int argno;
775 int first_arg;
776 const char *p;
778 p = argv[0] + strlen (argv[0]);
779 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
780 --p;
781 progname = p;
783 xmalloc_set_program_name (progname);
785 /* Unlock the stdio streams. */
786 unlock_std_streams ();
788 gcc_init_libintl ();
790 diagnostic_initialize (global_dc, 0);
792 /* Handle response files. */
793 expandargv (&argc, &argv);
795 argno = process_args (argc, argv);
796 if (optind == argc)
797 print_usage (true);
799 if (argc - argno > 1)
800 multiple_files = 1;
802 first_arg = argno;
804 for (; argno != argc; argno++)
806 if (flag_display_progress)
807 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
808 argc - first_arg);
809 process_file (argv[argno]);
811 if (flag_intermediate_format || argno == argc - 1)
813 process_all_functions ();
814 generate_results (argv[argno]);
815 release_structures ();
819 return 0;
822 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
823 otherwise the output of --help. */
825 static void
826 print_usage (int error_p)
828 FILE *file = error_p ? stderr : stdout;
829 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
831 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
832 fnotice (file, "Print code coverage information.\n\n");
833 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
834 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
835 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
836 rather than percentages\n");
837 fnotice (file, " -d, --display-progress Display progress information\n");
838 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
839 fnotice (file, " -h, --help Print this help, then exit\n");
840 fnotice (file, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
841 fnotice (file, " -j, --human-readable Output human readable numbers\n");
842 fnotice (file, " -k, --use-colors Emit colored output\n");
843 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
844 source files\n");
845 fnotice (file, " -m, --demangled-names Output demangled function names\n");
846 fnotice (file, " -n, --no-output Do not create an output file\n");
847 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
848 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
849 fnotice (file, " -q, --use-hotness-colors Emit perf-like colored output for hot lines\n");
850 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
851 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
852 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
853 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
854 fnotice (file, " -v, --version Print version number, then exit\n");
855 fnotice (file, " -w, --verbose Print verbose informations\n");
856 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
857 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
858 bug_report_url);
859 exit (status);
862 /* Print version information and exit. */
864 static void
865 print_version (void)
867 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
868 fprintf (stdout, "Copyright %s 2018 Free Software Foundation, Inc.\n",
869 _("(C)"));
870 fnotice (stdout,
871 _("This is free software; see the source for copying conditions.\n"
872 "There is NO warranty; not even for MERCHANTABILITY or \n"
873 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
874 exit (SUCCESS_EXIT_CODE);
877 static const struct option options[] =
879 { "help", no_argument, NULL, 'h' },
880 { "version", no_argument, NULL, 'v' },
881 { "verbose", no_argument, NULL, 'w' },
882 { "all-blocks", no_argument, NULL, 'a' },
883 { "branch-probabilities", no_argument, NULL, 'b' },
884 { "branch-counts", no_argument, NULL, 'c' },
885 { "intermediate-format", no_argument, NULL, 'i' },
886 { "human-readable", no_argument, NULL, 'j' },
887 { "no-output", no_argument, NULL, 'n' },
888 { "long-file-names", no_argument, NULL, 'l' },
889 { "function-summaries", no_argument, NULL, 'f' },
890 { "demangled-names", no_argument, NULL, 'm' },
891 { "preserve-paths", no_argument, NULL, 'p' },
892 { "relative-only", no_argument, NULL, 'r' },
893 { "object-directory", required_argument, NULL, 'o' },
894 { "object-file", required_argument, NULL, 'o' },
895 { "source-prefix", required_argument, NULL, 's' },
896 { "stdout", no_argument, NULL, 't' },
897 { "unconditional-branches", no_argument, NULL, 'u' },
898 { "display-progress", no_argument, NULL, 'd' },
899 { "hash-filenames", no_argument, NULL, 'x' },
900 { "use-colors", no_argument, NULL, 'k' },
901 { "use-hotness-colors", no_argument, NULL, 'q' },
902 { 0, 0, 0, 0 }
905 /* Process args, return index to first non-arg. */
907 static int
908 process_args (int argc, char **argv)
910 int opt;
912 const char *opts = "abcdfhijklmno:pqrs:tuvwx";
913 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
915 switch (opt)
917 case 'a':
918 flag_all_blocks = 1;
919 break;
920 case 'b':
921 flag_branches = 1;
922 break;
923 case 'c':
924 flag_counts = 1;
925 break;
926 case 'f':
927 flag_function_summary = 1;
928 break;
929 case 'h':
930 print_usage (false);
931 /* print_usage will exit. */
932 case 'l':
933 flag_long_names = 1;
934 break;
935 case 'j':
936 flag_human_readable_numbers = 1;
937 break;
938 case 'k':
939 flag_use_colors = 1;
940 break;
941 case 'q':
942 flag_use_hotness_colors = 1;
943 break;
944 case 'm':
945 flag_demangled_names = 1;
946 break;
947 case 'n':
948 flag_gcov_file = 0;
949 break;
950 case 'o':
951 object_directory = optarg;
952 break;
953 case 's':
954 source_prefix = optarg;
955 source_length = strlen (source_prefix);
956 break;
957 case 'r':
958 flag_relative_only = 1;
959 break;
960 case 'p':
961 flag_preserve_paths = 1;
962 break;
963 case 'u':
964 flag_unconditional = 1;
965 break;
966 case 'i':
967 flag_intermediate_format = 1;
968 flag_gcov_file = 1;
969 break;
970 case 'd':
971 flag_display_progress = 1;
972 break;
973 case 'x':
974 flag_hash_filenames = 1;
975 break;
976 case 'w':
977 flag_verbose = 1;
978 break;
979 case 't':
980 flag_use_stdout = 1;
981 break;
982 case 'v':
983 print_version ();
984 /* print_version will exit. */
985 default:
986 print_usage (true);
987 /* print_usage will exit. */
991 return optind;
994 /* Output intermediate LINE sitting on LINE_NUM to output file F. */
996 static void
997 output_intermediate_line (FILE *f, line_info *line, unsigned line_num)
999 if (!line->exists)
1000 return;
1002 fprintf (f, "lcount:%u,%s,%d\n", line_num,
1003 format_gcov (line->count, 0, -1),
1004 line->has_unexecuted_block);
1006 vector<arc_info *>::const_iterator it;
1007 if (flag_branches)
1008 for (it = line->branches.begin (); it != line->branches.end ();
1009 it++)
1011 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1013 const char *branch_type;
1014 /* branch:<line_num>,<branch_coverage_infoype>
1015 branch_coverage_infoype
1016 : notexec (Branch not executed)
1017 : taken (Branch executed and taken)
1018 : nottaken (Branch executed, but not taken)
1020 if ((*it)->src->count)
1021 branch_type
1022 = ((*it)->count > 0) ? "taken" : "nottaken";
1023 else
1024 branch_type = "notexec";
1025 fprintf (f, "branch:%d,%s\n", line_num, branch_type);
1030 /* Get the name of the gcov file. The return value must be free'd.
1032 It appends the '.gcov' extension to the *basename* of the file.
1033 The resulting file name will be in PWD.
1035 e.g.,
1036 input: foo.da, output: foo.da.gcov
1037 input: a/b/foo.cc, output: foo.cc.gcov */
1039 static char *
1040 get_gcov_intermediate_filename (const char *file_name)
1042 const char *gcov = ".gcov";
1043 char *result;
1044 const char *cptr;
1046 /* Find the 'basename'. */
1047 cptr = lbasename (file_name);
1049 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1050 sprintf (result, "%s%s", cptr, gcov);
1052 return result;
1055 /* Output the result in intermediate format used by 'lcov'.
1057 The intermediate format contains a single file named 'foo.cc.gcov',
1058 with no source code included.
1060 The default gcov outputs multiple files: 'foo.cc.gcov',
1061 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
1062 included. Instead the intermediate format here outputs only a single
1063 file 'foo.cc.gcov' similar to the above example. */
1065 static void
1066 output_intermediate_file (FILE *gcov_file, source_info *src)
1068 fprintf (gcov_file, "version:%s\n", version_string);
1069 fprintf (gcov_file, "file:%s\n", src->name); /* source file name */
1070 fprintf (gcov_file, "cwd:%s\n", bbg_cwd);
1072 std::sort (src->functions.begin (), src->functions.end (),
1073 function_line_start_cmp ());
1074 for (vector<function_info *>::iterator it = src->functions.begin ();
1075 it != src->functions.end (); it++)
1077 /* function:<name>,<line_number>,<execution_count> */
1078 fprintf (gcov_file, "function:%d,%d,%s,%s\n", (*it)->start_line,
1079 (*it)->end_line, format_gcov ((*it)->blocks[0].count, 0, -1),
1080 flag_demangled_names ? (*it)->demangled_name : (*it)->name);
1083 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1085 vector<function_info *> fns = src->get_functions_at_location (line_num);
1087 /* Print first group functions that begin on the line. */
1088 for (vector<function_info *>::iterator it2 = fns.begin ();
1089 it2 != fns.end (); it2++)
1091 vector<line_info> &lines = (*it2)->lines;
1092 for (unsigned i = 0; i < lines.size (); i++)
1094 line_info *line = &lines[i];
1095 output_intermediate_line (gcov_file, line, line_num + i);
1099 /* Follow with lines associated with the source file. */
1100 if (line_num < src->lines.size ())
1101 output_intermediate_line (gcov_file, &src->lines[line_num], line_num);
1105 /* Function start pair. */
1106 struct function_start
1108 unsigned source_file_idx;
1109 unsigned start_line;
1112 /* Traits class for function start hash maps below. */
1114 struct function_start_pair_hash : typed_noop_remove <function_start>
1116 typedef function_start value_type;
1117 typedef function_start compare_type;
1119 static hashval_t
1120 hash (const function_start &ref)
1122 inchash::hash hstate (0);
1123 hstate.add_int (ref.source_file_idx);
1124 hstate.add_int (ref.start_line);
1125 return hstate.end ();
1128 static bool
1129 equal (const function_start &ref1, const function_start &ref2)
1131 return (ref1.source_file_idx == ref2.source_file_idx
1132 && ref1.start_line == ref2.start_line);
1135 static void
1136 mark_deleted (function_start &ref)
1138 ref.start_line = ~1U;
1141 static void
1142 mark_empty (function_start &ref)
1144 ref.start_line = ~2U;
1147 static bool
1148 is_deleted (const function_start &ref)
1150 return ref.start_line == ~1U;
1153 static bool
1154 is_empty (const function_start &ref)
1156 return ref.start_line == ~2U;
1160 /* Process a single input file. */
1162 static void
1163 process_file (const char *file_name)
1165 create_file_names (file_name);
1167 for (unsigned i = 0; i < processed_files.size (); i++)
1168 if (strcmp (da_file_name, processed_files[i]) == 0)
1170 fnotice (stderr, "'%s' file is already processed\n",
1171 file_name);
1172 return;
1175 processed_files.push_back (xstrdup (da_file_name));
1177 read_graph_file ();
1178 read_count_file ();
1181 /* Process all functions in all files. */
1183 static void
1184 process_all_functions (void)
1186 hash_map<function_start_pair_hash, function_info *> fn_map;
1188 /* Identify group functions. */
1189 for (vector<function_info *>::iterator it = functions.begin ();
1190 it != functions.end (); it++)
1191 if (!(*it)->artificial)
1193 function_start needle;
1194 needle.source_file_idx = (*it)->src;
1195 needle.start_line = (*it)->start_line;
1197 function_info **slot = fn_map.get (needle);
1198 if (slot)
1200 (*slot)->is_group = 1;
1201 (*it)->is_group = 1;
1203 else
1204 fn_map.put (needle, *it);
1207 /* Remove all artificial function. */
1208 functions.erase (remove_if (functions.begin (), functions.end (),
1209 function_info::is_artificial), functions.end ());
1211 for (vector<function_info *>::iterator it = functions.begin ();
1212 it != functions.end (); it++)
1214 function_info *fn = *it;
1215 unsigned src = fn->src;
1217 if (!fn->counts.empty () || no_data_file)
1219 source_info *s = &sources[src];
1220 s->functions.push_back (fn);
1222 /* Mark last line in files touched by function. */
1223 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1224 block_no++)
1226 block_info *block = &fn->blocks[block_no];
1227 for (unsigned i = 0; i < block->locations.size (); i++)
1229 /* Sort lines of locations. */
1230 sort (block->locations[i].lines.begin (),
1231 block->locations[i].lines.end ());
1233 if (!block->locations[i].lines.empty ())
1235 s = &sources[block->locations[i].source_file_idx];
1236 unsigned last_line
1237 = block->locations[i].lines.back ();
1239 /* Record new lines for the function. */
1240 if (last_line >= s->lines.size ())
1242 s = &sources[block->locations[i].source_file_idx];
1243 unsigned last_line
1244 = block->locations[i].lines.back ();
1246 /* Record new lines for the function. */
1247 if (last_line >= s->lines.size ())
1249 /* Record new lines for a source file. */
1250 s->lines.resize (last_line + 1);
1257 /* Allocate lines for group function, following start_line
1258 and end_line information of the function. */
1259 if (fn->is_group)
1260 fn->lines.resize (fn->end_line - fn->start_line + 1);
1262 solve_flow_graph (fn);
1263 if (fn->has_catch)
1264 find_exception_blocks (fn);
1266 else
1268 /* The function was not in the executable -- some other
1269 instance must have been selected. */
1274 static void
1275 output_gcov_file (const char *file_name, source_info *src)
1277 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1279 if (src->coverage.lines)
1281 FILE *gcov_file = fopen (gcov_file_name, "w");
1282 if (gcov_file)
1284 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1285 output_lines (gcov_file, src);
1286 if (ferror (gcov_file))
1287 fnotice (stderr, "Error writing output file '%s'\n",
1288 gcov_file_name);
1289 fclose (gcov_file);
1291 else
1292 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1294 else
1296 unlink (gcov_file_name);
1297 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1299 free (gcov_file_name);
1302 static void
1303 generate_results (const char *file_name)
1305 FILE *gcov_intermediate_file = NULL;
1306 char *gcov_intermediate_filename = NULL;
1308 for (vector<function_info *>::iterator it = functions.begin ();
1309 it != functions.end (); it++)
1311 function_info *fn = *it;
1312 coverage_info coverage;
1314 memset (&coverage, 0, sizeof (coverage));
1315 coverage.name = flag_demangled_names ? fn->demangled_name : fn->name;
1316 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1317 if (flag_function_summary)
1319 function_summary (&coverage, "Function");
1320 fnotice (stdout, "\n");
1324 name_map needle;
1326 if (file_name)
1328 needle.name = file_name;
1329 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1330 needle);
1331 if (it != names.end ())
1332 file_name = sources[it->src].coverage.name;
1333 else
1334 file_name = canonicalize_name (file_name);
1337 if (flag_gcov_file && flag_intermediate_format && !flag_use_stdout)
1339 /* Open the intermediate file. */
1340 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1341 gcov_intermediate_file = fopen (gcov_intermediate_filename, "w");
1342 if (!gcov_intermediate_file)
1344 fnotice (stderr, "Cannot open intermediate output file %s\n",
1345 gcov_intermediate_filename);
1346 return;
1350 for (vector<source_info>::iterator it = sources.begin ();
1351 it != sources.end (); it++)
1353 source_info *src = &(*it);
1354 if (flag_relative_only)
1356 /* Ignore this source, if it is an absolute path (after
1357 source prefix removal). */
1358 char first = src->coverage.name[0];
1360 #if HAVE_DOS_BASED_FILE_SYSTEM
1361 if (first && src->coverage.name[1] == ':')
1362 first = src->coverage.name[2];
1363 #endif
1364 if (IS_DIR_SEPARATOR (first))
1365 continue;
1368 accumulate_line_counts (src);
1370 if (!flag_use_stdout)
1371 function_summary (&src->coverage, "File");
1372 total_lines += src->coverage.lines;
1373 total_executed += src->coverage.lines_executed;
1374 if (flag_gcov_file)
1376 if (flag_intermediate_format)
1377 /* Output the intermediate format without requiring source
1378 files. This outputs a section to a *single* file. */
1379 output_intermediate_file ((flag_use_stdout
1380 ? stdout : gcov_intermediate_file), src);
1381 else
1383 if (flag_use_stdout)
1385 if (src->coverage.lines)
1386 output_lines (stdout, src);
1388 else
1390 output_gcov_file (file_name, src);
1391 fnotice (stdout, "\n");
1397 if (flag_gcov_file && flag_intermediate_format && !flag_use_stdout)
1399 /* Now we've finished writing the intermediate file. */
1400 fclose (gcov_intermediate_file);
1401 XDELETEVEC (gcov_intermediate_filename);
1404 if (!file_name)
1405 executed_summary (total_lines, total_executed);
1408 /* Release all memory used. */
1410 static void
1411 release_structures (void)
1413 for (vector<function_info *>::iterator it = functions.begin ();
1414 it != functions.end (); it++)
1415 delete (*it);
1417 sources.resize (0);
1418 names.resize (0);
1419 functions.resize (0);
1422 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1423 is not specified, these are named from FILE_NAME sans extension. If
1424 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1425 directory, but named from the basename of the FILE_NAME, sans extension.
1426 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1427 and the data files are named from that. */
1429 static void
1430 create_file_names (const char *file_name)
1432 char *cptr;
1433 char *name;
1434 int length = strlen (file_name);
1435 int base;
1437 /* Free previous file names. */
1438 free (bbg_file_name);
1439 free (da_file_name);
1440 da_file_name = bbg_file_name = NULL;
1441 bbg_file_time = 0;
1442 bbg_stamp = 0;
1444 if (object_directory && object_directory[0])
1446 struct stat status;
1448 length += strlen (object_directory) + 2;
1449 name = XNEWVEC (char, length);
1450 name[0] = 0;
1452 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1453 strcat (name, object_directory);
1454 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1455 strcat (name, "/");
1457 else
1459 name = XNEWVEC (char, length + 1);
1460 strcpy (name, file_name);
1461 base = 0;
1464 if (base)
1466 /* Append source file name. */
1467 const char *cptr = lbasename (file_name);
1468 strcat (name, cptr ? cptr : file_name);
1471 /* Remove the extension. */
1472 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1473 if (cptr)
1474 *cptr = 0;
1476 length = strlen (name);
1478 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1479 strcpy (bbg_file_name, name);
1480 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1482 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1483 strcpy (da_file_name, name);
1484 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1486 free (name);
1487 return;
1490 /* Find or create a source file structure for FILE_NAME. Copies
1491 FILE_NAME on creation */
1493 static unsigned
1494 find_source (const char *file_name)
1496 char *canon;
1497 unsigned idx;
1498 struct stat status;
1500 if (!file_name)
1501 file_name = "<unknown>";
1503 name_map needle;
1504 needle.name = file_name;
1506 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1507 needle);
1508 if (it != names.end ())
1510 idx = it->src;
1511 goto check_date;
1514 /* Not found, try the canonical name. */
1515 canon = canonicalize_name (file_name);
1516 needle.name = canon;
1517 it = std::find (names.begin (), names.end (), needle);
1518 if (it == names.end ())
1520 /* Not found with canonical name, create a new source. */
1521 source_info *src;
1523 idx = sources.size ();
1524 needle = name_map (canon, idx);
1525 names.push_back (needle);
1527 sources.push_back (source_info ());
1528 src = &sources.back ();
1529 src->name = canon;
1530 src->coverage.name = src->name;
1531 src->index = idx;
1532 if (source_length
1533 #if HAVE_DOS_BASED_FILE_SYSTEM
1534 /* You lose if separators don't match exactly in the
1535 prefix. */
1536 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1537 #else
1538 && !strncmp (source_prefix, src->coverage.name, source_length)
1539 #endif
1540 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1541 src->coverage.name += source_length + 1;
1542 if (!stat (src->name, &status))
1543 src->file_time = status.st_mtime;
1545 else
1546 idx = it->src;
1548 needle.name = file_name;
1549 if (std::find (names.begin (), names.end (), needle) == names.end ())
1551 /* Append the non-canonical name. */
1552 names.push_back (name_map (xstrdup (file_name), idx));
1555 /* Resort the name map. */
1556 std::sort (names.begin (), names.end ());
1558 check_date:
1559 if (sources[idx].file_time > bbg_file_time)
1561 static int info_emitted;
1563 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1564 file_name, bbg_file_name);
1565 if (!info_emitted)
1567 fnotice (stderr,
1568 "(the message is displayed only once per source file)\n");
1569 info_emitted = 1;
1571 sources[idx].file_time = 0;
1574 return idx;
1577 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1579 static void
1580 read_graph_file (void)
1582 unsigned version;
1583 unsigned current_tag = 0;
1584 unsigned tag;
1586 if (!gcov_open (bbg_file_name, 1))
1588 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1589 return;
1591 bbg_file_time = gcov_time ();
1592 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1594 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1595 gcov_close ();
1596 return;
1599 version = gcov_read_unsigned ();
1600 if (version != GCOV_VERSION)
1602 char v[4], e[4];
1604 GCOV_UNSIGNED2STRING (v, version);
1605 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1607 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1608 bbg_file_name, v, e);
1610 bbg_stamp = gcov_read_unsigned ();
1611 bbg_cwd = xstrdup (gcov_read_string ());
1612 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1614 function_info *fn = NULL;
1615 while ((tag = gcov_read_unsigned ()))
1617 unsigned length = gcov_read_unsigned ();
1618 gcov_position_t base = gcov_position ();
1620 if (tag == GCOV_TAG_FUNCTION)
1622 char *function_name;
1623 unsigned ident;
1624 unsigned lineno_checksum, cfg_checksum;
1626 ident = gcov_read_unsigned ();
1627 lineno_checksum = gcov_read_unsigned ();
1628 cfg_checksum = gcov_read_unsigned ();
1629 function_name = xstrdup (gcov_read_string ());
1630 unsigned artificial = gcov_read_unsigned ();
1631 unsigned src_idx = find_source (gcov_read_string ());
1632 unsigned start_line = gcov_read_unsigned ();
1633 unsigned start_column = gcov_read_unsigned ();
1634 unsigned end_line = gcov_read_unsigned ();
1636 fn = new function_info ();
1637 functions.push_back (fn);
1638 fn->name = function_name;
1639 if (flag_demangled_names)
1641 fn->demangled_name = cplus_demangle (fn->name, DMGL_PARAMS);
1642 if (!fn->demangled_name)
1643 fn->demangled_name = fn->name;
1645 fn->ident = ident;
1646 fn->lineno_checksum = lineno_checksum;
1647 fn->cfg_checksum = cfg_checksum;
1648 fn->src = src_idx;
1649 fn->start_line = start_line;
1650 fn->start_column = start_column;
1651 fn->end_line = end_line;
1652 fn->artificial = artificial;
1654 current_tag = tag;
1656 else if (fn && tag == GCOV_TAG_BLOCKS)
1658 if (!fn->blocks.empty ())
1659 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1660 bbg_file_name, fn->name);
1661 else
1662 fn->blocks.resize (gcov_read_unsigned ());
1664 else if (fn && tag == GCOV_TAG_ARCS)
1666 unsigned src = gcov_read_unsigned ();
1667 fn->blocks[src].id = src;
1668 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1669 block_info *src_blk = &fn->blocks[src];
1670 unsigned mark_catches = 0;
1671 struct arc_info *arc;
1673 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1674 goto corrupt;
1676 while (num_dests--)
1678 unsigned dest = gcov_read_unsigned ();
1679 unsigned flags = gcov_read_unsigned ();
1681 if (dest >= fn->blocks.size ())
1682 goto corrupt;
1683 arc = XCNEW (arc_info);
1685 arc->dst = &fn->blocks[dest];
1686 arc->src = src_blk;
1688 arc->count = 0;
1689 arc->count_valid = 0;
1690 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1691 arc->fake = !!(flags & GCOV_ARC_FAKE);
1692 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1694 arc->succ_next = src_blk->succ;
1695 src_blk->succ = arc;
1696 src_blk->num_succ++;
1698 arc->pred_next = fn->blocks[dest].pred;
1699 fn->blocks[dest].pred = arc;
1700 fn->blocks[dest].num_pred++;
1702 if (arc->fake)
1704 if (src)
1706 /* Exceptional exit from this function, the
1707 source block must be a call. */
1708 fn->blocks[src].is_call_site = 1;
1709 arc->is_call_non_return = 1;
1710 mark_catches = 1;
1712 else
1714 /* Non-local return from a callee of this
1715 function. The destination block is a setjmp. */
1716 arc->is_nonlocal_return = 1;
1717 fn->blocks[dest].is_nonlocal_return = 1;
1721 if (!arc->on_tree)
1722 fn->counts.push_back (0);
1725 if (mark_catches)
1727 /* We have a fake exit from this block. The other
1728 non-fall through exits must be to catch handlers.
1729 Mark them as catch arcs. */
1731 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1732 if (!arc->fake && !arc->fall_through)
1734 arc->is_throw = 1;
1735 fn->has_catch = 1;
1739 else if (fn && tag == GCOV_TAG_LINES)
1741 unsigned blockno = gcov_read_unsigned ();
1742 block_info *block = &fn->blocks[blockno];
1744 if (blockno >= fn->blocks.size ())
1745 goto corrupt;
1747 while (true)
1749 unsigned lineno = gcov_read_unsigned ();
1751 if (lineno)
1752 block->locations.back ().lines.push_back (lineno);
1753 else
1755 const char *file_name = gcov_read_string ();
1757 if (!file_name)
1758 break;
1759 block->locations.push_back (block_location_info
1760 (find_source (file_name)));
1764 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1766 fn = NULL;
1767 current_tag = 0;
1769 gcov_sync (base, length);
1770 if (gcov_is_error ())
1772 corrupt:;
1773 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1774 break;
1777 gcov_close ();
1779 if (functions.empty ())
1780 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1783 /* Reads profiles from the count file and attach to each
1784 function. Return nonzero if fatal error. */
1786 static int
1787 read_count_file (void)
1789 unsigned ix;
1790 unsigned version;
1791 unsigned tag;
1792 function_info *fn = NULL;
1793 int error = 0;
1795 if (!gcov_open (da_file_name, 1))
1797 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1798 da_file_name);
1799 no_data_file = 1;
1800 return 0;
1802 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1804 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1805 cleanup:;
1806 gcov_close ();
1807 return 1;
1809 version = gcov_read_unsigned ();
1810 if (version != GCOV_VERSION)
1812 char v[4], e[4];
1814 GCOV_UNSIGNED2STRING (v, version);
1815 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1817 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1818 da_file_name, v, e);
1820 tag = gcov_read_unsigned ();
1821 if (tag != bbg_stamp)
1823 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1824 goto cleanup;
1827 while ((tag = gcov_read_unsigned ()))
1829 unsigned length = gcov_read_unsigned ();
1830 unsigned long base = gcov_position ();
1832 if (tag == GCOV_TAG_PROGRAM_SUMMARY)
1834 struct gcov_summary summary;
1835 gcov_read_summary (&summary);
1836 object_runs += summary.runs;
1837 program_count++;
1839 else if (tag == GCOV_TAG_FUNCTION && !length)
1840 ; /* placeholder */
1841 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1843 unsigned ident;
1845 /* Try to find the function in the list. To speed up the
1846 search, first start from the last function found. */
1847 ident = gcov_read_unsigned ();
1849 fn = NULL;
1850 for (vector<function_info *>::reverse_iterator it
1851 = functions.rbegin (); it != functions.rend (); it++)
1853 if ((*it)->ident == ident)
1855 fn = *it;
1856 break;
1860 if (!fn)
1862 else if (gcov_read_unsigned () != fn->lineno_checksum
1863 || gcov_read_unsigned () != fn->cfg_checksum)
1865 mismatch:;
1866 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1867 da_file_name, fn->name);
1868 goto cleanup;
1871 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1873 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1874 goto mismatch;
1876 for (ix = 0; ix != fn->counts.size (); ix++)
1877 fn->counts[ix] += gcov_read_counter ();
1879 gcov_sync (base, length);
1880 if ((error = gcov_is_error ()))
1882 fnotice (stderr,
1883 error < 0
1884 ? N_("%s:overflowed\n")
1885 : N_("%s:corrupted\n"),
1886 da_file_name);
1887 goto cleanup;
1891 gcov_close ();
1892 return 0;
1895 /* Solve the flow graph. Propagate counts from the instrumented arcs
1896 to the blocks and the uninstrumented arcs. */
1898 static void
1899 solve_flow_graph (function_info *fn)
1901 unsigned ix;
1902 arc_info *arc;
1903 gcov_type *count_ptr = &fn->counts.front ();
1904 block_info *blk;
1905 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
1906 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
1908 /* The arcs were built in reverse order. Fix that now. */
1909 for (ix = fn->blocks.size (); ix--;)
1911 arc_info *arc_p, *arc_n;
1913 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
1914 arc_p = arc, arc = arc_n)
1916 arc_n = arc->succ_next;
1917 arc->succ_next = arc_p;
1919 fn->blocks[ix].succ = arc_p;
1921 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
1922 arc_p = arc, arc = arc_n)
1924 arc_n = arc->pred_next;
1925 arc->pred_next = arc_p;
1927 fn->blocks[ix].pred = arc_p;
1930 if (fn->blocks.size () < 2)
1931 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
1932 bbg_file_name, fn->name);
1933 else
1935 if (fn->blocks[ENTRY_BLOCK].num_pred)
1936 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
1937 bbg_file_name, fn->name);
1938 else
1939 /* We can't deduce the entry block counts from the lack of
1940 predecessors. */
1941 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
1943 if (fn->blocks[EXIT_BLOCK].num_succ)
1944 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
1945 bbg_file_name, fn->name);
1946 else
1947 /* Likewise, we can't deduce exit block counts from the lack
1948 of its successors. */
1949 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
1952 /* Propagate the measured counts, this must be done in the same
1953 order as the code in profile.c */
1954 for (unsigned i = 0; i < fn->blocks.size (); i++)
1956 blk = &fn->blocks[i];
1957 block_info const *prev_dst = NULL;
1958 int out_of_order = 0;
1959 int non_fake_succ = 0;
1961 for (arc = blk->succ; arc; arc = arc->succ_next)
1963 if (!arc->fake)
1964 non_fake_succ++;
1966 if (!arc->on_tree)
1968 if (count_ptr)
1969 arc->count = *count_ptr++;
1970 arc->count_valid = 1;
1971 blk->num_succ--;
1972 arc->dst->num_pred--;
1974 if (prev_dst && prev_dst > arc->dst)
1975 out_of_order = 1;
1976 prev_dst = arc->dst;
1978 if (non_fake_succ == 1)
1980 /* If there is only one non-fake exit, it is an
1981 unconditional branch. */
1982 for (arc = blk->succ; arc; arc = arc->succ_next)
1983 if (!arc->fake)
1985 arc->is_unconditional = 1;
1986 /* If this block is instrumenting a call, it might be
1987 an artificial block. It is not artificial if it has
1988 a non-fallthrough exit, or the destination of this
1989 arc has more than one entry. Mark the destination
1990 block as a return site, if none of those conditions
1991 hold. */
1992 if (blk->is_call_site && arc->fall_through
1993 && arc->dst->pred == arc && !arc->pred_next)
1994 arc->dst->is_call_return = 1;
1998 /* Sort the successor arcs into ascending dst order. profile.c
1999 normally produces arcs in the right order, but sometimes with
2000 one or two out of order. We're not using a particularly
2001 smart sort. */
2002 if (out_of_order)
2004 arc_info *start = blk->succ;
2005 unsigned changes = 1;
2007 while (changes)
2009 arc_info *arc, *arc_p, *arc_n;
2011 changes = 0;
2012 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2014 if (arc->dst > arc_n->dst)
2016 changes = 1;
2017 if (arc_p)
2018 arc_p->succ_next = arc_n;
2019 else
2020 start = arc_n;
2021 arc->succ_next = arc_n->succ_next;
2022 arc_n->succ_next = arc;
2023 arc_p = arc_n;
2025 else
2027 arc_p = arc;
2028 arc = arc_n;
2032 blk->succ = start;
2035 /* Place it on the invalid chain, it will be ignored if that's
2036 wrong. */
2037 blk->invalid_chain = 1;
2038 blk->chain = invalid_blocks;
2039 invalid_blocks = blk;
2042 while (invalid_blocks || valid_blocks)
2044 while ((blk = invalid_blocks))
2046 gcov_type total = 0;
2047 const arc_info *arc;
2049 invalid_blocks = blk->chain;
2050 blk->invalid_chain = 0;
2051 if (!blk->num_succ)
2052 for (arc = blk->succ; arc; arc = arc->succ_next)
2053 total += arc->count;
2054 else if (!blk->num_pred)
2055 for (arc = blk->pred; arc; arc = arc->pred_next)
2056 total += arc->count;
2057 else
2058 continue;
2060 blk->count = total;
2061 blk->count_valid = 1;
2062 blk->chain = valid_blocks;
2063 blk->valid_chain = 1;
2064 valid_blocks = blk;
2066 while ((blk = valid_blocks))
2068 gcov_type total;
2069 arc_info *arc, *inv_arc;
2071 valid_blocks = blk->chain;
2072 blk->valid_chain = 0;
2073 if (blk->num_succ == 1)
2075 block_info *dst;
2077 total = blk->count;
2078 inv_arc = NULL;
2079 for (arc = blk->succ; arc; arc = arc->succ_next)
2081 total -= arc->count;
2082 if (!arc->count_valid)
2083 inv_arc = arc;
2085 dst = inv_arc->dst;
2086 inv_arc->count_valid = 1;
2087 inv_arc->count = total;
2088 blk->num_succ--;
2089 dst->num_pred--;
2090 if (dst->count_valid)
2092 if (dst->num_pred == 1 && !dst->valid_chain)
2094 dst->chain = valid_blocks;
2095 dst->valid_chain = 1;
2096 valid_blocks = dst;
2099 else
2101 if (!dst->num_pred && !dst->invalid_chain)
2103 dst->chain = invalid_blocks;
2104 dst->invalid_chain = 1;
2105 invalid_blocks = dst;
2109 if (blk->num_pred == 1)
2111 block_info *src;
2113 total = blk->count;
2114 inv_arc = NULL;
2115 for (arc = blk->pred; arc; arc = arc->pred_next)
2117 total -= arc->count;
2118 if (!arc->count_valid)
2119 inv_arc = arc;
2121 src = inv_arc->src;
2122 inv_arc->count_valid = 1;
2123 inv_arc->count = total;
2124 blk->num_pred--;
2125 src->num_succ--;
2126 if (src->count_valid)
2128 if (src->num_succ == 1 && !src->valid_chain)
2130 src->chain = valid_blocks;
2131 src->valid_chain = 1;
2132 valid_blocks = src;
2135 else
2137 if (!src->num_succ && !src->invalid_chain)
2139 src->chain = invalid_blocks;
2140 src->invalid_chain = 1;
2141 invalid_blocks = src;
2148 /* If the graph has been correctly solved, every block will have a
2149 valid count. */
2150 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2151 if (!fn->blocks[i].count_valid)
2153 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2154 bbg_file_name, fn->name);
2155 break;
2159 /* Mark all the blocks only reachable via an incoming catch. */
2161 static void
2162 find_exception_blocks (function_info *fn)
2164 unsigned ix;
2165 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2167 /* First mark all blocks as exceptional. */
2168 for (ix = fn->blocks.size (); ix--;)
2169 fn->blocks[ix].exceptional = 1;
2171 /* Now mark all the blocks reachable via non-fake edges */
2172 queue[0] = &fn->blocks[0];
2173 queue[0]->exceptional = 0;
2174 for (ix = 1; ix;)
2176 block_info *block = queue[--ix];
2177 const arc_info *arc;
2179 for (arc = block->succ; arc; arc = arc->succ_next)
2180 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2182 arc->dst->exceptional = 0;
2183 queue[ix++] = arc->dst;
2189 /* Increment totals in COVERAGE according to arc ARC. */
2191 static void
2192 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2194 if (arc->is_call_non_return)
2196 coverage->calls++;
2197 if (arc->src->count)
2198 coverage->calls_executed++;
2200 else if (!arc->is_unconditional)
2202 coverage->branches++;
2203 if (arc->src->count)
2204 coverage->branches_executed++;
2205 if (arc->count)
2206 coverage->branches_taken++;
2210 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2211 readable format. */
2213 static char const *
2214 format_count (gcov_type count)
2216 static char buffer[64];
2217 const char *units = " kMGTPEZY";
2219 if (count < 1000 || !flag_human_readable_numbers)
2221 sprintf (buffer, "%" PRId64, count);
2222 return buffer;
2225 unsigned i;
2226 gcov_type divisor = 1;
2227 for (i = 0; units[i+1]; i++, divisor *= 1000)
2229 if (count + divisor / 2 < 1000 * divisor)
2230 break;
2232 float r = 1.0f * count / divisor;
2233 sprintf (buffer, "%.1f%c", r, units[i]);
2234 return buffer;
2237 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2238 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2239 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2240 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2241 format TOP. Return pointer to a static string. */
2243 static char const *
2244 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2246 static char buffer[20];
2248 if (decimal_places >= 0)
2250 float ratio = bottom ? 100.0f * top / bottom: 0;
2252 /* Round up to 1% if there's a small non-zero value. */
2253 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2254 ratio = 1.0f;
2255 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2257 else
2258 return format_count (top);
2260 return buffer;
2263 /* Summary of execution */
2265 static void
2266 executed_summary (unsigned lines, unsigned executed)
2268 if (lines)
2269 fnotice (stdout, "Lines executed:%s of %d\n",
2270 format_gcov (executed, lines, 2), lines);
2271 else
2272 fnotice (stdout, "No executable lines\n");
2275 /* Output summary info for a function or file. */
2277 static void
2278 function_summary (const coverage_info *coverage, const char *title)
2280 fnotice (stdout, "%s '%s'\n", title, coverage->name);
2281 executed_summary (coverage->lines, coverage->lines_executed);
2283 if (flag_branches)
2285 if (coverage->branches)
2287 fnotice (stdout, "Branches executed:%s of %d\n",
2288 format_gcov (coverage->branches_executed,
2289 coverage->branches, 2),
2290 coverage->branches);
2291 fnotice (stdout, "Taken at least once:%s of %d\n",
2292 format_gcov (coverage->branches_taken,
2293 coverage->branches, 2),
2294 coverage->branches);
2296 else
2297 fnotice (stdout, "No branches\n");
2298 if (coverage->calls)
2299 fnotice (stdout, "Calls executed:%s of %d\n",
2300 format_gcov (coverage->calls_executed, coverage->calls, 2),
2301 coverage->calls);
2302 else
2303 fnotice (stdout, "No calls\n");
2307 /* Canonicalize the filename NAME by canonicalizing directory
2308 separators, eliding . components and resolving .. components
2309 appropriately. Always returns a unique string. */
2311 static char *
2312 canonicalize_name (const char *name)
2314 /* The canonical name cannot be longer than the incoming name. */
2315 char *result = XNEWVEC (char, strlen (name) + 1);
2316 const char *base = name, *probe;
2317 char *ptr = result;
2318 char *dd_base;
2319 int slash = 0;
2321 #if HAVE_DOS_BASED_FILE_SYSTEM
2322 if (base[0] && base[1] == ':')
2324 result[0] = base[0];
2325 result[1] = ':';
2326 base += 2;
2327 ptr += 2;
2329 #endif
2330 for (dd_base = ptr; *base; base = probe)
2332 size_t len;
2334 for (probe = base; *probe; probe++)
2335 if (IS_DIR_SEPARATOR (*probe))
2336 break;
2338 len = probe - base;
2339 if (len == 1 && base[0] == '.')
2340 /* Elide a '.' directory */
2342 else if (len == 2 && base[0] == '.' && base[1] == '.')
2344 /* '..', we can only elide it and the previous directory, if
2345 we're not a symlink. */
2346 struct stat ATTRIBUTE_UNUSED buf;
2348 *ptr = 0;
2349 if (dd_base == ptr
2350 #if defined (S_ISLNK)
2351 /* S_ISLNK is not POSIX.1-1996. */
2352 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2353 #endif
2356 /* Cannot elide, or unreadable or a symlink. */
2357 dd_base = ptr + 2 + slash;
2358 goto regular;
2360 while (ptr != dd_base && *ptr != '/')
2361 ptr--;
2362 slash = ptr != result;
2364 else
2366 regular:
2367 /* Regular pathname component. */
2368 if (slash)
2369 *ptr++ = '/';
2370 memcpy (ptr, base, len);
2371 ptr += len;
2372 slash = 1;
2375 for (; IS_DIR_SEPARATOR (*probe); probe++)
2376 continue;
2378 *ptr = 0;
2380 return result;
2383 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2385 static void
2386 md5sum_to_hex (const char *sum, char *buffer)
2388 for (unsigned i = 0; i < 16; i++)
2389 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2392 /* Generate an output file name. INPUT_NAME is the canonicalized main
2393 input file and SRC_NAME is the canonicalized file name.
2394 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2395 long_output_names we prepend the processed name of the input file
2396 to each output name (except when the current source file is the
2397 input file, so you don't get a double concatenation). The two
2398 components are separated by '##'. With preserve_paths we create a
2399 filename from all path components of the source file, replacing '/'
2400 with '#', and .. with '^', without it we simply take the basename
2401 component. (Remember, the canonicalized name will already have
2402 elided '.' components and converted \\ separators.) */
2404 static char *
2405 make_gcov_file_name (const char *input_name, const char *src_name)
2407 char *ptr;
2408 char *result;
2410 if (flag_long_names && input_name && strcmp (src_name, input_name))
2412 /* Generate the input filename part. */
2413 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2415 ptr = result;
2416 ptr = mangle_name (input_name, ptr);
2417 ptr[0] = ptr[1] = '#';
2418 ptr += 2;
2420 else
2422 result = XNEWVEC (char, strlen (src_name) + 10);
2423 ptr = result;
2426 ptr = mangle_name (src_name, ptr);
2427 strcpy (ptr, ".gcov");
2429 /* When hashing filenames, we shorten them by only using the filename
2430 component and appending a hash of the full (mangled) pathname. */
2431 if (flag_hash_filenames)
2433 md5_ctx ctx;
2434 char md5sum[16];
2435 char md5sum_hex[33];
2437 md5_init_ctx (&ctx);
2438 md5_process_bytes (src_name, strlen (src_name), &ctx);
2439 md5_finish_ctx (&ctx, md5sum);
2440 md5sum_to_hex (md5sum, md5sum_hex);
2441 free (result);
2443 result = XNEWVEC (char, strlen (src_name) + 50);
2444 ptr = result;
2445 ptr = mangle_name (src_name, ptr);
2446 ptr[0] = ptr[1] = '#';
2447 ptr += 2;
2448 memcpy (ptr, md5sum_hex, 32);
2449 ptr += 32;
2450 strcpy (ptr, ".gcov");
2453 return result;
2456 static char *
2457 mangle_name (char const *base, char *ptr)
2459 size_t len;
2461 /* Generate the source filename part. */
2462 if (!flag_preserve_paths)
2464 base = lbasename (base);
2465 len = strlen (base);
2466 memcpy (ptr, base, len);
2467 ptr += len;
2469 else
2470 ptr = mangle_path (base);
2472 return ptr;
2475 /* Scan through the bb_data for each line in the block, increment
2476 the line number execution count indicated by the execution count of
2477 the appropriate basic block. */
2479 static void
2480 add_line_counts (coverage_info *coverage, function_info *fn)
2482 bool has_any_line = false;
2483 /* Scan each basic block. */
2484 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2486 line_info *line = NULL;
2487 block_info *block = &fn->blocks[ix];
2488 if (block->count && ix && ix + 1 != fn->blocks.size ())
2489 fn->blocks_executed++;
2490 for (unsigned i = 0; i < block->locations.size (); i++)
2492 unsigned src_idx = block->locations[i].source_file_idx;
2493 vector<unsigned> &lines = block->locations[i].lines;
2495 block->cycle.arc = NULL;
2496 block->cycle.ident = ~0U;
2498 for (unsigned j = 0; j < lines.size (); j++)
2500 unsigned ln = lines[j];
2502 /* Line belongs to a function that is in a group. */
2503 if (fn->group_line_p (ln, src_idx))
2505 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2506 line = &(fn->lines[lines[j] - fn->start_line]);
2507 line->exists = 1;
2508 if (!block->exceptional)
2510 line->unexceptional = 1;
2511 if (block->count == 0)
2512 line->has_unexecuted_block = 1;
2514 line->count += block->count;
2516 else
2518 gcc_assert (ln < sources[src_idx].lines.size ());
2519 line = &(sources[src_idx].lines[ln]);
2520 if (coverage)
2522 if (!line->exists)
2523 coverage->lines++;
2524 if (!line->count && block->count)
2525 coverage->lines_executed++;
2527 line->exists = 1;
2528 if (!block->exceptional)
2530 line->unexceptional = 1;
2531 if (block->count == 0)
2532 line->has_unexecuted_block = 1;
2534 line->count += block->count;
2538 has_any_line = true;
2540 if (!ix || ix + 1 == fn->blocks.size ())
2541 /* Entry or exit block. */;
2542 else if (line != NULL)
2544 line->blocks.push_back (block);
2546 if (flag_branches)
2548 arc_info *arc;
2550 for (arc = block->succ; arc; arc = arc->succ_next)
2551 line->branches.push_back (arc);
2557 if (!has_any_line)
2558 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name, fn->name);
2561 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2562 is set to true, update source file summary. */
2564 static void accumulate_line_info (line_info *line, source_info *src,
2565 bool add_coverage)
2567 if (add_coverage)
2568 for (vector<arc_info *>::iterator it = line->branches.begin ();
2569 it != line->branches.end (); it++)
2570 add_branch_counts (&src->coverage, *it);
2572 if (!line->blocks.empty ())
2574 /* The user expects the line count to be the number of times
2575 a line has been executed. Simply summing the block count
2576 will give an artificially high number. The Right Thing
2577 is to sum the entry counts to the graph of blocks on this
2578 line, then find the elementary cycles of the local graph
2579 and add the transition counts of those cycles. */
2580 gcov_type count = 0;
2582 /* Cycle detection. */
2583 for (vector<block_info *>::iterator it = line->blocks.begin ();
2584 it != line->blocks.end (); it++)
2586 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2587 if (!line->has_block (arc->src))
2588 count += arc->count;
2589 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2590 arc->cs_count = arc->count;
2593 /* Now, add the count of loops entirely on this line. */
2594 count += get_cycles_count (*line);
2595 line->count = count;
2597 if (line->count > src->maximum_count)
2598 src->maximum_count = line->count;
2601 if (line->exists && add_coverage)
2603 src->coverage.lines++;
2604 if (line->count)
2605 src->coverage.lines_executed++;
2609 /* Accumulate the line counts of a file. */
2611 static void
2612 accumulate_line_counts (source_info *src)
2614 /* First work on group functions. */
2615 for (vector<function_info *>::iterator it = src->functions.begin ();
2616 it != src->functions.end (); it++)
2618 function_info *fn = *it;
2620 if (fn->src != src->index || !fn->is_group)
2621 continue;
2623 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2624 it2 != fn->lines.end (); it2++)
2626 line_info *line = &(*it2);
2627 accumulate_line_info (line, src, false);
2631 /* Work on global lines that line in source file SRC. */
2632 for (vector<line_info>::iterator it = src->lines.begin ();
2633 it != src->lines.end (); it++)
2634 accumulate_line_info (&(*it), src, true);
2636 /* If not using intermediate mode, sum lines of group functions and
2637 add them to lines that live in a source file. */
2638 if (!flag_intermediate_format)
2639 for (vector<function_info *>::iterator it = src->functions.begin ();
2640 it != src->functions.end (); it++)
2642 function_info *fn = *it;
2644 if (fn->src != src->index || !fn->is_group)
2645 continue;
2647 for (unsigned i = 0; i < fn->lines.size (); i++)
2649 line_info *fn_line = &fn->lines[i];
2650 if (fn_line->exists)
2652 unsigned ln = fn->start_line + i;
2653 line_info *src_line = &src->lines[ln];
2655 if (!src_line->exists)
2656 src->coverage.lines++;
2657 if (!src_line->count && fn_line->count)
2658 src->coverage.lines_executed++;
2660 src_line->count += fn_line->count;
2661 src_line->exists = 1;
2663 if (fn_line->has_unexecuted_block)
2664 src_line->has_unexecuted_block = 1;
2666 if (fn_line->unexceptional)
2667 src_line->unexceptional = 1;
2673 /* Output information about ARC number IX. Returns nonzero if
2674 anything is output. */
2676 static int
2677 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2679 if (arc->is_call_non_return)
2681 if (arc->src->count)
2683 fnotice (gcov_file, "call %2d returned %s\n", ix,
2684 format_gcov (arc->src->count - arc->count,
2685 arc->src->count, -flag_counts));
2687 else
2688 fnotice (gcov_file, "call %2d never executed\n", ix);
2690 else if (!arc->is_unconditional)
2692 if (arc->src->count)
2693 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2694 format_gcov (arc->count, arc->src->count, -flag_counts),
2695 arc->fall_through ? " (fallthrough)"
2696 : arc->is_throw ? " (throw)" : "");
2697 else
2698 fnotice (gcov_file, "branch %2d never executed", ix);
2700 if (flag_verbose)
2701 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2703 fnotice (gcov_file, "\n");
2705 else if (flag_unconditional && !arc->dst->is_call_return)
2707 if (arc->src->count)
2708 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2709 format_gcov (arc->count, arc->src->count, -flag_counts));
2710 else
2711 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2713 else
2714 return 0;
2715 return 1;
2718 static const char *
2719 read_line (FILE *file)
2721 static char *string;
2722 static size_t string_len;
2723 size_t pos = 0;
2724 char *ptr;
2726 if (!string_len)
2728 string_len = 200;
2729 string = XNEWVEC (char, string_len);
2732 while ((ptr = fgets (string + pos, string_len - pos, file)))
2734 size_t len = strlen (string + pos);
2736 if (len && string[pos + len - 1] == '\n')
2738 string[pos + len - 1] = 0;
2739 return string;
2741 pos += len;
2742 /* If the file contains NUL characters or an incomplete
2743 last line, which can happen more than once in one run,
2744 we have to avoid doubling the STRING_LEN unnecessarily. */
2745 if (pos > string_len / 2)
2747 string_len *= 2;
2748 string = XRESIZEVEC (char, string, string_len);
2752 return pos ? string : NULL;
2755 /* Pad string S with spaces from left to have total width equal to 9. */
2757 static void
2758 pad_count_string (string &s)
2760 if (s.size () < 9)
2761 s.insert (0, 9 - s.size (), ' ');
2764 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2765 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2766 an exceptional statement. The output is printed for LINE_NUM of given
2767 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2768 used to indicate non-executed blocks. */
2770 static void
2771 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2772 bool has_unexecuted_block,
2773 gcov_type count, unsigned line_num,
2774 const char *exceptional_string,
2775 const char *unexceptional_string,
2776 unsigned int maximum_count)
2778 string s;
2779 if (exists)
2781 if (count > 0)
2783 s = format_gcov (count, 0, -1);
2784 if (has_unexecuted_block
2785 && bbg_supports_has_unexecuted_blocks)
2787 if (flag_use_colors)
2789 pad_count_string (s);
2790 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2791 COLOR_SEPARATOR COLOR_FG_WHITE));
2792 s += SGR_RESET;
2794 else
2795 s += "*";
2797 pad_count_string (s);
2799 else
2801 if (flag_use_colors)
2803 s = "0";
2804 pad_count_string (s);
2805 if (unexceptional)
2806 s.insert (0, SGR_SEQ (COLOR_BG_RED
2807 COLOR_SEPARATOR COLOR_FG_WHITE));
2808 else
2809 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2810 COLOR_SEPARATOR COLOR_FG_WHITE));
2811 s += SGR_RESET;
2813 else
2815 s = unexceptional ? unexceptional_string : exceptional_string;
2816 pad_count_string (s);
2820 else
2822 s = "-";
2823 pad_count_string (s);
2826 /* Format line number in output. */
2827 char buffer[16];
2828 sprintf (buffer, "%5u", line_num);
2829 string linestr (buffer);
2831 if (flag_use_hotness_colors && maximum_count)
2833 if (count * 2 > maximum_count) /* > 50%. */
2834 linestr.insert (0, SGR_SEQ (COLOR_BG_RED));
2835 else if (count * 5 > maximum_count) /* > 20%. */
2836 linestr.insert (0, SGR_SEQ (COLOR_BG_YELLOW));
2837 else if (count * 10 > maximum_count) /* > 10%. */
2838 linestr.insert (0, SGR_SEQ (COLOR_BG_GREEN));
2839 linestr += SGR_RESET;
2842 fprintf (f, "%s:%s", s.c_str (), linestr.c_str ());
2845 static void
2846 print_source_line (FILE *f, const vector<const char *> &source_lines,
2847 unsigned line)
2849 gcc_assert (line >= 1);
2850 gcc_assert (line <= source_lines.size ());
2852 fprintf (f, ":%s\n", source_lines[line - 1]);
2855 /* Output line details for LINE and print it to F file. LINE lives on
2856 LINE_NUM. */
2858 static void
2859 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2861 if (flag_all_blocks)
2863 arc_info *arc;
2864 int ix, jx;
2866 ix = jx = 0;
2867 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2868 it != line->blocks.end (); it++)
2870 if (!(*it)->is_call_return)
2872 output_line_beginning (f, line->exists,
2873 (*it)->exceptional, false,
2874 (*it)->count, line_num,
2875 "%%%%%", "$$$$$", 0);
2876 fprintf (f, "-block %2d", ix++);
2877 if (flag_verbose)
2878 fprintf (f, " (BB %u)", (*it)->id);
2879 fprintf (f, "\n");
2881 if (flag_branches)
2882 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2883 jx += output_branch_count (f, jx, arc);
2886 else if (flag_branches)
2888 int ix;
2890 ix = 0;
2891 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
2892 it != line->branches.end (); it++)
2893 ix += output_branch_count (f, ix, (*it));
2897 /* Output detail statistics about function FN to file F. */
2899 static void
2900 output_function_details (FILE *f, const function_info *fn)
2902 if (!flag_branches)
2903 return;
2905 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
2906 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
2907 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
2909 for (; arc; arc = arc->pred_next)
2910 if (arc->fake)
2911 return_count -= arc->count;
2913 fprintf (f, "function %s",
2914 flag_demangled_names ? fn->demangled_name : fn->name);
2915 fprintf (f, " called %s",
2916 format_gcov (called_count, 0, -1));
2917 fprintf (f, " returned %s",
2918 format_gcov (return_count, called_count, 0));
2919 fprintf (f, " blocks executed %s",
2920 format_gcov (fn->blocks_executed, fn->blocks.size () - 2,
2921 0));
2922 fprintf (f, "\n");
2925 /* Read in the source file one line at a time, and output that line to
2926 the gcov file preceded by its execution count and other
2927 information. */
2929 static void
2930 output_lines (FILE *gcov_file, const source_info *src)
2932 #define DEFAULT_LINE_START " -: 0:"
2933 #define FN_SEPARATOR "------------------\n"
2935 FILE *source_file;
2936 const char *retval;
2938 /* Print legend of color hotness syntax. */
2939 if (flag_use_hotness_colors)
2940 fprintf (gcov_file, "%s", DEFAULT_LINE_START "Hotness legend: " \
2941 SGR_SEQ (COLOR_BG_RED) "> 50%" SGR_RESET " " \
2942 SGR_SEQ (COLOR_BG_YELLOW) "> 20%" SGR_RESET " " \
2943 SGR_SEQ (COLOR_BG_GREEN) "> 10%" SGR_RESET "\n");
2945 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
2947 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
2948 if (!multiple_files)
2950 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
2951 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
2952 no_data_file ? "-" : da_file_name);
2953 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
2955 fprintf (gcov_file, DEFAULT_LINE_START "Programs:%u\n", program_count);
2957 source_file = fopen (src->name, "r");
2958 if (!source_file)
2959 fnotice (stderr, "Cannot open source file %s\n", src->name);
2960 else if (src->file_time == 0)
2961 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
2963 vector<const char *> source_lines;
2964 if (source_file)
2965 while ((retval = read_line (source_file)) != NULL)
2966 source_lines.push_back (xstrdup (retval));
2968 unsigned line_start_group = 0;
2969 vector<function_info *> fns;
2971 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
2973 if (line_num >= src->lines.size ())
2975 fprintf (gcov_file, "%9s:%5u", "-", line_num);
2976 print_source_line (gcov_file, source_lines, line_num);
2977 continue;
2980 const line_info *line = &src->lines[line_num];
2982 if (line_start_group == 0)
2984 fns = src->get_functions_at_location (line_num);
2985 if (fns.size () > 1)
2987 /* It's possible to have functions that partially overlap,
2988 thus take the maximum end_line of functions starting
2989 at LINE_NUM. */
2990 for (unsigned i = 0; i < fns.size (); i++)
2991 if (fns[i]->end_line > line_start_group)
2992 line_start_group = fns[i]->end_line;
2994 else if (fns.size () == 1)
2996 function_info *fn = fns[0];
2997 output_function_details (gcov_file, fn);
3001 /* For lines which don't exist in the .bb file, print '-' before
3002 the source line. For lines which exist but were never
3003 executed, print '#####' or '=====' before the source line.
3004 Otherwise, print the execution count before the source line.
3005 There are 16 spaces of indentation added before the source
3006 line so that tabs won't be messed up. */
3007 output_line_beginning (gcov_file, line->exists, line->unexceptional,
3008 line->has_unexecuted_block, line->count,
3009 line_num, "=====", "#####", src->maximum_count);
3011 print_source_line (gcov_file, source_lines, line_num);
3012 output_line_details (gcov_file, line, line_num);
3014 if (line_start_group == line_num)
3016 for (vector<function_info *>::iterator it = fns.begin ();
3017 it != fns.end (); it++)
3019 function_info *fn = *it;
3020 vector<line_info> &lines = fn->lines;
3022 fprintf (gcov_file, FN_SEPARATOR);
3024 string fn_name
3025 = flag_demangled_names ? fn->demangled_name : fn->name;
3027 if (flag_use_colors)
3029 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
3030 fn_name += SGR_RESET;
3033 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
3035 output_function_details (gcov_file, fn);
3037 /* Print all lines covered by the function. */
3038 for (unsigned i = 0; i < lines.size (); i++)
3040 line_info *line = &lines[i];
3041 unsigned l = fn->start_line + i;
3043 /* For lines which don't exist in the .bb file, print '-'
3044 before the source line. For lines which exist but
3045 were never executed, print '#####' or '=====' before
3046 the source line. Otherwise, print the execution count
3047 before the source line.
3048 There are 16 spaces of indentation added before the source
3049 line so that tabs won't be messed up. */
3050 output_line_beginning (gcov_file, line->exists,
3051 line->unexceptional,
3052 line->has_unexecuted_block,
3053 line->count,
3054 l, "=====", "#####",
3055 src->maximum_count);
3057 print_source_line (gcov_file, source_lines, l);
3058 output_line_details (gcov_file, line, l);
3062 fprintf (gcov_file, FN_SEPARATOR);
3063 line_start_group = 0;
3067 if (source_file)
3068 fclose (source_file);