Fix version check for ATTRIBUTE_GCC_DUMP_PRINTF
[official-gcc.git] / gcc / gcov.c
blobff4020c713e64be666c6e222806bb7a562093f56
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 /* Functions in this source file. These are in ascending line
343 number order. */
344 vector <function_info *> functions;
347 source_info::source_info (): index (0), name (NULL), file_time (),
348 lines (), coverage (), functions ()
352 vector<function_info *>
353 source_info::get_functions_at_location (unsigned line_num) const
355 vector<function_info *> r;
357 for (vector<function_info *>::const_iterator it = functions.begin ();
358 it != functions.end (); it++)
360 if ((*it)->start_line == line_num && (*it)->src == index)
361 r.push_back (*it);
364 std::sort (r.begin (), r.end (), function_line_start_cmp ());
366 return r;
369 class name_map
371 public:
372 name_map ()
376 name_map (char *_name, unsigned _src): name (_name), src (_src)
380 bool operator== (const name_map &rhs) const
382 #if HAVE_DOS_BASED_FILE_SYSTEM
383 return strcasecmp (this->name, rhs.name) == 0;
384 #else
385 return strcmp (this->name, rhs.name) == 0;
386 #endif
389 bool operator< (const name_map &rhs) const
391 #if HAVE_DOS_BASED_FILE_SYSTEM
392 return strcasecmp (this->name, rhs.name) < 0;
393 #else
394 return strcmp (this->name, rhs.name) < 0;
395 #endif
398 const char *name; /* Source file name */
399 unsigned src; /* Source file */
402 /* Vector of all functions. */
403 static vector<function_info *> functions;
405 /* Vector of source files. */
406 static vector<source_info> sources;
408 /* Mapping of file names to sources */
409 static vector<name_map> names;
411 /* Record all processed files in order to warn about
412 a file being read multiple times. */
413 static vector<char *> processed_files;
415 /* This holds data summary information. */
417 static unsigned object_runs;
418 static unsigned program_count;
420 static unsigned total_lines;
421 static unsigned total_executed;
423 /* Modification time of graph file. */
425 static time_t bbg_file_time;
427 /* Name of the notes (gcno) output file. The "bbg" prefix is for
428 historical reasons, when the notes file contained only the
429 basic block graph notes. */
431 static char *bbg_file_name;
433 /* Stamp of the bbg file */
434 static unsigned bbg_stamp;
436 /* Supports has_unexecuted_blocks functionality. */
437 static unsigned bbg_supports_has_unexecuted_blocks;
439 /* Working directory in which a TU was compiled. */
440 static const char *bbg_cwd;
442 /* Name and file pointer of the input file for the count data (gcda). */
444 static char *da_file_name;
446 /* Data file is missing. */
448 static int no_data_file;
450 /* If there is several input files, compute and display results after
451 reading all data files. This way if two or more gcda file refer to
452 the same source file (eg inline subprograms in a .h file), the
453 counts are added. */
455 static int multiple_files = 0;
457 /* Output branch probabilities. */
459 static int flag_branches = 0;
461 /* Show unconditional branches too. */
462 static int flag_unconditional = 0;
464 /* Output a gcov file if this is true. This is on by default, and can
465 be turned off by the -n option. */
467 static int flag_gcov_file = 1;
469 /* Output to stdout instead to a gcov file. */
471 static int flag_use_stdout = 0;
473 /* Output progress indication if this is true. This is off by default
474 and can be turned on by the -d option. */
476 static int flag_display_progress = 0;
478 /* Output *.gcov file in intermediate format used by 'lcov'. */
480 static int flag_intermediate_format = 0;
482 /* Output demangled function names. */
484 static int flag_demangled_names = 0;
486 /* For included files, make the gcov output file name include the name
487 of the input source file. For example, if x.h is included in a.c,
488 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
490 static int flag_long_names = 0;
492 /* For situations when a long name can potentially hit filesystem path limit,
493 let's calculate md5sum of the path and append it to a file name. */
495 static int flag_hash_filenames = 0;
497 /* Print verbose informations. */
499 static int flag_verbose = 0;
501 /* Print colored output. */
503 static int flag_use_colors = 0;
505 /* Output count information for every basic block, not merely those
506 that contain line number information. */
508 static int flag_all_blocks = 0;
510 /* Output human readable numbers. */
512 static int flag_human_readable_numbers = 0;
514 /* Output summary info for each function. */
516 static int flag_function_summary = 0;
518 /* Object directory file prefix. This is the directory/file where the
519 graph and data files are looked for, if nonzero. */
521 static char *object_directory = 0;
523 /* Source directory prefix. This is removed from source pathnames
524 that match, when generating the output file name. */
526 static char *source_prefix = 0;
527 static size_t source_length = 0;
529 /* Only show data for sources with relative pathnames. Absolute ones
530 usually indicate a system header file, which although it may
531 contain inline functions, is usually uninteresting. */
532 static int flag_relative_only = 0;
534 /* Preserve all pathname components. Needed when object files and
535 source files are in subdirectories. '/' is mangled as '#', '.' is
536 elided and '..' mangled to '^'. */
538 static int flag_preserve_paths = 0;
540 /* Output the number of times a branch was taken as opposed to the percentage
541 of times it was taken. */
543 static int flag_counts = 0;
545 /* Forward declarations. */
546 static int process_args (int, char **);
547 static void print_usage (int) ATTRIBUTE_NORETURN;
548 static void print_version (void) ATTRIBUTE_NORETURN;
549 static void process_file (const char *);
550 static void process_all_functions (void);
551 static void generate_results (const char *);
552 static void create_file_names (const char *);
553 static char *canonicalize_name (const char *);
554 static unsigned find_source (const char *);
555 static void read_graph_file (void);
556 static int read_count_file (void);
557 static void solve_flow_graph (function_info *);
558 static void find_exception_blocks (function_info *);
559 static void add_branch_counts (coverage_info *, const arc_info *);
560 static void add_line_counts (coverage_info *, function_info *);
561 static void executed_summary (unsigned, unsigned);
562 static void function_summary (const coverage_info *, const char *);
563 static const char *format_gcov (gcov_type, gcov_type, int);
564 static void accumulate_line_counts (source_info *);
565 static void output_gcov_file (const char *, source_info *);
566 static int output_branch_count (FILE *, int, const arc_info *);
567 static void output_lines (FILE *, const source_info *);
568 static char *make_gcov_file_name (const char *, const char *);
569 static char *mangle_name (const char *, char *);
570 static void release_structures (void);
571 extern int main (int, char **);
573 function_info::function_info (): name (NULL), demangled_name (NULL),
574 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
575 artificial (0), is_group (0),
576 blocks (), blocks_executed (0), counts (),
577 start_line (0), start_column (), end_line (0), src (0), lines (), next (NULL)
581 function_info::~function_info ()
583 for (int i = blocks.size () - 1; i >= 0; i--)
585 arc_info *arc, *arc_n;
587 for (arc = blocks[i].succ; arc; arc = arc_n)
589 arc_n = arc->succ_next;
590 free (arc);
593 if (flag_demangled_names && demangled_name != name)
594 free (demangled_name);
595 free (name);
598 bool function_info::group_line_p (unsigned n, unsigned src_idx)
600 return is_group && src == src_idx && start_line <= n && n <= end_line;
603 /* Cycle detection!
604 There are a bajillion algorithms that do this. Boost's function is named
605 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
606 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
607 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
609 The basic algorithm is simple: effectively, we're finding all simple paths
610 in a subgraph (that shrinks every iteration). Duplicates are filtered by
611 "blocking" a path when a node is added to the path (this also prevents non-
612 simple paths)--the node is unblocked only when it participates in a cycle.
615 typedef vector<arc_info *> arc_vector_t;
616 typedef vector<const block_info *> block_vector_t;
618 /* Enum with types of loop in CFG. */
620 enum loop_type
622 NO_LOOP = 0,
623 LOOP = 1,
624 NEGATIVE_LOOP = 3
627 /* Loop_type operator that merges two values: A and B. */
629 inline loop_type& operator |= (loop_type& a, loop_type b)
631 return a = static_cast<loop_type> (a | b);
634 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
635 and subtract the value from all counts. The subtracted value is added
636 to COUNT. Returns type of loop. */
638 static loop_type
639 handle_cycle (const arc_vector_t &edges, int64_t &count)
641 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
642 that amount. */
643 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
644 for (unsigned i = 0; i < edges.size (); i++)
646 int64_t ecount = edges[i]->cs_count;
647 if (cycle_count > ecount)
648 cycle_count = ecount;
650 count += cycle_count;
651 for (unsigned i = 0; i < edges.size (); i++)
652 edges[i]->cs_count -= cycle_count;
654 return cycle_count < 0 ? NEGATIVE_LOOP : LOOP;
657 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
658 blocked by U in BLOCK_LISTS. */
660 static void
661 unblock (const block_info *u, block_vector_t &blocked,
662 vector<block_vector_t > &block_lists)
664 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
665 if (it == blocked.end ())
666 return;
668 unsigned index = it - blocked.begin ();
669 blocked.erase (it);
671 block_vector_t to_unblock (block_lists[index]);
673 block_lists.erase (block_lists.begin () + index);
675 for (block_vector_t::iterator it = to_unblock.begin ();
676 it != to_unblock.end (); it++)
677 unblock (*it, blocked, block_lists);
680 /* Find circuit going to block V, PATH is provisional seen cycle.
681 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
682 blocked by a block. COUNT is accumulated count of the current LINE.
683 Returns what type of loop it contains. */
685 static loop_type
686 circuit (block_info *v, arc_vector_t &path, block_info *start,
687 block_vector_t &blocked, vector<block_vector_t> &block_lists,
688 line_info &linfo, int64_t &count)
690 loop_type result = NO_LOOP;
692 /* Add v to the block list. */
693 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
694 blocked.push_back (v);
695 block_lists.push_back (block_vector_t ());
697 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
699 block_info *w = arc->dst;
700 if (w < start || !linfo.has_block (w))
701 continue;
703 path.push_back (arc);
704 if (w == start)
705 /* Cycle has been found. */
706 result |= handle_cycle (path, count);
707 else if (find (blocked.begin (), blocked.end (), w) == blocked.end ())
708 result |= circuit (w, path, start, blocked, block_lists, linfo, count);
710 path.pop_back ();
713 if (result != NO_LOOP)
714 unblock (v, blocked, block_lists);
715 else
716 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
718 block_info *w = arc->dst;
719 if (w < start || !linfo.has_block (w))
720 continue;
722 size_t index
723 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
724 gcc_assert (index < blocked.size ());
725 block_vector_t &list = block_lists[index];
726 if (find (list.begin (), list.end (), v) == list.end ())
727 list.push_back (v);
730 return result;
733 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
734 contains a negative loop, then perform the same function once again. */
736 static gcov_type
737 get_cycles_count (line_info &linfo, bool handle_negative_cycles = true)
739 /* Note that this algorithm works even if blocks aren't in sorted order.
740 Each iteration of the circuit detection is completely independent
741 (except for reducing counts, but that shouldn't matter anyways).
742 Therefore, operating on a permuted order (i.e., non-sorted) only
743 has the effect of permuting the output cycles. */
745 loop_type result = NO_LOOP;
746 gcov_type count = 0;
747 for (vector<block_info *>::iterator it = linfo.blocks.begin ();
748 it != linfo.blocks.end (); it++)
750 arc_vector_t path;
751 block_vector_t blocked;
752 vector<block_vector_t > block_lists;
753 result |= circuit (*it, path, *it, blocked, block_lists, linfo,
754 count);
757 /* If we have a negative cycle, repeat the find_cycles routine. */
758 if (result == NEGATIVE_LOOP && handle_negative_cycles)
759 count += get_cycles_count (linfo, false);
761 return count;
765 main (int argc, char **argv)
767 int argno;
768 int first_arg;
769 const char *p;
771 p = argv[0] + strlen (argv[0]);
772 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
773 --p;
774 progname = p;
776 xmalloc_set_program_name (progname);
778 /* Unlock the stdio streams. */
779 unlock_std_streams ();
781 gcc_init_libintl ();
783 diagnostic_initialize (global_dc, 0);
785 /* Handle response files. */
786 expandargv (&argc, &argv);
788 argno = process_args (argc, argv);
789 if (optind == argc)
790 print_usage (true);
792 if (argc - argno > 1)
793 multiple_files = 1;
795 first_arg = argno;
797 for (; argno != argc; argno++)
799 if (flag_display_progress)
800 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
801 argc - first_arg);
802 process_file (argv[argno]);
804 if (flag_intermediate_format || argno == argc - 1)
806 process_all_functions ();
807 generate_results (argv[argno]);
808 release_structures ();
812 return 0;
815 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
816 otherwise the output of --help. */
818 static void
819 print_usage (int error_p)
821 FILE *file = error_p ? stderr : stdout;
822 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
824 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
825 fnotice (file, "Print code coverage information.\n\n");
826 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
827 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
828 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
829 rather than percentages\n");
830 fnotice (file, " -d, --display-progress Display progress information\n");
831 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
832 fnotice (file, " -h, --help Print this help, then exit\n");
833 fnotice (file, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
834 fnotice (file, " -j, --human-readable Output human readable numbers\n");
835 fnotice (file, " -k, --use-colors Emit colored output\n");
836 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
837 source files\n");
838 fnotice (file, " -m, --demangled-names Output demangled function names\n");
839 fnotice (file, " -n, --no-output Do not create an output file\n");
840 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
841 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
842 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
843 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
844 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
845 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
846 fnotice (file, " -v, --version Print version number, then exit\n");
847 fnotice (file, " -w, --verbose Print verbose informations\n");
848 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
849 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
850 bug_report_url);
851 exit (status);
854 /* Print version information and exit. */
856 static void
857 print_version (void)
859 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
860 fprintf (stdout, "Copyright %s 2018 Free Software Foundation, Inc.\n",
861 _("(C)"));
862 fnotice (stdout,
863 _("This is free software; see the source for copying conditions.\n"
864 "There is NO warranty; not even for MERCHANTABILITY or \n"
865 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
866 exit (SUCCESS_EXIT_CODE);
869 static const struct option options[] =
871 { "help", no_argument, NULL, 'h' },
872 { "version", no_argument, NULL, 'v' },
873 { "verbose", no_argument, NULL, 'w' },
874 { "all-blocks", no_argument, NULL, 'a' },
875 { "branch-probabilities", no_argument, NULL, 'b' },
876 { "branch-counts", no_argument, NULL, 'c' },
877 { "intermediate-format", no_argument, NULL, 'i' },
878 { "human-readable", no_argument, NULL, 'j' },
879 { "no-output", no_argument, NULL, 'n' },
880 { "long-file-names", no_argument, NULL, 'l' },
881 { "function-summaries", no_argument, NULL, 'f' },
882 { "demangled-names", no_argument, NULL, 'm' },
883 { "preserve-paths", no_argument, NULL, 'p' },
884 { "relative-only", no_argument, NULL, 'r' },
885 { "object-directory", required_argument, NULL, 'o' },
886 { "object-file", required_argument, NULL, 'o' },
887 { "source-prefix", required_argument, NULL, 's' },
888 { "stdout", no_argument, NULL, 't' },
889 { "unconditional-branches", no_argument, NULL, 'u' },
890 { "display-progress", no_argument, NULL, 'd' },
891 { "hash-filenames", no_argument, NULL, 'x' },
892 { "use-colors", no_argument, NULL, 'k' },
893 { 0, 0, 0, 0 }
896 /* Process args, return index to first non-arg. */
898 static int
899 process_args (int argc, char **argv)
901 int opt;
903 const char *opts = "abcdfhijklmno:prs:tuvwx";
904 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
906 switch (opt)
908 case 'a':
909 flag_all_blocks = 1;
910 break;
911 case 'b':
912 flag_branches = 1;
913 break;
914 case 'c':
915 flag_counts = 1;
916 break;
917 case 'f':
918 flag_function_summary = 1;
919 break;
920 case 'h':
921 print_usage (false);
922 /* print_usage will exit. */
923 case 'l':
924 flag_long_names = 1;
925 break;
926 case 'j':
927 flag_human_readable_numbers = 1;
928 break;
929 case 'k':
930 flag_use_colors = 1;
931 break;
932 case 'm':
933 flag_demangled_names = 1;
934 break;
935 case 'n':
936 flag_gcov_file = 0;
937 break;
938 case 'o':
939 object_directory = optarg;
940 break;
941 case 's':
942 source_prefix = optarg;
943 source_length = strlen (source_prefix);
944 break;
945 case 'r':
946 flag_relative_only = 1;
947 break;
948 case 'p':
949 flag_preserve_paths = 1;
950 break;
951 case 'u':
952 flag_unconditional = 1;
953 break;
954 case 'i':
955 flag_intermediate_format = 1;
956 flag_gcov_file = 1;
957 break;
958 case 'd':
959 flag_display_progress = 1;
960 break;
961 case 'x':
962 flag_hash_filenames = 1;
963 break;
964 case 'w':
965 flag_verbose = 1;
966 break;
967 case 't':
968 flag_use_stdout = 1;
969 break;
970 case 'v':
971 print_version ();
972 /* print_version will exit. */
973 default:
974 print_usage (true);
975 /* print_usage will exit. */
979 return optind;
982 /* Output intermediate LINE sitting on LINE_NUM to output file F. */
984 static void
985 output_intermediate_line (FILE *f, line_info *line, unsigned line_num)
987 if (!line->exists)
988 return;
990 fprintf (f, "lcount:%u,%s,%d\n", line_num,
991 format_gcov (line->count, 0, -1),
992 line->has_unexecuted_block);
994 vector<arc_info *>::const_iterator it;
995 if (flag_branches)
996 for (it = line->branches.begin (); it != line->branches.end ();
997 it++)
999 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1001 const char *branch_type;
1002 /* branch:<line_num>,<branch_coverage_infoype>
1003 branch_coverage_infoype
1004 : notexec (Branch not executed)
1005 : taken (Branch executed and taken)
1006 : nottaken (Branch executed, but not taken)
1008 if ((*it)->src->count)
1009 branch_type
1010 = ((*it)->count > 0) ? "taken" : "nottaken";
1011 else
1012 branch_type = "notexec";
1013 fprintf (f, "branch:%d,%s\n", line_num, branch_type);
1018 /* Get the name of the gcov file. The return value must be free'd.
1020 It appends the '.gcov' extension to the *basename* of the file.
1021 The resulting file name will be in PWD.
1023 e.g.,
1024 input: foo.da, output: foo.da.gcov
1025 input: a/b/foo.cc, output: foo.cc.gcov */
1027 static char *
1028 get_gcov_intermediate_filename (const char *file_name)
1030 const char *gcov = ".gcov";
1031 char *result;
1032 const char *cptr;
1034 /* Find the 'basename'. */
1035 cptr = lbasename (file_name);
1037 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1038 sprintf (result, "%s%s", cptr, gcov);
1040 return result;
1043 /* Output the result in intermediate format used by 'lcov'.
1045 The intermediate format contains a single file named 'foo.cc.gcov',
1046 with no source code included.
1048 The default gcov outputs multiple files: 'foo.cc.gcov',
1049 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
1050 included. Instead the intermediate format here outputs only a single
1051 file 'foo.cc.gcov' similar to the above example. */
1053 static void
1054 output_intermediate_file (FILE *gcov_file, source_info *src)
1056 fprintf (gcov_file, "version:%s\n", version_string);
1057 fprintf (gcov_file, "file:%s\n", src->name); /* source file name */
1058 fprintf (gcov_file, "cwd:%s\n", bbg_cwd);
1060 std::sort (src->functions.begin (), src->functions.end (),
1061 function_line_start_cmp ());
1062 for (vector<function_info *>::iterator it = src->functions.begin ();
1063 it != src->functions.end (); it++)
1065 /* function:<name>,<line_number>,<execution_count> */
1066 fprintf (gcov_file, "function:%d,%d,%s,%s\n", (*it)->start_line,
1067 (*it)->end_line, format_gcov ((*it)->blocks[0].count, 0, -1),
1068 flag_demangled_names ? (*it)->demangled_name : (*it)->name);
1071 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1073 vector<function_info *> fns = src->get_functions_at_location (line_num);
1075 /* Print first group functions that begin on the line. */
1076 for (vector<function_info *>::iterator it2 = fns.begin ();
1077 it2 != fns.end (); it2++)
1079 vector<line_info> &lines = (*it2)->lines;
1080 for (unsigned i = 0; i < lines.size (); i++)
1082 line_info *line = &lines[i];
1083 output_intermediate_line (gcov_file, line, line_num + i);
1087 /* Follow with lines associated with the source file. */
1088 output_intermediate_line (gcov_file, &src->lines[line_num], line_num);
1092 /* Function start pair. */
1093 struct function_start
1095 unsigned source_file_idx;
1096 unsigned start_line;
1099 /* Traits class for function start hash maps below. */
1101 struct function_start_pair_hash : typed_noop_remove <function_start>
1103 typedef function_start value_type;
1104 typedef function_start compare_type;
1106 static hashval_t
1107 hash (const function_start &ref)
1109 inchash::hash hstate (0);
1110 hstate.add_int (ref.source_file_idx);
1111 hstate.add_int (ref.start_line);
1112 return hstate.end ();
1115 static bool
1116 equal (const function_start &ref1, const function_start &ref2)
1118 return (ref1.source_file_idx == ref2.source_file_idx
1119 && ref1.start_line == ref2.start_line);
1122 static void
1123 mark_deleted (function_start &ref)
1125 ref.start_line = ~1U;
1128 static void
1129 mark_empty (function_start &ref)
1131 ref.start_line = ~2U;
1134 static bool
1135 is_deleted (const function_start &ref)
1137 return ref.start_line == ~1U;
1140 static bool
1141 is_empty (const function_start &ref)
1143 return ref.start_line == ~2U;
1147 /* Process a single input file. */
1149 static void
1150 process_file (const char *file_name)
1152 create_file_names (file_name);
1154 for (unsigned i = 0; i < processed_files.size (); i++)
1155 if (strcmp (da_file_name, processed_files[i]) == 0)
1157 fnotice (stderr, "'%s' file is already processed\n",
1158 file_name);
1159 return;
1162 processed_files.push_back (xstrdup (da_file_name));
1164 read_graph_file ();
1165 read_count_file ();
1168 /* Process all functions in all files. */
1170 static void
1171 process_all_functions (void)
1173 hash_map<function_start_pair_hash, function_info *> fn_map;
1175 /* Identify group functions. */
1176 for (vector<function_info *>::iterator it = functions.begin ();
1177 it != functions.end (); it++)
1178 if (!(*it)->artificial)
1180 function_start needle;
1181 needle.source_file_idx = (*it)->src;
1182 needle.start_line = (*it)->start_line;
1184 function_info **slot = fn_map.get (needle);
1185 if (slot)
1187 (*slot)->is_group = 1;
1188 (*it)->is_group = 1;
1190 else
1191 fn_map.put (needle, *it);
1194 /* Remove all artificial function. */
1195 functions.erase (remove_if (functions.begin (), functions.end (),
1196 function_info::is_artificial), functions.end ());
1198 for (vector<function_info *>::iterator it = functions.begin ();
1199 it != functions.end (); it++)
1201 function_info *fn = *it;
1202 unsigned src = fn->src;
1204 if (!fn->counts.empty () || no_data_file)
1206 source_info *s = &sources[src];
1207 s->functions.push_back (fn);
1209 /* Mark last line in files touched by function. */
1210 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1211 block_no++)
1213 block_info *block = &fn->blocks[block_no];
1214 for (unsigned i = 0; i < block->locations.size (); i++)
1216 /* Sort lines of locations. */
1217 sort (block->locations[i].lines.begin (),
1218 block->locations[i].lines.end ());
1220 if (!block->locations[i].lines.empty ())
1222 s = &sources[block->locations[i].source_file_idx];
1223 unsigned last_line
1224 = block->locations[i].lines.back ();
1226 /* Record new lines for the function. */
1227 if (last_line >= s->lines.size ())
1229 s = &sources[block->locations[i].source_file_idx];
1230 unsigned last_line
1231 = block->locations[i].lines.back ();
1233 /* Record new lines for the function. */
1234 if (last_line >= s->lines.size ())
1236 /* Record new lines for a source file. */
1237 s->lines.resize (last_line + 1);
1244 /* Allocate lines for group function, following start_line
1245 and end_line information of the function. */
1246 if (fn->is_group)
1247 fn->lines.resize (fn->end_line - fn->start_line + 1);
1249 solve_flow_graph (fn);
1250 if (fn->has_catch)
1251 find_exception_blocks (fn);
1253 else
1255 /* The function was not in the executable -- some other
1256 instance must have been selected. */
1261 static void
1262 output_gcov_file (const char *file_name, source_info *src)
1264 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1266 if (src->coverage.lines)
1268 FILE *gcov_file = fopen (gcov_file_name, "w");
1269 if (gcov_file)
1271 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1272 output_lines (gcov_file, src);
1273 if (ferror (gcov_file))
1274 fnotice (stderr, "Error writing output file '%s'\n",
1275 gcov_file_name);
1276 fclose (gcov_file);
1278 else
1279 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1281 else
1283 unlink (gcov_file_name);
1284 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1286 free (gcov_file_name);
1289 static void
1290 generate_results (const char *file_name)
1292 FILE *gcov_intermediate_file = NULL;
1293 char *gcov_intermediate_filename = NULL;
1295 for (vector<function_info *>::iterator it = functions.begin ();
1296 it != functions.end (); it++)
1298 function_info *fn = *it;
1299 coverage_info coverage;
1301 memset (&coverage, 0, sizeof (coverage));
1302 coverage.name = flag_demangled_names ? fn->demangled_name : fn->name;
1303 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1304 if (flag_function_summary)
1306 function_summary (&coverage, "Function");
1307 fnotice (stdout, "\n");
1311 name_map needle;
1313 if (file_name)
1315 needle.name = file_name;
1316 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1317 needle);
1318 if (it != names.end ())
1319 file_name = sources[it->src].coverage.name;
1320 else
1321 file_name = canonicalize_name (file_name);
1324 if (flag_gcov_file && flag_intermediate_format && !flag_use_stdout)
1326 /* Open the intermediate file. */
1327 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1328 gcov_intermediate_file = fopen (gcov_intermediate_filename, "w");
1329 if (!gcov_intermediate_file)
1331 fnotice (stderr, "Cannot open intermediate output file %s\n",
1332 gcov_intermediate_filename);
1333 return;
1337 for (vector<source_info>::iterator it = sources.begin ();
1338 it != sources.end (); it++)
1340 source_info *src = &(*it);
1341 if (flag_relative_only)
1343 /* Ignore this source, if it is an absolute path (after
1344 source prefix removal). */
1345 char first = src->coverage.name[0];
1347 #if HAVE_DOS_BASED_FILE_SYSTEM
1348 if (first && src->coverage.name[1] == ':')
1349 first = src->coverage.name[2];
1350 #endif
1351 if (IS_DIR_SEPARATOR (first))
1352 continue;
1355 accumulate_line_counts (src);
1357 if (!flag_use_stdout)
1358 function_summary (&src->coverage, "File");
1359 total_lines += src->coverage.lines;
1360 total_executed += src->coverage.lines_executed;
1361 if (flag_gcov_file)
1363 if (flag_intermediate_format)
1364 /* Output the intermediate format without requiring source
1365 files. This outputs a section to a *single* file. */
1366 output_intermediate_file ((flag_use_stdout
1367 ? stdout : gcov_intermediate_file), src);
1368 else
1370 if (flag_use_stdout)
1372 if (src->coverage.lines)
1373 output_lines (stdout, src);
1375 else
1377 output_gcov_file (file_name, src);
1378 fnotice (stdout, "\n");
1384 if (flag_gcov_file && flag_intermediate_format && !flag_use_stdout)
1386 /* Now we've finished writing the intermediate file. */
1387 fclose (gcov_intermediate_file);
1388 XDELETEVEC (gcov_intermediate_filename);
1391 if (!file_name)
1392 executed_summary (total_lines, total_executed);
1395 /* Release all memory used. */
1397 static void
1398 release_structures (void)
1400 for (vector<function_info *>::iterator it = functions.begin ();
1401 it != functions.end (); it++)
1402 delete (*it);
1404 sources.resize (0);
1405 names.resize (0);
1406 functions.resize (0);
1409 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1410 is not specified, these are named from FILE_NAME sans extension. If
1411 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1412 directory, but named from the basename of the FILE_NAME, sans extension.
1413 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1414 and the data files are named from that. */
1416 static void
1417 create_file_names (const char *file_name)
1419 char *cptr;
1420 char *name;
1421 int length = strlen (file_name);
1422 int base;
1424 /* Free previous file names. */
1425 free (bbg_file_name);
1426 free (da_file_name);
1427 da_file_name = bbg_file_name = NULL;
1428 bbg_file_time = 0;
1429 bbg_stamp = 0;
1431 if (object_directory && object_directory[0])
1433 struct stat status;
1435 length += strlen (object_directory) + 2;
1436 name = XNEWVEC (char, length);
1437 name[0] = 0;
1439 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1440 strcat (name, object_directory);
1441 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1442 strcat (name, "/");
1444 else
1446 name = XNEWVEC (char, length + 1);
1447 strcpy (name, file_name);
1448 base = 0;
1451 if (base)
1453 /* Append source file name. */
1454 const char *cptr = lbasename (file_name);
1455 strcat (name, cptr ? cptr : file_name);
1458 /* Remove the extension. */
1459 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1460 if (cptr)
1461 *cptr = 0;
1463 length = strlen (name);
1465 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1466 strcpy (bbg_file_name, name);
1467 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1469 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1470 strcpy (da_file_name, name);
1471 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1473 free (name);
1474 return;
1477 /* Find or create a source file structure for FILE_NAME. Copies
1478 FILE_NAME on creation */
1480 static unsigned
1481 find_source (const char *file_name)
1483 char *canon;
1484 unsigned idx;
1485 struct stat status;
1487 if (!file_name)
1488 file_name = "<unknown>";
1490 name_map needle;
1491 needle.name = file_name;
1493 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1494 needle);
1495 if (it != names.end ())
1497 idx = it->src;
1498 goto check_date;
1501 /* Not found, try the canonical name. */
1502 canon = canonicalize_name (file_name);
1503 needle.name = canon;
1504 it = std::find (names.begin (), names.end (), needle);
1505 if (it == names.end ())
1507 /* Not found with canonical name, create a new source. */
1508 source_info *src;
1510 idx = sources.size ();
1511 needle = name_map (canon, idx);
1512 names.push_back (needle);
1514 sources.push_back (source_info ());
1515 src = &sources.back ();
1516 src->name = canon;
1517 src->coverage.name = src->name;
1518 src->index = idx;
1519 if (source_length
1520 #if HAVE_DOS_BASED_FILE_SYSTEM
1521 /* You lose if separators don't match exactly in the
1522 prefix. */
1523 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1524 #else
1525 && !strncmp (source_prefix, src->coverage.name, source_length)
1526 #endif
1527 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1528 src->coverage.name += source_length + 1;
1529 if (!stat (src->name, &status))
1530 src->file_time = status.st_mtime;
1532 else
1533 idx = it->src;
1535 needle.name = file_name;
1536 if (std::find (names.begin (), names.end (), needle) == names.end ())
1538 /* Append the non-canonical name. */
1539 names.push_back (name_map (xstrdup (file_name), idx));
1542 /* Resort the name map. */
1543 std::sort (names.begin (), names.end ());
1545 check_date:
1546 if (sources[idx].file_time > bbg_file_time)
1548 static int info_emitted;
1550 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1551 file_name, bbg_file_name);
1552 if (!info_emitted)
1554 fnotice (stderr,
1555 "(the message is displayed only once per source file)\n");
1556 info_emitted = 1;
1558 sources[idx].file_time = 0;
1561 return idx;
1564 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1566 static void
1567 read_graph_file (void)
1569 unsigned version;
1570 unsigned current_tag = 0;
1571 unsigned tag;
1573 if (!gcov_open (bbg_file_name, 1))
1575 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1576 return;
1578 bbg_file_time = gcov_time ();
1579 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1581 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1582 gcov_close ();
1583 return;
1586 version = gcov_read_unsigned ();
1587 if (version != GCOV_VERSION)
1589 char v[4], e[4];
1591 GCOV_UNSIGNED2STRING (v, version);
1592 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1594 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1595 bbg_file_name, v, e);
1597 bbg_stamp = gcov_read_unsigned ();
1598 bbg_cwd = xstrdup (gcov_read_string ());
1599 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1601 function_info *fn = NULL;
1602 while ((tag = gcov_read_unsigned ()))
1604 unsigned length = gcov_read_unsigned ();
1605 gcov_position_t base = gcov_position ();
1607 if (tag == GCOV_TAG_FUNCTION)
1609 char *function_name;
1610 unsigned ident;
1611 unsigned lineno_checksum, cfg_checksum;
1613 ident = gcov_read_unsigned ();
1614 lineno_checksum = gcov_read_unsigned ();
1615 cfg_checksum = gcov_read_unsigned ();
1616 function_name = xstrdup (gcov_read_string ());
1617 unsigned artificial = gcov_read_unsigned ();
1618 unsigned src_idx = find_source (gcov_read_string ());
1619 unsigned start_line = gcov_read_unsigned ();
1620 unsigned start_column = gcov_read_unsigned ();
1621 unsigned end_line = gcov_read_unsigned ();
1623 fn = new function_info ();
1624 functions.push_back (fn);
1625 fn->name = function_name;
1626 if (flag_demangled_names)
1628 fn->demangled_name = cplus_demangle (fn->name, DMGL_PARAMS);
1629 if (!fn->demangled_name)
1630 fn->demangled_name = fn->name;
1632 fn->ident = ident;
1633 fn->lineno_checksum = lineno_checksum;
1634 fn->cfg_checksum = cfg_checksum;
1635 fn->src = src_idx;
1636 fn->start_line = start_line;
1637 fn->start_column = start_column;
1638 fn->end_line = end_line;
1639 fn->artificial = artificial;
1641 current_tag = tag;
1643 else if (fn && tag == GCOV_TAG_BLOCKS)
1645 if (!fn->blocks.empty ())
1646 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1647 bbg_file_name, fn->name);
1648 else
1649 fn->blocks.resize (gcov_read_unsigned ());
1651 else if (fn && tag == GCOV_TAG_ARCS)
1653 unsigned src = gcov_read_unsigned ();
1654 fn->blocks[src].id = src;
1655 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1656 block_info *src_blk = &fn->blocks[src];
1657 unsigned mark_catches = 0;
1658 struct arc_info *arc;
1660 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1661 goto corrupt;
1663 while (num_dests--)
1665 unsigned dest = gcov_read_unsigned ();
1666 unsigned flags = gcov_read_unsigned ();
1668 if (dest >= fn->blocks.size ())
1669 goto corrupt;
1670 arc = XCNEW (arc_info);
1672 arc->dst = &fn->blocks[dest];
1673 arc->src = src_blk;
1675 arc->count = 0;
1676 arc->count_valid = 0;
1677 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1678 arc->fake = !!(flags & GCOV_ARC_FAKE);
1679 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1681 arc->succ_next = src_blk->succ;
1682 src_blk->succ = arc;
1683 src_blk->num_succ++;
1685 arc->pred_next = fn->blocks[dest].pred;
1686 fn->blocks[dest].pred = arc;
1687 fn->blocks[dest].num_pred++;
1689 if (arc->fake)
1691 if (src)
1693 /* Exceptional exit from this function, the
1694 source block must be a call. */
1695 fn->blocks[src].is_call_site = 1;
1696 arc->is_call_non_return = 1;
1697 mark_catches = 1;
1699 else
1701 /* Non-local return from a callee of this
1702 function. The destination block is a setjmp. */
1703 arc->is_nonlocal_return = 1;
1704 fn->blocks[dest].is_nonlocal_return = 1;
1708 if (!arc->on_tree)
1709 fn->counts.push_back (0);
1712 if (mark_catches)
1714 /* We have a fake exit from this block. The other
1715 non-fall through exits must be to catch handlers.
1716 Mark them as catch arcs. */
1718 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1719 if (!arc->fake && !arc->fall_through)
1721 arc->is_throw = 1;
1722 fn->has_catch = 1;
1726 else if (fn && tag == GCOV_TAG_LINES)
1728 unsigned blockno = gcov_read_unsigned ();
1729 block_info *block = &fn->blocks[blockno];
1731 if (blockno >= fn->blocks.size ())
1732 goto corrupt;
1734 while (true)
1736 unsigned lineno = gcov_read_unsigned ();
1738 if (lineno)
1739 block->locations.back ().lines.push_back (lineno);
1740 else
1742 const char *file_name = gcov_read_string ();
1744 if (!file_name)
1745 break;
1746 block->locations.push_back (block_location_info
1747 (find_source (file_name)));
1751 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1753 fn = NULL;
1754 current_tag = 0;
1756 gcov_sync (base, length);
1757 if (gcov_is_error ())
1759 corrupt:;
1760 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1761 break;
1764 gcov_close ();
1766 if (functions.empty ())
1767 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1770 /* Reads profiles from the count file and attach to each
1771 function. Return nonzero if fatal error. */
1773 static int
1774 read_count_file (void)
1776 unsigned ix;
1777 unsigned version;
1778 unsigned tag;
1779 function_info *fn = NULL;
1780 int error = 0;
1782 if (!gcov_open (da_file_name, 1))
1784 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1785 da_file_name);
1786 no_data_file = 1;
1787 return 0;
1789 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1791 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1792 cleanup:;
1793 gcov_close ();
1794 return 1;
1796 version = gcov_read_unsigned ();
1797 if (version != GCOV_VERSION)
1799 char v[4], e[4];
1801 GCOV_UNSIGNED2STRING (v, version);
1802 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1804 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1805 da_file_name, v, e);
1807 tag = gcov_read_unsigned ();
1808 if (tag != bbg_stamp)
1810 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1811 goto cleanup;
1814 while ((tag = gcov_read_unsigned ()))
1816 unsigned length = gcov_read_unsigned ();
1817 unsigned long base = gcov_position ();
1819 if (tag == GCOV_TAG_PROGRAM_SUMMARY)
1821 struct gcov_summary summary;
1822 gcov_read_summary (&summary);
1823 object_runs += summary.runs;
1824 program_count++;
1826 else if (tag == GCOV_TAG_FUNCTION && !length)
1827 ; /* placeholder */
1828 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1830 unsigned ident;
1832 /* Try to find the function in the list. To speed up the
1833 search, first start from the last function found. */
1834 ident = gcov_read_unsigned ();
1836 fn = NULL;
1837 for (vector<function_info *>::reverse_iterator it
1838 = functions.rbegin (); it != functions.rend (); it++)
1840 if ((*it)->ident == ident)
1842 fn = *it;
1843 break;
1847 if (!fn)
1849 else if (gcov_read_unsigned () != fn->lineno_checksum
1850 || gcov_read_unsigned () != fn->cfg_checksum)
1852 mismatch:;
1853 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1854 da_file_name, fn->name);
1855 goto cleanup;
1858 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1860 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1861 goto mismatch;
1863 for (ix = 0; ix != fn->counts.size (); ix++)
1864 fn->counts[ix] += gcov_read_counter ();
1866 gcov_sync (base, length);
1867 if ((error = gcov_is_error ()))
1869 fnotice (stderr,
1870 error < 0
1871 ? N_("%s:overflowed\n")
1872 : N_("%s:corrupted\n"),
1873 da_file_name);
1874 goto cleanup;
1878 gcov_close ();
1879 return 0;
1882 /* Solve the flow graph. Propagate counts from the instrumented arcs
1883 to the blocks and the uninstrumented arcs. */
1885 static void
1886 solve_flow_graph (function_info *fn)
1888 unsigned ix;
1889 arc_info *arc;
1890 gcov_type *count_ptr = &fn->counts.front ();
1891 block_info *blk;
1892 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
1893 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
1895 /* The arcs were built in reverse order. Fix that now. */
1896 for (ix = fn->blocks.size (); ix--;)
1898 arc_info *arc_p, *arc_n;
1900 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
1901 arc_p = arc, arc = arc_n)
1903 arc_n = arc->succ_next;
1904 arc->succ_next = arc_p;
1906 fn->blocks[ix].succ = arc_p;
1908 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
1909 arc_p = arc, arc = arc_n)
1911 arc_n = arc->pred_next;
1912 arc->pred_next = arc_p;
1914 fn->blocks[ix].pred = arc_p;
1917 if (fn->blocks.size () < 2)
1918 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
1919 bbg_file_name, fn->name);
1920 else
1922 if (fn->blocks[ENTRY_BLOCK].num_pred)
1923 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
1924 bbg_file_name, fn->name);
1925 else
1926 /* We can't deduce the entry block counts from the lack of
1927 predecessors. */
1928 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
1930 if (fn->blocks[EXIT_BLOCK].num_succ)
1931 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
1932 bbg_file_name, fn->name);
1933 else
1934 /* Likewise, we can't deduce exit block counts from the lack
1935 of its successors. */
1936 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
1939 /* Propagate the measured counts, this must be done in the same
1940 order as the code in profile.c */
1941 for (unsigned i = 0; i < fn->blocks.size (); i++)
1943 blk = &fn->blocks[i];
1944 block_info const *prev_dst = NULL;
1945 int out_of_order = 0;
1946 int non_fake_succ = 0;
1948 for (arc = blk->succ; arc; arc = arc->succ_next)
1950 if (!arc->fake)
1951 non_fake_succ++;
1953 if (!arc->on_tree)
1955 if (count_ptr)
1956 arc->count = *count_ptr++;
1957 arc->count_valid = 1;
1958 blk->num_succ--;
1959 arc->dst->num_pred--;
1961 if (prev_dst && prev_dst > arc->dst)
1962 out_of_order = 1;
1963 prev_dst = arc->dst;
1965 if (non_fake_succ == 1)
1967 /* If there is only one non-fake exit, it is an
1968 unconditional branch. */
1969 for (arc = blk->succ; arc; arc = arc->succ_next)
1970 if (!arc->fake)
1972 arc->is_unconditional = 1;
1973 /* If this block is instrumenting a call, it might be
1974 an artificial block. It is not artificial if it has
1975 a non-fallthrough exit, or the destination of this
1976 arc has more than one entry. Mark the destination
1977 block as a return site, if none of those conditions
1978 hold. */
1979 if (blk->is_call_site && arc->fall_through
1980 && arc->dst->pred == arc && !arc->pred_next)
1981 arc->dst->is_call_return = 1;
1985 /* Sort the successor arcs into ascending dst order. profile.c
1986 normally produces arcs in the right order, but sometimes with
1987 one or two out of order. We're not using a particularly
1988 smart sort. */
1989 if (out_of_order)
1991 arc_info *start = blk->succ;
1992 unsigned changes = 1;
1994 while (changes)
1996 arc_info *arc, *arc_p, *arc_n;
1998 changes = 0;
1999 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2001 if (arc->dst > arc_n->dst)
2003 changes = 1;
2004 if (arc_p)
2005 arc_p->succ_next = arc_n;
2006 else
2007 start = arc_n;
2008 arc->succ_next = arc_n->succ_next;
2009 arc_n->succ_next = arc;
2010 arc_p = arc_n;
2012 else
2014 arc_p = arc;
2015 arc = arc_n;
2019 blk->succ = start;
2022 /* Place it on the invalid chain, it will be ignored if that's
2023 wrong. */
2024 blk->invalid_chain = 1;
2025 blk->chain = invalid_blocks;
2026 invalid_blocks = blk;
2029 while (invalid_blocks || valid_blocks)
2031 while ((blk = invalid_blocks))
2033 gcov_type total = 0;
2034 const arc_info *arc;
2036 invalid_blocks = blk->chain;
2037 blk->invalid_chain = 0;
2038 if (!blk->num_succ)
2039 for (arc = blk->succ; arc; arc = arc->succ_next)
2040 total += arc->count;
2041 else if (!blk->num_pred)
2042 for (arc = blk->pred; arc; arc = arc->pred_next)
2043 total += arc->count;
2044 else
2045 continue;
2047 blk->count = total;
2048 blk->count_valid = 1;
2049 blk->chain = valid_blocks;
2050 blk->valid_chain = 1;
2051 valid_blocks = blk;
2053 while ((blk = valid_blocks))
2055 gcov_type total;
2056 arc_info *arc, *inv_arc;
2058 valid_blocks = blk->chain;
2059 blk->valid_chain = 0;
2060 if (blk->num_succ == 1)
2062 block_info *dst;
2064 total = blk->count;
2065 inv_arc = NULL;
2066 for (arc = blk->succ; arc; arc = arc->succ_next)
2068 total -= arc->count;
2069 if (!arc->count_valid)
2070 inv_arc = arc;
2072 dst = inv_arc->dst;
2073 inv_arc->count_valid = 1;
2074 inv_arc->count = total;
2075 blk->num_succ--;
2076 dst->num_pred--;
2077 if (dst->count_valid)
2079 if (dst->num_pred == 1 && !dst->valid_chain)
2081 dst->chain = valid_blocks;
2082 dst->valid_chain = 1;
2083 valid_blocks = dst;
2086 else
2088 if (!dst->num_pred && !dst->invalid_chain)
2090 dst->chain = invalid_blocks;
2091 dst->invalid_chain = 1;
2092 invalid_blocks = dst;
2096 if (blk->num_pred == 1)
2098 block_info *src;
2100 total = blk->count;
2101 inv_arc = NULL;
2102 for (arc = blk->pred; arc; arc = arc->pred_next)
2104 total -= arc->count;
2105 if (!arc->count_valid)
2106 inv_arc = arc;
2108 src = inv_arc->src;
2109 inv_arc->count_valid = 1;
2110 inv_arc->count = total;
2111 blk->num_pred--;
2112 src->num_succ--;
2113 if (src->count_valid)
2115 if (src->num_succ == 1 && !src->valid_chain)
2117 src->chain = valid_blocks;
2118 src->valid_chain = 1;
2119 valid_blocks = src;
2122 else
2124 if (!src->num_succ && !src->invalid_chain)
2126 src->chain = invalid_blocks;
2127 src->invalid_chain = 1;
2128 invalid_blocks = src;
2135 /* If the graph has been correctly solved, every block will have a
2136 valid count. */
2137 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2138 if (!fn->blocks[i].count_valid)
2140 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2141 bbg_file_name, fn->name);
2142 break;
2146 /* Mark all the blocks only reachable via an incoming catch. */
2148 static void
2149 find_exception_blocks (function_info *fn)
2151 unsigned ix;
2152 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2154 /* First mark all blocks as exceptional. */
2155 for (ix = fn->blocks.size (); ix--;)
2156 fn->blocks[ix].exceptional = 1;
2158 /* Now mark all the blocks reachable via non-fake edges */
2159 queue[0] = &fn->blocks[0];
2160 queue[0]->exceptional = 0;
2161 for (ix = 1; ix;)
2163 block_info *block = queue[--ix];
2164 const arc_info *arc;
2166 for (arc = block->succ; arc; arc = arc->succ_next)
2167 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2169 arc->dst->exceptional = 0;
2170 queue[ix++] = arc->dst;
2176 /* Increment totals in COVERAGE according to arc ARC. */
2178 static void
2179 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2181 if (arc->is_call_non_return)
2183 coverage->calls++;
2184 if (arc->src->count)
2185 coverage->calls_executed++;
2187 else if (!arc->is_unconditional)
2189 coverage->branches++;
2190 if (arc->src->count)
2191 coverage->branches_executed++;
2192 if (arc->count)
2193 coverage->branches_taken++;
2197 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2198 readable format. */
2200 static char const *
2201 format_count (gcov_type count)
2203 static char buffer[64];
2204 const char *units = " kMGTPEZY";
2206 if (count < 1000 || !flag_human_readable_numbers)
2208 sprintf (buffer, "%" PRId64, count);
2209 return buffer;
2212 unsigned i;
2213 gcov_type divisor = 1;
2214 for (i = 0; units[i+1]; i++, divisor *= 1000)
2216 if (count + divisor / 2 < 1000 * divisor)
2217 break;
2219 gcov_type r = (count + divisor / 2) / divisor;
2220 sprintf (buffer, "%" PRId64 "%c", r, units[i]);
2221 return buffer;
2224 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2225 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2226 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2227 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2228 format TOP. Return pointer to a static string. */
2230 static char const *
2231 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2233 static char buffer[20];
2235 if (decimal_places >= 0)
2237 float ratio = bottom ? 100.0f * top / bottom: 0;
2239 /* Round up to 1% if there's a small non-zero value. */
2240 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2241 ratio = 1.0f;
2242 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2244 else
2245 return format_count (top);
2247 return buffer;
2250 /* Summary of execution */
2252 static void
2253 executed_summary (unsigned lines, unsigned executed)
2255 if (lines)
2256 fnotice (stdout, "Lines executed:%s of %d\n",
2257 format_gcov (executed, lines, 2), lines);
2258 else
2259 fnotice (stdout, "No executable lines\n");
2262 /* Output summary info for a function or file. */
2264 static void
2265 function_summary (const coverage_info *coverage, const char *title)
2267 fnotice (stdout, "%s '%s'\n", title, coverage->name);
2268 executed_summary (coverage->lines, coverage->lines_executed);
2270 if (flag_branches)
2272 if (coverage->branches)
2274 fnotice (stdout, "Branches executed:%s of %d\n",
2275 format_gcov (coverage->branches_executed,
2276 coverage->branches, 2),
2277 coverage->branches);
2278 fnotice (stdout, "Taken at least once:%s of %d\n",
2279 format_gcov (coverage->branches_taken,
2280 coverage->branches, 2),
2281 coverage->branches);
2283 else
2284 fnotice (stdout, "No branches\n");
2285 if (coverage->calls)
2286 fnotice (stdout, "Calls executed:%s of %d\n",
2287 format_gcov (coverage->calls_executed, coverage->calls, 2),
2288 coverage->calls);
2289 else
2290 fnotice (stdout, "No calls\n");
2294 /* Canonicalize the filename NAME by canonicalizing directory
2295 separators, eliding . components and resolving .. components
2296 appropriately. Always returns a unique string. */
2298 static char *
2299 canonicalize_name (const char *name)
2301 /* The canonical name cannot be longer than the incoming name. */
2302 char *result = XNEWVEC (char, strlen (name) + 1);
2303 const char *base = name, *probe;
2304 char *ptr = result;
2305 char *dd_base;
2306 int slash = 0;
2308 #if HAVE_DOS_BASED_FILE_SYSTEM
2309 if (base[0] && base[1] == ':')
2311 result[0] = base[0];
2312 result[1] = ':';
2313 base += 2;
2314 ptr += 2;
2316 #endif
2317 for (dd_base = ptr; *base; base = probe)
2319 size_t len;
2321 for (probe = base; *probe; probe++)
2322 if (IS_DIR_SEPARATOR (*probe))
2323 break;
2325 len = probe - base;
2326 if (len == 1 && base[0] == '.')
2327 /* Elide a '.' directory */
2329 else if (len == 2 && base[0] == '.' && base[1] == '.')
2331 /* '..', we can only elide it and the previous directory, if
2332 we're not a symlink. */
2333 struct stat ATTRIBUTE_UNUSED buf;
2335 *ptr = 0;
2336 if (dd_base == ptr
2337 #if defined (S_ISLNK)
2338 /* S_ISLNK is not POSIX.1-1996. */
2339 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2340 #endif
2343 /* Cannot elide, or unreadable or a symlink. */
2344 dd_base = ptr + 2 + slash;
2345 goto regular;
2347 while (ptr != dd_base && *ptr != '/')
2348 ptr--;
2349 slash = ptr != result;
2351 else
2353 regular:
2354 /* Regular pathname component. */
2355 if (slash)
2356 *ptr++ = '/';
2357 memcpy (ptr, base, len);
2358 ptr += len;
2359 slash = 1;
2362 for (; IS_DIR_SEPARATOR (*probe); probe++)
2363 continue;
2365 *ptr = 0;
2367 return result;
2370 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2372 static void
2373 md5sum_to_hex (const char *sum, char *buffer)
2375 for (unsigned i = 0; i < 16; i++)
2376 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2379 /* Generate an output file name. INPUT_NAME is the canonicalized main
2380 input file and SRC_NAME is the canonicalized file name.
2381 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2382 long_output_names we prepend the processed name of the input file
2383 to each output name (except when the current source file is the
2384 input file, so you don't get a double concatenation). The two
2385 components are separated by '##'. With preserve_paths we create a
2386 filename from all path components of the source file, replacing '/'
2387 with '#', and .. with '^', without it we simply take the basename
2388 component. (Remember, the canonicalized name will already have
2389 elided '.' components and converted \\ separators.) */
2391 static char *
2392 make_gcov_file_name (const char *input_name, const char *src_name)
2394 char *ptr;
2395 char *result;
2397 if (flag_long_names && input_name && strcmp (src_name, input_name))
2399 /* Generate the input filename part. */
2400 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2402 ptr = result;
2403 ptr = mangle_name (input_name, ptr);
2404 ptr[0] = ptr[1] = '#';
2405 ptr += 2;
2407 else
2409 result = XNEWVEC (char, strlen (src_name) + 10);
2410 ptr = result;
2413 ptr = mangle_name (src_name, ptr);
2414 strcpy (ptr, ".gcov");
2416 /* When hashing filenames, we shorten them by only using the filename
2417 component and appending a hash of the full (mangled) pathname. */
2418 if (flag_hash_filenames)
2420 md5_ctx ctx;
2421 char md5sum[16];
2422 char md5sum_hex[33];
2424 md5_init_ctx (&ctx);
2425 md5_process_bytes (src_name, strlen (src_name), &ctx);
2426 md5_finish_ctx (&ctx, md5sum);
2427 md5sum_to_hex (md5sum, md5sum_hex);
2428 free (result);
2430 result = XNEWVEC (char, strlen (src_name) + 50);
2431 ptr = result;
2432 ptr = mangle_name (src_name, ptr);
2433 ptr[0] = ptr[1] = '#';
2434 ptr += 2;
2435 memcpy (ptr, md5sum_hex, 32);
2436 ptr += 32;
2437 strcpy (ptr, ".gcov");
2440 return result;
2443 static char *
2444 mangle_name (char const *base, char *ptr)
2446 size_t len;
2448 /* Generate the source filename part. */
2449 if (!flag_preserve_paths)
2451 base = lbasename (base);
2452 len = strlen (base);
2453 memcpy (ptr, base, len);
2454 ptr += len;
2456 else
2457 ptr = mangle_path (base);
2459 return ptr;
2462 /* Scan through the bb_data for each line in the block, increment
2463 the line number execution count indicated by the execution count of
2464 the appropriate basic block. */
2466 static void
2467 add_line_counts (coverage_info *coverage, function_info *fn)
2469 bool has_any_line = false;
2470 /* Scan each basic block. */
2471 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2473 line_info *line = NULL;
2474 block_info *block = &fn->blocks[ix];
2475 if (block->count && ix && ix + 1 != fn->blocks.size ())
2476 fn->blocks_executed++;
2477 for (unsigned i = 0; i < block->locations.size (); i++)
2479 unsigned src_idx = block->locations[i].source_file_idx;
2480 vector<unsigned> &lines = block->locations[i].lines;
2482 block->cycle.arc = NULL;
2483 block->cycle.ident = ~0U;
2485 for (unsigned j = 0; j < lines.size (); j++)
2487 unsigned ln = lines[j];
2489 /* Line belongs to a function that is in a group. */
2490 if (fn->group_line_p (ln, src_idx))
2492 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2493 line = &(fn->lines[lines[j] - fn->start_line]);
2494 line->exists = 1;
2495 if (!block->exceptional)
2497 line->unexceptional = 1;
2498 if (block->count == 0)
2499 line->has_unexecuted_block = 1;
2501 line->count += block->count;
2503 else
2505 gcc_assert (ln < sources[src_idx].lines.size ());
2506 line = &(sources[src_idx].lines[ln]);
2507 if (coverage)
2509 if (!line->exists)
2510 coverage->lines++;
2511 if (!line->count && block->count)
2512 coverage->lines_executed++;
2514 line->exists = 1;
2515 if (!block->exceptional)
2517 line->unexceptional = 1;
2518 if (block->count == 0)
2519 line->has_unexecuted_block = 1;
2521 line->count += block->count;
2525 has_any_line = true;
2527 if (!ix || ix + 1 == fn->blocks.size ())
2528 /* Entry or exit block. */;
2529 else if (line != NULL)
2531 line->blocks.push_back (block);
2533 if (flag_branches)
2535 arc_info *arc;
2537 for (arc = block->succ; arc; arc = arc->succ_next)
2538 line->branches.push_back (arc);
2544 if (!has_any_line)
2545 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name, fn->name);
2548 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2549 is set to true, update source file summary. */
2551 static void accumulate_line_info (line_info *line, source_info *src,
2552 bool add_coverage)
2554 if (add_coverage)
2555 for (vector<arc_info *>::iterator it = line->branches.begin ();
2556 it != line->branches.end (); it++)
2557 add_branch_counts (&src->coverage, *it);
2559 if (!line->blocks.empty ())
2561 /* The user expects the line count to be the number of times
2562 a line has been executed. Simply summing the block count
2563 will give an artificially high number. The Right Thing
2564 is to sum the entry counts to the graph of blocks on this
2565 line, then find the elementary cycles of the local graph
2566 and add the transition counts of those cycles. */
2567 gcov_type count = 0;
2569 /* Cycle detection. */
2570 for (vector<block_info *>::iterator it = line->blocks.begin ();
2571 it != line->blocks.end (); it++)
2573 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2574 if (!line->has_block (arc->src))
2575 count += arc->count;
2576 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2577 arc->cs_count = arc->count;
2580 /* Now, add the count of loops entirely on this line. */
2581 count += get_cycles_count (*line);
2582 line->count = count;
2585 if (line->exists && add_coverage)
2587 src->coverage.lines++;
2588 if (line->count)
2589 src->coverage.lines_executed++;
2593 /* Accumulate the line counts of a file. */
2595 static void
2596 accumulate_line_counts (source_info *src)
2598 /* First work on group functions. */
2599 for (vector<function_info *>::iterator it = src->functions.begin ();
2600 it != src->functions.end (); it++)
2602 function_info *fn = *it;
2604 if (fn->src != src->index || !fn->is_group)
2605 continue;
2607 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2608 it2 != fn->lines.end (); it2++)
2610 line_info *line = &(*it2);
2611 accumulate_line_info (line, src, false);
2615 /* Work on global lines that line in source file SRC. */
2616 for (vector<line_info>::iterator it = src->lines.begin ();
2617 it != src->lines.end (); it++)
2618 accumulate_line_info (&(*it), src, true);
2620 /* If not using intermediate mode, sum lines of group functions and
2621 add them to lines that live in a source file. */
2622 if (!flag_intermediate_format)
2623 for (vector<function_info *>::iterator it = src->functions.begin ();
2624 it != src->functions.end (); it++)
2626 function_info *fn = *it;
2628 if (fn->src != src->index || !fn->is_group)
2629 continue;
2631 for (unsigned i = 0; i < fn->lines.size (); i++)
2633 line_info *fn_line = &fn->lines[i];
2634 if (fn_line->exists)
2636 unsigned ln = fn->start_line + i;
2637 line_info *src_line = &src->lines[ln];
2639 if (!src_line->exists)
2640 src->coverage.lines++;
2641 if (!src_line->count && fn_line->count)
2642 src->coverage.lines_executed++;
2644 src_line->count += fn_line->count;
2645 src_line->exists = 1;
2647 if (fn_line->has_unexecuted_block)
2648 src_line->has_unexecuted_block = 1;
2650 if (fn_line->unexceptional)
2651 src_line->unexceptional = 1;
2657 /* Output information about ARC number IX. Returns nonzero if
2658 anything is output. */
2660 static int
2661 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2663 if (arc->is_call_non_return)
2665 if (arc->src->count)
2667 fnotice (gcov_file, "call %2d returned %s\n", ix,
2668 format_gcov (arc->src->count - arc->count,
2669 arc->src->count, -flag_counts));
2671 else
2672 fnotice (gcov_file, "call %2d never executed\n", ix);
2674 else if (!arc->is_unconditional)
2676 if (arc->src->count)
2677 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2678 format_gcov (arc->count, arc->src->count, -flag_counts),
2679 arc->fall_through ? " (fallthrough)"
2680 : arc->is_throw ? " (throw)" : "");
2681 else
2682 fnotice (gcov_file, "branch %2d never executed", ix);
2684 if (flag_verbose)
2685 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2687 fnotice (gcov_file, "\n");
2689 else if (flag_unconditional && !arc->dst->is_call_return)
2691 if (arc->src->count)
2692 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2693 format_gcov (arc->count, arc->src->count, -flag_counts));
2694 else
2695 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2697 else
2698 return 0;
2699 return 1;
2702 static const char *
2703 read_line (FILE *file)
2705 static char *string;
2706 static size_t string_len;
2707 size_t pos = 0;
2708 char *ptr;
2710 if (!string_len)
2712 string_len = 200;
2713 string = XNEWVEC (char, string_len);
2716 while ((ptr = fgets (string + pos, string_len - pos, file)))
2718 size_t len = strlen (string + pos);
2720 if (len && string[pos + len - 1] == '\n')
2722 string[pos + len - 1] = 0;
2723 return string;
2725 pos += len;
2726 /* If the file contains NUL characters or an incomplete
2727 last line, which can happen more than once in one run,
2728 we have to avoid doubling the STRING_LEN unnecessarily. */
2729 if (pos > string_len / 2)
2731 string_len *= 2;
2732 string = XRESIZEVEC (char, string, string_len);
2736 return pos ? string : NULL;
2739 /* Pad string S with spaces from left to have total width equal to 9. */
2741 static void
2742 pad_count_string (string &s)
2744 if (s.size () < 9)
2745 s.insert (0, 9 - s.size (), ' ');
2748 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2749 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2750 an exceptional statement. The output is printed for LINE_NUM of given
2751 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2752 used to indicate non-executed blocks. */
2754 static void
2755 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2756 bool has_unexecuted_block,
2757 gcov_type count, unsigned line_num,
2758 const char *exceptional_string,
2759 const char *unexceptional_string)
2761 string s;
2762 if (exists)
2764 if (count > 0)
2766 s = format_gcov (count, 0, -1);
2767 if (has_unexecuted_block
2768 && bbg_supports_has_unexecuted_blocks)
2770 if (flag_use_colors)
2772 pad_count_string (s);
2773 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2774 COLOR_SEPARATOR COLOR_FG_WHITE));
2775 s += SGR_RESET;
2777 else
2778 s += "*";
2780 pad_count_string (s);
2782 else
2784 if (flag_use_colors)
2786 s = "0";
2787 pad_count_string (s);
2788 if (unexceptional)
2789 s.insert (0, SGR_SEQ (COLOR_BG_RED
2790 COLOR_SEPARATOR COLOR_FG_WHITE));
2791 else
2792 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2793 COLOR_SEPARATOR COLOR_FG_WHITE));
2794 s += SGR_RESET;
2796 else
2798 s = unexceptional ? unexceptional_string : exceptional_string;
2799 pad_count_string (s);
2803 else
2805 s = "-";
2806 pad_count_string (s);
2809 fprintf (f, "%s:%5u", s.c_str (), line_num);
2812 static void
2813 print_source_line (FILE *f, const vector<const char *> &source_lines,
2814 unsigned line)
2816 gcc_assert (line >= 1);
2817 gcc_assert (line <= source_lines.size ());
2819 fprintf (f, ":%s\n", source_lines[line - 1]);
2822 /* Output line details for LINE and print it to F file. LINE lives on
2823 LINE_NUM. */
2825 static void
2826 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2828 if (flag_all_blocks)
2830 arc_info *arc;
2831 int ix, jx;
2833 ix = jx = 0;
2834 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2835 it != line->blocks.end (); it++)
2837 if (!(*it)->is_call_return)
2839 output_line_beginning (f, line->exists,
2840 (*it)->exceptional, false,
2841 (*it)->count, line_num,
2842 "%%%%%", "$$$$$");
2843 fprintf (f, "-block %2d", ix++);
2844 if (flag_verbose)
2845 fprintf (f, " (BB %u)", (*it)->id);
2846 fprintf (f, "\n");
2848 if (flag_branches)
2849 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2850 jx += output_branch_count (f, jx, arc);
2853 else if (flag_branches)
2855 int ix;
2857 ix = 0;
2858 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
2859 it != line->branches.end (); it++)
2860 ix += output_branch_count (f, ix, (*it));
2864 /* Output detail statistics about function FN to file F. */
2866 static void
2867 output_function_details (FILE *f, const function_info *fn)
2869 if (!flag_branches)
2870 return;
2872 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
2873 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
2874 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
2876 for (; arc; arc = arc->pred_next)
2877 if (arc->fake)
2878 return_count -= arc->count;
2880 fprintf (f, "function %s",
2881 flag_demangled_names ? fn->demangled_name : fn->name);
2882 fprintf (f, " called %s",
2883 format_gcov (called_count, 0, -1));
2884 fprintf (f, " returned %s",
2885 format_gcov (return_count, called_count, 0));
2886 fprintf (f, " blocks executed %s",
2887 format_gcov (fn->blocks_executed, fn->blocks.size () - 2,
2888 0));
2889 fprintf (f, "\n");
2892 /* Read in the source file one line at a time, and output that line to
2893 the gcov file preceded by its execution count and other
2894 information. */
2896 static void
2897 output_lines (FILE *gcov_file, const source_info *src)
2899 #define DEFAULT_LINE_START " -: 0:"
2900 #define FN_SEPARATOR "------------------\n"
2902 FILE *source_file;
2903 const char *retval;
2905 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
2906 if (!multiple_files)
2908 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
2909 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
2910 no_data_file ? "-" : da_file_name);
2911 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
2913 fprintf (gcov_file, DEFAULT_LINE_START "Programs:%u\n", program_count);
2915 source_file = fopen (src->name, "r");
2916 if (!source_file)
2917 fnotice (stderr, "Cannot open source file %s\n", src->name);
2918 else if (src->file_time == 0)
2919 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
2921 vector<const char *> source_lines;
2922 if (source_file)
2923 while ((retval = read_line (source_file)) != NULL)
2924 source_lines.push_back (xstrdup (retval));
2926 unsigned line_start_group = 0;
2927 vector<function_info *> fns;
2929 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
2931 if (line_num >= src->lines.size ())
2933 fprintf (gcov_file, "%9s:%5u", "-", line_num);
2934 print_source_line (gcov_file, source_lines, line_num);
2935 continue;
2938 const line_info *line = &src->lines[line_num];
2940 if (line_start_group == 0)
2942 fns = src->get_functions_at_location (line_num);
2943 if (fns.size () > 1)
2945 /* It's possible to have functions that partially overlap,
2946 thus take the maximum end_line of functions starting
2947 at LINE_NUM. */
2948 for (unsigned i = 0; i < fns.size (); i++)
2949 if (fns[i]->end_line > line_start_group)
2950 line_start_group = fns[i]->end_line;
2952 else if (fns.size () == 1)
2954 function_info *fn = fns[0];
2955 output_function_details (gcov_file, fn);
2959 /* For lines which don't exist in the .bb file, print '-' before
2960 the source line. For lines which exist but were never
2961 executed, print '#####' or '=====' before the source line.
2962 Otherwise, print the execution count before the source line.
2963 There are 16 spaces of indentation added before the source
2964 line so that tabs won't be messed up. */
2965 output_line_beginning (gcov_file, line->exists, line->unexceptional,
2966 line->has_unexecuted_block, line->count,
2967 line_num, "=====", "#####");
2969 print_source_line (gcov_file, source_lines, line_num);
2970 output_line_details (gcov_file, line, line_num);
2972 if (line_start_group == line_num)
2974 for (vector<function_info *>::iterator it = fns.begin ();
2975 it != fns.end (); it++)
2977 function_info *fn = *it;
2978 vector<line_info> &lines = fn->lines;
2980 fprintf (gcov_file, FN_SEPARATOR);
2982 string fn_name
2983 = flag_demangled_names ? fn->demangled_name : fn->name;
2985 if (flag_use_colors)
2987 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
2988 fn_name += SGR_RESET;
2991 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
2993 output_function_details (gcov_file, fn);
2995 /* Print all lines covered by the function. */
2996 for (unsigned i = 0; i < lines.size (); i++)
2998 line_info *line = &lines[i];
2999 unsigned l = fn->start_line + i;
3001 /* For lines which don't exist in the .bb file, print '-'
3002 before the source line. For lines which exist but
3003 were never executed, print '#####' or '=====' before
3004 the source line. Otherwise, print the execution count
3005 before the source line.
3006 There are 16 spaces of indentation added before the source
3007 line so that tabs won't be messed up. */
3008 output_line_beginning (gcov_file, line->exists,
3009 line->unexceptional,
3010 line->has_unexecuted_block,
3011 line->count,
3012 l, "=====", "#####");
3014 print_source_line (gcov_file, source_lines, l);
3015 output_line_details (gcov_file, line, l);
3019 fprintf (gcov_file, FN_SEPARATOR);
3020 line_start_group = 0;
3024 if (source_file)
3025 fclose (source_file);