PR rtl-optimization/88470
[official-gcc.git] / gcc / gcov.c
blob7e39f9bd57e59e8f2bf2b677c6c8f5fc5088b4f3
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"
47 #include "pretty-print.h"
48 #include "json.h"
50 #include <zlib.h>
51 #include <getopt.h>
53 #include "md5.h"
55 using namespace std;
57 #define IN_GCOV 1
58 #include "gcov-io.h"
59 #include "gcov-io.c"
61 /* The gcno file is generated by -ftest-coverage option. The gcda file is
62 generated by a program compiled with -fprofile-arcs. Their formats
63 are documented in gcov-io.h. */
65 /* The functions in this file for creating and solution program flow graphs
66 are very similar to functions in the gcc source file profile.c. In
67 some places we make use of the knowledge of how profile.c works to
68 select particular algorithms here. */
70 /* The code validates that the profile information read in corresponds
71 to the code currently being compiled. Rather than checking for
72 identical files, the code below compares a checksum on the CFG
73 (based on the order of basic blocks and the arcs in the CFG). If
74 the CFG checksum in the gcda file match the CFG checksum in the
75 gcno file, the profile data will be used. */
77 /* This is the size of the buffer used to read in source file lines. */
79 struct function_info;
80 struct block_info;
81 struct source_info;
83 /* Describes an arc between two basic blocks. */
85 struct arc_info
87 /* source and destination blocks. */
88 struct block_info *src;
89 struct block_info *dst;
91 /* transition counts. */
92 gcov_type count;
93 /* used in cycle search, so that we do not clobber original counts. */
94 gcov_type cs_count;
96 unsigned int count_valid : 1;
97 unsigned int on_tree : 1;
98 unsigned int fake : 1;
99 unsigned int fall_through : 1;
101 /* Arc to a catch handler. */
102 unsigned int is_throw : 1;
104 /* Arc is for a function that abnormally returns. */
105 unsigned int is_call_non_return : 1;
107 /* Arc is for catch/setjmp. */
108 unsigned int is_nonlocal_return : 1;
110 /* Is an unconditional branch. */
111 unsigned int is_unconditional : 1;
113 /* Loop making arc. */
114 unsigned int cycle : 1;
116 /* Links to next arc on src and dst lists. */
117 struct arc_info *succ_next;
118 struct arc_info *pred_next;
121 /* Describes which locations (lines and files) are associated with
122 a basic block. */
124 struct block_location_info
126 block_location_info (unsigned _source_file_idx):
127 source_file_idx (_source_file_idx)
130 unsigned source_file_idx;
131 vector<unsigned> lines;
134 /* Describes a basic block. Contains lists of arcs to successor and
135 predecessor blocks. */
137 struct block_info
139 /* Constructor. */
140 block_info ();
142 /* Chain of exit and entry arcs. */
143 arc_info *succ;
144 arc_info *pred;
146 /* Number of unprocessed exit and entry arcs. */
147 gcov_type num_succ;
148 gcov_type num_pred;
150 unsigned id;
152 /* Block execution count. */
153 gcov_type count;
154 unsigned count_valid : 1;
155 unsigned valid_chain : 1;
156 unsigned invalid_chain : 1;
157 unsigned exceptional : 1;
159 /* Block is a call instrumenting site. */
160 unsigned is_call_site : 1; /* Does the call. */
161 unsigned is_call_return : 1; /* Is the return. */
163 /* Block is a landing pad for longjmp or throw. */
164 unsigned is_nonlocal_return : 1;
166 vector<block_location_info> locations;
168 struct
170 /* Single line graph cycle workspace. Used for all-blocks
171 mode. */
172 arc_info *arc;
173 unsigned ident;
174 } cycle; /* Used in all-blocks mode, after blocks are linked onto
175 lines. */
177 /* Temporary chain for solving graph, and for chaining blocks on one
178 line. */
179 struct block_info *chain;
183 block_info::block_info (): succ (NULL), pred (NULL), num_succ (0), num_pred (0),
184 id (0), count (0), count_valid (0), valid_chain (0), invalid_chain (0),
185 exceptional (0), is_call_site (0), is_call_return (0), is_nonlocal_return (0),
186 locations (), chain (NULL)
188 cycle.arc = NULL;
191 /* Describes a single line of source. Contains a chain of basic blocks
192 with code on it. */
194 struct line_info
196 /* Default constructor. */
197 line_info ();
199 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
200 bool has_block (block_info *needle);
202 /* Execution count. */
203 gcov_type count;
205 /* Branches from blocks that end on this line. */
206 vector<arc_info *> branches;
208 /* blocks which start on this line. Used in all-blocks mode. */
209 vector<block_info *> blocks;
211 unsigned exists : 1;
212 unsigned unexceptional : 1;
213 unsigned has_unexecuted_block : 1;
216 line_info::line_info (): count (0), branches (), blocks (), exists (false),
217 unexceptional (0), has_unexecuted_block (0)
221 bool
222 line_info::has_block (block_info *needle)
224 return std::find (blocks.begin (), blocks.end (), needle) != blocks.end ();
227 /* Output demangled function names. */
229 static int flag_demangled_names = 0;
231 /* Describes a single function. Contains an array of basic blocks. */
233 struct function_info
235 function_info ();
236 ~function_info ();
238 /* Return true when line N belongs to the function in source file SRC_IDX.
239 The line must be defined in body of the function, can't be inlined. */
240 bool group_line_p (unsigned n, unsigned src_idx);
242 /* Function filter based on function_info::artificial variable. */
244 static inline bool
245 is_artificial (function_info *fn)
247 return fn->artificial;
250 /* Name of function. */
251 char *m_name;
252 char *m_demangled_name;
253 unsigned ident;
254 unsigned lineno_checksum;
255 unsigned cfg_checksum;
257 /* The graph contains at least one fake incoming edge. */
258 unsigned has_catch : 1;
260 /* True when the function is artificial and does not exist
261 in a source file. */
262 unsigned artificial : 1;
264 /* True when multiple functions start at a line in a source file. */
265 unsigned is_group : 1;
267 /* Array of basic blocks. Like in GCC, the entry block is
268 at blocks[0] and the exit block is at blocks[1]. */
269 #define ENTRY_BLOCK (0)
270 #define EXIT_BLOCK (1)
271 vector<block_info> blocks;
272 unsigned blocks_executed;
274 /* Raw arc coverage counts. */
275 vector<gcov_type> counts;
277 /* First line number. */
278 unsigned start_line;
280 /* First line column. */
281 unsigned start_column;
283 /* Last line number. */
284 unsigned end_line;
286 /* Index of source file where the function is defined. */
287 unsigned src;
289 /* Vector of line information. */
290 vector<line_info> lines;
292 /* Next function. */
293 struct function_info *next;
295 /* Get demangled name of a function. The demangled name
296 is converted when it is used for the first time. */
297 char *get_demangled_name ()
299 if (m_demangled_name == NULL)
301 m_demangled_name = cplus_demangle (m_name, DMGL_PARAMS);
302 if (!m_demangled_name)
303 m_demangled_name = m_name;
306 return m_demangled_name;
309 /* Get name of the function based on flag_demangled_names. */
310 char *get_name ()
312 return flag_demangled_names ? get_demangled_name () : m_name;
315 /* Return number of basic blocks (without entry and exit block). */
316 unsigned get_block_count ()
318 return blocks.size () - 2;
322 /* Function info comparer that will sort functions according to starting
323 line. */
325 struct function_line_start_cmp
327 inline bool operator() (const function_info *lhs,
328 const function_info *rhs)
330 return (lhs->start_line == rhs->start_line
331 ? lhs->start_column < rhs->start_column
332 : lhs->start_line < rhs->start_line);
336 /* Describes coverage of a file or function. */
338 struct coverage_info
340 int lines;
341 int lines_executed;
343 int branches;
344 int branches_executed;
345 int branches_taken;
347 int calls;
348 int calls_executed;
350 char *name;
353 /* Describes a file mentioned in the block graph. Contains an array
354 of line info. */
356 struct source_info
358 /* Default constructor. */
359 source_info ();
361 vector<function_info *> get_functions_at_location (unsigned line_num) const;
363 /* Index of the source_info in sources vector. */
364 unsigned index;
366 /* Canonical name of source file. */
367 char *name;
368 time_t file_time;
370 /* Vector of line information. */
371 vector<line_info> lines;
373 coverage_info coverage;
375 /* Maximum line count in the source file. */
376 unsigned int maximum_count;
378 /* Functions in this source file. These are in ascending line
379 number order. */
380 vector <function_info *> functions;
383 source_info::source_info (): index (0), name (NULL), file_time (),
384 lines (), coverage (), maximum_count (0), functions ()
388 vector<function_info *>
389 source_info::get_functions_at_location (unsigned line_num) const
391 vector<function_info *> r;
393 for (vector<function_info *>::const_iterator it = functions.begin ();
394 it != functions.end (); it++)
396 if ((*it)->start_line == line_num && (*it)->src == index)
397 r.push_back (*it);
400 std::sort (r.begin (), r.end (), function_line_start_cmp ());
402 return r;
405 class name_map
407 public:
408 name_map ()
412 name_map (char *_name, unsigned _src): name (_name), src (_src)
416 bool operator== (const name_map &rhs) const
418 #if HAVE_DOS_BASED_FILE_SYSTEM
419 return strcasecmp (this->name, rhs.name) == 0;
420 #else
421 return strcmp (this->name, rhs.name) == 0;
422 #endif
425 bool operator< (const name_map &rhs) const
427 #if HAVE_DOS_BASED_FILE_SYSTEM
428 return strcasecmp (this->name, rhs.name) < 0;
429 #else
430 return strcmp (this->name, rhs.name) < 0;
431 #endif
434 const char *name; /* Source file name */
435 unsigned src; /* Source file */
438 /* Vector of all functions. */
439 static vector<function_info *> functions;
441 /* Vector of source files. */
442 static vector<source_info> sources;
444 /* Mapping of file names to sources */
445 static vector<name_map> names;
447 /* Record all processed files in order to warn about
448 a file being read multiple times. */
449 static vector<char *> processed_files;
451 /* This holds data summary information. */
453 static unsigned object_runs;
455 static unsigned total_lines;
456 static unsigned total_executed;
458 /* Modification time of graph file. */
460 static time_t bbg_file_time;
462 /* Name of the notes (gcno) output file. The "bbg" prefix is for
463 historical reasons, when the notes file contained only the
464 basic block graph notes. */
466 static char *bbg_file_name;
468 /* Stamp of the bbg file */
469 static unsigned bbg_stamp;
471 /* Supports has_unexecuted_blocks functionality. */
472 static unsigned bbg_supports_has_unexecuted_blocks;
474 /* Working directory in which a TU was compiled. */
475 static const char *bbg_cwd;
477 /* Name and file pointer of the input file for the count data (gcda). */
479 static char *da_file_name;
481 /* Data file is missing. */
483 static int no_data_file;
485 /* If there is several input files, compute and display results after
486 reading all data files. This way if two or more gcda file refer to
487 the same source file (eg inline subprograms in a .h file), the
488 counts are added. */
490 static int multiple_files = 0;
492 /* Output branch probabilities. */
494 static int flag_branches = 0;
496 /* Show unconditional branches too. */
497 static int flag_unconditional = 0;
499 /* Output a gcov file if this is true. This is on by default, and can
500 be turned off by the -n option. */
502 static int flag_gcov_file = 1;
504 /* Output to stdout instead to a gcov file. */
506 static int flag_use_stdout = 0;
508 /* Output progress indication if this is true. This is off by default
509 and can be turned on by the -d option. */
511 static int flag_display_progress = 0;
513 /* Output *.gcov file in JSON intermediate format used by consumers. */
515 static int flag_json_format = 0;
517 /* For included files, make the gcov output file name include the name
518 of the input source file. For example, if x.h is included in a.c,
519 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
521 static int flag_long_names = 0;
523 /* For situations when a long name can potentially hit filesystem path limit,
524 let's calculate md5sum of the path and append it to a file name. */
526 static int flag_hash_filenames = 0;
528 /* Print verbose informations. */
530 static int flag_verbose = 0;
532 /* Print colored output. */
534 static int flag_use_colors = 0;
536 /* Use perf-like colors to indicate hot lines. */
538 static int flag_use_hotness_colors = 0;
540 /* Output count information for every basic block, not merely those
541 that contain line number information. */
543 static int flag_all_blocks = 0;
545 /* Output human readable numbers. */
547 static int flag_human_readable_numbers = 0;
549 /* Output summary info for each function. */
551 static int flag_function_summary = 0;
553 /* Object directory file prefix. This is the directory/file where the
554 graph and data files are looked for, if nonzero. */
556 static char *object_directory = 0;
558 /* Source directory prefix. This is removed from source pathnames
559 that match, when generating the output file name. */
561 static char *source_prefix = 0;
562 static size_t source_length = 0;
564 /* Only show data for sources with relative pathnames. Absolute ones
565 usually indicate a system header file, which although it may
566 contain inline functions, is usually uninteresting. */
567 static int flag_relative_only = 0;
569 /* Preserve all pathname components. Needed when object files and
570 source files are in subdirectories. '/' is mangled as '#', '.' is
571 elided and '..' mangled to '^'. */
573 static int flag_preserve_paths = 0;
575 /* Output the number of times a branch was taken as opposed to the percentage
576 of times it was taken. */
578 static int flag_counts = 0;
580 /* Forward declarations. */
581 static int process_args (int, char **);
582 static void print_usage (int) ATTRIBUTE_NORETURN;
583 static void print_version (void) ATTRIBUTE_NORETURN;
584 static void process_file (const char *);
585 static void process_all_functions (void);
586 static void generate_results (const char *);
587 static void create_file_names (const char *);
588 static char *canonicalize_name (const char *);
589 static unsigned find_source (const char *);
590 static void read_graph_file (void);
591 static int read_count_file (void);
592 static void solve_flow_graph (function_info *);
593 static void find_exception_blocks (function_info *);
594 static void add_branch_counts (coverage_info *, const arc_info *);
595 static void add_line_counts (coverage_info *, function_info *);
596 static void executed_summary (unsigned, unsigned);
597 static void function_summary (const coverage_info *, const char *);
598 static const char *format_gcov (gcov_type, gcov_type, int);
599 static void accumulate_line_counts (source_info *);
600 static void output_gcov_file (const char *, source_info *);
601 static int output_branch_count (FILE *, int, const arc_info *);
602 static void output_lines (FILE *, const source_info *);
603 static char *make_gcov_file_name (const char *, const char *);
604 static char *mangle_name (const char *, char *);
605 static void release_structures (void);
606 extern int main (int, char **);
608 function_info::function_info (): m_name (NULL), m_demangled_name (NULL),
609 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
610 artificial (0), is_group (0),
611 blocks (), blocks_executed (0), counts (),
612 start_line (0), start_column (), end_line (0), src (0), lines (), next (NULL)
616 function_info::~function_info ()
618 for (int i = blocks.size () - 1; i >= 0; i--)
620 arc_info *arc, *arc_n;
622 for (arc = blocks[i].succ; arc; arc = arc_n)
624 arc_n = arc->succ_next;
625 free (arc);
628 if (m_demangled_name != m_name)
629 free (m_demangled_name);
630 free (m_name);
633 bool function_info::group_line_p (unsigned n, unsigned src_idx)
635 return is_group && src == src_idx && start_line <= n && n <= end_line;
638 /* Cycle detection!
639 There are a bajillion algorithms that do this. Boost's function is named
640 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
641 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
642 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
644 The basic algorithm is simple: effectively, we're finding all simple paths
645 in a subgraph (that shrinks every iteration). Duplicates are filtered by
646 "blocking" a path when a node is added to the path (this also prevents non-
647 simple paths)--the node is unblocked only when it participates in a cycle.
650 typedef vector<arc_info *> arc_vector_t;
651 typedef vector<const block_info *> block_vector_t;
653 /* Enum with types of loop in CFG. */
655 enum loop_type
657 NO_LOOP = 0,
658 LOOP = 1,
659 NEGATIVE_LOOP = 3
662 /* Loop_type operator that merges two values: A and B. */
664 inline loop_type& operator |= (loop_type& a, loop_type b)
666 return a = static_cast<loop_type> (a | b);
669 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
670 and subtract the value from all counts. The subtracted value is added
671 to COUNT. Returns type of loop. */
673 static loop_type
674 handle_cycle (const arc_vector_t &edges, int64_t &count)
676 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
677 that amount. */
678 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
679 for (unsigned i = 0; i < edges.size (); i++)
681 int64_t ecount = edges[i]->cs_count;
682 if (cycle_count > ecount)
683 cycle_count = ecount;
685 count += cycle_count;
686 for (unsigned i = 0; i < edges.size (); i++)
687 edges[i]->cs_count -= cycle_count;
689 return cycle_count < 0 ? NEGATIVE_LOOP : LOOP;
692 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
693 blocked by U in BLOCK_LISTS. */
695 static void
696 unblock (const block_info *u, block_vector_t &blocked,
697 vector<block_vector_t > &block_lists)
699 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
700 if (it == blocked.end ())
701 return;
703 unsigned index = it - blocked.begin ();
704 blocked.erase (it);
706 block_vector_t to_unblock (block_lists[index]);
708 block_lists.erase (block_lists.begin () + index);
710 for (block_vector_t::iterator it = to_unblock.begin ();
711 it != to_unblock.end (); it++)
712 unblock (*it, blocked, block_lists);
715 /* Find circuit going to block V, PATH is provisional seen cycle.
716 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
717 blocked by a block. COUNT is accumulated count of the current LINE.
718 Returns what type of loop it contains. */
720 static loop_type
721 circuit (block_info *v, arc_vector_t &path, block_info *start,
722 block_vector_t &blocked, vector<block_vector_t> &block_lists,
723 line_info &linfo, int64_t &count)
725 loop_type result = NO_LOOP;
727 /* Add v to the block list. */
728 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
729 blocked.push_back (v);
730 block_lists.push_back (block_vector_t ());
732 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
734 block_info *w = arc->dst;
735 if (w < start || !linfo.has_block (w))
736 continue;
738 path.push_back (arc);
739 if (w == start)
740 /* Cycle has been found. */
741 result |= handle_cycle (path, count);
742 else if (find (blocked.begin (), blocked.end (), w) == blocked.end ())
743 result |= circuit (w, path, start, blocked, block_lists, linfo, count);
745 path.pop_back ();
748 if (result != NO_LOOP)
749 unblock (v, blocked, block_lists);
750 else
751 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
753 block_info *w = arc->dst;
754 if (w < start || !linfo.has_block (w))
755 continue;
757 size_t index
758 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
759 gcc_assert (index < blocked.size ());
760 block_vector_t &list = block_lists[index];
761 if (find (list.begin (), list.end (), v) == list.end ())
762 list.push_back (v);
765 return result;
768 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
769 contains a negative loop, then perform the same function once again. */
771 static gcov_type
772 get_cycles_count (line_info &linfo, bool handle_negative_cycles = true)
774 /* Note that this algorithm works even if blocks aren't in sorted order.
775 Each iteration of the circuit detection is completely independent
776 (except for reducing counts, but that shouldn't matter anyways).
777 Therefore, operating on a permuted order (i.e., non-sorted) only
778 has the effect of permuting the output cycles. */
780 loop_type result = NO_LOOP;
781 gcov_type count = 0;
782 for (vector<block_info *>::iterator it = linfo.blocks.begin ();
783 it != linfo.blocks.end (); it++)
785 arc_vector_t path;
786 block_vector_t blocked;
787 vector<block_vector_t > block_lists;
788 result |= circuit (*it, path, *it, blocked, block_lists, linfo,
789 count);
792 /* If we have a negative cycle, repeat the find_cycles routine. */
793 if (result == NEGATIVE_LOOP && handle_negative_cycles)
794 count += get_cycles_count (linfo, false);
796 return count;
800 main (int argc, char **argv)
802 int argno;
803 int first_arg;
804 const char *p;
806 p = argv[0] + strlen (argv[0]);
807 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
808 --p;
809 progname = p;
811 xmalloc_set_program_name (progname);
813 /* Unlock the stdio streams. */
814 unlock_std_streams ();
816 gcc_init_libintl ();
818 diagnostic_initialize (global_dc, 0);
820 /* Handle response files. */
821 expandargv (&argc, &argv);
823 argno = process_args (argc, argv);
824 if (optind == argc)
825 print_usage (true);
827 if (argc - argno > 1)
828 multiple_files = 1;
830 first_arg = argno;
832 for (; argno != argc; argno++)
834 if (flag_display_progress)
835 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
836 argc - first_arg);
837 process_file (argv[argno]);
839 if (flag_json_format || argno == argc - 1)
841 process_all_functions ();
842 generate_results (argv[argno]);
843 release_structures ();
847 return 0;
850 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
851 otherwise the output of --help. */
853 static void
854 print_usage (int error_p)
856 FILE *file = error_p ? stderr : stdout;
857 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
859 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
860 fnotice (file, "Print code coverage information.\n\n");
861 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
862 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
863 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
864 rather than percentages\n");
865 fnotice (file, " -d, --display-progress Display progress information\n");
866 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
867 fnotice (file, " -h, --help Print this help, then exit\n");
868 fnotice (file, " -i, --json-format Output JSON intermediate format into .gcov.json.gz file\n");
869 fnotice (file, " -j, --human-readable Output human readable numbers\n");
870 fnotice (file, " -k, --use-colors Emit colored output\n");
871 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
872 source files\n");
873 fnotice (file, " -m, --demangled-names Output demangled function names\n");
874 fnotice (file, " -n, --no-output Do not create an output file\n");
875 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
876 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
877 fnotice (file, " -q, --use-hotness-colors Emit perf-like colored output for hot lines\n");
878 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
879 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
880 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
881 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
882 fnotice (file, " -v, --version Print version number, then exit\n");
883 fnotice (file, " -w, --verbose Print verbose informations\n");
884 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
885 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
886 bug_report_url);
887 exit (status);
890 /* Print version information and exit. */
892 static void
893 print_version (void)
895 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
896 fprintf (stdout, "Copyright %s 2018 Free Software Foundation, Inc.\n",
897 _("(C)"));
898 fnotice (stdout,
899 _("This is free software; see the source for copying conditions.\n"
900 "There is NO warranty; not even for MERCHANTABILITY or \n"
901 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
902 exit (SUCCESS_EXIT_CODE);
905 static const struct option options[] =
907 { "help", no_argument, NULL, 'h' },
908 { "version", no_argument, NULL, 'v' },
909 { "verbose", no_argument, NULL, 'w' },
910 { "all-blocks", no_argument, NULL, 'a' },
911 { "branch-probabilities", no_argument, NULL, 'b' },
912 { "branch-counts", no_argument, NULL, 'c' },
913 { "json-format", no_argument, NULL, 'i' },
914 { "human-readable", no_argument, NULL, 'j' },
915 { "no-output", no_argument, NULL, 'n' },
916 { "long-file-names", no_argument, NULL, 'l' },
917 { "function-summaries", no_argument, NULL, 'f' },
918 { "demangled-names", no_argument, NULL, 'm' },
919 { "preserve-paths", no_argument, NULL, 'p' },
920 { "relative-only", no_argument, NULL, 'r' },
921 { "object-directory", required_argument, NULL, 'o' },
922 { "object-file", required_argument, NULL, 'o' },
923 { "source-prefix", required_argument, NULL, 's' },
924 { "stdout", no_argument, NULL, 't' },
925 { "unconditional-branches", no_argument, NULL, 'u' },
926 { "display-progress", no_argument, NULL, 'd' },
927 { "hash-filenames", no_argument, NULL, 'x' },
928 { "use-colors", no_argument, NULL, 'k' },
929 { "use-hotness-colors", no_argument, NULL, 'q' },
930 { 0, 0, 0, 0 }
933 /* Process args, return index to first non-arg. */
935 static int
936 process_args (int argc, char **argv)
938 int opt;
940 const char *opts = "abcdfhijklmno:pqrs:tuvwx";
941 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
943 switch (opt)
945 case 'a':
946 flag_all_blocks = 1;
947 break;
948 case 'b':
949 flag_branches = 1;
950 break;
951 case 'c':
952 flag_counts = 1;
953 break;
954 case 'f':
955 flag_function_summary = 1;
956 break;
957 case 'h':
958 print_usage (false);
959 /* print_usage will exit. */
960 case 'l':
961 flag_long_names = 1;
962 break;
963 case 'j':
964 flag_human_readable_numbers = 1;
965 break;
966 case 'k':
967 flag_use_colors = 1;
968 break;
969 case 'q':
970 flag_use_hotness_colors = 1;
971 break;
972 case 'm':
973 flag_demangled_names = 1;
974 break;
975 case 'n':
976 flag_gcov_file = 0;
977 break;
978 case 'o':
979 object_directory = optarg;
980 break;
981 case 's':
982 source_prefix = optarg;
983 source_length = strlen (source_prefix);
984 break;
985 case 'r':
986 flag_relative_only = 1;
987 break;
988 case 'p':
989 flag_preserve_paths = 1;
990 break;
991 case 'u':
992 flag_unconditional = 1;
993 break;
994 case 'i':
995 flag_json_format = 1;
996 flag_gcov_file = 1;
997 break;
998 case 'd':
999 flag_display_progress = 1;
1000 break;
1001 case 'x':
1002 flag_hash_filenames = 1;
1003 break;
1004 case 'w':
1005 flag_verbose = 1;
1006 break;
1007 case 't':
1008 flag_use_stdout = 1;
1009 break;
1010 case 'v':
1011 print_version ();
1012 /* print_version will exit. */
1013 default:
1014 print_usage (true);
1015 /* print_usage will exit. */
1019 return optind;
1022 /* Output intermediate LINE sitting on LINE_NUM to JSON OBJECT. */
1024 static void
1025 output_intermediate_json_line (json::array *object,
1026 line_info *line, unsigned line_num)
1028 if (!line->exists)
1029 return;
1031 json::object *lineo = new json::object ();
1032 lineo->set ("line_number", new json::number (line_num));
1033 lineo->set ("count", new json::number (line->count));
1034 lineo->set ("unexecuted_block",
1035 new json::literal (line->has_unexecuted_block));
1037 json::array *branches = new json::array ();
1038 lineo->set ("branches", branches);
1040 vector<arc_info *>::const_iterator it;
1041 if (flag_branches)
1042 for (it = line->branches.begin (); it != line->branches.end ();
1043 it++)
1045 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1047 json::object *branch = new json::object ();
1048 branch->set ("count", new json::number ((*it)->count));
1049 branch->set ("throw", new json::literal ((*it)->is_throw));
1050 branch->set ("fallthrough",
1051 new json::literal ((*it)->fall_through));
1052 branches->append (branch);
1056 object->append (lineo);
1059 /* Get the name of the gcov file. The return value must be free'd.
1061 It appends the '.gcov' extension to the *basename* of the file.
1062 The resulting file name will be in PWD.
1064 e.g.,
1065 input: foo.da, output: foo.da.gcov
1066 input: a/b/foo.cc, output: foo.cc.gcov */
1068 static char *
1069 get_gcov_intermediate_filename (const char *file_name)
1071 const char *gcov = ".gcov.json.gz";
1072 char *result;
1073 const char *cptr;
1075 /* Find the 'basename'. */
1076 cptr = lbasename (file_name);
1078 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1079 sprintf (result, "%s%s", cptr, gcov);
1081 return result;
1084 /* Output the result in JSON intermediate format.
1085 Source info SRC is dumped into JSON_FILES which is JSON array. */
1087 static void
1088 output_json_intermediate_file (json::array *json_files, source_info *src)
1090 json::object *root = new json::object ();
1091 json_files->append (root);
1093 root->set ("file", new json::string (src->name));
1095 json::array *functions = new json::array ();
1096 root->set ("functions", functions);
1098 std::sort (src->functions.begin (), src->functions.end (),
1099 function_line_start_cmp ());
1100 for (vector<function_info *>::iterator it = src->functions.begin ();
1101 it != src->functions.end (); it++)
1103 json::object *function = new json::object ();
1104 function->set ("name", new json::string ((*it)->m_name));
1105 function->set ("demangled_name",
1106 new json::string ((*it)->get_demangled_name ()));
1107 function->set ("start_line", new json::number ((*it)->start_line));
1108 function->set ("end_line", new json::number ((*it)->end_line));
1109 function->set ("blocks",
1110 new json::number ((*it)->get_block_count ()));
1111 function->set ("blocks_executed",
1112 new json::number ((*it)->blocks_executed));
1113 function->set ("execution_count",
1114 new json::number ((*it)->blocks[0].count));
1116 functions->append (function);
1119 json::array *lineso = new json::array ();
1120 root->set ("lines", lineso);
1122 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1124 vector<function_info *> fns = src->get_functions_at_location (line_num);
1126 /* Print first group functions that begin on the line. */
1127 for (vector<function_info *>::iterator it2 = fns.begin ();
1128 it2 != fns.end (); it2++)
1130 vector<line_info> &lines = (*it2)->lines;
1131 for (unsigned i = 0; i < lines.size (); i++)
1133 line_info *line = &lines[i];
1134 output_intermediate_json_line (lineso, line, line_num + i);
1138 /* Follow with lines associated with the source file. */
1139 if (line_num < src->lines.size ())
1140 output_intermediate_json_line (lineso, &src->lines[line_num], line_num);
1144 /* Function start pair. */
1145 struct function_start
1147 unsigned source_file_idx;
1148 unsigned start_line;
1151 /* Traits class for function start hash maps below. */
1153 struct function_start_pair_hash : typed_noop_remove <function_start>
1155 typedef function_start value_type;
1156 typedef function_start compare_type;
1158 static hashval_t
1159 hash (const function_start &ref)
1161 inchash::hash hstate (0);
1162 hstate.add_int (ref.source_file_idx);
1163 hstate.add_int (ref.start_line);
1164 return hstate.end ();
1167 static bool
1168 equal (const function_start &ref1, const function_start &ref2)
1170 return (ref1.source_file_idx == ref2.source_file_idx
1171 && ref1.start_line == ref2.start_line);
1174 static void
1175 mark_deleted (function_start &ref)
1177 ref.start_line = ~1U;
1180 static void
1181 mark_empty (function_start &ref)
1183 ref.start_line = ~2U;
1186 static bool
1187 is_deleted (const function_start &ref)
1189 return ref.start_line == ~1U;
1192 static bool
1193 is_empty (const function_start &ref)
1195 return ref.start_line == ~2U;
1199 /* Process a single input file. */
1201 static void
1202 process_file (const char *file_name)
1204 create_file_names (file_name);
1206 for (unsigned i = 0; i < processed_files.size (); i++)
1207 if (strcmp (da_file_name, processed_files[i]) == 0)
1209 fnotice (stderr, "'%s' file is already processed\n",
1210 file_name);
1211 return;
1214 processed_files.push_back (xstrdup (da_file_name));
1216 read_graph_file ();
1217 read_count_file ();
1220 /* Process all functions in all files. */
1222 static void
1223 process_all_functions (void)
1225 hash_map<function_start_pair_hash, function_info *> fn_map;
1227 /* Identify group functions. */
1228 for (vector<function_info *>::iterator it = functions.begin ();
1229 it != functions.end (); it++)
1230 if (!(*it)->artificial)
1232 function_start needle;
1233 needle.source_file_idx = (*it)->src;
1234 needle.start_line = (*it)->start_line;
1236 function_info **slot = fn_map.get (needle);
1237 if (slot)
1239 (*slot)->is_group = 1;
1240 (*it)->is_group = 1;
1242 else
1243 fn_map.put (needle, *it);
1246 /* Remove all artificial function. */
1247 functions.erase (remove_if (functions.begin (), functions.end (),
1248 function_info::is_artificial), functions.end ());
1250 for (vector<function_info *>::iterator it = functions.begin ();
1251 it != functions.end (); it++)
1253 function_info *fn = *it;
1254 unsigned src = fn->src;
1256 if (!fn->counts.empty () || no_data_file)
1258 source_info *s = &sources[src];
1259 s->functions.push_back (fn);
1261 /* Mark last line in files touched by function. */
1262 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1263 block_no++)
1265 block_info *block = &fn->blocks[block_no];
1266 for (unsigned i = 0; i < block->locations.size (); i++)
1268 /* Sort lines of locations. */
1269 sort (block->locations[i].lines.begin (),
1270 block->locations[i].lines.end ());
1272 if (!block->locations[i].lines.empty ())
1274 s = &sources[block->locations[i].source_file_idx];
1275 unsigned last_line
1276 = block->locations[i].lines.back ();
1278 /* Record new lines for the function. */
1279 if (last_line >= s->lines.size ())
1281 s = &sources[block->locations[i].source_file_idx];
1282 unsigned last_line
1283 = block->locations[i].lines.back ();
1285 /* Record new lines for the function. */
1286 if (last_line >= s->lines.size ())
1288 /* Record new lines for a source file. */
1289 s->lines.resize (last_line + 1);
1296 /* Allocate lines for group function, following start_line
1297 and end_line information of the function. */
1298 if (fn->is_group)
1299 fn->lines.resize (fn->end_line - fn->start_line + 1);
1301 solve_flow_graph (fn);
1302 if (fn->has_catch)
1303 find_exception_blocks (fn);
1305 else
1307 /* The function was not in the executable -- some other
1308 instance must have been selected. */
1313 static void
1314 output_gcov_file (const char *file_name, source_info *src)
1316 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1318 if (src->coverage.lines)
1320 FILE *gcov_file = fopen (gcov_file_name, "w");
1321 if (gcov_file)
1323 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1324 output_lines (gcov_file, src);
1325 if (ferror (gcov_file))
1326 fnotice (stderr, "Error writing output file '%s'\n",
1327 gcov_file_name);
1328 fclose (gcov_file);
1330 else
1331 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1333 else
1335 unlink (gcov_file_name);
1336 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1338 free (gcov_file_name);
1341 static void
1342 generate_results (const char *file_name)
1344 char *gcov_intermediate_filename;
1346 for (vector<function_info *>::iterator it = functions.begin ();
1347 it != functions.end (); it++)
1349 function_info *fn = *it;
1350 coverage_info coverage;
1352 memset (&coverage, 0, sizeof (coverage));
1353 coverage.name = fn->get_name ();
1354 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1355 if (flag_function_summary)
1357 function_summary (&coverage, "Function");
1358 fnotice (stdout, "\n");
1362 name_map needle;
1364 if (file_name)
1366 needle.name = file_name;
1367 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1368 needle);
1369 if (it != names.end ())
1370 file_name = sources[it->src].coverage.name;
1371 else
1372 file_name = canonicalize_name (file_name);
1375 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1377 json::object *root = new json::object ();
1378 root->set ("format_version", new json::string ("1"));
1379 root->set ("gcc_version", new json::string (version_string));
1381 if (bbg_cwd != NULL)
1382 root->set ("current_working_directory", new json::string (bbg_cwd));
1384 json::array *json_files = new json::array ();
1385 root->set ("files", json_files);
1387 for (vector<source_info>::iterator it = sources.begin ();
1388 it != sources.end (); it++)
1390 source_info *src = &(*it);
1391 if (flag_relative_only)
1393 /* Ignore this source, if it is an absolute path (after
1394 source prefix removal). */
1395 char first = src->coverage.name[0];
1397 #if HAVE_DOS_BASED_FILE_SYSTEM
1398 if (first && src->coverage.name[1] == ':')
1399 first = src->coverage.name[2];
1400 #endif
1401 if (IS_DIR_SEPARATOR (first))
1402 continue;
1405 accumulate_line_counts (src);
1407 if (!flag_use_stdout)
1408 function_summary (&src->coverage, "File");
1409 total_lines += src->coverage.lines;
1410 total_executed += src->coverage.lines_executed;
1411 if (flag_gcov_file)
1413 if (flag_json_format)
1414 output_json_intermediate_file (json_files, src);
1415 else
1417 if (flag_use_stdout)
1419 if (src->coverage.lines)
1420 output_lines (stdout, src);
1422 else
1424 output_gcov_file (file_name, src);
1425 fnotice (stdout, "\n");
1431 if (flag_gcov_file && flag_json_format)
1433 if (flag_use_stdout)
1435 root->dump (stdout);
1436 printf ("\n");
1438 else
1440 pretty_printer pp;
1441 root->print (&pp);
1442 pp_formatted_text (&pp);
1444 gzFile output = gzopen (gcov_intermediate_filename, "w");
1445 if (output == NULL)
1447 fnotice (stderr, "Cannot open JSON output file %s\n",
1448 gcov_intermediate_filename);
1449 return;
1452 if (gzputs (output, pp_formatted_text (&pp)) == EOF
1453 || gzclose (output))
1455 fnotice (stderr, "Error writing JSON output file %s\n",
1456 gcov_intermediate_filename);
1457 return;
1462 if (!file_name)
1463 executed_summary (total_lines, total_executed);
1466 /* Release all memory used. */
1468 static void
1469 release_structures (void)
1471 for (vector<function_info *>::iterator it = functions.begin ();
1472 it != functions.end (); it++)
1473 delete (*it);
1475 sources.resize (0);
1476 names.resize (0);
1477 functions.resize (0);
1480 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1481 is not specified, these are named from FILE_NAME sans extension. If
1482 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1483 directory, but named from the basename of the FILE_NAME, sans extension.
1484 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1485 and the data files are named from that. */
1487 static void
1488 create_file_names (const char *file_name)
1490 char *cptr;
1491 char *name;
1492 int length = strlen (file_name);
1493 int base;
1495 /* Free previous file names. */
1496 free (bbg_file_name);
1497 free (da_file_name);
1498 da_file_name = bbg_file_name = NULL;
1499 bbg_file_time = 0;
1500 bbg_stamp = 0;
1502 if (object_directory && object_directory[0])
1504 struct stat status;
1506 length += strlen (object_directory) + 2;
1507 name = XNEWVEC (char, length);
1508 name[0] = 0;
1510 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1511 strcat (name, object_directory);
1512 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1513 strcat (name, "/");
1515 else
1517 name = XNEWVEC (char, length + 1);
1518 strcpy (name, file_name);
1519 base = 0;
1522 if (base)
1524 /* Append source file name. */
1525 const char *cptr = lbasename (file_name);
1526 strcat (name, cptr ? cptr : file_name);
1529 /* Remove the extension. */
1530 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1531 if (cptr)
1532 *cptr = 0;
1534 length = strlen (name);
1536 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1537 strcpy (bbg_file_name, name);
1538 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1540 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1541 strcpy (da_file_name, name);
1542 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1544 free (name);
1545 return;
1548 /* Find or create a source file structure for FILE_NAME. Copies
1549 FILE_NAME on creation */
1551 static unsigned
1552 find_source (const char *file_name)
1554 char *canon;
1555 unsigned idx;
1556 struct stat status;
1558 if (!file_name)
1559 file_name = "<unknown>";
1561 name_map needle;
1562 needle.name = file_name;
1564 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1565 needle);
1566 if (it != names.end ())
1568 idx = it->src;
1569 goto check_date;
1572 /* Not found, try the canonical name. */
1573 canon = canonicalize_name (file_name);
1574 needle.name = canon;
1575 it = std::find (names.begin (), names.end (), needle);
1576 if (it == names.end ())
1578 /* Not found with canonical name, create a new source. */
1579 source_info *src;
1581 idx = sources.size ();
1582 needle = name_map (canon, idx);
1583 names.push_back (needle);
1585 sources.push_back (source_info ());
1586 src = &sources.back ();
1587 src->name = canon;
1588 src->coverage.name = src->name;
1589 src->index = idx;
1590 if (source_length
1591 #if HAVE_DOS_BASED_FILE_SYSTEM
1592 /* You lose if separators don't match exactly in the
1593 prefix. */
1594 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1595 #else
1596 && !strncmp (source_prefix, src->coverage.name, source_length)
1597 #endif
1598 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1599 src->coverage.name += source_length + 1;
1600 if (!stat (src->name, &status))
1601 src->file_time = status.st_mtime;
1603 else
1604 idx = it->src;
1606 needle.name = file_name;
1607 if (std::find (names.begin (), names.end (), needle) == names.end ())
1609 /* Append the non-canonical name. */
1610 names.push_back (name_map (xstrdup (file_name), idx));
1613 /* Resort the name map. */
1614 std::sort (names.begin (), names.end ());
1616 check_date:
1617 if (sources[idx].file_time > bbg_file_time)
1619 static int info_emitted;
1621 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1622 file_name, bbg_file_name);
1623 if (!info_emitted)
1625 fnotice (stderr,
1626 "(the message is displayed only once per source file)\n");
1627 info_emitted = 1;
1629 sources[idx].file_time = 0;
1632 return idx;
1635 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1637 static void
1638 read_graph_file (void)
1640 unsigned version;
1641 unsigned current_tag = 0;
1642 unsigned tag;
1644 if (!gcov_open (bbg_file_name, 1))
1646 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1647 return;
1649 bbg_file_time = gcov_time ();
1650 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1652 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1653 gcov_close ();
1654 return;
1657 version = gcov_read_unsigned ();
1658 if (version != GCOV_VERSION)
1660 char v[4], e[4];
1662 GCOV_UNSIGNED2STRING (v, version);
1663 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1665 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1666 bbg_file_name, v, e);
1668 bbg_stamp = gcov_read_unsigned ();
1669 bbg_cwd = xstrdup (gcov_read_string ());
1670 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1672 function_info *fn = NULL;
1673 while ((tag = gcov_read_unsigned ()))
1675 unsigned length = gcov_read_unsigned ();
1676 gcov_position_t base = gcov_position ();
1678 if (tag == GCOV_TAG_FUNCTION)
1680 char *function_name;
1681 unsigned ident;
1682 unsigned lineno_checksum, cfg_checksum;
1684 ident = gcov_read_unsigned ();
1685 lineno_checksum = gcov_read_unsigned ();
1686 cfg_checksum = gcov_read_unsigned ();
1687 function_name = xstrdup (gcov_read_string ());
1688 unsigned artificial = gcov_read_unsigned ();
1689 unsigned src_idx = find_source (gcov_read_string ());
1690 unsigned start_line = gcov_read_unsigned ();
1691 unsigned start_column = gcov_read_unsigned ();
1692 unsigned end_line = gcov_read_unsigned ();
1694 fn = new function_info ();
1695 functions.push_back (fn);
1696 fn->m_name = function_name;
1697 fn->ident = ident;
1698 fn->lineno_checksum = lineno_checksum;
1699 fn->cfg_checksum = cfg_checksum;
1700 fn->src = src_idx;
1701 fn->start_line = start_line;
1702 fn->start_column = start_column;
1703 fn->end_line = end_line;
1704 fn->artificial = artificial;
1706 current_tag = tag;
1708 else if (fn && tag == GCOV_TAG_BLOCKS)
1710 if (!fn->blocks.empty ())
1711 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1712 bbg_file_name, fn->get_name ());
1713 else
1714 fn->blocks.resize (gcov_read_unsigned ());
1716 else if (fn && tag == GCOV_TAG_ARCS)
1718 unsigned src = gcov_read_unsigned ();
1719 fn->blocks[src].id = src;
1720 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1721 block_info *src_blk = &fn->blocks[src];
1722 unsigned mark_catches = 0;
1723 struct arc_info *arc;
1725 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1726 goto corrupt;
1728 while (num_dests--)
1730 unsigned dest = gcov_read_unsigned ();
1731 unsigned flags = gcov_read_unsigned ();
1733 if (dest >= fn->blocks.size ())
1734 goto corrupt;
1735 arc = XCNEW (arc_info);
1737 arc->dst = &fn->blocks[dest];
1738 arc->src = src_blk;
1740 arc->count = 0;
1741 arc->count_valid = 0;
1742 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1743 arc->fake = !!(flags & GCOV_ARC_FAKE);
1744 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1746 arc->succ_next = src_blk->succ;
1747 src_blk->succ = arc;
1748 src_blk->num_succ++;
1750 arc->pred_next = fn->blocks[dest].pred;
1751 fn->blocks[dest].pred = arc;
1752 fn->blocks[dest].num_pred++;
1754 if (arc->fake)
1756 if (src)
1758 /* Exceptional exit from this function, the
1759 source block must be a call. */
1760 fn->blocks[src].is_call_site = 1;
1761 arc->is_call_non_return = 1;
1762 mark_catches = 1;
1764 else
1766 /* Non-local return from a callee of this
1767 function. The destination block is a setjmp. */
1768 arc->is_nonlocal_return = 1;
1769 fn->blocks[dest].is_nonlocal_return = 1;
1773 if (!arc->on_tree)
1774 fn->counts.push_back (0);
1777 if (mark_catches)
1779 /* We have a fake exit from this block. The other
1780 non-fall through exits must be to catch handlers.
1781 Mark them as catch arcs. */
1783 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1784 if (!arc->fake && !arc->fall_through)
1786 arc->is_throw = 1;
1787 fn->has_catch = 1;
1791 else if (fn && tag == GCOV_TAG_LINES)
1793 unsigned blockno = gcov_read_unsigned ();
1794 block_info *block = &fn->blocks[blockno];
1796 if (blockno >= fn->blocks.size ())
1797 goto corrupt;
1799 while (true)
1801 unsigned lineno = gcov_read_unsigned ();
1803 if (lineno)
1804 block->locations.back ().lines.push_back (lineno);
1805 else
1807 const char *file_name = gcov_read_string ();
1809 if (!file_name)
1810 break;
1811 block->locations.push_back (block_location_info
1812 (find_source (file_name)));
1816 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1818 fn = NULL;
1819 current_tag = 0;
1821 gcov_sync (base, length);
1822 if (gcov_is_error ())
1824 corrupt:;
1825 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1826 break;
1829 gcov_close ();
1831 if (functions.empty ())
1832 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1835 /* Reads profiles from the count file and attach to each
1836 function. Return nonzero if fatal error. */
1838 static int
1839 read_count_file (void)
1841 unsigned ix;
1842 unsigned version;
1843 unsigned tag;
1844 function_info *fn = NULL;
1845 int error = 0;
1847 if (!gcov_open (da_file_name, 1))
1849 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1850 da_file_name);
1851 no_data_file = 1;
1852 return 0;
1854 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1856 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1857 cleanup:;
1858 gcov_close ();
1859 return 1;
1861 version = gcov_read_unsigned ();
1862 if (version != GCOV_VERSION)
1864 char v[4], e[4];
1866 GCOV_UNSIGNED2STRING (v, version);
1867 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1869 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1870 da_file_name, v, e);
1872 tag = gcov_read_unsigned ();
1873 if (tag != bbg_stamp)
1875 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1876 goto cleanup;
1879 while ((tag = gcov_read_unsigned ()))
1881 unsigned length = gcov_read_unsigned ();
1882 unsigned long base = gcov_position ();
1884 if (tag == GCOV_TAG_OBJECT_SUMMARY)
1886 struct gcov_summary summary;
1887 gcov_read_summary (&summary);
1888 object_runs = summary.runs;
1890 else if (tag == GCOV_TAG_FUNCTION && !length)
1891 ; /* placeholder */
1892 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1894 unsigned ident;
1896 /* Try to find the function in the list. To speed up the
1897 search, first start from the last function found. */
1898 ident = gcov_read_unsigned ();
1900 fn = NULL;
1901 for (vector<function_info *>::reverse_iterator it
1902 = functions.rbegin (); it != functions.rend (); it++)
1904 if ((*it)->ident == ident)
1906 fn = *it;
1907 break;
1911 if (!fn)
1913 else if (gcov_read_unsigned () != fn->lineno_checksum
1914 || gcov_read_unsigned () != fn->cfg_checksum)
1916 mismatch:;
1917 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1918 da_file_name, fn->get_name ());
1919 goto cleanup;
1922 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1924 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1925 goto mismatch;
1927 for (ix = 0; ix != fn->counts.size (); ix++)
1928 fn->counts[ix] += gcov_read_counter ();
1930 gcov_sync (base, length);
1931 if ((error = gcov_is_error ()))
1933 fnotice (stderr,
1934 error < 0
1935 ? N_("%s:overflowed\n")
1936 : N_("%s:corrupted\n"),
1937 da_file_name);
1938 goto cleanup;
1942 gcov_close ();
1943 return 0;
1946 /* Solve the flow graph. Propagate counts from the instrumented arcs
1947 to the blocks and the uninstrumented arcs. */
1949 static void
1950 solve_flow_graph (function_info *fn)
1952 unsigned ix;
1953 arc_info *arc;
1954 gcov_type *count_ptr = &fn->counts.front ();
1955 block_info *blk;
1956 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
1957 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
1959 /* The arcs were built in reverse order. Fix that now. */
1960 for (ix = fn->blocks.size (); ix--;)
1962 arc_info *arc_p, *arc_n;
1964 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
1965 arc_p = arc, arc = arc_n)
1967 arc_n = arc->succ_next;
1968 arc->succ_next = arc_p;
1970 fn->blocks[ix].succ = arc_p;
1972 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
1973 arc_p = arc, arc = arc_n)
1975 arc_n = arc->pred_next;
1976 arc->pred_next = arc_p;
1978 fn->blocks[ix].pred = arc_p;
1981 if (fn->blocks.size () < 2)
1982 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
1983 bbg_file_name, fn->get_name ());
1984 else
1986 if (fn->blocks[ENTRY_BLOCK].num_pred)
1987 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
1988 bbg_file_name, fn->get_name ());
1989 else
1990 /* We can't deduce the entry block counts from the lack of
1991 predecessors. */
1992 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
1994 if (fn->blocks[EXIT_BLOCK].num_succ)
1995 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
1996 bbg_file_name, fn->get_name ());
1997 else
1998 /* Likewise, we can't deduce exit block counts from the lack
1999 of its successors. */
2000 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
2003 /* Propagate the measured counts, this must be done in the same
2004 order as the code in profile.c */
2005 for (unsigned i = 0; i < fn->blocks.size (); i++)
2007 blk = &fn->blocks[i];
2008 block_info const *prev_dst = NULL;
2009 int out_of_order = 0;
2010 int non_fake_succ = 0;
2012 for (arc = blk->succ; arc; arc = arc->succ_next)
2014 if (!arc->fake)
2015 non_fake_succ++;
2017 if (!arc->on_tree)
2019 if (count_ptr)
2020 arc->count = *count_ptr++;
2021 arc->count_valid = 1;
2022 blk->num_succ--;
2023 arc->dst->num_pred--;
2025 if (prev_dst && prev_dst > arc->dst)
2026 out_of_order = 1;
2027 prev_dst = arc->dst;
2029 if (non_fake_succ == 1)
2031 /* If there is only one non-fake exit, it is an
2032 unconditional branch. */
2033 for (arc = blk->succ; arc; arc = arc->succ_next)
2034 if (!arc->fake)
2036 arc->is_unconditional = 1;
2037 /* If this block is instrumenting a call, it might be
2038 an artificial block. It is not artificial if it has
2039 a non-fallthrough exit, or the destination of this
2040 arc has more than one entry. Mark the destination
2041 block as a return site, if none of those conditions
2042 hold. */
2043 if (blk->is_call_site && arc->fall_through
2044 && arc->dst->pred == arc && !arc->pred_next)
2045 arc->dst->is_call_return = 1;
2049 /* Sort the successor arcs into ascending dst order. profile.c
2050 normally produces arcs in the right order, but sometimes with
2051 one or two out of order. We're not using a particularly
2052 smart sort. */
2053 if (out_of_order)
2055 arc_info *start = blk->succ;
2056 unsigned changes = 1;
2058 while (changes)
2060 arc_info *arc, *arc_p, *arc_n;
2062 changes = 0;
2063 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2065 if (arc->dst > arc_n->dst)
2067 changes = 1;
2068 if (arc_p)
2069 arc_p->succ_next = arc_n;
2070 else
2071 start = arc_n;
2072 arc->succ_next = arc_n->succ_next;
2073 arc_n->succ_next = arc;
2074 arc_p = arc_n;
2076 else
2078 arc_p = arc;
2079 arc = arc_n;
2083 blk->succ = start;
2086 /* Place it on the invalid chain, it will be ignored if that's
2087 wrong. */
2088 blk->invalid_chain = 1;
2089 blk->chain = invalid_blocks;
2090 invalid_blocks = blk;
2093 while (invalid_blocks || valid_blocks)
2095 while ((blk = invalid_blocks))
2097 gcov_type total = 0;
2098 const arc_info *arc;
2100 invalid_blocks = blk->chain;
2101 blk->invalid_chain = 0;
2102 if (!blk->num_succ)
2103 for (arc = blk->succ; arc; arc = arc->succ_next)
2104 total += arc->count;
2105 else if (!blk->num_pred)
2106 for (arc = blk->pred; arc; arc = arc->pred_next)
2107 total += arc->count;
2108 else
2109 continue;
2111 blk->count = total;
2112 blk->count_valid = 1;
2113 blk->chain = valid_blocks;
2114 blk->valid_chain = 1;
2115 valid_blocks = blk;
2117 while ((blk = valid_blocks))
2119 gcov_type total;
2120 arc_info *arc, *inv_arc;
2122 valid_blocks = blk->chain;
2123 blk->valid_chain = 0;
2124 if (blk->num_succ == 1)
2126 block_info *dst;
2128 total = blk->count;
2129 inv_arc = NULL;
2130 for (arc = blk->succ; arc; arc = arc->succ_next)
2132 total -= arc->count;
2133 if (!arc->count_valid)
2134 inv_arc = arc;
2136 dst = inv_arc->dst;
2137 inv_arc->count_valid = 1;
2138 inv_arc->count = total;
2139 blk->num_succ--;
2140 dst->num_pred--;
2141 if (dst->count_valid)
2143 if (dst->num_pred == 1 && !dst->valid_chain)
2145 dst->chain = valid_blocks;
2146 dst->valid_chain = 1;
2147 valid_blocks = dst;
2150 else
2152 if (!dst->num_pred && !dst->invalid_chain)
2154 dst->chain = invalid_blocks;
2155 dst->invalid_chain = 1;
2156 invalid_blocks = dst;
2160 if (blk->num_pred == 1)
2162 block_info *src;
2164 total = blk->count;
2165 inv_arc = NULL;
2166 for (arc = blk->pred; arc; arc = arc->pred_next)
2168 total -= arc->count;
2169 if (!arc->count_valid)
2170 inv_arc = arc;
2172 src = inv_arc->src;
2173 inv_arc->count_valid = 1;
2174 inv_arc->count = total;
2175 blk->num_pred--;
2176 src->num_succ--;
2177 if (src->count_valid)
2179 if (src->num_succ == 1 && !src->valid_chain)
2181 src->chain = valid_blocks;
2182 src->valid_chain = 1;
2183 valid_blocks = src;
2186 else
2188 if (!src->num_succ && !src->invalid_chain)
2190 src->chain = invalid_blocks;
2191 src->invalid_chain = 1;
2192 invalid_blocks = src;
2199 /* If the graph has been correctly solved, every block will have a
2200 valid count. */
2201 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2202 if (!fn->blocks[i].count_valid)
2204 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2205 bbg_file_name, fn->get_name ());
2206 break;
2210 /* Mark all the blocks only reachable via an incoming catch. */
2212 static void
2213 find_exception_blocks (function_info *fn)
2215 unsigned ix;
2216 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2218 /* First mark all blocks as exceptional. */
2219 for (ix = fn->blocks.size (); ix--;)
2220 fn->blocks[ix].exceptional = 1;
2222 /* Now mark all the blocks reachable via non-fake edges */
2223 queue[0] = &fn->blocks[0];
2224 queue[0]->exceptional = 0;
2225 for (ix = 1; ix;)
2227 block_info *block = queue[--ix];
2228 const arc_info *arc;
2230 for (arc = block->succ; arc; arc = arc->succ_next)
2231 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2233 arc->dst->exceptional = 0;
2234 queue[ix++] = arc->dst;
2240 /* Increment totals in COVERAGE according to arc ARC. */
2242 static void
2243 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2245 if (arc->is_call_non_return)
2247 coverage->calls++;
2248 if (arc->src->count)
2249 coverage->calls_executed++;
2251 else if (!arc->is_unconditional)
2253 coverage->branches++;
2254 if (arc->src->count)
2255 coverage->branches_executed++;
2256 if (arc->count)
2257 coverage->branches_taken++;
2261 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2262 readable format. */
2264 static char const *
2265 format_count (gcov_type count)
2267 static char buffer[64];
2268 const char *units = " kMGTPEZY";
2270 if (count < 1000 || !flag_human_readable_numbers)
2272 sprintf (buffer, "%" PRId64, count);
2273 return buffer;
2276 unsigned i;
2277 gcov_type divisor = 1;
2278 for (i = 0; units[i+1]; i++, divisor *= 1000)
2280 if (count + divisor / 2 < 1000 * divisor)
2281 break;
2283 float r = 1.0f * count / divisor;
2284 sprintf (buffer, "%.1f%c", r, units[i]);
2285 return buffer;
2288 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2289 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2290 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2291 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2292 format TOP. Return pointer to a static string. */
2294 static char const *
2295 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2297 static char buffer[20];
2299 if (decimal_places >= 0)
2301 float ratio = bottom ? 100.0f * top / bottom: 0;
2303 /* Round up to 1% if there's a small non-zero value. */
2304 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2305 ratio = 1.0f;
2306 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2308 else
2309 return format_count (top);
2311 return buffer;
2314 /* Summary of execution */
2316 static void
2317 executed_summary (unsigned lines, unsigned executed)
2319 if (lines)
2320 fnotice (stdout, "Lines executed:%s of %d\n",
2321 format_gcov (executed, lines, 2), lines);
2322 else
2323 fnotice (stdout, "No executable lines\n");
2326 /* Output summary info for a function or file. */
2328 static void
2329 function_summary (const coverage_info *coverage, const char *title)
2331 fnotice (stdout, "%s '%s'\n", title, coverage->name);
2332 executed_summary (coverage->lines, coverage->lines_executed);
2334 if (flag_branches)
2336 if (coverage->branches)
2338 fnotice (stdout, "Branches executed:%s of %d\n",
2339 format_gcov (coverage->branches_executed,
2340 coverage->branches, 2),
2341 coverage->branches);
2342 fnotice (stdout, "Taken at least once:%s of %d\n",
2343 format_gcov (coverage->branches_taken,
2344 coverage->branches, 2),
2345 coverage->branches);
2347 else
2348 fnotice (stdout, "No branches\n");
2349 if (coverage->calls)
2350 fnotice (stdout, "Calls executed:%s of %d\n",
2351 format_gcov (coverage->calls_executed, coverage->calls, 2),
2352 coverage->calls);
2353 else
2354 fnotice (stdout, "No calls\n");
2358 /* Canonicalize the filename NAME by canonicalizing directory
2359 separators, eliding . components and resolving .. components
2360 appropriately. Always returns a unique string. */
2362 static char *
2363 canonicalize_name (const char *name)
2365 /* The canonical name cannot be longer than the incoming name. */
2366 char *result = XNEWVEC (char, strlen (name) + 1);
2367 const char *base = name, *probe;
2368 char *ptr = result;
2369 char *dd_base;
2370 int slash = 0;
2372 #if HAVE_DOS_BASED_FILE_SYSTEM
2373 if (base[0] && base[1] == ':')
2375 result[0] = base[0];
2376 result[1] = ':';
2377 base += 2;
2378 ptr += 2;
2380 #endif
2381 for (dd_base = ptr; *base; base = probe)
2383 size_t len;
2385 for (probe = base; *probe; probe++)
2386 if (IS_DIR_SEPARATOR (*probe))
2387 break;
2389 len = probe - base;
2390 if (len == 1 && base[0] == '.')
2391 /* Elide a '.' directory */
2393 else if (len == 2 && base[0] == '.' && base[1] == '.')
2395 /* '..', we can only elide it and the previous directory, if
2396 we're not a symlink. */
2397 struct stat ATTRIBUTE_UNUSED buf;
2399 *ptr = 0;
2400 if (dd_base == ptr
2401 #if defined (S_ISLNK)
2402 /* S_ISLNK is not POSIX.1-1996. */
2403 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2404 #endif
2407 /* Cannot elide, or unreadable or a symlink. */
2408 dd_base = ptr + 2 + slash;
2409 goto regular;
2411 while (ptr != dd_base && *ptr != '/')
2412 ptr--;
2413 slash = ptr != result;
2415 else
2417 regular:
2418 /* Regular pathname component. */
2419 if (slash)
2420 *ptr++ = '/';
2421 memcpy (ptr, base, len);
2422 ptr += len;
2423 slash = 1;
2426 for (; IS_DIR_SEPARATOR (*probe); probe++)
2427 continue;
2429 *ptr = 0;
2431 return result;
2434 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2436 static void
2437 md5sum_to_hex (const char *sum, char *buffer)
2439 for (unsigned i = 0; i < 16; i++)
2440 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2443 /* Generate an output file name. INPUT_NAME is the canonicalized main
2444 input file and SRC_NAME is the canonicalized file name.
2445 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2446 long_output_names we prepend the processed name of the input file
2447 to each output name (except when the current source file is the
2448 input file, so you don't get a double concatenation). The two
2449 components are separated by '##'. With preserve_paths we create a
2450 filename from all path components of the source file, replacing '/'
2451 with '#', and .. with '^', without it we simply take the basename
2452 component. (Remember, the canonicalized name will already have
2453 elided '.' components and converted \\ separators.) */
2455 static char *
2456 make_gcov_file_name (const char *input_name, const char *src_name)
2458 char *ptr;
2459 char *result;
2461 if (flag_long_names && input_name && strcmp (src_name, input_name))
2463 /* Generate the input filename part. */
2464 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2466 ptr = result;
2467 ptr = mangle_name (input_name, ptr);
2468 ptr[0] = ptr[1] = '#';
2469 ptr += 2;
2471 else
2473 result = XNEWVEC (char, strlen (src_name) + 10);
2474 ptr = result;
2477 ptr = mangle_name (src_name, ptr);
2478 strcpy (ptr, ".gcov");
2480 /* When hashing filenames, we shorten them by only using the filename
2481 component and appending a hash of the full (mangled) pathname. */
2482 if (flag_hash_filenames)
2484 md5_ctx ctx;
2485 char md5sum[16];
2486 char md5sum_hex[33];
2488 md5_init_ctx (&ctx);
2489 md5_process_bytes (src_name, strlen (src_name), &ctx);
2490 md5_finish_ctx (&ctx, md5sum);
2491 md5sum_to_hex (md5sum, md5sum_hex);
2492 free (result);
2494 result = XNEWVEC (char, strlen (src_name) + 50);
2495 ptr = result;
2496 ptr = mangle_name (src_name, ptr);
2497 ptr[0] = ptr[1] = '#';
2498 ptr += 2;
2499 memcpy (ptr, md5sum_hex, 32);
2500 ptr += 32;
2501 strcpy (ptr, ".gcov");
2504 return result;
2507 static char *
2508 mangle_name (char const *base, char *ptr)
2510 size_t len;
2512 /* Generate the source filename part. */
2513 if (!flag_preserve_paths)
2515 base = lbasename (base);
2516 len = strlen (base);
2517 memcpy (ptr, base, len);
2518 ptr += len;
2520 else
2521 ptr = mangle_path (base);
2523 return ptr;
2526 /* Scan through the bb_data for each line in the block, increment
2527 the line number execution count indicated by the execution count of
2528 the appropriate basic block. */
2530 static void
2531 add_line_counts (coverage_info *coverage, function_info *fn)
2533 bool has_any_line = false;
2534 /* Scan each basic block. */
2535 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2537 line_info *line = NULL;
2538 block_info *block = &fn->blocks[ix];
2539 if (block->count && ix && ix + 1 != fn->blocks.size ())
2540 fn->blocks_executed++;
2541 for (unsigned i = 0; i < block->locations.size (); i++)
2543 unsigned src_idx = block->locations[i].source_file_idx;
2544 vector<unsigned> &lines = block->locations[i].lines;
2546 block->cycle.arc = NULL;
2547 block->cycle.ident = ~0U;
2549 for (unsigned j = 0; j < lines.size (); j++)
2551 unsigned ln = lines[j];
2553 /* Line belongs to a function that is in a group. */
2554 if (fn->group_line_p (ln, src_idx))
2556 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2557 line = &(fn->lines[lines[j] - fn->start_line]);
2558 line->exists = 1;
2559 if (!block->exceptional)
2561 line->unexceptional = 1;
2562 if (block->count == 0)
2563 line->has_unexecuted_block = 1;
2565 line->count += block->count;
2567 else
2569 gcc_assert (ln < sources[src_idx].lines.size ());
2570 line = &(sources[src_idx].lines[ln]);
2571 if (coverage)
2573 if (!line->exists)
2574 coverage->lines++;
2575 if (!line->count && block->count)
2576 coverage->lines_executed++;
2578 line->exists = 1;
2579 if (!block->exceptional)
2581 line->unexceptional = 1;
2582 if (block->count == 0)
2583 line->has_unexecuted_block = 1;
2585 line->count += block->count;
2589 has_any_line = true;
2591 if (!ix || ix + 1 == fn->blocks.size ())
2592 /* Entry or exit block. */;
2593 else if (line != NULL)
2595 line->blocks.push_back (block);
2597 if (flag_branches)
2599 arc_info *arc;
2601 for (arc = block->succ; arc; arc = arc->succ_next)
2602 line->branches.push_back (arc);
2608 if (!has_any_line)
2609 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name,
2610 fn->get_name ());
2613 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2614 is set to true, update source file summary. */
2616 static void accumulate_line_info (line_info *line, source_info *src,
2617 bool add_coverage)
2619 if (add_coverage)
2620 for (vector<arc_info *>::iterator it = line->branches.begin ();
2621 it != line->branches.end (); it++)
2622 add_branch_counts (&src->coverage, *it);
2624 if (!line->blocks.empty ())
2626 /* The user expects the line count to be the number of times
2627 a line has been executed. Simply summing the block count
2628 will give an artificially high number. The Right Thing
2629 is to sum the entry counts to the graph of blocks on this
2630 line, then find the elementary cycles of the local graph
2631 and add the transition counts of those cycles. */
2632 gcov_type count = 0;
2634 /* Cycle detection. */
2635 for (vector<block_info *>::iterator it = line->blocks.begin ();
2636 it != line->blocks.end (); it++)
2638 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2639 if (!line->has_block (arc->src))
2640 count += arc->count;
2641 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2642 arc->cs_count = arc->count;
2645 /* Now, add the count of loops entirely on this line. */
2646 count += get_cycles_count (*line);
2647 line->count = count;
2649 if (line->count > src->maximum_count)
2650 src->maximum_count = line->count;
2653 if (line->exists && add_coverage)
2655 src->coverage.lines++;
2656 if (line->count)
2657 src->coverage.lines_executed++;
2661 /* Accumulate the line counts of a file. */
2663 static void
2664 accumulate_line_counts (source_info *src)
2666 /* First work on group functions. */
2667 for (vector<function_info *>::iterator it = src->functions.begin ();
2668 it != src->functions.end (); it++)
2670 function_info *fn = *it;
2672 if (fn->src != src->index || !fn->is_group)
2673 continue;
2675 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2676 it2 != fn->lines.end (); it2++)
2678 line_info *line = &(*it2);
2679 accumulate_line_info (line, src, false);
2683 /* Work on global lines that line in source file SRC. */
2684 for (vector<line_info>::iterator it = src->lines.begin ();
2685 it != src->lines.end (); it++)
2686 accumulate_line_info (&(*it), src, true);
2688 /* If not using intermediate mode, sum lines of group functions and
2689 add them to lines that live in a source file. */
2690 if (!flag_json_format)
2691 for (vector<function_info *>::iterator it = src->functions.begin ();
2692 it != src->functions.end (); it++)
2694 function_info *fn = *it;
2696 if (fn->src != src->index || !fn->is_group)
2697 continue;
2699 for (unsigned i = 0; i < fn->lines.size (); i++)
2701 line_info *fn_line = &fn->lines[i];
2702 if (fn_line->exists)
2704 unsigned ln = fn->start_line + i;
2705 line_info *src_line = &src->lines[ln];
2707 if (!src_line->exists)
2708 src->coverage.lines++;
2709 if (!src_line->count && fn_line->count)
2710 src->coverage.lines_executed++;
2712 src_line->count += fn_line->count;
2713 src_line->exists = 1;
2715 if (fn_line->has_unexecuted_block)
2716 src_line->has_unexecuted_block = 1;
2718 if (fn_line->unexceptional)
2719 src_line->unexceptional = 1;
2725 /* Output information about ARC number IX. Returns nonzero if
2726 anything is output. */
2728 static int
2729 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2731 if (arc->is_call_non_return)
2733 if (arc->src->count)
2735 fnotice (gcov_file, "call %2d returned %s\n", ix,
2736 format_gcov (arc->src->count - arc->count,
2737 arc->src->count, -flag_counts));
2739 else
2740 fnotice (gcov_file, "call %2d never executed\n", ix);
2742 else if (!arc->is_unconditional)
2744 if (arc->src->count)
2745 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2746 format_gcov (arc->count, arc->src->count, -flag_counts),
2747 arc->fall_through ? " (fallthrough)"
2748 : arc->is_throw ? " (throw)" : "");
2749 else
2750 fnotice (gcov_file, "branch %2d never executed", ix);
2752 if (flag_verbose)
2753 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2755 fnotice (gcov_file, "\n");
2757 else if (flag_unconditional && !arc->dst->is_call_return)
2759 if (arc->src->count)
2760 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2761 format_gcov (arc->count, arc->src->count, -flag_counts));
2762 else
2763 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2765 else
2766 return 0;
2767 return 1;
2770 static const char *
2771 read_line (FILE *file)
2773 static char *string;
2774 static size_t string_len;
2775 size_t pos = 0;
2776 char *ptr;
2778 if (!string_len)
2780 string_len = 200;
2781 string = XNEWVEC (char, string_len);
2784 while ((ptr = fgets (string + pos, string_len - pos, file)))
2786 size_t len = strlen (string + pos);
2788 if (len && string[pos + len - 1] == '\n')
2790 string[pos + len - 1] = 0;
2791 return string;
2793 pos += len;
2794 /* If the file contains NUL characters or an incomplete
2795 last line, which can happen more than once in one run,
2796 we have to avoid doubling the STRING_LEN unnecessarily. */
2797 if (pos > string_len / 2)
2799 string_len *= 2;
2800 string = XRESIZEVEC (char, string, string_len);
2804 return pos ? string : NULL;
2807 /* Pad string S with spaces from left to have total width equal to 9. */
2809 static void
2810 pad_count_string (string &s)
2812 if (s.size () < 9)
2813 s.insert (0, 9 - s.size (), ' ');
2816 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2817 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2818 an exceptional statement. The output is printed for LINE_NUM of given
2819 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2820 used to indicate non-executed blocks. */
2822 static void
2823 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2824 bool has_unexecuted_block,
2825 gcov_type count, unsigned line_num,
2826 const char *exceptional_string,
2827 const char *unexceptional_string,
2828 unsigned int maximum_count)
2830 string s;
2831 if (exists)
2833 if (count > 0)
2835 s = format_gcov (count, 0, -1);
2836 if (has_unexecuted_block
2837 && bbg_supports_has_unexecuted_blocks)
2839 if (flag_use_colors)
2841 pad_count_string (s);
2842 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2843 COLOR_SEPARATOR COLOR_FG_WHITE));
2844 s += SGR_RESET;
2846 else
2847 s += "*";
2849 pad_count_string (s);
2851 else
2853 if (flag_use_colors)
2855 s = "0";
2856 pad_count_string (s);
2857 if (unexceptional)
2858 s.insert (0, SGR_SEQ (COLOR_BG_RED
2859 COLOR_SEPARATOR COLOR_FG_WHITE));
2860 else
2861 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2862 COLOR_SEPARATOR COLOR_FG_WHITE));
2863 s += SGR_RESET;
2865 else
2867 s = unexceptional ? unexceptional_string : exceptional_string;
2868 pad_count_string (s);
2872 else
2874 s = "-";
2875 pad_count_string (s);
2878 /* Format line number in output. */
2879 char buffer[16];
2880 sprintf (buffer, "%5u", line_num);
2881 string linestr (buffer);
2883 if (flag_use_hotness_colors && maximum_count)
2885 if (count * 2 > maximum_count) /* > 50%. */
2886 linestr.insert (0, SGR_SEQ (COLOR_BG_RED));
2887 else if (count * 5 > maximum_count) /* > 20%. */
2888 linestr.insert (0, SGR_SEQ (COLOR_BG_YELLOW));
2889 else if (count * 10 > maximum_count) /* > 10%. */
2890 linestr.insert (0, SGR_SEQ (COLOR_BG_GREEN));
2891 linestr += SGR_RESET;
2894 fprintf (f, "%s:%s", s.c_str (), linestr.c_str ());
2897 static void
2898 print_source_line (FILE *f, const vector<const char *> &source_lines,
2899 unsigned line)
2901 gcc_assert (line >= 1);
2902 gcc_assert (line <= source_lines.size ());
2904 fprintf (f, ":%s\n", source_lines[line - 1]);
2907 /* Output line details for LINE and print it to F file. LINE lives on
2908 LINE_NUM. */
2910 static void
2911 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2913 if (flag_all_blocks)
2915 arc_info *arc;
2916 int ix, jx;
2918 ix = jx = 0;
2919 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2920 it != line->blocks.end (); it++)
2922 if (!(*it)->is_call_return)
2924 output_line_beginning (f, line->exists,
2925 (*it)->exceptional, false,
2926 (*it)->count, line_num,
2927 "%%%%%", "$$$$$", 0);
2928 fprintf (f, "-block %2d", ix++);
2929 if (flag_verbose)
2930 fprintf (f, " (BB %u)", (*it)->id);
2931 fprintf (f, "\n");
2933 if (flag_branches)
2934 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2935 jx += output_branch_count (f, jx, arc);
2938 else if (flag_branches)
2940 int ix;
2942 ix = 0;
2943 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
2944 it != line->branches.end (); it++)
2945 ix += output_branch_count (f, ix, (*it));
2949 /* Output detail statistics about function FN to file F. */
2951 static void
2952 output_function_details (FILE *f, function_info *fn)
2954 if (!flag_branches)
2955 return;
2957 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
2958 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
2959 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
2961 for (; arc; arc = arc->pred_next)
2962 if (arc->fake)
2963 return_count -= arc->count;
2965 fprintf (f, "function %s", fn->get_name ());
2966 fprintf (f, " called %s",
2967 format_gcov (called_count, 0, -1));
2968 fprintf (f, " returned %s",
2969 format_gcov (return_count, called_count, 0));
2970 fprintf (f, " blocks executed %s",
2971 format_gcov (fn->blocks_executed, fn->get_block_count (), 0));
2972 fprintf (f, "\n");
2975 /* Read in the source file one line at a time, and output that line to
2976 the gcov file preceded by its execution count and other
2977 information. */
2979 static void
2980 output_lines (FILE *gcov_file, const source_info *src)
2982 #define DEFAULT_LINE_START " -: 0:"
2983 #define FN_SEPARATOR "------------------\n"
2985 FILE *source_file;
2986 const char *retval;
2988 /* Print colorization legend. */
2989 if (flag_use_colors)
2990 fprintf (gcov_file, "%s",
2991 DEFAULT_LINE_START "Colorization: profile count: " \
2992 SGR_SEQ (COLOR_BG_CYAN) "zero coverage (exceptional)" SGR_RESET \
2993 " " \
2994 SGR_SEQ (COLOR_BG_RED) "zero coverage (unexceptional)" SGR_RESET \
2995 " " \
2996 SGR_SEQ (COLOR_BG_MAGENTA) "unexecuted block" SGR_RESET "\n");
2998 if (flag_use_hotness_colors)
2999 fprintf (gcov_file, "%s",
3000 DEFAULT_LINE_START "Colorization: line numbers: hotness: " \
3001 SGR_SEQ (COLOR_BG_RED) "> 50%" SGR_RESET " " \
3002 SGR_SEQ (COLOR_BG_YELLOW) "> 20%" SGR_RESET " " \
3003 SGR_SEQ (COLOR_BG_GREEN) "> 10%" SGR_RESET "\n");
3005 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
3006 if (!multiple_files)
3008 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
3009 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
3010 no_data_file ? "-" : da_file_name);
3011 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
3014 source_file = fopen (src->name, "r");
3015 if (!source_file)
3016 fnotice (stderr, "Cannot open source file %s\n", src->name);
3017 else if (src->file_time == 0)
3018 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
3020 vector<const char *> source_lines;
3021 if (source_file)
3022 while ((retval = read_line (source_file)) != NULL)
3023 source_lines.push_back (xstrdup (retval));
3025 unsigned line_start_group = 0;
3026 vector<function_info *> fns;
3028 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
3030 if (line_num >= src->lines.size ())
3032 fprintf (gcov_file, "%9s:%5u", "-", line_num);
3033 print_source_line (gcov_file, source_lines, line_num);
3034 continue;
3037 const line_info *line = &src->lines[line_num];
3039 if (line_start_group == 0)
3041 fns = src->get_functions_at_location (line_num);
3042 if (fns.size () > 1)
3044 /* It's possible to have functions that partially overlap,
3045 thus take the maximum end_line of functions starting
3046 at LINE_NUM. */
3047 for (unsigned i = 0; i < fns.size (); i++)
3048 if (fns[i]->end_line > line_start_group)
3049 line_start_group = fns[i]->end_line;
3051 else if (fns.size () == 1)
3053 function_info *fn = fns[0];
3054 output_function_details (gcov_file, fn);
3058 /* For lines which don't exist in the .bb file, print '-' before
3059 the source line. For lines which exist but were never
3060 executed, print '#####' or '=====' before the source line.
3061 Otherwise, print the execution count before the source line.
3062 There are 16 spaces of indentation added before the source
3063 line so that tabs won't be messed up. */
3064 output_line_beginning (gcov_file, line->exists, line->unexceptional,
3065 line->has_unexecuted_block, line->count,
3066 line_num, "=====", "#####", src->maximum_count);
3068 print_source_line (gcov_file, source_lines, line_num);
3069 output_line_details (gcov_file, line, line_num);
3071 if (line_start_group == line_num)
3073 for (vector<function_info *>::iterator it = fns.begin ();
3074 it != fns.end (); it++)
3076 function_info *fn = *it;
3077 vector<line_info> &lines = fn->lines;
3079 fprintf (gcov_file, FN_SEPARATOR);
3081 string fn_name = fn->get_name ();
3082 if (flag_use_colors)
3084 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
3085 fn_name += SGR_RESET;
3088 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
3090 output_function_details (gcov_file, fn);
3092 /* Print all lines covered by the function. */
3093 for (unsigned i = 0; i < lines.size (); i++)
3095 line_info *line = &lines[i];
3096 unsigned l = fn->start_line + i;
3098 /* For lines which don't exist in the .bb file, print '-'
3099 before the source line. For lines which exist but
3100 were never executed, print '#####' or '=====' before
3101 the source line. Otherwise, print the execution count
3102 before the source line.
3103 There are 16 spaces of indentation added before the source
3104 line so that tabs won't be messed up. */
3105 output_line_beginning (gcov_file, line->exists,
3106 line->unexceptional,
3107 line->has_unexecuted_block,
3108 line->count,
3109 l, "=====", "#####",
3110 src->maximum_count);
3112 print_source_line (gcov_file, source_lines, l);
3113 output_line_details (gcov_file, line, l);
3117 fprintf (gcov_file, FN_SEPARATOR);
3118 line_start_group = 0;
3122 if (source_file)
3123 fclose (source_file);