typeck.c (cp_truthvalue_conversion): Add tsubst_flags_t parameter and use it in calls...
[official-gcc.git] / gcc / gcov.c
blob66eac9051ea7dd10c0963d1db52f15106f1c2265
1 /* Gcov.c: prepend line execution counts and branch probabilities to a
2 source file.
3 Copyright (C) 1990-2019 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 class function_info;
80 class block_info;
81 class source_info;
83 /* Describes an arc between two basic blocks. */
85 struct arc_info
87 /* source and destination blocks. */
88 class block_info *src;
89 class 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 class block_location_info
126 public:
127 block_location_info (unsigned _source_file_idx):
128 source_file_idx (_source_file_idx)
131 unsigned source_file_idx;
132 vector<unsigned> lines;
135 /* Describes a basic block. Contains lists of arcs to successor and
136 predecessor blocks. */
138 class block_info
140 public:
141 /* Constructor. */
142 block_info ();
144 /* Chain of exit and entry arcs. */
145 arc_info *succ;
146 arc_info *pred;
148 /* Number of unprocessed exit and entry arcs. */
149 gcov_type num_succ;
150 gcov_type num_pred;
152 unsigned id;
154 /* Block execution count. */
155 gcov_type count;
156 unsigned count_valid : 1;
157 unsigned valid_chain : 1;
158 unsigned invalid_chain : 1;
159 unsigned exceptional : 1;
161 /* Block is a call instrumenting site. */
162 unsigned is_call_site : 1; /* Does the call. */
163 unsigned is_call_return : 1; /* Is the return. */
165 /* Block is a landing pad for longjmp or throw. */
166 unsigned is_nonlocal_return : 1;
168 vector<block_location_info> locations;
170 struct
172 /* Single line graph cycle workspace. Used for all-blocks
173 mode. */
174 arc_info *arc;
175 unsigned ident;
176 } cycle; /* Used in all-blocks mode, after blocks are linked onto
177 lines. */
179 /* Temporary chain for solving graph, and for chaining blocks on one
180 line. */
181 class block_info *chain;
185 block_info::block_info (): succ (NULL), pred (NULL), num_succ (0), num_pred (0),
186 id (0), count (0), count_valid (0), valid_chain (0), invalid_chain (0),
187 exceptional (0), is_call_site (0), is_call_return (0), is_nonlocal_return (0),
188 locations (), chain (NULL)
190 cycle.arc = NULL;
193 /* Describes a single line of source. Contains a chain of basic blocks
194 with code on it. */
196 class line_info
198 public:
199 /* Default constructor. */
200 line_info ();
202 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
203 bool has_block (block_info *needle);
205 /* Execution count. */
206 gcov_type count;
208 /* Branches from blocks that end on this line. */
209 vector<arc_info *> branches;
211 /* blocks which start on this line. Used in all-blocks mode. */
212 vector<block_info *> blocks;
214 unsigned exists : 1;
215 unsigned unexceptional : 1;
216 unsigned has_unexecuted_block : 1;
219 line_info::line_info (): count (0), branches (), blocks (), exists (false),
220 unexceptional (0), has_unexecuted_block (0)
224 bool
225 line_info::has_block (block_info *needle)
227 return std::find (blocks.begin (), blocks.end (), needle) != blocks.end ();
230 /* Output demangled function names. */
232 static int flag_demangled_names = 0;
234 /* Describes a single function. Contains an array of basic blocks. */
236 class function_info
238 public:
239 function_info ();
240 ~function_info ();
242 /* Return true when line N belongs to the function in source file SRC_IDX.
243 The line must be defined in body of the function, can't be inlined. */
244 bool group_line_p (unsigned n, unsigned src_idx);
246 /* Function filter based on function_info::artificial variable. */
248 static inline bool
249 is_artificial (function_info *fn)
251 return fn->artificial;
254 /* Name of function. */
255 char *m_name;
256 char *m_demangled_name;
257 unsigned ident;
258 unsigned lineno_checksum;
259 unsigned cfg_checksum;
261 /* The graph contains at least one fake incoming edge. */
262 unsigned has_catch : 1;
264 /* True when the function is artificial and does not exist
265 in a source file. */
266 unsigned artificial : 1;
268 /* True when multiple functions start at a line in a source file. */
269 unsigned is_group : 1;
271 /* Array of basic blocks. Like in GCC, the entry block is
272 at blocks[0] and the exit block is at blocks[1]. */
273 #define ENTRY_BLOCK (0)
274 #define EXIT_BLOCK (1)
275 vector<block_info> blocks;
276 unsigned blocks_executed;
278 /* Raw arc coverage counts. */
279 vector<gcov_type> counts;
281 /* First line number. */
282 unsigned start_line;
284 /* First line column. */
285 unsigned start_column;
287 /* Last line number. */
288 unsigned end_line;
290 /* Last line column. */
291 unsigned end_column;
293 /* Index of source file where the function is defined. */
294 unsigned src;
296 /* Vector of line information. */
297 vector<line_info> lines;
299 /* Next function. */
300 class function_info *next;
302 /* Get demangled name of a function. The demangled name
303 is converted when it is used for the first time. */
304 char *get_demangled_name ()
306 if (m_demangled_name == NULL)
308 m_demangled_name = cplus_demangle (m_name, DMGL_PARAMS);
309 if (!m_demangled_name)
310 m_demangled_name = m_name;
313 return m_demangled_name;
316 /* Get name of the function based on flag_demangled_names. */
317 char *get_name ()
319 return flag_demangled_names ? get_demangled_name () : m_name;
322 /* Return number of basic blocks (without entry and exit block). */
323 unsigned get_block_count ()
325 return blocks.size () - 2;
329 /* Function info comparer that will sort functions according to starting
330 line. */
332 struct function_line_start_cmp
334 inline bool operator() (const function_info *lhs,
335 const function_info *rhs)
337 return (lhs->start_line == rhs->start_line
338 ? lhs->start_column < rhs->start_column
339 : lhs->start_line < rhs->start_line);
343 /* Describes coverage of a file or function. */
345 struct coverage_info
347 int lines;
348 int lines_executed;
350 int branches;
351 int branches_executed;
352 int branches_taken;
354 int calls;
355 int calls_executed;
357 char *name;
360 /* Describes a file mentioned in the block graph. Contains an array
361 of line info. */
363 class source_info
365 public:
366 /* Default constructor. */
367 source_info ();
369 vector<function_info *> *get_functions_at_location (unsigned line_num) const;
371 /* Register a new function. */
372 void add_function (function_info *fn);
374 /* Index of the source_info in sources vector. */
375 unsigned index;
377 /* Canonical name of source file. */
378 char *name;
379 time_t file_time;
381 /* Vector of line information. */
382 vector<line_info> lines;
384 coverage_info coverage;
386 /* Maximum line count in the source file. */
387 unsigned int maximum_count;
389 /* Functions in this source file. These are in ascending line
390 number order. */
391 vector<function_info *> functions;
393 /* Line number to functions map. */
394 vector<vector<function_info *> *> line_to_function_map;
397 source_info::source_info (): index (0), name (NULL), file_time (),
398 lines (), coverage (), maximum_count (0), functions ()
402 /* Register a new function. */
403 void
404 source_info::add_function (function_info *fn)
406 functions.push_back (fn);
408 if (fn->start_line >= line_to_function_map.size ())
409 line_to_function_map.resize (fn->start_line + 1);
411 vector<function_info *> **slot = &line_to_function_map[fn->start_line];
412 if (*slot == NULL)
413 *slot = new vector<function_info *> ();
415 (*slot)->push_back (fn);
418 vector<function_info *> *
419 source_info::get_functions_at_location (unsigned line_num) const
421 if (line_num >= line_to_function_map.size ())
422 return NULL;
424 vector<function_info *> *slot = line_to_function_map[line_num];
425 if (slot != NULL)
426 std::sort (slot->begin (), slot->end (), function_line_start_cmp ());
428 return slot;
431 class name_map
433 public:
434 name_map ()
438 name_map (char *_name, unsigned _src): name (_name), src (_src)
442 bool operator== (const name_map &rhs) const
444 #if HAVE_DOS_BASED_FILE_SYSTEM
445 return strcasecmp (this->name, rhs.name) == 0;
446 #else
447 return strcmp (this->name, rhs.name) == 0;
448 #endif
451 bool operator< (const name_map &rhs) const
453 #if HAVE_DOS_BASED_FILE_SYSTEM
454 return strcasecmp (this->name, rhs.name) < 0;
455 #else
456 return strcmp (this->name, rhs.name) < 0;
457 #endif
460 const char *name; /* Source file name */
461 unsigned src; /* Source file */
464 /* Vector of all functions. */
465 static vector<function_info *> functions;
467 /* Function ident to function_info * map. */
468 static map<unsigned, function_info *> ident_to_fn;
470 /* Vector of source files. */
471 static vector<source_info> sources;
473 /* Mapping of file names to sources */
474 static vector<name_map> names;
476 /* Record all processed files in order to warn about
477 a file being read multiple times. */
478 static vector<char *> processed_files;
480 /* This holds data summary information. */
482 static unsigned object_runs;
484 static unsigned total_lines;
485 static unsigned total_executed;
487 /* Modification time of graph file. */
489 static time_t bbg_file_time;
491 /* Name of the notes (gcno) output file. The "bbg" prefix is for
492 historical reasons, when the notes file contained only the
493 basic block graph notes. */
495 static char *bbg_file_name;
497 /* Stamp of the bbg file */
498 static unsigned bbg_stamp;
500 /* Supports has_unexecuted_blocks functionality. */
501 static unsigned bbg_supports_has_unexecuted_blocks;
503 /* Working directory in which a TU was compiled. */
504 static const char *bbg_cwd;
506 /* Name and file pointer of the input file for the count data (gcda). */
508 static char *da_file_name;
510 /* Data file is missing. */
512 static int no_data_file;
514 /* If there is several input files, compute and display results after
515 reading all data files. This way if two or more gcda file refer to
516 the same source file (eg inline subprograms in a .h file), the
517 counts are added. */
519 static int multiple_files = 0;
521 /* Output branch probabilities. */
523 static int flag_branches = 0;
525 /* Show unconditional branches too. */
526 static int flag_unconditional = 0;
528 /* Output a gcov file if this is true. This is on by default, and can
529 be turned off by the -n option. */
531 static int flag_gcov_file = 1;
533 /* Output to stdout instead to a gcov file. */
535 static int flag_use_stdout = 0;
537 /* Output progress indication if this is true. This is off by default
538 and can be turned on by the -d option. */
540 static int flag_display_progress = 0;
542 /* Output *.gcov file in JSON intermediate format used by consumers. */
544 static int flag_json_format = 0;
546 /* For included files, make the gcov output file name include the name
547 of the input source file. For example, if x.h is included in a.c,
548 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
550 static int flag_long_names = 0;
552 /* For situations when a long name can potentially hit filesystem path limit,
553 let's calculate md5sum of the path and append it to a file name. */
555 static int flag_hash_filenames = 0;
557 /* Print verbose informations. */
559 static int flag_verbose = 0;
561 /* Print colored output. */
563 static int flag_use_colors = 0;
565 /* Use perf-like colors to indicate hot lines. */
567 static int flag_use_hotness_colors = 0;
569 /* Output count information for every basic block, not merely those
570 that contain line number information. */
572 static int flag_all_blocks = 0;
574 /* Output human readable numbers. */
576 static int flag_human_readable_numbers = 0;
578 /* Output summary info for each function. */
580 static int flag_function_summary = 0;
582 /* Object directory file prefix. This is the directory/file where the
583 graph and data files are looked for, if nonzero. */
585 static char *object_directory = 0;
587 /* Source directory prefix. This is removed from source pathnames
588 that match, when generating the output file name. */
590 static char *source_prefix = 0;
591 static size_t source_length = 0;
593 /* Only show data for sources with relative pathnames. Absolute ones
594 usually indicate a system header file, which although it may
595 contain inline functions, is usually uninteresting. */
596 static int flag_relative_only = 0;
598 /* Preserve all pathname components. Needed when object files and
599 source files are in subdirectories. '/' is mangled as '#', '.' is
600 elided and '..' mangled to '^'. */
602 static int flag_preserve_paths = 0;
604 /* Output the number of times a branch was taken as opposed to the percentage
605 of times it was taken. */
607 static int flag_counts = 0;
609 /* Forward declarations. */
610 static int process_args (int, char **);
611 static void print_usage (int) ATTRIBUTE_NORETURN;
612 static void print_version (void) ATTRIBUTE_NORETURN;
613 static void process_file (const char *);
614 static void process_all_functions (void);
615 static void generate_results (const char *);
616 static void create_file_names (const char *);
617 static char *canonicalize_name (const char *);
618 static unsigned find_source (const char *);
619 static void read_graph_file (void);
620 static int read_count_file (void);
621 static void solve_flow_graph (function_info *);
622 static void find_exception_blocks (function_info *);
623 static void add_branch_counts (coverage_info *, const arc_info *);
624 static void add_line_counts (coverage_info *, function_info *);
625 static void executed_summary (unsigned, unsigned);
626 static void function_summary (const coverage_info *);
627 static void file_summary (const coverage_info *);
628 static const char *format_gcov (gcov_type, gcov_type, int);
629 static void accumulate_line_counts (source_info *);
630 static void output_gcov_file (const char *, source_info *);
631 static int output_branch_count (FILE *, int, const arc_info *);
632 static void output_lines (FILE *, const source_info *);
633 static char *make_gcov_file_name (const char *, const char *);
634 static char *mangle_name (const char *, char *);
635 static void release_structures (void);
636 extern int main (int, char **);
638 function_info::function_info (): m_name (NULL), m_demangled_name (NULL),
639 ident (0), lineno_checksum (0), cfg_checksum (0), has_catch (0),
640 artificial (0), is_group (0),
641 blocks (), blocks_executed (0), counts (),
642 start_line (0), start_column (0), end_line (0), end_column (0),
643 src (0), lines (), next (NULL)
647 function_info::~function_info ()
649 for (int i = blocks.size () - 1; i >= 0; i--)
651 arc_info *arc, *arc_n;
653 for (arc = blocks[i].succ; arc; arc = arc_n)
655 arc_n = arc->succ_next;
656 free (arc);
659 if (m_demangled_name != m_name)
660 free (m_demangled_name);
661 free (m_name);
664 bool function_info::group_line_p (unsigned n, unsigned src_idx)
666 return is_group && src == src_idx && start_line <= n && n <= end_line;
669 /* Cycle detection!
670 There are a bajillion algorithms that do this. Boost's function is named
671 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
672 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
673 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
675 The basic algorithm is simple: effectively, we're finding all simple paths
676 in a subgraph (that shrinks every iteration). Duplicates are filtered by
677 "blocking" a path when a node is added to the path (this also prevents non-
678 simple paths)--the node is unblocked only when it participates in a cycle.
681 typedef vector<arc_info *> arc_vector_t;
682 typedef vector<const block_info *> block_vector_t;
684 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
685 and subtract the value from all counts. The subtracted value is added
686 to COUNT. Returns type of loop. */
688 static void
689 handle_cycle (const arc_vector_t &edges, int64_t &count)
691 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
692 that amount. */
693 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
694 for (unsigned i = 0; i < edges.size (); i++)
696 int64_t ecount = edges[i]->cs_count;
697 if (cycle_count > ecount)
698 cycle_count = ecount;
700 count += cycle_count;
701 for (unsigned i = 0; i < edges.size (); i++)
702 edges[i]->cs_count -= cycle_count;
704 gcc_assert (cycle_count > 0);
707 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
708 blocked by U in BLOCK_LISTS. */
710 static void
711 unblock (const block_info *u, block_vector_t &blocked,
712 vector<block_vector_t > &block_lists)
714 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
715 if (it == blocked.end ())
716 return;
718 unsigned index = it - blocked.begin ();
719 blocked.erase (it);
721 block_vector_t to_unblock (block_lists[index]);
723 block_lists.erase (block_lists.begin () + index);
725 for (block_vector_t::iterator it = to_unblock.begin ();
726 it != to_unblock.end (); it++)
727 unblock (*it, blocked, block_lists);
730 /* Return true when PATH contains a zero cycle arc count. */
732 static bool
733 path_contains_zero_or_negative_cycle_arc (arc_vector_t &path)
735 for (unsigned i = 0; i < path.size (); i++)
736 if (path[i]->cs_count <= 0)
737 return true;
738 return false;
741 /* Find circuit going to block V, PATH is provisional seen cycle.
742 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
743 blocked by a block. COUNT is accumulated count of the current LINE.
744 Returns what type of loop it contains. */
746 static bool
747 circuit (block_info *v, arc_vector_t &path, block_info *start,
748 block_vector_t &blocked, vector<block_vector_t> &block_lists,
749 line_info &linfo, int64_t &count)
751 bool loop_found = false;
753 /* Add v to the block list. */
754 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
755 blocked.push_back (v);
756 block_lists.push_back (block_vector_t ());
758 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
760 block_info *w = arc->dst;
761 if (w < start
762 || arc->cs_count <= 0
763 || !linfo.has_block (w))
764 continue;
766 path.push_back (arc);
767 if (w == start)
769 /* Cycle has been found. */
770 handle_cycle (path, count);
771 loop_found = true;
773 else if (!path_contains_zero_or_negative_cycle_arc (path)
774 && find (blocked.begin (), blocked.end (), w) == blocked.end ())
775 loop_found |= circuit (w, path, start, blocked, block_lists, linfo,
776 count);
778 path.pop_back ();
781 if (loop_found)
782 unblock (v, blocked, block_lists);
783 else
784 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
786 block_info *w = arc->dst;
787 if (w < start
788 || arc->cs_count <= 0
789 || !linfo.has_block (w))
790 continue;
792 size_t index
793 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
794 gcc_assert (index < blocked.size ());
795 block_vector_t &list = block_lists[index];
796 if (find (list.begin (), list.end (), v) == list.end ())
797 list.push_back (v);
800 return loop_found;
803 /* Find cycles for a LINFO. */
805 static gcov_type
806 get_cycles_count (line_info &linfo)
808 /* Note that this algorithm works even if blocks aren't in sorted order.
809 Each iteration of the circuit detection is completely independent
810 (except for reducing counts, but that shouldn't matter anyways).
811 Therefore, operating on a permuted order (i.e., non-sorted) only
812 has the effect of permuting the output cycles. */
814 bool loop_found = false;
815 gcov_type count = 0;
816 for (vector<block_info *>::iterator it = linfo.blocks.begin ();
817 it != linfo.blocks.end (); it++)
819 arc_vector_t path;
820 block_vector_t blocked;
821 vector<block_vector_t > block_lists;
822 loop_found |= circuit (*it, path, *it, blocked, block_lists, linfo,
823 count);
826 return count;
830 main (int argc, char **argv)
832 int argno;
833 int first_arg;
834 const char *p;
836 p = argv[0] + strlen (argv[0]);
837 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
838 --p;
839 progname = p;
841 xmalloc_set_program_name (progname);
843 /* Unlock the stdio streams. */
844 unlock_std_streams ();
846 gcc_init_libintl ();
848 diagnostic_initialize (global_dc, 0);
850 /* Handle response files. */
851 expandargv (&argc, &argv);
853 argno = process_args (argc, argv);
854 if (optind == argc)
855 print_usage (true);
857 if (argc - argno > 1)
858 multiple_files = 1;
860 first_arg = argno;
862 for (; argno != argc; argno++)
864 if (flag_display_progress)
865 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
866 argc - first_arg);
867 process_file (argv[argno]);
869 if (flag_json_format || argno == argc - 1)
871 process_all_functions ();
872 generate_results (argv[argno]);
873 release_structures ();
877 return 0;
880 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
881 otherwise the output of --help. */
883 static void
884 print_usage (int error_p)
886 FILE *file = error_p ? stderr : stdout;
887 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
889 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
890 fnotice (file, "Print code coverage information.\n\n");
891 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
892 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
893 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
894 rather than percentages\n");
895 fnotice (file, " -d, --display-progress Display progress information\n");
896 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
897 fnotice (file, " -h, --help Print this help, then exit\n");
898 fnotice (file, " -i, --json-format Output JSON intermediate format into .gcov.json.gz file\n");
899 fnotice (file, " -j, --human-readable Output human readable numbers\n");
900 fnotice (file, " -k, --use-colors Emit colored output\n");
901 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
902 source files\n");
903 fnotice (file, " -m, --demangled-names Output demangled function names\n");
904 fnotice (file, " -n, --no-output Do not create an output file\n");
905 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
906 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
907 fnotice (file, " -q, --use-hotness-colors Emit perf-like colored output for hot lines\n");
908 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
909 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
910 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
911 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
912 fnotice (file, " -v, --version Print version number, then exit\n");
913 fnotice (file, " -w, --verbose Print verbose informations\n");
914 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
915 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
916 bug_report_url);
917 exit (status);
920 /* Print version information and exit. */
922 static void
923 print_version (void)
925 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
926 fprintf (stdout, "Copyright %s 2019 Free Software Foundation, Inc.\n",
927 _("(C)"));
928 fnotice (stdout,
929 _("This is free software; see the source for copying conditions.\n"
930 "There is NO warranty; not even for MERCHANTABILITY or \n"
931 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
932 exit (SUCCESS_EXIT_CODE);
935 static const struct option options[] =
937 { "help", no_argument, NULL, 'h' },
938 { "version", no_argument, NULL, 'v' },
939 { "verbose", no_argument, NULL, 'w' },
940 { "all-blocks", no_argument, NULL, 'a' },
941 { "branch-probabilities", no_argument, NULL, 'b' },
942 { "branch-counts", no_argument, NULL, 'c' },
943 { "json-format", no_argument, NULL, 'i' },
944 { "human-readable", no_argument, NULL, 'j' },
945 { "no-output", no_argument, NULL, 'n' },
946 { "long-file-names", no_argument, NULL, 'l' },
947 { "function-summaries", no_argument, NULL, 'f' },
948 { "demangled-names", no_argument, NULL, 'm' },
949 { "preserve-paths", no_argument, NULL, 'p' },
950 { "relative-only", no_argument, NULL, 'r' },
951 { "object-directory", required_argument, NULL, 'o' },
952 { "object-file", required_argument, NULL, 'o' },
953 { "source-prefix", required_argument, NULL, 's' },
954 { "stdout", no_argument, NULL, 't' },
955 { "unconditional-branches", no_argument, NULL, 'u' },
956 { "display-progress", no_argument, NULL, 'd' },
957 { "hash-filenames", no_argument, NULL, 'x' },
958 { "use-colors", no_argument, NULL, 'k' },
959 { "use-hotness-colors", no_argument, NULL, 'q' },
960 { 0, 0, 0, 0 }
963 /* Process args, return index to first non-arg. */
965 static int
966 process_args (int argc, char **argv)
968 int opt;
970 const char *opts = "abcdfhijklmno:pqrs:tuvwx";
971 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
973 switch (opt)
975 case 'a':
976 flag_all_blocks = 1;
977 break;
978 case 'b':
979 flag_branches = 1;
980 break;
981 case 'c':
982 flag_counts = 1;
983 break;
984 case 'f':
985 flag_function_summary = 1;
986 break;
987 case 'h':
988 print_usage (false);
989 /* print_usage will exit. */
990 case 'l':
991 flag_long_names = 1;
992 break;
993 case 'j':
994 flag_human_readable_numbers = 1;
995 break;
996 case 'k':
997 flag_use_colors = 1;
998 break;
999 case 'q':
1000 flag_use_hotness_colors = 1;
1001 break;
1002 case 'm':
1003 flag_demangled_names = 1;
1004 break;
1005 case 'n':
1006 flag_gcov_file = 0;
1007 break;
1008 case 'o':
1009 object_directory = optarg;
1010 break;
1011 case 's':
1012 source_prefix = optarg;
1013 source_length = strlen (source_prefix);
1014 break;
1015 case 'r':
1016 flag_relative_only = 1;
1017 break;
1018 case 'p':
1019 flag_preserve_paths = 1;
1020 break;
1021 case 'u':
1022 flag_unconditional = 1;
1023 break;
1024 case 'i':
1025 flag_json_format = 1;
1026 flag_gcov_file = 1;
1027 break;
1028 case 'd':
1029 flag_display_progress = 1;
1030 break;
1031 case 'x':
1032 flag_hash_filenames = 1;
1033 break;
1034 case 'w':
1035 flag_verbose = 1;
1036 break;
1037 case 't':
1038 flag_use_stdout = 1;
1039 break;
1040 case 'v':
1041 print_version ();
1042 /* print_version will exit. */
1043 default:
1044 print_usage (true);
1045 /* print_usage will exit. */
1049 return optind;
1052 /* Output intermediate LINE sitting on LINE_NUM to JSON OBJECT.
1053 Add FUNCTION_NAME to the LINE. */
1055 static void
1056 output_intermediate_json_line (json::array *object,
1057 line_info *line, unsigned line_num,
1058 const char *function_name)
1060 if (!line->exists)
1061 return;
1063 json::object *lineo = new json::object ();
1064 lineo->set ("line_number", new json::integer_number (line_num));
1065 if (function_name != NULL)
1066 lineo->set ("function_name", new json::string (function_name));
1067 lineo->set ("count", new json::integer_number (line->count));
1068 lineo->set ("unexecuted_block",
1069 new json::literal (line->has_unexecuted_block));
1071 json::array *branches = new json::array ();
1072 lineo->set ("branches", branches);
1074 vector<arc_info *>::const_iterator it;
1075 if (flag_branches)
1076 for (it = line->branches.begin (); it != line->branches.end ();
1077 it++)
1079 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1081 json::object *branch = new json::object ();
1082 branch->set ("count", new json::integer_number ((*it)->count));
1083 branch->set ("throw", new json::literal ((*it)->is_throw));
1084 branch->set ("fallthrough",
1085 new json::literal ((*it)->fall_through));
1086 branches->append (branch);
1090 object->append (lineo);
1093 /* Get the name of the gcov file. The return value must be free'd.
1095 It appends the '.gcov' extension to the *basename* of the file.
1096 The resulting file name will be in PWD.
1098 e.g.,
1099 input: foo.da, output: foo.da.gcov
1100 input: a/b/foo.cc, output: foo.cc.gcov */
1102 static char *
1103 get_gcov_intermediate_filename (const char *file_name)
1105 const char *gcov = ".gcov.json.gz";
1106 char *result;
1107 const char *cptr;
1109 /* Find the 'basename'. */
1110 cptr = lbasename (file_name);
1112 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1113 sprintf (result, "%s%s", cptr, gcov);
1115 return result;
1118 /* Output the result in JSON intermediate format.
1119 Source info SRC is dumped into JSON_FILES which is JSON array. */
1121 static void
1122 output_json_intermediate_file (json::array *json_files, source_info *src)
1124 json::object *root = new json::object ();
1125 json_files->append (root);
1127 root->set ("file", new json::string (src->name));
1129 json::array *functions = new json::array ();
1130 root->set ("functions", functions);
1132 std::sort (src->functions.begin (), src->functions.end (),
1133 function_line_start_cmp ());
1134 for (vector<function_info *>::iterator it = src->functions.begin ();
1135 it != src->functions.end (); it++)
1137 json::object *function = new json::object ();
1138 function->set ("name", new json::string ((*it)->m_name));
1139 function->set ("demangled_name",
1140 new json::string ((*it)->get_demangled_name ()));
1141 function->set ("start_line",
1142 new json::integer_number ((*it)->start_line));
1143 function->set ("start_column",
1144 new json::integer_number ((*it)->start_column));
1145 function->set ("end_line", new json::integer_number ((*it)->end_line));
1146 function->set ("end_column",
1147 new json::integer_number ((*it)->end_column));
1148 function->set ("blocks",
1149 new json::integer_number ((*it)->get_block_count ()));
1150 function->set ("blocks_executed",
1151 new json::integer_number ((*it)->blocks_executed));
1152 function->set ("execution_count",
1153 new json::integer_number ((*it)->blocks[0].count));
1155 functions->append (function);
1158 json::array *lineso = new json::array ();
1159 root->set ("lines", lineso);
1161 function_info *last_non_group_fn = NULL;
1163 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1165 vector<function_info *> *fns = src->get_functions_at_location (line_num);
1167 if (fns != NULL)
1168 /* Print first group functions that begin on the line. */
1169 for (vector<function_info *>::iterator it2 = fns->begin ();
1170 it2 != fns->end (); it2++)
1172 if (!(*it2)->is_group)
1173 last_non_group_fn = *it2;
1175 vector<line_info> &lines = (*it2)->lines;
1176 for (unsigned i = 0; i < lines.size (); i++)
1178 line_info *line = &lines[i];
1179 output_intermediate_json_line (lineso, line, line_num + i,
1180 (*it2)->m_name);
1184 /* Follow with lines associated with the source file. */
1185 if (line_num < src->lines.size ())
1186 output_intermediate_json_line (lineso, &src->lines[line_num], line_num,
1187 (last_non_group_fn != NULL
1188 ? last_non_group_fn->m_name : NULL));
1192 /* Function start pair. */
1193 struct function_start
1195 unsigned source_file_idx;
1196 unsigned start_line;
1199 /* Traits class for function start hash maps below. */
1201 struct function_start_pair_hash : typed_noop_remove <function_start>
1203 typedef function_start value_type;
1204 typedef function_start compare_type;
1206 static hashval_t
1207 hash (const function_start &ref)
1209 inchash::hash hstate (0);
1210 hstate.add_int (ref.source_file_idx);
1211 hstate.add_int (ref.start_line);
1212 return hstate.end ();
1215 static bool
1216 equal (const function_start &ref1, const function_start &ref2)
1218 return (ref1.source_file_idx == ref2.source_file_idx
1219 && ref1.start_line == ref2.start_line);
1222 static void
1223 mark_deleted (function_start &ref)
1225 ref.start_line = ~1U;
1228 static void
1229 mark_empty (function_start &ref)
1231 ref.start_line = ~2U;
1234 static bool
1235 is_deleted (const function_start &ref)
1237 return ref.start_line == ~1U;
1240 static bool
1241 is_empty (const function_start &ref)
1243 return ref.start_line == ~2U;
1247 /* Process a single input file. */
1249 static void
1250 process_file (const char *file_name)
1252 create_file_names (file_name);
1254 for (unsigned i = 0; i < processed_files.size (); i++)
1255 if (strcmp (da_file_name, processed_files[i]) == 0)
1257 fnotice (stderr, "'%s' file is already processed\n",
1258 file_name);
1259 return;
1262 processed_files.push_back (xstrdup (da_file_name));
1264 read_graph_file ();
1265 read_count_file ();
1268 /* Process all functions in all files. */
1270 static void
1271 process_all_functions (void)
1273 hash_map<function_start_pair_hash, function_info *> fn_map;
1275 /* Identify group functions. */
1276 for (vector<function_info *>::iterator it = functions.begin ();
1277 it != functions.end (); it++)
1278 if (!(*it)->artificial)
1280 function_start needle;
1281 needle.source_file_idx = (*it)->src;
1282 needle.start_line = (*it)->start_line;
1284 function_info **slot = fn_map.get (needle);
1285 if (slot)
1287 (*slot)->is_group = 1;
1288 (*it)->is_group = 1;
1290 else
1291 fn_map.put (needle, *it);
1294 /* Remove all artificial function. */
1295 functions.erase (remove_if (functions.begin (), functions.end (),
1296 function_info::is_artificial), functions.end ());
1298 for (vector<function_info *>::iterator it = functions.begin ();
1299 it != functions.end (); it++)
1301 function_info *fn = *it;
1302 unsigned src = fn->src;
1304 if (!fn->counts.empty () || no_data_file)
1306 source_info *s = &sources[src];
1307 s->add_function (fn);
1309 /* Mark last line in files touched by function. */
1310 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1311 block_no++)
1313 block_info *block = &fn->blocks[block_no];
1314 for (unsigned i = 0; i < block->locations.size (); i++)
1316 /* Sort lines of locations. */
1317 sort (block->locations[i].lines.begin (),
1318 block->locations[i].lines.end ());
1320 if (!block->locations[i].lines.empty ())
1322 s = &sources[block->locations[i].source_file_idx];
1323 unsigned last_line
1324 = block->locations[i].lines.back ();
1326 /* Record new lines for the function. */
1327 if (last_line >= s->lines.size ())
1329 s = &sources[block->locations[i].source_file_idx];
1330 unsigned last_line
1331 = block->locations[i].lines.back ();
1333 /* Record new lines for the function. */
1334 if (last_line >= s->lines.size ())
1336 /* Record new lines for a source file. */
1337 s->lines.resize (last_line + 1);
1344 /* Allocate lines for group function, following start_line
1345 and end_line information of the function. */
1346 if (fn->is_group)
1347 fn->lines.resize (fn->end_line - fn->start_line + 1);
1349 solve_flow_graph (fn);
1350 if (fn->has_catch)
1351 find_exception_blocks (fn);
1353 else
1355 /* The function was not in the executable -- some other
1356 instance must have been selected. */
1361 static void
1362 output_gcov_file (const char *file_name, source_info *src)
1364 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1366 if (src->coverage.lines)
1368 FILE *gcov_file = fopen (gcov_file_name, "w");
1369 if (gcov_file)
1371 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1372 output_lines (gcov_file, src);
1373 if (ferror (gcov_file))
1374 fnotice (stderr, "Error writing output file '%s'\n",
1375 gcov_file_name);
1376 fclose (gcov_file);
1378 else
1379 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1381 else
1383 unlink (gcov_file_name);
1384 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1386 free (gcov_file_name);
1389 static void
1390 generate_results (const char *file_name)
1392 char *gcov_intermediate_filename;
1394 for (vector<function_info *>::iterator it = functions.begin ();
1395 it != functions.end (); it++)
1397 function_info *fn = *it;
1398 coverage_info coverage;
1400 memset (&coverage, 0, sizeof (coverage));
1401 coverage.name = fn->get_name ();
1402 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1403 if (flag_function_summary)
1405 function_summary (&coverage);
1406 fnotice (stdout, "\n");
1410 name_map needle;
1412 if (file_name)
1414 needle.name = file_name;
1415 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1416 needle);
1417 if (it != names.end ())
1418 file_name = sources[it->src].coverage.name;
1419 else
1420 file_name = canonicalize_name (file_name);
1423 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1425 json::object *root = new json::object ();
1426 root->set ("format_version", new json::string ("1"));
1427 root->set ("gcc_version", new json::string (version_string));
1429 if (bbg_cwd != NULL)
1430 root->set ("current_working_directory", new json::string (bbg_cwd));
1431 root->set ("data_file", new json::string (file_name));
1433 json::array *json_files = new json::array ();
1434 root->set ("files", json_files);
1436 for (vector<source_info>::iterator it = sources.begin ();
1437 it != sources.end (); it++)
1439 source_info *src = &(*it);
1440 if (flag_relative_only)
1442 /* Ignore this source, if it is an absolute path (after
1443 source prefix removal). */
1444 char first = src->coverage.name[0];
1446 #if HAVE_DOS_BASED_FILE_SYSTEM
1447 if (first && src->coverage.name[1] == ':')
1448 first = src->coverage.name[2];
1449 #endif
1450 if (IS_DIR_SEPARATOR (first))
1451 continue;
1454 accumulate_line_counts (src);
1456 if (!flag_use_stdout)
1457 file_summary (&src->coverage);
1458 total_lines += src->coverage.lines;
1459 total_executed += src->coverage.lines_executed;
1460 if (flag_gcov_file)
1462 if (flag_json_format)
1463 output_json_intermediate_file (json_files, src);
1464 else
1466 if (flag_use_stdout)
1468 if (src->coverage.lines)
1469 output_lines (stdout, src);
1471 else
1473 output_gcov_file (file_name, src);
1474 fnotice (stdout, "\n");
1480 if (flag_gcov_file && flag_json_format)
1482 if (flag_use_stdout)
1484 root->dump (stdout);
1485 printf ("\n");
1487 else
1489 pretty_printer pp;
1490 root->print (&pp);
1491 pp_formatted_text (&pp);
1493 gzFile output = gzopen (gcov_intermediate_filename, "w");
1494 if (output == NULL)
1496 fnotice (stderr, "Cannot open JSON output file %s\n",
1497 gcov_intermediate_filename);
1498 return;
1501 if (gzputs (output, pp_formatted_text (&pp)) == EOF
1502 || gzclose (output))
1504 fnotice (stderr, "Error writing JSON output file %s\n",
1505 gcov_intermediate_filename);
1506 return;
1511 if (!file_name)
1512 executed_summary (total_lines, total_executed);
1515 /* Release all memory used. */
1517 static void
1518 release_structures (void)
1520 for (vector<function_info *>::iterator it = functions.begin ();
1521 it != functions.end (); it++)
1522 delete (*it);
1524 sources.resize (0);
1525 names.resize (0);
1526 functions.resize (0);
1527 ident_to_fn.clear ();
1530 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1531 is not specified, these are named from FILE_NAME sans extension. If
1532 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1533 directory, but named from the basename of the FILE_NAME, sans extension.
1534 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1535 and the data files are named from that. */
1537 static void
1538 create_file_names (const char *file_name)
1540 char *cptr;
1541 char *name;
1542 int length = strlen (file_name);
1543 int base;
1545 /* Free previous file names. */
1546 free (bbg_file_name);
1547 free (da_file_name);
1548 da_file_name = bbg_file_name = NULL;
1549 bbg_file_time = 0;
1550 bbg_stamp = 0;
1552 if (object_directory && object_directory[0])
1554 struct stat status;
1556 length += strlen (object_directory) + 2;
1557 name = XNEWVEC (char, length);
1558 name[0] = 0;
1560 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1561 strcat (name, object_directory);
1562 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1563 strcat (name, "/");
1565 else
1567 name = XNEWVEC (char, length + 1);
1568 strcpy (name, file_name);
1569 base = 0;
1572 if (base)
1574 /* Append source file name. */
1575 const char *cptr = lbasename (file_name);
1576 strcat (name, cptr ? cptr : file_name);
1579 /* Remove the extension. */
1580 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1581 if (cptr)
1582 *cptr = 0;
1584 length = strlen (name);
1586 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1587 strcpy (bbg_file_name, name);
1588 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1590 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1591 strcpy (da_file_name, name);
1592 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1594 free (name);
1595 return;
1598 /* Find or create a source file structure for FILE_NAME. Copies
1599 FILE_NAME on creation */
1601 static unsigned
1602 find_source (const char *file_name)
1604 char *canon;
1605 unsigned idx;
1606 struct stat status;
1608 if (!file_name)
1609 file_name = "<unknown>";
1611 name_map needle;
1612 needle.name = file_name;
1614 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1615 needle);
1616 if (it != names.end ())
1618 idx = it->src;
1619 goto check_date;
1622 /* Not found, try the canonical name. */
1623 canon = canonicalize_name (file_name);
1624 needle.name = canon;
1625 it = std::find (names.begin (), names.end (), needle);
1626 if (it == names.end ())
1628 /* Not found with canonical name, create a new source. */
1629 source_info *src;
1631 idx = sources.size ();
1632 needle = name_map (canon, idx);
1633 names.push_back (needle);
1635 sources.push_back (source_info ());
1636 src = &sources.back ();
1637 src->name = canon;
1638 src->coverage.name = src->name;
1639 src->index = idx;
1640 if (source_length
1641 #if HAVE_DOS_BASED_FILE_SYSTEM
1642 /* You lose if separators don't match exactly in the
1643 prefix. */
1644 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1645 #else
1646 && !strncmp (source_prefix, src->coverage.name, source_length)
1647 #endif
1648 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1649 src->coverage.name += source_length + 1;
1650 if (!stat (src->name, &status))
1651 src->file_time = status.st_mtime;
1653 else
1654 idx = it->src;
1656 needle.name = file_name;
1657 if (std::find (names.begin (), names.end (), needle) == names.end ())
1659 /* Append the non-canonical name. */
1660 names.push_back (name_map (xstrdup (file_name), idx));
1663 /* Resort the name map. */
1664 std::sort (names.begin (), names.end ());
1666 check_date:
1667 if (sources[idx].file_time > bbg_file_time)
1669 static int info_emitted;
1671 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1672 file_name, bbg_file_name);
1673 if (!info_emitted)
1675 fnotice (stderr,
1676 "(the message is displayed only once per source file)\n");
1677 info_emitted = 1;
1679 sources[idx].file_time = 0;
1682 return idx;
1685 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1687 static void
1688 read_graph_file (void)
1690 unsigned version;
1691 unsigned current_tag = 0;
1692 unsigned tag;
1694 if (!gcov_open (bbg_file_name, 1))
1696 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1697 return;
1699 bbg_file_time = gcov_time ();
1700 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1702 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1703 gcov_close ();
1704 return;
1707 version = gcov_read_unsigned ();
1708 if (version != GCOV_VERSION)
1710 char v[4], e[4];
1712 GCOV_UNSIGNED2STRING (v, version);
1713 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1715 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1716 bbg_file_name, v, e);
1718 bbg_stamp = gcov_read_unsigned ();
1719 bbg_cwd = xstrdup (gcov_read_string ());
1720 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1722 function_info *fn = NULL;
1723 while ((tag = gcov_read_unsigned ()))
1725 unsigned length = gcov_read_unsigned ();
1726 gcov_position_t base = gcov_position ();
1728 if (tag == GCOV_TAG_FUNCTION)
1730 char *function_name;
1731 unsigned ident;
1732 unsigned lineno_checksum, cfg_checksum;
1734 ident = gcov_read_unsigned ();
1735 lineno_checksum = gcov_read_unsigned ();
1736 cfg_checksum = gcov_read_unsigned ();
1737 function_name = xstrdup (gcov_read_string ());
1738 unsigned artificial = gcov_read_unsigned ();
1739 unsigned src_idx = find_source (gcov_read_string ());
1740 unsigned start_line = gcov_read_unsigned ();
1741 unsigned start_column = gcov_read_unsigned ();
1742 unsigned end_line = gcov_read_unsigned ();
1743 unsigned end_column = gcov_read_unsigned ();
1745 fn = new function_info ();
1746 functions.push_back (fn);
1747 ident_to_fn[ident] = fn;
1749 fn->m_name = function_name;
1750 fn->ident = ident;
1751 fn->lineno_checksum = lineno_checksum;
1752 fn->cfg_checksum = cfg_checksum;
1753 fn->src = src_idx;
1754 fn->start_line = start_line;
1755 fn->start_column = start_column;
1756 fn->end_line = end_line;
1757 fn->end_column = end_column;
1758 fn->artificial = artificial;
1760 current_tag = tag;
1762 else if (fn && tag == GCOV_TAG_BLOCKS)
1764 if (!fn->blocks.empty ())
1765 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1766 bbg_file_name, fn->get_name ());
1767 else
1768 fn->blocks.resize (gcov_read_unsigned ());
1770 else if (fn && tag == GCOV_TAG_ARCS)
1772 unsigned src = gcov_read_unsigned ();
1773 fn->blocks[src].id = src;
1774 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1775 block_info *src_blk = &fn->blocks[src];
1776 unsigned mark_catches = 0;
1777 struct arc_info *arc;
1779 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1780 goto corrupt;
1782 while (num_dests--)
1784 unsigned dest = gcov_read_unsigned ();
1785 unsigned flags = gcov_read_unsigned ();
1787 if (dest >= fn->blocks.size ())
1788 goto corrupt;
1789 arc = XCNEW (arc_info);
1791 arc->dst = &fn->blocks[dest];
1792 arc->src = src_blk;
1794 arc->count = 0;
1795 arc->count_valid = 0;
1796 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1797 arc->fake = !!(flags & GCOV_ARC_FAKE);
1798 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1800 arc->succ_next = src_blk->succ;
1801 src_blk->succ = arc;
1802 src_blk->num_succ++;
1804 arc->pred_next = fn->blocks[dest].pred;
1805 fn->blocks[dest].pred = arc;
1806 fn->blocks[dest].num_pred++;
1808 if (arc->fake)
1810 if (src)
1812 /* Exceptional exit from this function, the
1813 source block must be a call. */
1814 fn->blocks[src].is_call_site = 1;
1815 arc->is_call_non_return = 1;
1816 mark_catches = 1;
1818 else
1820 /* Non-local return from a callee of this
1821 function. The destination block is a setjmp. */
1822 arc->is_nonlocal_return = 1;
1823 fn->blocks[dest].is_nonlocal_return = 1;
1827 if (!arc->on_tree)
1828 fn->counts.push_back (0);
1831 if (mark_catches)
1833 /* We have a fake exit from this block. The other
1834 non-fall through exits must be to catch handlers.
1835 Mark them as catch arcs. */
1837 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1838 if (!arc->fake && !arc->fall_through)
1840 arc->is_throw = 1;
1841 fn->has_catch = 1;
1845 else if (fn && tag == GCOV_TAG_LINES)
1847 unsigned blockno = gcov_read_unsigned ();
1848 block_info *block = &fn->blocks[blockno];
1850 if (blockno >= fn->blocks.size ())
1851 goto corrupt;
1853 while (true)
1855 unsigned lineno = gcov_read_unsigned ();
1857 if (lineno)
1858 block->locations.back ().lines.push_back (lineno);
1859 else
1861 const char *file_name = gcov_read_string ();
1863 if (!file_name)
1864 break;
1865 block->locations.push_back (block_location_info
1866 (find_source (file_name)));
1870 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1872 fn = NULL;
1873 current_tag = 0;
1875 gcov_sync (base, length);
1876 if (gcov_is_error ())
1878 corrupt:;
1879 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1880 break;
1883 gcov_close ();
1885 if (functions.empty ())
1886 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1889 /* Reads profiles from the count file and attach to each
1890 function. Return nonzero if fatal error. */
1892 static int
1893 read_count_file (void)
1895 unsigned ix;
1896 unsigned version;
1897 unsigned tag;
1898 function_info *fn = NULL;
1899 int error = 0;
1900 map<unsigned, function_info *>::iterator it;
1902 if (!gcov_open (da_file_name, 1))
1904 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1905 da_file_name);
1906 no_data_file = 1;
1907 return 0;
1909 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1911 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1912 cleanup:;
1913 gcov_close ();
1914 return 1;
1916 version = gcov_read_unsigned ();
1917 if (version != GCOV_VERSION)
1919 char v[4], e[4];
1921 GCOV_UNSIGNED2STRING (v, version);
1922 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1924 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1925 da_file_name, v, e);
1927 tag = gcov_read_unsigned ();
1928 if (tag != bbg_stamp)
1930 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1931 goto cleanup;
1934 while ((tag = gcov_read_unsigned ()))
1936 unsigned length = gcov_read_unsigned ();
1937 unsigned long base = gcov_position ();
1939 if (tag == GCOV_TAG_OBJECT_SUMMARY)
1941 struct gcov_summary summary;
1942 gcov_read_summary (&summary);
1943 object_runs = summary.runs;
1945 else if (tag == GCOV_TAG_FUNCTION && !length)
1946 ; /* placeholder */
1947 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1949 unsigned ident;
1950 ident = gcov_read_unsigned ();
1951 fn = NULL;
1952 it = ident_to_fn.find (ident);
1953 if (it != ident_to_fn.end ())
1954 fn = it->second;
1956 if (!fn)
1958 else if (gcov_read_unsigned () != fn->lineno_checksum
1959 || gcov_read_unsigned () != fn->cfg_checksum)
1961 mismatch:;
1962 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1963 da_file_name, fn->get_name ());
1964 goto cleanup;
1967 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1969 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1970 goto mismatch;
1972 for (ix = 0; ix != fn->counts.size (); ix++)
1973 fn->counts[ix] += gcov_read_counter ();
1975 gcov_sync (base, length);
1976 if ((error = gcov_is_error ()))
1978 fnotice (stderr,
1979 error < 0
1980 ? N_("%s:overflowed\n")
1981 : N_("%s:corrupted\n"),
1982 da_file_name);
1983 goto cleanup;
1987 gcov_close ();
1988 return 0;
1991 /* Solve the flow graph. Propagate counts from the instrumented arcs
1992 to the blocks and the uninstrumented arcs. */
1994 static void
1995 solve_flow_graph (function_info *fn)
1997 unsigned ix;
1998 arc_info *arc;
1999 gcov_type *count_ptr = &fn->counts.front ();
2000 block_info *blk;
2001 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
2002 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
2004 /* The arcs were built in reverse order. Fix that now. */
2005 for (ix = fn->blocks.size (); ix--;)
2007 arc_info *arc_p, *arc_n;
2009 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
2010 arc_p = arc, arc = arc_n)
2012 arc_n = arc->succ_next;
2013 arc->succ_next = arc_p;
2015 fn->blocks[ix].succ = arc_p;
2017 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
2018 arc_p = arc, arc = arc_n)
2020 arc_n = arc->pred_next;
2021 arc->pred_next = arc_p;
2023 fn->blocks[ix].pred = arc_p;
2026 if (fn->blocks.size () < 2)
2027 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
2028 bbg_file_name, fn->get_name ());
2029 else
2031 if (fn->blocks[ENTRY_BLOCK].num_pred)
2032 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
2033 bbg_file_name, fn->get_name ());
2034 else
2035 /* We can't deduce the entry block counts from the lack of
2036 predecessors. */
2037 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
2039 if (fn->blocks[EXIT_BLOCK].num_succ)
2040 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
2041 bbg_file_name, fn->get_name ());
2042 else
2043 /* Likewise, we can't deduce exit block counts from the lack
2044 of its successors. */
2045 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
2048 /* Propagate the measured counts, this must be done in the same
2049 order as the code in profile.c */
2050 for (unsigned i = 0; i < fn->blocks.size (); i++)
2052 blk = &fn->blocks[i];
2053 block_info const *prev_dst = NULL;
2054 int out_of_order = 0;
2055 int non_fake_succ = 0;
2057 for (arc = blk->succ; arc; arc = arc->succ_next)
2059 if (!arc->fake)
2060 non_fake_succ++;
2062 if (!arc->on_tree)
2064 if (count_ptr)
2065 arc->count = *count_ptr++;
2066 arc->count_valid = 1;
2067 blk->num_succ--;
2068 arc->dst->num_pred--;
2070 if (prev_dst && prev_dst > arc->dst)
2071 out_of_order = 1;
2072 prev_dst = arc->dst;
2074 if (non_fake_succ == 1)
2076 /* If there is only one non-fake exit, it is an
2077 unconditional branch. */
2078 for (arc = blk->succ; arc; arc = arc->succ_next)
2079 if (!arc->fake)
2081 arc->is_unconditional = 1;
2082 /* If this block is instrumenting a call, it might be
2083 an artificial block. It is not artificial if it has
2084 a non-fallthrough exit, or the destination of this
2085 arc has more than one entry. Mark the destination
2086 block as a return site, if none of those conditions
2087 hold. */
2088 if (blk->is_call_site && arc->fall_through
2089 && arc->dst->pred == arc && !arc->pred_next)
2090 arc->dst->is_call_return = 1;
2094 /* Sort the successor arcs into ascending dst order. profile.c
2095 normally produces arcs in the right order, but sometimes with
2096 one or two out of order. We're not using a particularly
2097 smart sort. */
2098 if (out_of_order)
2100 arc_info *start = blk->succ;
2101 unsigned changes = 1;
2103 while (changes)
2105 arc_info *arc, *arc_p, *arc_n;
2107 changes = 0;
2108 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2110 if (arc->dst > arc_n->dst)
2112 changes = 1;
2113 if (arc_p)
2114 arc_p->succ_next = arc_n;
2115 else
2116 start = arc_n;
2117 arc->succ_next = arc_n->succ_next;
2118 arc_n->succ_next = arc;
2119 arc_p = arc_n;
2121 else
2123 arc_p = arc;
2124 arc = arc_n;
2128 blk->succ = start;
2131 /* Place it on the invalid chain, it will be ignored if that's
2132 wrong. */
2133 blk->invalid_chain = 1;
2134 blk->chain = invalid_blocks;
2135 invalid_blocks = blk;
2138 while (invalid_blocks || valid_blocks)
2140 while ((blk = invalid_blocks))
2142 gcov_type total = 0;
2143 const arc_info *arc;
2145 invalid_blocks = blk->chain;
2146 blk->invalid_chain = 0;
2147 if (!blk->num_succ)
2148 for (arc = blk->succ; arc; arc = arc->succ_next)
2149 total += arc->count;
2150 else if (!blk->num_pred)
2151 for (arc = blk->pred; arc; arc = arc->pred_next)
2152 total += arc->count;
2153 else
2154 continue;
2156 blk->count = total;
2157 blk->count_valid = 1;
2158 blk->chain = valid_blocks;
2159 blk->valid_chain = 1;
2160 valid_blocks = blk;
2162 while ((blk = valid_blocks))
2164 gcov_type total;
2165 arc_info *arc, *inv_arc;
2167 valid_blocks = blk->chain;
2168 blk->valid_chain = 0;
2169 if (blk->num_succ == 1)
2171 block_info *dst;
2173 total = blk->count;
2174 inv_arc = NULL;
2175 for (arc = blk->succ; arc; arc = arc->succ_next)
2177 total -= arc->count;
2178 if (!arc->count_valid)
2179 inv_arc = arc;
2181 dst = inv_arc->dst;
2182 inv_arc->count_valid = 1;
2183 inv_arc->count = total;
2184 blk->num_succ--;
2185 dst->num_pred--;
2186 if (dst->count_valid)
2188 if (dst->num_pred == 1 && !dst->valid_chain)
2190 dst->chain = valid_blocks;
2191 dst->valid_chain = 1;
2192 valid_blocks = dst;
2195 else
2197 if (!dst->num_pred && !dst->invalid_chain)
2199 dst->chain = invalid_blocks;
2200 dst->invalid_chain = 1;
2201 invalid_blocks = dst;
2205 if (blk->num_pred == 1)
2207 block_info *src;
2209 total = blk->count;
2210 inv_arc = NULL;
2211 for (arc = blk->pred; arc; arc = arc->pred_next)
2213 total -= arc->count;
2214 if (!arc->count_valid)
2215 inv_arc = arc;
2217 src = inv_arc->src;
2218 inv_arc->count_valid = 1;
2219 inv_arc->count = total;
2220 blk->num_pred--;
2221 src->num_succ--;
2222 if (src->count_valid)
2224 if (src->num_succ == 1 && !src->valid_chain)
2226 src->chain = valid_blocks;
2227 src->valid_chain = 1;
2228 valid_blocks = src;
2231 else
2233 if (!src->num_succ && !src->invalid_chain)
2235 src->chain = invalid_blocks;
2236 src->invalid_chain = 1;
2237 invalid_blocks = src;
2244 /* If the graph has been correctly solved, every block will have a
2245 valid count. */
2246 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2247 if (!fn->blocks[i].count_valid)
2249 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2250 bbg_file_name, fn->get_name ());
2251 break;
2255 /* Mark all the blocks only reachable via an incoming catch. */
2257 static void
2258 find_exception_blocks (function_info *fn)
2260 unsigned ix;
2261 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2263 /* First mark all blocks as exceptional. */
2264 for (ix = fn->blocks.size (); ix--;)
2265 fn->blocks[ix].exceptional = 1;
2267 /* Now mark all the blocks reachable via non-fake edges */
2268 queue[0] = &fn->blocks[0];
2269 queue[0]->exceptional = 0;
2270 for (ix = 1; ix;)
2272 block_info *block = queue[--ix];
2273 const arc_info *arc;
2275 for (arc = block->succ; arc; arc = arc->succ_next)
2276 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2278 arc->dst->exceptional = 0;
2279 queue[ix++] = arc->dst;
2285 /* Increment totals in COVERAGE according to arc ARC. */
2287 static void
2288 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2290 if (arc->is_call_non_return)
2292 coverage->calls++;
2293 if (arc->src->count)
2294 coverage->calls_executed++;
2296 else if (!arc->is_unconditional)
2298 coverage->branches++;
2299 if (arc->src->count)
2300 coverage->branches_executed++;
2301 if (arc->count)
2302 coverage->branches_taken++;
2306 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2307 readable format. */
2309 static char const *
2310 format_count (gcov_type count)
2312 static char buffer[64];
2313 const char *units = " kMGTPEZY";
2315 if (count < 1000 || !flag_human_readable_numbers)
2317 sprintf (buffer, "%" PRId64, count);
2318 return buffer;
2321 unsigned i;
2322 gcov_type divisor = 1;
2323 for (i = 0; units[i+1]; i++, divisor *= 1000)
2325 if (count + divisor / 2 < 1000 * divisor)
2326 break;
2328 float r = 1.0f * count / divisor;
2329 sprintf (buffer, "%.1f%c", r, units[i]);
2330 return buffer;
2333 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2334 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2335 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2336 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2337 format TOP. Return pointer to a static string. */
2339 static char const *
2340 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2342 static char buffer[20];
2344 if (decimal_places >= 0)
2346 float ratio = bottom ? 100.0f * top / bottom: 0;
2348 /* Round up to 1% if there's a small non-zero value. */
2349 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2350 ratio = 1.0f;
2351 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2353 else
2354 return format_count (top);
2356 return buffer;
2359 /* Summary of execution */
2361 static void
2362 executed_summary (unsigned lines, unsigned executed)
2364 if (lines)
2365 fnotice (stdout, "Lines executed:%s of %d\n",
2366 format_gcov (executed, lines, 2), lines);
2367 else
2368 fnotice (stdout, "No executable lines\n");
2371 /* Output summary info for a function. */
2373 static void
2374 function_summary (const coverage_info *coverage)
2376 fnotice (stdout, "%s '%s'\n", "Function", coverage->name);
2377 executed_summary (coverage->lines, coverage->lines_executed);
2380 /* Output summary info for a file. */
2382 static void
2383 file_summary (const coverage_info *coverage)
2385 fnotice (stdout, "%s '%s'\n", "File", coverage->name);
2386 executed_summary (coverage->lines, coverage->lines_executed);
2388 if (flag_branches)
2390 if (coverage->branches)
2392 fnotice (stdout, "Branches executed:%s of %d\n",
2393 format_gcov (coverage->branches_executed,
2394 coverage->branches, 2),
2395 coverage->branches);
2396 fnotice (stdout, "Taken at least once:%s of %d\n",
2397 format_gcov (coverage->branches_taken,
2398 coverage->branches, 2),
2399 coverage->branches);
2401 else
2402 fnotice (stdout, "No branches\n");
2403 if (coverage->calls)
2404 fnotice (stdout, "Calls executed:%s of %d\n",
2405 format_gcov (coverage->calls_executed, coverage->calls, 2),
2406 coverage->calls);
2407 else
2408 fnotice (stdout, "No calls\n");
2412 /* Canonicalize the filename NAME by canonicalizing directory
2413 separators, eliding . components and resolving .. components
2414 appropriately. Always returns a unique string. */
2416 static char *
2417 canonicalize_name (const char *name)
2419 /* The canonical name cannot be longer than the incoming name. */
2420 char *result = XNEWVEC (char, strlen (name) + 1);
2421 const char *base = name, *probe;
2422 char *ptr = result;
2423 char *dd_base;
2424 int slash = 0;
2426 #if HAVE_DOS_BASED_FILE_SYSTEM
2427 if (base[0] && base[1] == ':')
2429 result[0] = base[0];
2430 result[1] = ':';
2431 base += 2;
2432 ptr += 2;
2434 #endif
2435 for (dd_base = ptr; *base; base = probe)
2437 size_t len;
2439 for (probe = base; *probe; probe++)
2440 if (IS_DIR_SEPARATOR (*probe))
2441 break;
2443 len = probe - base;
2444 if (len == 1 && base[0] == '.')
2445 /* Elide a '.' directory */
2447 else if (len == 2 && base[0] == '.' && base[1] == '.')
2449 /* '..', we can only elide it and the previous directory, if
2450 we're not a symlink. */
2451 struct stat ATTRIBUTE_UNUSED buf;
2453 *ptr = 0;
2454 if (dd_base == ptr
2455 #if defined (S_ISLNK)
2456 /* S_ISLNK is not POSIX.1-1996. */
2457 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2458 #endif
2461 /* Cannot elide, or unreadable or a symlink. */
2462 dd_base = ptr + 2 + slash;
2463 goto regular;
2465 while (ptr != dd_base && *ptr != '/')
2466 ptr--;
2467 slash = ptr != result;
2469 else
2471 regular:
2472 /* Regular pathname component. */
2473 if (slash)
2474 *ptr++ = '/';
2475 memcpy (ptr, base, len);
2476 ptr += len;
2477 slash = 1;
2480 for (; IS_DIR_SEPARATOR (*probe); probe++)
2481 continue;
2483 *ptr = 0;
2485 return result;
2488 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2490 static void
2491 md5sum_to_hex (const char *sum, char *buffer)
2493 for (unsigned i = 0; i < 16; i++)
2494 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2497 /* Generate an output file name. INPUT_NAME is the canonicalized main
2498 input file and SRC_NAME is the canonicalized file name.
2499 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2500 long_output_names we prepend the processed name of the input file
2501 to each output name (except when the current source file is the
2502 input file, so you don't get a double concatenation). The two
2503 components are separated by '##'. With preserve_paths we create a
2504 filename from all path components of the source file, replacing '/'
2505 with '#', and .. with '^', without it we simply take the basename
2506 component. (Remember, the canonicalized name will already have
2507 elided '.' components and converted \\ separators.) */
2509 static char *
2510 make_gcov_file_name (const char *input_name, const char *src_name)
2512 char *ptr;
2513 char *result;
2515 if (flag_long_names && input_name && strcmp (src_name, input_name))
2517 /* Generate the input filename part. */
2518 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2520 ptr = result;
2521 ptr = mangle_name (input_name, ptr);
2522 ptr[0] = ptr[1] = '#';
2523 ptr += 2;
2525 else
2527 result = XNEWVEC (char, strlen (src_name) + 10);
2528 ptr = result;
2531 ptr = mangle_name (src_name, ptr);
2532 strcpy (ptr, ".gcov");
2534 /* When hashing filenames, we shorten them by only using the filename
2535 component and appending a hash of the full (mangled) pathname. */
2536 if (flag_hash_filenames)
2538 md5_ctx ctx;
2539 char md5sum[16];
2540 char md5sum_hex[33];
2542 md5_init_ctx (&ctx);
2543 md5_process_bytes (src_name, strlen (src_name), &ctx);
2544 md5_finish_ctx (&ctx, md5sum);
2545 md5sum_to_hex (md5sum, md5sum_hex);
2546 free (result);
2548 result = XNEWVEC (char, strlen (src_name) + 50);
2549 ptr = result;
2550 ptr = mangle_name (src_name, ptr);
2551 ptr[0] = ptr[1] = '#';
2552 ptr += 2;
2553 memcpy (ptr, md5sum_hex, 32);
2554 ptr += 32;
2555 strcpy (ptr, ".gcov");
2558 return result;
2561 /* Mangle BASE name, copy it at the beginning of PTR buffer and
2562 return address of the \0 character of the buffer. */
2564 static char *
2565 mangle_name (char const *base, char *ptr)
2567 size_t len;
2569 /* Generate the source filename part. */
2570 if (!flag_preserve_paths)
2571 base = lbasename (base);
2572 else
2573 base = mangle_path (base);
2575 len = strlen (base);
2576 memcpy (ptr, base, len);
2577 ptr += len;
2579 return ptr;
2582 /* Scan through the bb_data for each line in the block, increment
2583 the line number execution count indicated by the execution count of
2584 the appropriate basic block. */
2586 static void
2587 add_line_counts (coverage_info *coverage, function_info *fn)
2589 bool has_any_line = false;
2590 /* Scan each basic block. */
2591 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2593 line_info *line = NULL;
2594 block_info *block = &fn->blocks[ix];
2595 if (block->count && ix && ix + 1 != fn->blocks.size ())
2596 fn->blocks_executed++;
2597 for (unsigned i = 0; i < block->locations.size (); i++)
2599 unsigned src_idx = block->locations[i].source_file_idx;
2600 vector<unsigned> &lines = block->locations[i].lines;
2602 block->cycle.arc = NULL;
2603 block->cycle.ident = ~0U;
2605 for (unsigned j = 0; j < lines.size (); j++)
2607 unsigned ln = lines[j];
2609 /* Line belongs to a function that is in a group. */
2610 if (fn->group_line_p (ln, src_idx))
2612 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2613 line = &(fn->lines[lines[j] - fn->start_line]);
2614 line->exists = 1;
2615 if (!block->exceptional)
2617 line->unexceptional = 1;
2618 if (block->count == 0)
2619 line->has_unexecuted_block = 1;
2621 line->count += block->count;
2623 else
2625 gcc_assert (ln < sources[src_idx].lines.size ());
2626 line = &(sources[src_idx].lines[ln]);
2627 if (coverage)
2629 if (!line->exists)
2630 coverage->lines++;
2631 if (!line->count && block->count)
2632 coverage->lines_executed++;
2634 line->exists = 1;
2635 if (!block->exceptional)
2637 line->unexceptional = 1;
2638 if (block->count == 0)
2639 line->has_unexecuted_block = 1;
2641 line->count += block->count;
2645 has_any_line = true;
2647 if (!ix || ix + 1 == fn->blocks.size ())
2648 /* Entry or exit block. */;
2649 else if (line != NULL)
2651 line->blocks.push_back (block);
2653 if (flag_branches)
2655 arc_info *arc;
2657 for (arc = block->succ; arc; arc = arc->succ_next)
2658 line->branches.push_back (arc);
2664 if (!has_any_line)
2665 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name,
2666 fn->get_name ());
2669 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2670 is set to true, update source file summary. */
2672 static void accumulate_line_info (line_info *line, source_info *src,
2673 bool add_coverage)
2675 if (add_coverage)
2676 for (vector<arc_info *>::iterator it = line->branches.begin ();
2677 it != line->branches.end (); it++)
2678 add_branch_counts (&src->coverage, *it);
2680 if (!line->blocks.empty ())
2682 /* The user expects the line count to be the number of times
2683 a line has been executed. Simply summing the block count
2684 will give an artificially high number. The Right Thing
2685 is to sum the entry counts to the graph of blocks on this
2686 line, then find the elementary cycles of the local graph
2687 and add the transition counts of those cycles. */
2688 gcov_type count = 0;
2690 /* Cycle detection. */
2691 for (vector<block_info *>::iterator it = line->blocks.begin ();
2692 it != line->blocks.end (); it++)
2694 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2695 if (!line->has_block (arc->src))
2696 count += arc->count;
2697 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2698 arc->cs_count = arc->count;
2701 /* Now, add the count of loops entirely on this line. */
2702 count += get_cycles_count (*line);
2703 line->count = count;
2705 if (line->count > src->maximum_count)
2706 src->maximum_count = line->count;
2709 if (line->exists && add_coverage)
2711 src->coverage.lines++;
2712 if (line->count)
2713 src->coverage.lines_executed++;
2717 /* Accumulate the line counts of a file. */
2719 static void
2720 accumulate_line_counts (source_info *src)
2722 /* First work on group functions. */
2723 for (vector<function_info *>::iterator it = src->functions.begin ();
2724 it != src->functions.end (); it++)
2726 function_info *fn = *it;
2728 if (fn->src != src->index || !fn->is_group)
2729 continue;
2731 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2732 it2 != fn->lines.end (); it2++)
2734 line_info *line = &(*it2);
2735 accumulate_line_info (line, src, false);
2739 /* Work on global lines that line in source file SRC. */
2740 for (vector<line_info>::iterator it = src->lines.begin ();
2741 it != src->lines.end (); it++)
2742 accumulate_line_info (&(*it), src, true);
2744 /* If not using intermediate mode, sum lines of group functions and
2745 add them to lines that live in a source file. */
2746 if (!flag_json_format)
2747 for (vector<function_info *>::iterator it = src->functions.begin ();
2748 it != src->functions.end (); it++)
2750 function_info *fn = *it;
2752 if (fn->src != src->index || !fn->is_group)
2753 continue;
2755 for (unsigned i = 0; i < fn->lines.size (); i++)
2757 line_info *fn_line = &fn->lines[i];
2758 if (fn_line->exists)
2760 unsigned ln = fn->start_line + i;
2761 line_info *src_line = &src->lines[ln];
2763 if (!src_line->exists)
2764 src->coverage.lines++;
2765 if (!src_line->count && fn_line->count)
2766 src->coverage.lines_executed++;
2768 src_line->count += fn_line->count;
2769 src_line->exists = 1;
2771 if (fn_line->has_unexecuted_block)
2772 src_line->has_unexecuted_block = 1;
2774 if (fn_line->unexceptional)
2775 src_line->unexceptional = 1;
2781 /* Output information about ARC number IX. Returns nonzero if
2782 anything is output. */
2784 static int
2785 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2787 if (arc->is_call_non_return)
2789 if (arc->src->count)
2791 fnotice (gcov_file, "call %2d returned %s\n", ix,
2792 format_gcov (arc->src->count - arc->count,
2793 arc->src->count, -flag_counts));
2795 else
2796 fnotice (gcov_file, "call %2d never executed\n", ix);
2798 else if (!arc->is_unconditional)
2800 if (arc->src->count)
2801 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2802 format_gcov (arc->count, arc->src->count, -flag_counts),
2803 arc->fall_through ? " (fallthrough)"
2804 : arc->is_throw ? " (throw)" : "");
2805 else
2806 fnotice (gcov_file, "branch %2d never executed", ix);
2808 if (flag_verbose)
2809 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2811 fnotice (gcov_file, "\n");
2813 else if (flag_unconditional && !arc->dst->is_call_return)
2815 if (arc->src->count)
2816 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2817 format_gcov (arc->count, arc->src->count, -flag_counts));
2818 else
2819 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2821 else
2822 return 0;
2823 return 1;
2826 static const char *
2827 read_line (FILE *file)
2829 static char *string;
2830 static size_t string_len;
2831 size_t pos = 0;
2832 char *ptr;
2834 if (!string_len)
2836 string_len = 200;
2837 string = XNEWVEC (char, string_len);
2840 while ((ptr = fgets (string + pos, string_len - pos, file)))
2842 size_t len = strlen (string + pos);
2844 if (len && string[pos + len - 1] == '\n')
2846 string[pos + len - 1] = 0;
2847 return string;
2849 pos += len;
2850 /* If the file contains NUL characters or an incomplete
2851 last line, which can happen more than once in one run,
2852 we have to avoid doubling the STRING_LEN unnecessarily. */
2853 if (pos > string_len / 2)
2855 string_len *= 2;
2856 string = XRESIZEVEC (char, string, string_len);
2860 return pos ? string : NULL;
2863 /* Pad string S with spaces from left to have total width equal to 9. */
2865 static void
2866 pad_count_string (string &s)
2868 if (s.size () < 9)
2869 s.insert (0, 9 - s.size (), ' ');
2872 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2873 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2874 an exceptional statement. The output is printed for LINE_NUM of given
2875 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2876 used to indicate non-executed blocks. */
2878 static void
2879 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2880 bool has_unexecuted_block,
2881 gcov_type count, unsigned line_num,
2882 const char *exceptional_string,
2883 const char *unexceptional_string,
2884 unsigned int maximum_count)
2886 string s;
2887 if (exists)
2889 if (count > 0)
2891 s = format_gcov (count, 0, -1);
2892 if (has_unexecuted_block
2893 && bbg_supports_has_unexecuted_blocks)
2895 if (flag_use_colors)
2897 pad_count_string (s);
2898 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2899 COLOR_SEPARATOR COLOR_FG_WHITE));
2900 s += SGR_RESET;
2902 else
2903 s += "*";
2905 pad_count_string (s);
2907 else
2909 if (flag_use_colors)
2911 s = "0";
2912 pad_count_string (s);
2913 if (unexceptional)
2914 s.insert (0, SGR_SEQ (COLOR_BG_RED
2915 COLOR_SEPARATOR COLOR_FG_WHITE));
2916 else
2917 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2918 COLOR_SEPARATOR COLOR_FG_WHITE));
2919 s += SGR_RESET;
2921 else
2923 s = unexceptional ? unexceptional_string : exceptional_string;
2924 pad_count_string (s);
2928 else
2930 s = "-";
2931 pad_count_string (s);
2934 /* Format line number in output. */
2935 char buffer[16];
2936 sprintf (buffer, "%5u", line_num);
2937 string linestr (buffer);
2939 if (flag_use_hotness_colors && maximum_count)
2941 if (count * 2 > maximum_count) /* > 50%. */
2942 linestr.insert (0, SGR_SEQ (COLOR_BG_RED));
2943 else if (count * 5 > maximum_count) /* > 20%. */
2944 linestr.insert (0, SGR_SEQ (COLOR_BG_YELLOW));
2945 else if (count * 10 > maximum_count) /* > 10%. */
2946 linestr.insert (0, SGR_SEQ (COLOR_BG_GREEN));
2947 linestr += SGR_RESET;
2950 fprintf (f, "%s:%s", s.c_str (), linestr.c_str ());
2953 static void
2954 print_source_line (FILE *f, const vector<const char *> &source_lines,
2955 unsigned line)
2957 gcc_assert (line >= 1);
2958 gcc_assert (line <= source_lines.size ());
2960 fprintf (f, ":%s\n", source_lines[line - 1]);
2963 /* Output line details for LINE and print it to F file. LINE lives on
2964 LINE_NUM. */
2966 static void
2967 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2969 if (flag_all_blocks)
2971 arc_info *arc;
2972 int ix, jx;
2974 ix = jx = 0;
2975 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2976 it != line->blocks.end (); it++)
2978 if (!(*it)->is_call_return)
2980 output_line_beginning (f, line->exists,
2981 (*it)->exceptional, false,
2982 (*it)->count, line_num,
2983 "%%%%%", "$$$$$", 0);
2984 fprintf (f, "-block %2d", ix++);
2985 if (flag_verbose)
2986 fprintf (f, " (BB %u)", (*it)->id);
2987 fprintf (f, "\n");
2989 if (flag_branches)
2990 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2991 jx += output_branch_count (f, jx, arc);
2994 else if (flag_branches)
2996 int ix;
2998 ix = 0;
2999 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
3000 it != line->branches.end (); it++)
3001 ix += output_branch_count (f, ix, (*it));
3005 /* Output detail statistics about function FN to file F. */
3007 static void
3008 output_function_details (FILE *f, function_info *fn)
3010 if (!flag_branches)
3011 return;
3013 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
3014 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
3015 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
3017 for (; arc; arc = arc->pred_next)
3018 if (arc->fake)
3019 return_count -= arc->count;
3021 fprintf (f, "function %s", fn->get_name ());
3022 fprintf (f, " called %s",
3023 format_gcov (called_count, 0, -1));
3024 fprintf (f, " returned %s",
3025 format_gcov (return_count, called_count, 0));
3026 fprintf (f, " blocks executed %s",
3027 format_gcov (fn->blocks_executed, fn->get_block_count (), 0));
3028 fprintf (f, "\n");
3031 /* Read in the source file one line at a time, and output that line to
3032 the gcov file preceded by its execution count and other
3033 information. */
3035 static void
3036 output_lines (FILE *gcov_file, const source_info *src)
3038 #define DEFAULT_LINE_START " -: 0:"
3039 #define FN_SEPARATOR "------------------\n"
3041 FILE *source_file;
3042 const char *retval;
3044 /* Print colorization legend. */
3045 if (flag_use_colors)
3046 fprintf (gcov_file, "%s",
3047 DEFAULT_LINE_START "Colorization: profile count: " \
3048 SGR_SEQ (COLOR_BG_CYAN) "zero coverage (exceptional)" SGR_RESET \
3049 " " \
3050 SGR_SEQ (COLOR_BG_RED) "zero coverage (unexceptional)" SGR_RESET \
3051 " " \
3052 SGR_SEQ (COLOR_BG_MAGENTA) "unexecuted block" SGR_RESET "\n");
3054 if (flag_use_hotness_colors)
3055 fprintf (gcov_file, "%s",
3056 DEFAULT_LINE_START "Colorization: line numbers: hotness: " \
3057 SGR_SEQ (COLOR_BG_RED) "> 50%" SGR_RESET " " \
3058 SGR_SEQ (COLOR_BG_YELLOW) "> 20%" SGR_RESET " " \
3059 SGR_SEQ (COLOR_BG_GREEN) "> 10%" SGR_RESET "\n");
3061 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
3062 if (!multiple_files)
3064 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
3065 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
3066 no_data_file ? "-" : da_file_name);
3067 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
3070 source_file = fopen (src->name, "r");
3071 if (!source_file)
3072 fnotice (stderr, "Cannot open source file %s\n", src->name);
3073 else if (src->file_time == 0)
3074 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
3076 vector<const char *> source_lines;
3077 if (source_file)
3078 while ((retval = read_line (source_file)) != NULL)
3079 source_lines.push_back (xstrdup (retval));
3081 unsigned line_start_group = 0;
3082 vector<function_info *> *fns;
3084 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
3086 if (line_num >= src->lines.size ())
3088 fprintf (gcov_file, "%9s:%5u", "-", line_num);
3089 print_source_line (gcov_file, source_lines, line_num);
3090 continue;
3093 const line_info *line = &src->lines[line_num];
3095 if (line_start_group == 0)
3097 fns = src->get_functions_at_location (line_num);
3098 if (fns != NULL && fns->size () > 1)
3100 /* It's possible to have functions that partially overlap,
3101 thus take the maximum end_line of functions starting
3102 at LINE_NUM. */
3103 for (unsigned i = 0; i < fns->size (); i++)
3104 if ((*fns)[i]->end_line > line_start_group)
3105 line_start_group = (*fns)[i]->end_line;
3107 else if (fns != NULL && fns->size () == 1)
3109 function_info *fn = (*fns)[0];
3110 output_function_details (gcov_file, fn);
3114 /* For lines which don't exist in the .bb file, print '-' before
3115 the source line. For lines which exist but were never
3116 executed, print '#####' or '=====' before the source line.
3117 Otherwise, print the execution count before the source line.
3118 There are 16 spaces of indentation added before the source
3119 line so that tabs won't be messed up. */
3120 output_line_beginning (gcov_file, line->exists, line->unexceptional,
3121 line->has_unexecuted_block, line->count,
3122 line_num, "=====", "#####", src->maximum_count);
3124 print_source_line (gcov_file, source_lines, line_num);
3125 output_line_details (gcov_file, line, line_num);
3127 if (line_start_group == line_num)
3129 for (vector<function_info *>::iterator it = fns->begin ();
3130 it != fns->end (); it++)
3132 function_info *fn = *it;
3133 vector<line_info> &lines = fn->lines;
3135 fprintf (gcov_file, FN_SEPARATOR);
3137 string fn_name = fn->get_name ();
3138 if (flag_use_colors)
3140 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
3141 fn_name += SGR_RESET;
3144 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
3146 output_function_details (gcov_file, fn);
3148 /* Print all lines covered by the function. */
3149 for (unsigned i = 0; i < lines.size (); i++)
3151 line_info *line = &lines[i];
3152 unsigned l = fn->start_line + i;
3154 /* For lines which don't exist in the .bb file, print '-'
3155 before the source line. For lines which exist but
3156 were never executed, print '#####' or '=====' before
3157 the source line. Otherwise, print the execution count
3158 before the source line.
3159 There are 16 spaces of indentation added before the source
3160 line so that tabs won't be messed up. */
3161 output_line_beginning (gcov_file, line->exists,
3162 line->unexceptional,
3163 line->has_unexecuted_block,
3164 line->count,
3165 l, "=====", "#####",
3166 src->maximum_count);
3168 print_source_line (gcov_file, source_lines, l);
3169 output_line_details (gcov_file, line, l);
3173 fprintf (gcov_file, FN_SEPARATOR);
3174 line_start_group = 0;
3178 if (source_file)
3179 fclose (source_file);