]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gcov.c
Update copyright years.
[thirdparty/gcc.git] / gcc / gcov.c
1 /* Gcov.c: prepend line execution counts and branch probabilities to a
2 source file.
3 Copyright (C) 1990-2021 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>
7
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.
12
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.
17
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/>. */
21
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. */
26
27 /* ??? Should have an option to print the number of basic blocks, and the
28 percent of them that are covered. */
29
30 /* Need an option to show individual block counts, and show
31 probabilities of fall through arcs. */
32
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"
49
50 #include <zlib.h>
51 #include <getopt.h>
52
53 #include "md5.h"
54
55 using namespace std;
56
57 #define IN_GCOV 1
58 #include "gcov-io.h"
59 #include "gcov-io.c"
60
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. */
64
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. */
69
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. */
76
77 /* This is the size of the buffer used to read in source file lines. */
78
79 class function_info;
80 class block_info;
81 class source_info;
82
83 /* Describes an arc between two basic blocks. */
84
85 struct arc_info
86 {
87 /* source and destination blocks. */
88 class block_info *src;
89 class block_info *dst;
90
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;
95
96 unsigned int count_valid : 1;
97 unsigned int on_tree : 1;
98 unsigned int fake : 1;
99 unsigned int fall_through : 1;
100
101 /* Arc to a catch handler. */
102 unsigned int is_throw : 1;
103
104 /* Arc is for a function that abnormally returns. */
105 unsigned int is_call_non_return : 1;
106
107 /* Arc is for catch/setjmp. */
108 unsigned int is_nonlocal_return : 1;
109
110 /* Is an unconditional branch. */
111 unsigned int is_unconditional : 1;
112
113 /* Loop making arc. */
114 unsigned int cycle : 1;
115
116 /* Links to next arc on src and dst lists. */
117 struct arc_info *succ_next;
118 struct arc_info *pred_next;
119 };
120
121 /* Describes which locations (lines and files) are associated with
122 a basic block. */
123
124 class block_location_info
125 {
126 public:
127 block_location_info (unsigned _source_file_idx):
128 source_file_idx (_source_file_idx)
129 {}
130
131 unsigned source_file_idx;
132 vector<unsigned> lines;
133 };
134
135 /* Describes a basic block. Contains lists of arcs to successor and
136 predecessor blocks. */
137
138 class block_info
139 {
140 public:
141 /* Constructor. */
142 block_info ();
143
144 /* Chain of exit and entry arcs. */
145 arc_info *succ;
146 arc_info *pred;
147
148 /* Number of unprocessed exit and entry arcs. */
149 gcov_type num_succ;
150 gcov_type num_pred;
151
152 unsigned id;
153
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;
160
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. */
164
165 /* Block is a landing pad for longjmp or throw. */
166 unsigned is_nonlocal_return : 1;
167
168 vector<block_location_info> locations;
169
170 struct
171 {
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. */
178
179 /* Temporary chain for solving graph, and for chaining blocks on one
180 line. */
181 class block_info *chain;
182
183 };
184
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)
189 {
190 cycle.arc = NULL;
191 }
192
193 /* Describes a single line of source. Contains a chain of basic blocks
194 with code on it. */
195
196 class line_info
197 {
198 public:
199 /* Default constructor. */
200 line_info ();
201
202 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
203 bool has_block (block_info *needle);
204
205 /* Execution count. */
206 gcov_type count;
207
208 /* Branches from blocks that end on this line. */
209 vector<arc_info *> branches;
210
211 /* blocks which start on this line. Used in all-blocks mode. */
212 vector<block_info *> blocks;
213
214 unsigned exists : 1;
215 unsigned unexceptional : 1;
216 unsigned has_unexecuted_block : 1;
217 };
218
219 line_info::line_info (): count (0), branches (), blocks (), exists (false),
220 unexceptional (0), has_unexecuted_block (0)
221 {
222 }
223
224 bool
225 line_info::has_block (block_info *needle)
226 {
227 return std::find (blocks.begin (), blocks.end (), needle) != blocks.end ();
228 }
229
230 /* Output demangled function names. */
231
232 static int flag_demangled_names = 0;
233
234 /* Describes a single function. Contains an array of basic blocks. */
235
236 class function_info
237 {
238 public:
239 function_info ();
240 ~function_info ();
241
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);
245
246 /* Function filter based on function_info::artificial variable. */
247
248 static inline bool
249 is_artificial (function_info *fn)
250 {
251 return fn->artificial;
252 }
253
254 /* Name of function. */
255 char *m_name;
256 char *m_demangled_name;
257 unsigned ident;
258 unsigned lineno_checksum;
259 unsigned cfg_checksum;
260
261 /* The graph contains at least one fake incoming edge. */
262 unsigned has_catch : 1;
263
264 /* True when the function is artificial and does not exist
265 in a source file. */
266 unsigned artificial : 1;
267
268 /* True when multiple functions start at a line in a source file. */
269 unsigned is_group : 1;
270
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;
277
278 /* Raw arc coverage counts. */
279 vector<gcov_type> counts;
280
281 /* First line number. */
282 unsigned start_line;
283
284 /* First line column. */
285 unsigned start_column;
286
287 /* Last line number. */
288 unsigned end_line;
289
290 /* Last line column. */
291 unsigned end_column;
292
293 /* Index of source file where the function is defined. */
294 unsigned src;
295
296 /* Vector of line information (used only for group functions). */
297 vector<line_info> lines;
298
299 /* Next function. */
300 class function_info *next;
301
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 ()
305 {
306 if (m_demangled_name == NULL)
307 {
308 m_demangled_name = cplus_demangle (m_name, DMGL_PARAMS);
309 if (!m_demangled_name)
310 m_demangled_name = m_name;
311 }
312
313 return m_demangled_name;
314 }
315
316 /* Get name of the function based on flag_demangled_names. */
317 char *get_name ()
318 {
319 return flag_demangled_names ? get_demangled_name () : m_name;
320 }
321
322 /* Return number of basic blocks (without entry and exit block). */
323 unsigned get_block_count ()
324 {
325 return blocks.size () - 2;
326 }
327 };
328
329 /* Function info comparer that will sort functions according to starting
330 line. */
331
332 struct function_line_start_cmp
333 {
334 inline bool operator() (const function_info *lhs,
335 const function_info *rhs)
336 {
337 return (lhs->start_line == rhs->start_line
338 ? lhs->start_column < rhs->start_column
339 : lhs->start_line < rhs->start_line);
340 }
341 };
342
343 /* Describes coverage of a file or function. */
344
345 struct coverage_info
346 {
347 int lines;
348 int lines_executed;
349
350 int branches;
351 int branches_executed;
352 int branches_taken;
353
354 int calls;
355 int calls_executed;
356
357 char *name;
358 };
359
360 /* Describes a file mentioned in the block graph. Contains an array
361 of line info. */
362
363 class source_info
364 {
365 public:
366 /* Default constructor. */
367 source_info ();
368
369 vector<function_info *> *get_functions_at_location (unsigned line_num) const;
370
371 /* Register a new function. */
372 void add_function (function_info *fn);
373
374 /* Index of the source_info in sources vector. */
375 unsigned index;
376
377 /* Canonical name of source file. */
378 char *name;
379 time_t file_time;
380
381 /* Vector of line information. */
382 vector<line_info> lines;
383
384 coverage_info coverage;
385
386 /* Maximum line count in the source file. */
387 unsigned int maximum_count;
388
389 /* Functions in this source file. These are in ascending line
390 number order. */
391 vector<function_info *> functions;
392
393 /* Line number to functions map. */
394 vector<vector<function_info *> *> line_to_function_map;
395 };
396
397 source_info::source_info (): index (0), name (NULL), file_time (),
398 lines (), coverage (), maximum_count (0), functions ()
399 {
400 }
401
402 /* Register a new function. */
403 void
404 source_info::add_function (function_info *fn)
405 {
406 functions.push_back (fn);
407
408 if (fn->start_line >= line_to_function_map.size ())
409 line_to_function_map.resize (fn->start_line + 1);
410
411 vector<function_info *> **slot = &line_to_function_map[fn->start_line];
412 if (*slot == NULL)
413 *slot = new vector<function_info *> ();
414
415 (*slot)->push_back (fn);
416 }
417
418 vector<function_info *> *
419 source_info::get_functions_at_location (unsigned line_num) const
420 {
421 if (line_num >= line_to_function_map.size ())
422 return NULL;
423
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 ());
427
428 return slot;
429 }
430
431 class name_map
432 {
433 public:
434 name_map ()
435 {
436 }
437
438 name_map (char *_name, unsigned _src): name (_name), src (_src)
439 {
440 }
441
442 bool operator== (const name_map &rhs) const
443 {
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
449 }
450
451 bool operator< (const name_map &rhs) const
452 {
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
458 }
459
460 const char *name; /* Source file name */
461 unsigned src; /* Source file */
462 };
463
464 /* Vector of all functions. */
465 static vector<function_info *> functions;
466
467 /* Function ident to function_info * map. */
468 static map<unsigned, function_info *> ident_to_fn;
469
470 /* Vector of source files. */
471 static vector<source_info> sources;
472
473 /* Mapping of file names to sources */
474 static vector<name_map> names;
475
476 /* Record all processed files in order to warn about
477 a file being read multiple times. */
478 static vector<char *> processed_files;
479
480 /* This holds data summary information. */
481
482 static unsigned object_runs;
483
484 static unsigned total_lines;
485 static unsigned total_executed;
486
487 /* Modification time of graph file. */
488
489 static time_t bbg_file_time;
490
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. */
494
495 static char *bbg_file_name;
496
497 /* Stamp of the bbg file */
498 static unsigned bbg_stamp;
499
500 /* Supports has_unexecuted_blocks functionality. */
501 static unsigned bbg_supports_has_unexecuted_blocks;
502
503 /* Working directory in which a TU was compiled. */
504 static const char *bbg_cwd;
505
506 /* Name and file pointer of the input file for the count data (gcda). */
507
508 static char *da_file_name;
509
510 /* Data file is missing. */
511
512 static int no_data_file;
513
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. */
518
519 static int multiple_files = 0;
520
521 /* Output branch probabilities. */
522
523 static int flag_branches = 0;
524
525 /* Show unconditional branches too. */
526 static int flag_unconditional = 0;
527
528 /* Output a gcov file if this is true. This is on by default, and can
529 be turned off by the -n option. */
530
531 static int flag_gcov_file = 1;
532
533 /* Output to stdout instead to a gcov file. */
534
535 static int flag_use_stdout = 0;
536
537 /* Output progress indication if this is true. This is off by default
538 and can be turned on by the -d option. */
539
540 static int flag_display_progress = 0;
541
542 /* Output *.gcov file in JSON intermediate format used by consumers. */
543
544 static int flag_json_format = 0;
545
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. */
549
550 static int flag_long_names = 0;
551
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. */
554
555 static int flag_hash_filenames = 0;
556
557 /* Print verbose informations. */
558
559 static int flag_verbose = 0;
560
561 /* Print colored output. */
562
563 static int flag_use_colors = 0;
564
565 /* Use perf-like colors to indicate hot lines. */
566
567 static int flag_use_hotness_colors = 0;
568
569 /* Output count information for every basic block, not merely those
570 that contain line number information. */
571
572 static int flag_all_blocks = 0;
573
574 /* Output human readable numbers. */
575
576 static int flag_human_readable_numbers = 0;
577
578 /* Output summary info for each function. */
579
580 static int flag_function_summary = 0;
581
582 /* Object directory file prefix. This is the directory/file where the
583 graph and data files are looked for, if nonzero. */
584
585 static char *object_directory = 0;
586
587 /* Source directory prefix. This is removed from source pathnames
588 that match, when generating the output file name. */
589
590 static char *source_prefix = 0;
591 static size_t source_length = 0;
592
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;
597
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 '^'. */
601
602 static int flag_preserve_paths = 0;
603
604 /* Output the number of times a branch was taken as opposed to the percentage
605 of times it was taken. */
606
607 static int flag_counts = 0;
608
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 **);
637
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)
644 {
645 }
646
647 function_info::~function_info ()
648 {
649 for (int i = blocks.size () - 1; i >= 0; i--)
650 {
651 arc_info *arc, *arc_n;
652
653 for (arc = blocks[i].succ; arc; arc = arc_n)
654 {
655 arc_n = arc->succ_next;
656 free (arc);
657 }
658 }
659 if (m_demangled_name != m_name)
660 free (m_demangled_name);
661 free (m_name);
662 }
663
664 bool function_info::group_line_p (unsigned n, unsigned src_idx)
665 {
666 return is_group && src == src_idx && start_line <= n && n <= end_line;
667 }
668
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>).
674
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.
679 */
680
681 typedef vector<arc_info *> arc_vector_t;
682 typedef vector<const block_info *> block_vector_t;
683
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. */
687
688 static void
689 handle_cycle (const arc_vector_t &edges, int64_t &count)
690 {
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++)
695 {
696 int64_t ecount = edges[i]->cs_count;
697 if (cycle_count > ecount)
698 cycle_count = ecount;
699 }
700 count += cycle_count;
701 for (unsigned i = 0; i < edges.size (); i++)
702 edges[i]->cs_count -= cycle_count;
703
704 gcc_assert (cycle_count > 0);
705 }
706
707 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
708 blocked by U in BLOCK_LISTS. */
709
710 static void
711 unblock (const block_info *u, block_vector_t &blocked,
712 vector<block_vector_t > &block_lists)
713 {
714 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
715 if (it == blocked.end ())
716 return;
717
718 unsigned index = it - blocked.begin ();
719 blocked.erase (it);
720
721 block_vector_t to_unblock (block_lists[index]);
722
723 block_lists.erase (block_lists.begin () + index);
724
725 for (block_vector_t::iterator it = to_unblock.begin ();
726 it != to_unblock.end (); it++)
727 unblock (*it, blocked, block_lists);
728 }
729
730 /* Return true when PATH contains a zero cycle arc count. */
731
732 static bool
733 path_contains_zero_or_negative_cycle_arc (arc_vector_t &path)
734 {
735 for (unsigned i = 0; i < path.size (); i++)
736 if (path[i]->cs_count <= 0)
737 return true;
738 return false;
739 }
740
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. */
745
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)
750 {
751 bool loop_found = false;
752
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 ());
757
758 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
759 {
760 block_info *w = arc->dst;
761 if (w < start
762 || arc->cs_count <= 0
763 || !linfo.has_block (w))
764 continue;
765
766 path.push_back (arc);
767 if (w == start)
768 {
769 /* Cycle has been found. */
770 handle_cycle (path, count);
771 loop_found = true;
772 }
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);
777
778 path.pop_back ();
779 }
780
781 if (loop_found)
782 unblock (v, blocked, block_lists);
783 else
784 for (arc_info *arc = v->succ; arc; arc = arc->succ_next)
785 {
786 block_info *w = arc->dst;
787 if (w < start
788 || arc->cs_count <= 0
789 || !linfo.has_block (w))
790 continue;
791
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);
798 }
799
800 return loop_found;
801 }
802
803 /* Find cycles for a LINFO. */
804
805 static gcov_type
806 get_cycles_count (line_info &linfo)
807 {
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. */
813
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++)
818 {
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);
824 }
825
826 return count;
827 }
828
829 int
830 main (int argc, char **argv)
831 {
832 int argno;
833 int first_arg;
834 const char *p;
835
836 p = argv[0] + strlen (argv[0]);
837 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
838 --p;
839 progname = p;
840
841 xmalloc_set_program_name (progname);
842
843 /* Unlock the stdio streams. */
844 unlock_std_streams ();
845
846 gcc_init_libintl ();
847
848 diagnostic_initialize (global_dc, 0);
849
850 /* Handle response files. */
851 expandargv (&argc, &argv);
852
853 argno = process_args (argc, argv);
854 if (optind == argc)
855 print_usage (true);
856
857 if (argc - argno > 1)
858 multiple_files = 1;
859
860 first_arg = argno;
861
862 for (; argno != argc; argno++)
863 {
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]);
868
869 if (flag_json_format || argno == argc - 1)
870 {
871 process_all_functions ();
872 generate_results (argv[argno]);
873 release_structures ();
874 }
875 }
876
877 if (!flag_use_stdout)
878 executed_summary (total_lines, total_executed);
879
880 return 0;
881 }
882 \f
883 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
884 otherwise the output of --help. */
885
886 static void
887 print_usage (int error_p)
888 {
889 FILE *file = error_p ? stderr : stdout;
890 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
891
892 fnotice (file, "Usage: gcov [OPTION...] SOURCE|OBJ...\n\n");
893 fnotice (file, "Print code coverage information.\n\n");
894 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
895 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
896 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
897 rather than percentages\n");
898 fnotice (file, " -d, --display-progress Display progress information\n");
899 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
900 fnotice (file, " -h, --help Print this help, then exit\n");
901 fnotice (file, " -j, --json-format Output JSON intermediate format\n\
902 into .gcov.json.gz file\n");
903 fnotice (file, " -H, --human-readable Output human readable numbers\n");
904 fnotice (file, " -k, --use-colors Emit colored output\n");
905 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
906 source files\n");
907 fnotice (file, " -m, --demangled-names Output demangled function names\n");
908 fnotice (file, " -n, --no-output Do not create an output file\n");
909 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
910 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
911 fnotice (file, " -q, --use-hotness-colors Emit perf-like colored output for hot lines\n");
912 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
913 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
914 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
915 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
916 fnotice (file, " -v, --version Print version number, then exit\n");
917 fnotice (file, " -w, --verbose Print verbose informations\n");
918 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
919 fnotice (file, "\nObsolete options:\n");
920 fnotice (file, " -i, --json-format Replaced with -j, --json-format\n");
921 fnotice (file, " -j, --human-readable Replaced with -H, --human-readable\n");
922 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
923 bug_report_url);
924 exit (status);
925 }
926
927 /* Print version information and exit. */
928
929 static void
930 print_version (void)
931 {
932 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
933 fprintf (stdout, "Copyright %s 2021 Free Software Foundation, Inc.\n",
934 _("(C)"));
935 fnotice (stdout,
936 _("This is free software; see the source for copying conditions. There is NO\n\
937 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
938 exit (SUCCESS_EXIT_CODE);
939 }
940
941 static const struct option options[] =
942 {
943 { "help", no_argument, NULL, 'h' },
944 { "version", no_argument, NULL, 'v' },
945 { "verbose", no_argument, NULL, 'w' },
946 { "all-blocks", no_argument, NULL, 'a' },
947 { "branch-probabilities", no_argument, NULL, 'b' },
948 { "branch-counts", no_argument, NULL, 'c' },
949 { "json-format", no_argument, NULL, 'j' },
950 { "human-readable", no_argument, NULL, 'H' },
951 { "no-output", no_argument, NULL, 'n' },
952 { "long-file-names", no_argument, NULL, 'l' },
953 { "function-summaries", no_argument, NULL, 'f' },
954 { "demangled-names", no_argument, NULL, 'm' },
955 { "preserve-paths", no_argument, NULL, 'p' },
956 { "relative-only", no_argument, NULL, 'r' },
957 { "object-directory", required_argument, NULL, 'o' },
958 { "object-file", required_argument, NULL, 'o' },
959 { "source-prefix", required_argument, NULL, 's' },
960 { "stdout", no_argument, NULL, 't' },
961 { "unconditional-branches", no_argument, NULL, 'u' },
962 { "display-progress", no_argument, NULL, 'd' },
963 { "hash-filenames", no_argument, NULL, 'x' },
964 { "use-colors", no_argument, NULL, 'k' },
965 { "use-hotness-colors", no_argument, NULL, 'q' },
966 { 0, 0, 0, 0 }
967 };
968
969 /* Process args, return index to first non-arg. */
970
971 static int
972 process_args (int argc, char **argv)
973 {
974 int opt;
975
976 const char *opts = "abcdfhHijklmno:pqrs:tuvwx";
977 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
978 {
979 switch (opt)
980 {
981 case 'a':
982 flag_all_blocks = 1;
983 break;
984 case 'b':
985 flag_branches = 1;
986 break;
987 case 'c':
988 flag_counts = 1;
989 break;
990 case 'f':
991 flag_function_summary = 1;
992 break;
993 case 'h':
994 print_usage (false);
995 /* print_usage will exit. */
996 case 'l':
997 flag_long_names = 1;
998 break;
999 case 'H':
1000 flag_human_readable_numbers = 1;
1001 break;
1002 case 'k':
1003 flag_use_colors = 1;
1004 break;
1005 case 'q':
1006 flag_use_hotness_colors = 1;
1007 break;
1008 case 'm':
1009 flag_demangled_names = 1;
1010 break;
1011 case 'n':
1012 flag_gcov_file = 0;
1013 break;
1014 case 'o':
1015 object_directory = optarg;
1016 break;
1017 case 's':
1018 source_prefix = optarg;
1019 source_length = strlen (source_prefix);
1020 break;
1021 case 'r':
1022 flag_relative_only = 1;
1023 break;
1024 case 'p':
1025 flag_preserve_paths = 1;
1026 break;
1027 case 'u':
1028 flag_unconditional = 1;
1029 break;
1030 case 'i':
1031 case 'j':
1032 flag_json_format = 1;
1033 flag_gcov_file = 1;
1034 break;
1035 case 'd':
1036 flag_display_progress = 1;
1037 break;
1038 case 'x':
1039 flag_hash_filenames = 1;
1040 break;
1041 case 'w':
1042 flag_verbose = 1;
1043 break;
1044 case 't':
1045 flag_use_stdout = 1;
1046 break;
1047 case 'v':
1048 print_version ();
1049 /* print_version will exit. */
1050 default:
1051 print_usage (true);
1052 /* print_usage will exit. */
1053 }
1054 }
1055
1056 return optind;
1057 }
1058
1059 /* Output intermediate LINE sitting on LINE_NUM to JSON OBJECT.
1060 Add FUNCTION_NAME to the LINE. */
1061
1062 static void
1063 output_intermediate_json_line (json::array *object,
1064 line_info *line, unsigned line_num,
1065 const char *function_name)
1066 {
1067 if (!line->exists)
1068 return;
1069
1070 json::object *lineo = new json::object ();
1071 lineo->set ("line_number", new json::integer_number (line_num));
1072 if (function_name != NULL)
1073 lineo->set ("function_name", new json::string (function_name));
1074 lineo->set ("count", new json::integer_number (line->count));
1075 lineo->set ("unexecuted_block",
1076 new json::literal (line->has_unexecuted_block));
1077
1078 json::array *branches = new json::array ();
1079 lineo->set ("branches", branches);
1080
1081 vector<arc_info *>::const_iterator it;
1082 if (flag_branches)
1083 for (it = line->branches.begin (); it != line->branches.end ();
1084 it++)
1085 {
1086 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1087 {
1088 json::object *branch = new json::object ();
1089 branch->set ("count", new json::integer_number ((*it)->count));
1090 branch->set ("throw", new json::literal ((*it)->is_throw));
1091 branch->set ("fallthrough",
1092 new json::literal ((*it)->fall_through));
1093 branches->append (branch);
1094 }
1095 }
1096
1097 object->append (lineo);
1098 }
1099
1100 /* Get the name of the gcov file. The return value must be free'd.
1101
1102 It appends the '.gcov' extension to the *basename* of the file.
1103 The resulting file name will be in PWD.
1104
1105 e.g.,
1106 input: foo.da, output: foo.da.gcov
1107 input: a/b/foo.cc, output: foo.cc.gcov */
1108
1109 static char *
1110 get_gcov_intermediate_filename (const char *file_name)
1111 {
1112 const char *gcov = ".gcov.json.gz";
1113 char *result;
1114 const char *cptr;
1115
1116 /* Find the 'basename'. */
1117 cptr = lbasename (file_name);
1118
1119 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1120 sprintf (result, "%s%s", cptr, gcov);
1121
1122 return result;
1123 }
1124
1125 /* Output the result in JSON intermediate format.
1126 Source info SRC is dumped into JSON_FILES which is JSON array. */
1127
1128 static void
1129 output_json_intermediate_file (json::array *json_files, source_info *src)
1130 {
1131 json::object *root = new json::object ();
1132 json_files->append (root);
1133
1134 root->set ("file", new json::string (src->name));
1135
1136 json::array *functions = new json::array ();
1137 root->set ("functions", functions);
1138
1139 std::sort (src->functions.begin (), src->functions.end (),
1140 function_line_start_cmp ());
1141 for (vector<function_info *>::iterator it = src->functions.begin ();
1142 it != src->functions.end (); it++)
1143 {
1144 json::object *function = new json::object ();
1145 function->set ("name", new json::string ((*it)->m_name));
1146 function->set ("demangled_name",
1147 new json::string ((*it)->get_demangled_name ()));
1148 function->set ("start_line",
1149 new json::integer_number ((*it)->start_line));
1150 function->set ("start_column",
1151 new json::integer_number ((*it)->start_column));
1152 function->set ("end_line", new json::integer_number ((*it)->end_line));
1153 function->set ("end_column",
1154 new json::integer_number ((*it)->end_column));
1155 function->set ("blocks",
1156 new json::integer_number ((*it)->get_block_count ()));
1157 function->set ("blocks_executed",
1158 new json::integer_number ((*it)->blocks_executed));
1159 function->set ("execution_count",
1160 new json::integer_number ((*it)->blocks[0].count));
1161
1162 functions->append (function);
1163 }
1164
1165 json::array *lineso = new json::array ();
1166 root->set ("lines", lineso);
1167
1168 vector<function_info *> last_non_group_fns;
1169
1170 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1171 {
1172 vector<function_info *> *fns = src->get_functions_at_location (line_num);
1173
1174 if (fns != NULL)
1175 /* Print info for all group functions that begin on the line. */
1176 for (vector<function_info *>::iterator it2 = fns->begin ();
1177 it2 != fns->end (); it2++)
1178 {
1179 if (!(*it2)->is_group)
1180 last_non_group_fns.push_back (*it2);
1181
1182 vector<line_info> &lines = (*it2)->lines;
1183 /* The LINES array is allocated only for group functions. */
1184 for (unsigned i = 0; i < lines.size (); i++)
1185 {
1186 line_info *line = &lines[i];
1187 output_intermediate_json_line (lineso, line, line_num + i,
1188 (*it2)->m_name);
1189 }
1190 }
1191
1192 /* Follow with lines associated with the source file. */
1193 if (line_num < src->lines.size ())
1194 {
1195 unsigned size = last_non_group_fns.size ();
1196 function_info *last_fn = size > 0 ? last_non_group_fns[size - 1] : NULL;
1197 const char *fname = last_fn ? last_fn->m_name : NULL;
1198 output_intermediate_json_line (lineso, &src->lines[line_num], line_num,
1199 fname);
1200
1201 /* Pop ending function from stack. */
1202 if (last_fn != NULL && last_fn->end_line == line_num)
1203 last_non_group_fns.pop_back ();
1204 }
1205 }
1206 }
1207
1208 /* Function start pair. */
1209 struct function_start
1210 {
1211 unsigned source_file_idx;
1212 unsigned start_line;
1213 };
1214
1215 /* Traits class for function start hash maps below. */
1216
1217 struct function_start_pair_hash : typed_noop_remove <function_start>
1218 {
1219 typedef function_start value_type;
1220 typedef function_start compare_type;
1221
1222 static hashval_t
1223 hash (const function_start &ref)
1224 {
1225 inchash::hash hstate (0);
1226 hstate.add_int (ref.source_file_idx);
1227 hstate.add_int (ref.start_line);
1228 return hstate.end ();
1229 }
1230
1231 static bool
1232 equal (const function_start &ref1, const function_start &ref2)
1233 {
1234 return (ref1.source_file_idx == ref2.source_file_idx
1235 && ref1.start_line == ref2.start_line);
1236 }
1237
1238 static void
1239 mark_deleted (function_start &ref)
1240 {
1241 ref.start_line = ~1U;
1242 }
1243
1244 static const bool empty_zero_p = false;
1245
1246 static void
1247 mark_empty (function_start &ref)
1248 {
1249 ref.start_line = ~2U;
1250 }
1251
1252 static bool
1253 is_deleted (const function_start &ref)
1254 {
1255 return ref.start_line == ~1U;
1256 }
1257
1258 static bool
1259 is_empty (const function_start &ref)
1260 {
1261 return ref.start_line == ~2U;
1262 }
1263 };
1264
1265 /* Process a single input file. */
1266
1267 static void
1268 process_file (const char *file_name)
1269 {
1270 create_file_names (file_name);
1271
1272 for (unsigned i = 0; i < processed_files.size (); i++)
1273 if (strcmp (da_file_name, processed_files[i]) == 0)
1274 {
1275 fnotice (stderr, "'%s' file is already processed\n",
1276 file_name);
1277 return;
1278 }
1279
1280 processed_files.push_back (xstrdup (da_file_name));
1281
1282 read_graph_file ();
1283 read_count_file ();
1284 }
1285
1286 /* Process all functions in all files. */
1287
1288 static void
1289 process_all_functions (void)
1290 {
1291 hash_map<function_start_pair_hash, function_info *> fn_map;
1292
1293 /* Identify group functions. */
1294 for (vector<function_info *>::iterator it = functions.begin ();
1295 it != functions.end (); it++)
1296 if (!(*it)->artificial)
1297 {
1298 function_start needle;
1299 needle.source_file_idx = (*it)->src;
1300 needle.start_line = (*it)->start_line;
1301
1302 function_info **slot = fn_map.get (needle);
1303 if (slot)
1304 {
1305 (*slot)->is_group = 1;
1306 (*it)->is_group = 1;
1307 }
1308 else
1309 fn_map.put (needle, *it);
1310 }
1311
1312 /* Remove all artificial function. */
1313 functions.erase (remove_if (functions.begin (), functions.end (),
1314 function_info::is_artificial), functions.end ());
1315
1316 for (vector<function_info *>::iterator it = functions.begin ();
1317 it != functions.end (); it++)
1318 {
1319 function_info *fn = *it;
1320 unsigned src = fn->src;
1321
1322 if (!fn->counts.empty () || no_data_file)
1323 {
1324 source_info *s = &sources[src];
1325 s->add_function (fn);
1326
1327 /* Mark last line in files touched by function. */
1328 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1329 block_no++)
1330 {
1331 block_info *block = &fn->blocks[block_no];
1332 for (unsigned i = 0; i < block->locations.size (); i++)
1333 {
1334 /* Sort lines of locations. */
1335 sort (block->locations[i].lines.begin (),
1336 block->locations[i].lines.end ());
1337
1338 if (!block->locations[i].lines.empty ())
1339 {
1340 s = &sources[block->locations[i].source_file_idx];
1341 unsigned last_line
1342 = block->locations[i].lines.back ();
1343
1344 /* Record new lines for the function. */
1345 if (last_line >= s->lines.size ())
1346 {
1347 s = &sources[block->locations[i].source_file_idx];
1348 unsigned last_line
1349 = block->locations[i].lines.back ();
1350
1351 /* Record new lines for the function. */
1352 if (last_line >= s->lines.size ())
1353 {
1354 /* Record new lines for a source file. */
1355 s->lines.resize (last_line + 1);
1356 }
1357 }
1358 }
1359 }
1360 }
1361
1362 /* Allocate lines for group function, following start_line
1363 and end_line information of the function. */
1364 if (fn->is_group)
1365 fn->lines.resize (fn->end_line - fn->start_line + 1);
1366
1367 solve_flow_graph (fn);
1368 if (fn->has_catch)
1369 find_exception_blocks (fn);
1370 }
1371 else
1372 {
1373 /* The function was not in the executable -- some other
1374 instance must have been selected. */
1375 }
1376 }
1377 }
1378
1379 static void
1380 output_gcov_file (const char *file_name, source_info *src)
1381 {
1382 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1383
1384 if (src->coverage.lines)
1385 {
1386 FILE *gcov_file = fopen (gcov_file_name, "w");
1387 if (gcov_file)
1388 {
1389 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1390 output_lines (gcov_file, src);
1391 if (ferror (gcov_file))
1392 fnotice (stderr, "Error writing output file '%s'\n",
1393 gcov_file_name);
1394 fclose (gcov_file);
1395 }
1396 else
1397 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1398 }
1399 else
1400 {
1401 unlink (gcov_file_name);
1402 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1403 }
1404 free (gcov_file_name);
1405 }
1406
1407 static void
1408 generate_results (const char *file_name)
1409 {
1410 char *gcov_intermediate_filename;
1411
1412 for (vector<function_info *>::iterator it = functions.begin ();
1413 it != functions.end (); it++)
1414 {
1415 function_info *fn = *it;
1416 coverage_info coverage;
1417
1418 memset (&coverage, 0, sizeof (coverage));
1419 coverage.name = fn->get_name ();
1420 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1421 if (flag_function_summary)
1422 {
1423 function_summary (&coverage);
1424 fnotice (stdout, "\n");
1425 }
1426 }
1427
1428 name_map needle;
1429 needle.name = file_name;
1430 vector<name_map>::iterator it
1431 = std::find (names.begin (), names.end (), needle);
1432 if (it != names.end ())
1433 file_name = sources[it->src].coverage.name;
1434 else
1435 file_name = canonicalize_name (file_name);
1436
1437 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1438
1439 json::object *root = new json::object ();
1440 root->set ("format_version", new json::string ("1"));
1441 root->set ("gcc_version", new json::string (version_string));
1442
1443 if (bbg_cwd != NULL)
1444 root->set ("current_working_directory", new json::string (bbg_cwd));
1445 root->set ("data_file", new json::string (file_name));
1446
1447 json::array *json_files = new json::array ();
1448 root->set ("files", json_files);
1449
1450 for (vector<source_info>::iterator it = sources.begin ();
1451 it != sources.end (); it++)
1452 {
1453 source_info *src = &(*it);
1454 if (flag_relative_only)
1455 {
1456 /* Ignore this source, if it is an absolute path (after
1457 source prefix removal). */
1458 char first = src->coverage.name[0];
1459
1460 #if HAVE_DOS_BASED_FILE_SYSTEM
1461 if (first && src->coverage.name[1] == ':')
1462 first = src->coverage.name[2];
1463 #endif
1464 if (IS_DIR_SEPARATOR (first))
1465 continue;
1466 }
1467
1468 accumulate_line_counts (src);
1469
1470 if (!flag_use_stdout)
1471 file_summary (&src->coverage);
1472 total_lines += src->coverage.lines;
1473 total_executed += src->coverage.lines_executed;
1474 if (flag_gcov_file)
1475 {
1476 if (flag_json_format)
1477 {
1478 output_json_intermediate_file (json_files, src);
1479 if (!flag_use_stdout)
1480 fnotice (stdout, "\n");
1481 }
1482 else
1483 {
1484 if (flag_use_stdout)
1485 {
1486 if (src->coverage.lines)
1487 output_lines (stdout, src);
1488 }
1489 else
1490 {
1491 output_gcov_file (file_name, src);
1492 fnotice (stdout, "\n");
1493 }
1494 }
1495 }
1496 }
1497
1498 if (flag_gcov_file && flag_json_format)
1499 {
1500 if (flag_use_stdout)
1501 {
1502 root->dump (stdout);
1503 printf ("\n");
1504 }
1505 else
1506 {
1507 pretty_printer pp;
1508 root->print (&pp);
1509 pp_formatted_text (&pp);
1510
1511 gzFile output = gzopen (gcov_intermediate_filename, "w");
1512 if (output == NULL)
1513 {
1514 fnotice (stderr, "Cannot open JSON output file %s\n",
1515 gcov_intermediate_filename);
1516 return;
1517 }
1518
1519 if (gzputs (output, pp_formatted_text (&pp)) == EOF
1520 || gzclose (output))
1521 {
1522 fnotice (stderr, "Error writing JSON output file %s\n",
1523 gcov_intermediate_filename);
1524 return;
1525 }
1526 }
1527 }
1528 }
1529
1530 /* Release all memory used. */
1531
1532 static void
1533 release_structures (void)
1534 {
1535 for (vector<function_info *>::iterator it = functions.begin ();
1536 it != functions.end (); it++)
1537 delete (*it);
1538
1539 sources.resize (0);
1540 names.resize (0);
1541 functions.resize (0);
1542 ident_to_fn.clear ();
1543 }
1544
1545 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1546 is not specified, these are named from FILE_NAME sans extension. If
1547 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1548 directory, but named from the basename of the FILE_NAME, sans extension.
1549 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1550 and the data files are named from that. */
1551
1552 static void
1553 create_file_names (const char *file_name)
1554 {
1555 char *cptr;
1556 char *name;
1557 int length = strlen (file_name);
1558 int base;
1559
1560 /* Free previous file names. */
1561 free (bbg_file_name);
1562 free (da_file_name);
1563 da_file_name = bbg_file_name = NULL;
1564 bbg_file_time = 0;
1565 bbg_stamp = 0;
1566
1567 if (object_directory && object_directory[0])
1568 {
1569 struct stat status;
1570
1571 length += strlen (object_directory) + 2;
1572 name = XNEWVEC (char, length);
1573 name[0] = 0;
1574
1575 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1576 strcat (name, object_directory);
1577 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1578 strcat (name, "/");
1579 }
1580 else
1581 {
1582 name = XNEWVEC (char, length + 1);
1583 strcpy (name, file_name);
1584 base = 0;
1585 }
1586
1587 if (base)
1588 {
1589 /* Append source file name. */
1590 const char *cptr = lbasename (file_name);
1591 strcat (name, cptr ? cptr : file_name);
1592 }
1593
1594 /* Remove the extension. */
1595 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1596 if (cptr)
1597 *cptr = 0;
1598
1599 length = strlen (name);
1600
1601 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1602 strcpy (bbg_file_name, name);
1603 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1604
1605 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1606 strcpy (da_file_name, name);
1607 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1608
1609 free (name);
1610 return;
1611 }
1612
1613 /* Find or create a source file structure for FILE_NAME. Copies
1614 FILE_NAME on creation */
1615
1616 static unsigned
1617 find_source (const char *file_name)
1618 {
1619 char *canon;
1620 unsigned idx;
1621 struct stat status;
1622
1623 if (!file_name)
1624 file_name = "<unknown>";
1625
1626 name_map needle;
1627 needle.name = file_name;
1628
1629 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1630 needle);
1631 if (it != names.end ())
1632 {
1633 idx = it->src;
1634 goto check_date;
1635 }
1636
1637 /* Not found, try the canonical name. */
1638 canon = canonicalize_name (file_name);
1639 needle.name = canon;
1640 it = std::find (names.begin (), names.end (), needle);
1641 if (it == names.end ())
1642 {
1643 /* Not found with canonical name, create a new source. */
1644 source_info *src;
1645
1646 idx = sources.size ();
1647 needle = name_map (canon, idx);
1648 names.push_back (needle);
1649
1650 sources.push_back (source_info ());
1651 src = &sources.back ();
1652 src->name = canon;
1653 src->coverage.name = src->name;
1654 src->index = idx;
1655 if (source_length
1656 #if HAVE_DOS_BASED_FILE_SYSTEM
1657 /* You lose if separators don't match exactly in the
1658 prefix. */
1659 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1660 #else
1661 && !strncmp (source_prefix, src->coverage.name, source_length)
1662 #endif
1663 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1664 src->coverage.name += source_length + 1;
1665 if (!stat (src->name, &status))
1666 src->file_time = status.st_mtime;
1667 }
1668 else
1669 idx = it->src;
1670
1671 needle.name = file_name;
1672 if (std::find (names.begin (), names.end (), needle) == names.end ())
1673 {
1674 /* Append the non-canonical name. */
1675 names.push_back (name_map (xstrdup (file_name), idx));
1676 }
1677
1678 /* Resort the name map. */
1679 std::sort (names.begin (), names.end ());
1680
1681 check_date:
1682 if (sources[idx].file_time > bbg_file_time)
1683 {
1684 static int info_emitted;
1685
1686 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1687 file_name, bbg_file_name);
1688 if (!info_emitted)
1689 {
1690 fnotice (stderr,
1691 "(the message is displayed only once per source file)\n");
1692 info_emitted = 1;
1693 }
1694 sources[idx].file_time = 0;
1695 }
1696
1697 return idx;
1698 }
1699
1700 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1701
1702 static void
1703 read_graph_file (void)
1704 {
1705 unsigned version;
1706 unsigned current_tag = 0;
1707 unsigned tag;
1708
1709 if (!gcov_open (bbg_file_name, 1))
1710 {
1711 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1712 return;
1713 }
1714 bbg_file_time = gcov_time ();
1715 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1716 {
1717 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1718 gcov_close ();
1719 return;
1720 }
1721
1722 version = gcov_read_unsigned ();
1723 if (version != GCOV_VERSION)
1724 {
1725 char v[4], e[4];
1726
1727 GCOV_UNSIGNED2STRING (v, version);
1728 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1729
1730 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1731 bbg_file_name, v, e);
1732 }
1733 bbg_stamp = gcov_read_unsigned ();
1734 bbg_cwd = xstrdup (gcov_read_string ());
1735 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1736
1737 function_info *fn = NULL;
1738 while ((tag = gcov_read_unsigned ()))
1739 {
1740 unsigned length = gcov_read_unsigned ();
1741 gcov_position_t base = gcov_position ();
1742
1743 if (tag == GCOV_TAG_FUNCTION)
1744 {
1745 char *function_name;
1746 unsigned ident;
1747 unsigned lineno_checksum, cfg_checksum;
1748
1749 ident = gcov_read_unsigned ();
1750 lineno_checksum = gcov_read_unsigned ();
1751 cfg_checksum = gcov_read_unsigned ();
1752 function_name = xstrdup (gcov_read_string ());
1753 unsigned artificial = gcov_read_unsigned ();
1754 unsigned src_idx = find_source (gcov_read_string ());
1755 unsigned start_line = gcov_read_unsigned ();
1756 unsigned start_column = gcov_read_unsigned ();
1757 unsigned end_line = gcov_read_unsigned ();
1758 unsigned end_column = gcov_read_unsigned ();
1759
1760 fn = new function_info ();
1761 functions.push_back (fn);
1762 ident_to_fn[ident] = fn;
1763
1764 fn->m_name = function_name;
1765 fn->ident = ident;
1766 fn->lineno_checksum = lineno_checksum;
1767 fn->cfg_checksum = cfg_checksum;
1768 fn->src = src_idx;
1769 fn->start_line = start_line;
1770 fn->start_column = start_column;
1771 fn->end_line = end_line;
1772 fn->end_column = end_column;
1773 fn->artificial = artificial;
1774
1775 current_tag = tag;
1776 }
1777 else if (fn && tag == GCOV_TAG_BLOCKS)
1778 {
1779 if (!fn->blocks.empty ())
1780 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1781 bbg_file_name, fn->get_name ());
1782 else
1783 fn->blocks.resize (gcov_read_unsigned ());
1784 }
1785 else if (fn && tag == GCOV_TAG_ARCS)
1786 {
1787 unsigned src = gcov_read_unsigned ();
1788 fn->blocks[src].id = src;
1789 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1790 block_info *src_blk = &fn->blocks[src];
1791 unsigned mark_catches = 0;
1792 struct arc_info *arc;
1793
1794 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1795 goto corrupt;
1796
1797 while (num_dests--)
1798 {
1799 unsigned dest = gcov_read_unsigned ();
1800 unsigned flags = gcov_read_unsigned ();
1801
1802 if (dest >= fn->blocks.size ())
1803 goto corrupt;
1804 arc = XCNEW (arc_info);
1805
1806 arc->dst = &fn->blocks[dest];
1807 arc->src = src_blk;
1808
1809 arc->count = 0;
1810 arc->count_valid = 0;
1811 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1812 arc->fake = !!(flags & GCOV_ARC_FAKE);
1813 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1814
1815 arc->succ_next = src_blk->succ;
1816 src_blk->succ = arc;
1817 src_blk->num_succ++;
1818
1819 arc->pred_next = fn->blocks[dest].pred;
1820 fn->blocks[dest].pred = arc;
1821 fn->blocks[dest].num_pred++;
1822
1823 if (arc->fake)
1824 {
1825 if (src)
1826 {
1827 /* Exceptional exit from this function, the
1828 source block must be a call. */
1829 fn->blocks[src].is_call_site = 1;
1830 arc->is_call_non_return = 1;
1831 mark_catches = 1;
1832 }
1833 else
1834 {
1835 /* Non-local return from a callee of this
1836 function. The destination block is a setjmp. */
1837 arc->is_nonlocal_return = 1;
1838 fn->blocks[dest].is_nonlocal_return = 1;
1839 }
1840 }
1841
1842 if (!arc->on_tree)
1843 fn->counts.push_back (0);
1844 }
1845
1846 if (mark_catches)
1847 {
1848 /* We have a fake exit from this block. The other
1849 non-fall through exits must be to catch handlers.
1850 Mark them as catch arcs. */
1851
1852 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1853 if (!arc->fake && !arc->fall_through)
1854 {
1855 arc->is_throw = 1;
1856 fn->has_catch = 1;
1857 }
1858 }
1859 }
1860 else if (fn && tag == GCOV_TAG_LINES)
1861 {
1862 unsigned blockno = gcov_read_unsigned ();
1863 block_info *block = &fn->blocks[blockno];
1864
1865 if (blockno >= fn->blocks.size ())
1866 goto corrupt;
1867
1868 while (true)
1869 {
1870 unsigned lineno = gcov_read_unsigned ();
1871
1872 if (lineno)
1873 block->locations.back ().lines.push_back (lineno);
1874 else
1875 {
1876 const char *file_name = gcov_read_string ();
1877
1878 if (!file_name)
1879 break;
1880 block->locations.push_back (block_location_info
1881 (find_source (file_name)));
1882 }
1883 }
1884 }
1885 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1886 {
1887 fn = NULL;
1888 current_tag = 0;
1889 }
1890 gcov_sync (base, length);
1891 if (gcov_is_error ())
1892 {
1893 corrupt:;
1894 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1895 break;
1896 }
1897 }
1898 gcov_close ();
1899
1900 if (functions.empty ())
1901 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1902 }
1903
1904 /* Reads profiles from the count file and attach to each
1905 function. Return nonzero if fatal error. */
1906
1907 static int
1908 read_count_file (void)
1909 {
1910 unsigned ix;
1911 unsigned version;
1912 unsigned tag;
1913 function_info *fn = NULL;
1914 int error = 0;
1915 map<unsigned, function_info *>::iterator it;
1916
1917 if (!gcov_open (da_file_name, 1))
1918 {
1919 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1920 da_file_name);
1921 no_data_file = 1;
1922 return 0;
1923 }
1924 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1925 {
1926 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1927 cleanup:;
1928 gcov_close ();
1929 return 1;
1930 }
1931 version = gcov_read_unsigned ();
1932 if (version != GCOV_VERSION)
1933 {
1934 char v[4], e[4];
1935
1936 GCOV_UNSIGNED2STRING (v, version);
1937 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1938
1939 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1940 da_file_name, v, e);
1941 }
1942 tag = gcov_read_unsigned ();
1943 if (tag != bbg_stamp)
1944 {
1945 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1946 goto cleanup;
1947 }
1948
1949 while ((tag = gcov_read_unsigned ()))
1950 {
1951 unsigned length = gcov_read_unsigned ();
1952 int read_length = (int)length;
1953 unsigned long base = gcov_position ();
1954
1955 if (tag == GCOV_TAG_OBJECT_SUMMARY)
1956 {
1957 struct gcov_summary summary;
1958 gcov_read_summary (&summary);
1959 object_runs = summary.runs;
1960 }
1961 else if (tag == GCOV_TAG_FUNCTION && !length)
1962 ; /* placeholder */
1963 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1964 {
1965 unsigned ident;
1966 ident = gcov_read_unsigned ();
1967 fn = NULL;
1968 it = ident_to_fn.find (ident);
1969 if (it != ident_to_fn.end ())
1970 fn = it->second;
1971
1972 if (!fn)
1973 ;
1974 else if (gcov_read_unsigned () != fn->lineno_checksum
1975 || gcov_read_unsigned () != fn->cfg_checksum)
1976 {
1977 mismatch:;
1978 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1979 da_file_name, fn->get_name ());
1980 goto cleanup;
1981 }
1982 }
1983 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1984 {
1985 length = abs (read_length);
1986 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1987 goto mismatch;
1988
1989 if (read_length > 0)
1990 for (ix = 0; ix != fn->counts.size (); ix++)
1991 fn->counts[ix] += gcov_read_counter ();
1992 }
1993 if (read_length < 0)
1994 read_length = 0;
1995 gcov_sync (base, read_length);
1996 if ((error = gcov_is_error ()))
1997 {
1998 fnotice (stderr,
1999 error < 0
2000 ? N_("%s:overflowed\n")
2001 : N_("%s:corrupted\n"),
2002 da_file_name);
2003 goto cleanup;
2004 }
2005 }
2006
2007 gcov_close ();
2008 return 0;
2009 }
2010
2011 /* Solve the flow graph. Propagate counts from the instrumented arcs
2012 to the blocks and the uninstrumented arcs. */
2013
2014 static void
2015 solve_flow_graph (function_info *fn)
2016 {
2017 unsigned ix;
2018 arc_info *arc;
2019 gcov_type *count_ptr = &fn->counts.front ();
2020 block_info *blk;
2021 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
2022 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
2023
2024 /* The arcs were built in reverse order. Fix that now. */
2025 for (ix = fn->blocks.size (); ix--;)
2026 {
2027 arc_info *arc_p, *arc_n;
2028
2029 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
2030 arc_p = arc, arc = arc_n)
2031 {
2032 arc_n = arc->succ_next;
2033 arc->succ_next = arc_p;
2034 }
2035 fn->blocks[ix].succ = arc_p;
2036
2037 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
2038 arc_p = arc, arc = arc_n)
2039 {
2040 arc_n = arc->pred_next;
2041 arc->pred_next = arc_p;
2042 }
2043 fn->blocks[ix].pred = arc_p;
2044 }
2045
2046 if (fn->blocks.size () < 2)
2047 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
2048 bbg_file_name, fn->get_name ());
2049 else
2050 {
2051 if (fn->blocks[ENTRY_BLOCK].num_pred)
2052 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
2053 bbg_file_name, fn->get_name ());
2054 else
2055 /* We can't deduce the entry block counts from the lack of
2056 predecessors. */
2057 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
2058
2059 if (fn->blocks[EXIT_BLOCK].num_succ)
2060 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
2061 bbg_file_name, fn->get_name ());
2062 else
2063 /* Likewise, we can't deduce exit block counts from the lack
2064 of its successors. */
2065 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
2066 }
2067
2068 /* Propagate the measured counts, this must be done in the same
2069 order as the code in profile.c */
2070 for (unsigned i = 0; i < fn->blocks.size (); i++)
2071 {
2072 blk = &fn->blocks[i];
2073 block_info const *prev_dst = NULL;
2074 int out_of_order = 0;
2075 int non_fake_succ = 0;
2076
2077 for (arc = blk->succ; arc; arc = arc->succ_next)
2078 {
2079 if (!arc->fake)
2080 non_fake_succ++;
2081
2082 if (!arc->on_tree)
2083 {
2084 if (count_ptr)
2085 arc->count = *count_ptr++;
2086 arc->count_valid = 1;
2087 blk->num_succ--;
2088 arc->dst->num_pred--;
2089 }
2090 if (prev_dst && prev_dst > arc->dst)
2091 out_of_order = 1;
2092 prev_dst = arc->dst;
2093 }
2094 if (non_fake_succ == 1)
2095 {
2096 /* If there is only one non-fake exit, it is an
2097 unconditional branch. */
2098 for (arc = blk->succ; arc; arc = arc->succ_next)
2099 if (!arc->fake)
2100 {
2101 arc->is_unconditional = 1;
2102 /* If this block is instrumenting a call, it might be
2103 an artificial block. It is not artificial if it has
2104 a non-fallthrough exit, or the destination of this
2105 arc has more than one entry. Mark the destination
2106 block as a return site, if none of those conditions
2107 hold. */
2108 if (blk->is_call_site && arc->fall_through
2109 && arc->dst->pred == arc && !arc->pred_next)
2110 arc->dst->is_call_return = 1;
2111 }
2112 }
2113
2114 /* Sort the successor arcs into ascending dst order. profile.c
2115 normally produces arcs in the right order, but sometimes with
2116 one or two out of order. We're not using a particularly
2117 smart sort. */
2118 if (out_of_order)
2119 {
2120 arc_info *start = blk->succ;
2121 unsigned changes = 1;
2122
2123 while (changes)
2124 {
2125 arc_info *arc, *arc_p, *arc_n;
2126
2127 changes = 0;
2128 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2129 {
2130 if (arc->dst > arc_n->dst)
2131 {
2132 changes = 1;
2133 if (arc_p)
2134 arc_p->succ_next = arc_n;
2135 else
2136 start = arc_n;
2137 arc->succ_next = arc_n->succ_next;
2138 arc_n->succ_next = arc;
2139 arc_p = arc_n;
2140 }
2141 else
2142 {
2143 arc_p = arc;
2144 arc = arc_n;
2145 }
2146 }
2147 }
2148 blk->succ = start;
2149 }
2150
2151 /* Place it on the invalid chain, it will be ignored if that's
2152 wrong. */
2153 blk->invalid_chain = 1;
2154 blk->chain = invalid_blocks;
2155 invalid_blocks = blk;
2156 }
2157
2158 while (invalid_blocks || valid_blocks)
2159 {
2160 while ((blk = invalid_blocks))
2161 {
2162 gcov_type total = 0;
2163 const arc_info *arc;
2164
2165 invalid_blocks = blk->chain;
2166 blk->invalid_chain = 0;
2167 if (!blk->num_succ)
2168 for (arc = blk->succ; arc; arc = arc->succ_next)
2169 total += arc->count;
2170 else if (!blk->num_pred)
2171 for (arc = blk->pred; arc; arc = arc->pred_next)
2172 total += arc->count;
2173 else
2174 continue;
2175
2176 blk->count = total;
2177 blk->count_valid = 1;
2178 blk->chain = valid_blocks;
2179 blk->valid_chain = 1;
2180 valid_blocks = blk;
2181 }
2182 while ((blk = valid_blocks))
2183 {
2184 gcov_type total;
2185 arc_info *arc, *inv_arc;
2186
2187 valid_blocks = blk->chain;
2188 blk->valid_chain = 0;
2189 if (blk->num_succ == 1)
2190 {
2191 block_info *dst;
2192
2193 total = blk->count;
2194 inv_arc = NULL;
2195 for (arc = blk->succ; arc; arc = arc->succ_next)
2196 {
2197 total -= arc->count;
2198 if (!arc->count_valid)
2199 inv_arc = arc;
2200 }
2201 dst = inv_arc->dst;
2202 inv_arc->count_valid = 1;
2203 inv_arc->count = total;
2204 blk->num_succ--;
2205 dst->num_pred--;
2206 if (dst->count_valid)
2207 {
2208 if (dst->num_pred == 1 && !dst->valid_chain)
2209 {
2210 dst->chain = valid_blocks;
2211 dst->valid_chain = 1;
2212 valid_blocks = dst;
2213 }
2214 }
2215 else
2216 {
2217 if (!dst->num_pred && !dst->invalid_chain)
2218 {
2219 dst->chain = invalid_blocks;
2220 dst->invalid_chain = 1;
2221 invalid_blocks = dst;
2222 }
2223 }
2224 }
2225 if (blk->num_pred == 1)
2226 {
2227 block_info *src;
2228
2229 total = blk->count;
2230 inv_arc = NULL;
2231 for (arc = blk->pred; arc; arc = arc->pred_next)
2232 {
2233 total -= arc->count;
2234 if (!arc->count_valid)
2235 inv_arc = arc;
2236 }
2237 src = inv_arc->src;
2238 inv_arc->count_valid = 1;
2239 inv_arc->count = total;
2240 blk->num_pred--;
2241 src->num_succ--;
2242 if (src->count_valid)
2243 {
2244 if (src->num_succ == 1 && !src->valid_chain)
2245 {
2246 src->chain = valid_blocks;
2247 src->valid_chain = 1;
2248 valid_blocks = src;
2249 }
2250 }
2251 else
2252 {
2253 if (!src->num_succ && !src->invalid_chain)
2254 {
2255 src->chain = invalid_blocks;
2256 src->invalid_chain = 1;
2257 invalid_blocks = src;
2258 }
2259 }
2260 }
2261 }
2262 }
2263
2264 /* If the graph has been correctly solved, every block will have a
2265 valid count. */
2266 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2267 if (!fn->blocks[i].count_valid)
2268 {
2269 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2270 bbg_file_name, fn->get_name ());
2271 break;
2272 }
2273 }
2274
2275 /* Mark all the blocks only reachable via an incoming catch. */
2276
2277 static void
2278 find_exception_blocks (function_info *fn)
2279 {
2280 unsigned ix;
2281 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2282
2283 /* First mark all blocks as exceptional. */
2284 for (ix = fn->blocks.size (); ix--;)
2285 fn->blocks[ix].exceptional = 1;
2286
2287 /* Now mark all the blocks reachable via non-fake edges */
2288 queue[0] = &fn->blocks[0];
2289 queue[0]->exceptional = 0;
2290 for (ix = 1; ix;)
2291 {
2292 block_info *block = queue[--ix];
2293 const arc_info *arc;
2294
2295 for (arc = block->succ; arc; arc = arc->succ_next)
2296 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2297 {
2298 arc->dst->exceptional = 0;
2299 queue[ix++] = arc->dst;
2300 }
2301 }
2302 }
2303 \f
2304
2305 /* Increment totals in COVERAGE according to arc ARC. */
2306
2307 static void
2308 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2309 {
2310 if (arc->is_call_non_return)
2311 {
2312 coverage->calls++;
2313 if (arc->src->count)
2314 coverage->calls_executed++;
2315 }
2316 else if (!arc->is_unconditional)
2317 {
2318 coverage->branches++;
2319 if (arc->src->count)
2320 coverage->branches_executed++;
2321 if (arc->count)
2322 coverage->branches_taken++;
2323 }
2324 }
2325
2326 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2327 readable format. */
2328
2329 static char const *
2330 format_count (gcov_type count)
2331 {
2332 static char buffer[64];
2333 const char *units = " kMGTPEZY";
2334
2335 if (count < 1000 || !flag_human_readable_numbers)
2336 {
2337 sprintf (buffer, "%" PRId64, count);
2338 return buffer;
2339 }
2340
2341 unsigned i;
2342 gcov_type divisor = 1;
2343 for (i = 0; units[i+1]; i++, divisor *= 1000)
2344 {
2345 if (count + divisor / 2 < 1000 * divisor)
2346 break;
2347 }
2348 float r = 1.0f * count / divisor;
2349 sprintf (buffer, "%.1f%c", r, units[i]);
2350 return buffer;
2351 }
2352
2353 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2354 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2355 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2356 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2357 format TOP. Return pointer to a static string. */
2358
2359 static char const *
2360 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2361 {
2362 static char buffer[20];
2363
2364 if (decimal_places >= 0)
2365 {
2366 float ratio = bottom ? 100.0f * top / bottom: 0;
2367
2368 /* Round up to 1% if there's a small non-zero value. */
2369 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2370 ratio = 1.0f;
2371 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2372 }
2373 else
2374 return format_count (top);
2375
2376 return buffer;
2377 }
2378
2379 /* Summary of execution */
2380
2381 static void
2382 executed_summary (unsigned lines, unsigned executed)
2383 {
2384 if (lines)
2385 fnotice (stdout, "Lines executed:%s of %d\n",
2386 format_gcov (executed, lines, 2), lines);
2387 else
2388 fnotice (stdout, "No executable lines\n");
2389 }
2390
2391 /* Output summary info for a function. */
2392
2393 static void
2394 function_summary (const coverage_info *coverage)
2395 {
2396 fnotice (stdout, "%s '%s'\n", "Function", coverage->name);
2397 executed_summary (coverage->lines, coverage->lines_executed);
2398 }
2399
2400 /* Output summary info for a file. */
2401
2402 static void
2403 file_summary (const coverage_info *coverage)
2404 {
2405 fnotice (stdout, "%s '%s'\n", "File", coverage->name);
2406 executed_summary (coverage->lines, coverage->lines_executed);
2407
2408 if (flag_branches)
2409 {
2410 if (coverage->branches)
2411 {
2412 fnotice (stdout, "Branches executed:%s of %d\n",
2413 format_gcov (coverage->branches_executed,
2414 coverage->branches, 2),
2415 coverage->branches);
2416 fnotice (stdout, "Taken at least once:%s of %d\n",
2417 format_gcov (coverage->branches_taken,
2418 coverage->branches, 2),
2419 coverage->branches);
2420 }
2421 else
2422 fnotice (stdout, "No branches\n");
2423 if (coverage->calls)
2424 fnotice (stdout, "Calls executed:%s of %d\n",
2425 format_gcov (coverage->calls_executed, coverage->calls, 2),
2426 coverage->calls);
2427 else
2428 fnotice (stdout, "No calls\n");
2429 }
2430 }
2431
2432 /* Canonicalize the filename NAME by canonicalizing directory
2433 separators, eliding . components and resolving .. components
2434 appropriately. Always returns a unique string. */
2435
2436 static char *
2437 canonicalize_name (const char *name)
2438 {
2439 /* The canonical name cannot be longer than the incoming name. */
2440 char *result = XNEWVEC (char, strlen (name) + 1);
2441 const char *base = name, *probe;
2442 char *ptr = result;
2443 char *dd_base;
2444 int slash = 0;
2445
2446 #if HAVE_DOS_BASED_FILE_SYSTEM
2447 if (base[0] && base[1] == ':')
2448 {
2449 result[0] = base[0];
2450 result[1] = ':';
2451 base += 2;
2452 ptr += 2;
2453 }
2454 #endif
2455 for (dd_base = ptr; *base; base = probe)
2456 {
2457 size_t len;
2458
2459 for (probe = base; *probe; probe++)
2460 if (IS_DIR_SEPARATOR (*probe))
2461 break;
2462
2463 len = probe - base;
2464 if (len == 1 && base[0] == '.')
2465 /* Elide a '.' directory */
2466 ;
2467 else if (len == 2 && base[0] == '.' && base[1] == '.')
2468 {
2469 /* '..', we can only elide it and the previous directory, if
2470 we're not a symlink. */
2471 struct stat ATTRIBUTE_UNUSED buf;
2472
2473 *ptr = 0;
2474 if (dd_base == ptr
2475 #if defined (S_ISLNK)
2476 /* S_ISLNK is not POSIX.1-1996. */
2477 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2478 #endif
2479 )
2480 {
2481 /* Cannot elide, or unreadable or a symlink. */
2482 dd_base = ptr + 2 + slash;
2483 goto regular;
2484 }
2485 while (ptr != dd_base && *ptr != '/')
2486 ptr--;
2487 slash = ptr != result;
2488 }
2489 else
2490 {
2491 regular:
2492 /* Regular pathname component. */
2493 if (slash)
2494 *ptr++ = '/';
2495 memcpy (ptr, base, len);
2496 ptr += len;
2497 slash = 1;
2498 }
2499
2500 for (; IS_DIR_SEPARATOR (*probe); probe++)
2501 continue;
2502 }
2503 *ptr = 0;
2504
2505 return result;
2506 }
2507
2508 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2509
2510 static void
2511 md5sum_to_hex (const char *sum, char *buffer)
2512 {
2513 for (unsigned i = 0; i < 16; i++)
2514 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2515 }
2516
2517 /* Generate an output file name. INPUT_NAME is the canonicalized main
2518 input file and SRC_NAME is the canonicalized file name.
2519 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2520 long_output_names we prepend the processed name of the input file
2521 to each output name (except when the current source file is the
2522 input file, so you don't get a double concatenation). The two
2523 components are separated by '##'. With preserve_paths we create a
2524 filename from all path components of the source file, replacing '/'
2525 with '#', and .. with '^', without it we simply take the basename
2526 component. (Remember, the canonicalized name will already have
2527 elided '.' components and converted \\ separators.) */
2528
2529 static char *
2530 make_gcov_file_name (const char *input_name, const char *src_name)
2531 {
2532 char *ptr;
2533 char *result;
2534
2535 if (flag_long_names && input_name && strcmp (src_name, input_name))
2536 {
2537 /* Generate the input filename part. */
2538 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2539
2540 ptr = result;
2541 ptr = mangle_name (input_name, ptr);
2542 ptr[0] = ptr[1] = '#';
2543 ptr += 2;
2544 }
2545 else
2546 {
2547 result = XNEWVEC (char, strlen (src_name) + 10);
2548 ptr = result;
2549 }
2550
2551 ptr = mangle_name (src_name, ptr);
2552 strcpy (ptr, ".gcov");
2553
2554 /* When hashing filenames, we shorten them by only using the filename
2555 component and appending a hash of the full (mangled) pathname. */
2556 if (flag_hash_filenames)
2557 {
2558 md5_ctx ctx;
2559 char md5sum[16];
2560 char md5sum_hex[33];
2561
2562 md5_init_ctx (&ctx);
2563 md5_process_bytes (src_name, strlen (src_name), &ctx);
2564 md5_finish_ctx (&ctx, md5sum);
2565 md5sum_to_hex (md5sum, md5sum_hex);
2566 free (result);
2567
2568 result = XNEWVEC (char, strlen (src_name) + 50);
2569 ptr = result;
2570 ptr = mangle_name (src_name, ptr);
2571 ptr[0] = ptr[1] = '#';
2572 ptr += 2;
2573 memcpy (ptr, md5sum_hex, 32);
2574 ptr += 32;
2575 strcpy (ptr, ".gcov");
2576 }
2577
2578 return result;
2579 }
2580
2581 /* Mangle BASE name, copy it at the beginning of PTR buffer and
2582 return address of the \0 character of the buffer. */
2583
2584 static char *
2585 mangle_name (char const *base, char *ptr)
2586 {
2587 size_t len;
2588
2589 /* Generate the source filename part. */
2590 if (!flag_preserve_paths)
2591 base = lbasename (base);
2592 else
2593 base = mangle_path (base);
2594
2595 len = strlen (base);
2596 memcpy (ptr, base, len);
2597 ptr += len;
2598
2599 return ptr;
2600 }
2601
2602 /* Scan through the bb_data for each line in the block, increment
2603 the line number execution count indicated by the execution count of
2604 the appropriate basic block. */
2605
2606 static void
2607 add_line_counts (coverage_info *coverage, function_info *fn)
2608 {
2609 bool has_any_line = false;
2610 /* Scan each basic block. */
2611 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2612 {
2613 line_info *line = NULL;
2614 block_info *block = &fn->blocks[ix];
2615 if (block->count && ix && ix + 1 != fn->blocks.size ())
2616 fn->blocks_executed++;
2617 for (unsigned i = 0; i < block->locations.size (); i++)
2618 {
2619 unsigned src_idx = block->locations[i].source_file_idx;
2620 vector<unsigned> &lines = block->locations[i].lines;
2621
2622 block->cycle.arc = NULL;
2623 block->cycle.ident = ~0U;
2624
2625 for (unsigned j = 0; j < lines.size (); j++)
2626 {
2627 unsigned ln = lines[j];
2628
2629 /* Line belongs to a function that is in a group. */
2630 if (fn->group_line_p (ln, src_idx))
2631 {
2632 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2633 line = &(fn->lines[lines[j] - fn->start_line]);
2634 line->exists = 1;
2635 if (!block->exceptional)
2636 {
2637 line->unexceptional = 1;
2638 if (block->count == 0)
2639 line->has_unexecuted_block = 1;
2640 }
2641 line->count += block->count;
2642 }
2643 else
2644 {
2645 gcc_assert (ln < sources[src_idx].lines.size ());
2646 line = &(sources[src_idx].lines[ln]);
2647 if (coverage)
2648 {
2649 if (!line->exists)
2650 coverage->lines++;
2651 if (!line->count && block->count)
2652 coverage->lines_executed++;
2653 }
2654 line->exists = 1;
2655 if (!block->exceptional)
2656 {
2657 line->unexceptional = 1;
2658 if (block->count == 0)
2659 line->has_unexecuted_block = 1;
2660 }
2661 line->count += block->count;
2662 }
2663 }
2664
2665 has_any_line = true;
2666
2667 if (!ix || ix + 1 == fn->blocks.size ())
2668 /* Entry or exit block. */;
2669 else if (line != NULL)
2670 {
2671 line->blocks.push_back (block);
2672
2673 if (flag_branches)
2674 {
2675 arc_info *arc;
2676
2677 for (arc = block->succ; arc; arc = arc->succ_next)
2678 line->branches.push_back (arc);
2679 }
2680 }
2681 }
2682 }
2683
2684 if (!has_any_line)
2685 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name,
2686 fn->get_name ());
2687 }
2688
2689 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2690 is set to true, update source file summary. */
2691
2692 static void accumulate_line_info (line_info *line, source_info *src,
2693 bool add_coverage)
2694 {
2695 if (add_coverage)
2696 for (vector<arc_info *>::iterator it = line->branches.begin ();
2697 it != line->branches.end (); it++)
2698 add_branch_counts (&src->coverage, *it);
2699
2700 if (!line->blocks.empty ())
2701 {
2702 /* The user expects the line count to be the number of times
2703 a line has been executed. Simply summing the block count
2704 will give an artificially high number. The Right Thing
2705 is to sum the entry counts to the graph of blocks on this
2706 line, then find the elementary cycles of the local graph
2707 and add the transition counts of those cycles. */
2708 gcov_type count = 0;
2709
2710 /* Cycle detection. */
2711 for (vector<block_info *>::iterator it = line->blocks.begin ();
2712 it != line->blocks.end (); it++)
2713 {
2714 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2715 if (!line->has_block (arc->src))
2716 count += arc->count;
2717 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2718 arc->cs_count = arc->count;
2719 }
2720
2721 /* Now, add the count of loops entirely on this line. */
2722 count += get_cycles_count (*line);
2723 line->count = count;
2724
2725 if (line->count > src->maximum_count)
2726 src->maximum_count = line->count;
2727 }
2728
2729 if (line->exists && add_coverage)
2730 {
2731 src->coverage.lines++;
2732 if (line->count)
2733 src->coverage.lines_executed++;
2734 }
2735 }
2736
2737 /* Accumulate the line counts of a file. */
2738
2739 static void
2740 accumulate_line_counts (source_info *src)
2741 {
2742 /* First work on group functions. */
2743 for (vector<function_info *>::iterator it = src->functions.begin ();
2744 it != src->functions.end (); it++)
2745 {
2746 function_info *fn = *it;
2747
2748 if (fn->src != src->index || !fn->is_group)
2749 continue;
2750
2751 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2752 it2 != fn->lines.end (); it2++)
2753 {
2754 line_info *line = &(*it2);
2755 accumulate_line_info (line, src, false);
2756 }
2757 }
2758
2759 /* Work on global lines that line in source file SRC. */
2760 for (vector<line_info>::iterator it = src->lines.begin ();
2761 it != src->lines.end (); it++)
2762 accumulate_line_info (&(*it), src, true);
2763
2764 /* If not using intermediate mode, sum lines of group functions and
2765 add them to lines that live in a source file. */
2766 if (!flag_json_format)
2767 for (vector<function_info *>::iterator it = src->functions.begin ();
2768 it != src->functions.end (); it++)
2769 {
2770 function_info *fn = *it;
2771
2772 if (fn->src != src->index || !fn->is_group)
2773 continue;
2774
2775 for (unsigned i = 0; i < fn->lines.size (); i++)
2776 {
2777 line_info *fn_line = &fn->lines[i];
2778 if (fn_line->exists)
2779 {
2780 unsigned ln = fn->start_line + i;
2781 line_info *src_line = &src->lines[ln];
2782
2783 if (!src_line->exists)
2784 src->coverage.lines++;
2785 if (!src_line->count && fn_line->count)
2786 src->coverage.lines_executed++;
2787
2788 src_line->count += fn_line->count;
2789 src_line->exists = 1;
2790
2791 if (fn_line->has_unexecuted_block)
2792 src_line->has_unexecuted_block = 1;
2793
2794 if (fn_line->unexceptional)
2795 src_line->unexceptional = 1;
2796 }
2797 }
2798 }
2799 }
2800
2801 /* Output information about ARC number IX. Returns nonzero if
2802 anything is output. */
2803
2804 static int
2805 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2806 {
2807 if (arc->is_call_non_return)
2808 {
2809 if (arc->src->count)
2810 {
2811 fnotice (gcov_file, "call %2d returned %s\n", ix,
2812 format_gcov (arc->src->count - arc->count,
2813 arc->src->count, -flag_counts));
2814 }
2815 else
2816 fnotice (gcov_file, "call %2d never executed\n", ix);
2817 }
2818 else if (!arc->is_unconditional)
2819 {
2820 if (arc->src->count)
2821 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2822 format_gcov (arc->count, arc->src->count, -flag_counts),
2823 arc->fall_through ? " (fallthrough)"
2824 : arc->is_throw ? " (throw)" : "");
2825 else
2826 fnotice (gcov_file, "branch %2d never executed", ix);
2827
2828 if (flag_verbose)
2829 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2830
2831 fnotice (gcov_file, "\n");
2832 }
2833 else if (flag_unconditional && !arc->dst->is_call_return)
2834 {
2835 if (arc->src->count)
2836 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2837 format_gcov (arc->count, arc->src->count, -flag_counts));
2838 else
2839 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2840 }
2841 else
2842 return 0;
2843 return 1;
2844 }
2845
2846 static const char *
2847 read_line (FILE *file)
2848 {
2849 static char *string;
2850 static size_t string_len;
2851 size_t pos = 0;
2852 char *ptr;
2853
2854 if (!string_len)
2855 {
2856 string_len = 200;
2857 string = XNEWVEC (char, string_len);
2858 }
2859
2860 while ((ptr = fgets (string + pos, string_len - pos, file)))
2861 {
2862 size_t len = strlen (string + pos);
2863
2864 if (len && string[pos + len - 1] == '\n')
2865 {
2866 string[pos + len - 1] = 0;
2867 return string;
2868 }
2869 pos += len;
2870 /* If the file contains NUL characters or an incomplete
2871 last line, which can happen more than once in one run,
2872 we have to avoid doubling the STRING_LEN unnecessarily. */
2873 if (pos > string_len / 2)
2874 {
2875 string_len *= 2;
2876 string = XRESIZEVEC (char, string, string_len);
2877 }
2878 }
2879
2880 return pos ? string : NULL;
2881 }
2882
2883 /* Pad string S with spaces from left to have total width equal to 9. */
2884
2885 static void
2886 pad_count_string (string &s)
2887 {
2888 if (s.size () < 9)
2889 s.insert (0, 9 - s.size (), ' ');
2890 }
2891
2892 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2893 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2894 an exceptional statement. The output is printed for LINE_NUM of given
2895 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2896 used to indicate non-executed blocks. */
2897
2898 static void
2899 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2900 bool has_unexecuted_block,
2901 gcov_type count, unsigned line_num,
2902 const char *exceptional_string,
2903 const char *unexceptional_string,
2904 unsigned int maximum_count)
2905 {
2906 string s;
2907 if (exists)
2908 {
2909 if (count > 0)
2910 {
2911 s = format_gcov (count, 0, -1);
2912 if (has_unexecuted_block
2913 && bbg_supports_has_unexecuted_blocks)
2914 {
2915 if (flag_use_colors)
2916 {
2917 pad_count_string (s);
2918 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2919 COLOR_SEPARATOR COLOR_FG_WHITE));
2920 s += SGR_RESET;
2921 }
2922 else
2923 s += "*";
2924 }
2925 pad_count_string (s);
2926 }
2927 else
2928 {
2929 if (flag_use_colors)
2930 {
2931 s = "0";
2932 pad_count_string (s);
2933 if (unexceptional)
2934 s.insert (0, SGR_SEQ (COLOR_BG_RED
2935 COLOR_SEPARATOR COLOR_FG_WHITE));
2936 else
2937 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2938 COLOR_SEPARATOR COLOR_FG_WHITE));
2939 s += SGR_RESET;
2940 }
2941 else
2942 {
2943 s = unexceptional ? unexceptional_string : exceptional_string;
2944 pad_count_string (s);
2945 }
2946 }
2947 }
2948 else
2949 {
2950 s = "-";
2951 pad_count_string (s);
2952 }
2953
2954 /* Format line number in output. */
2955 char buffer[16];
2956 sprintf (buffer, "%5u", line_num);
2957 string linestr (buffer);
2958
2959 if (flag_use_hotness_colors && maximum_count)
2960 {
2961 if (count * 2 > maximum_count) /* > 50%. */
2962 linestr.insert (0, SGR_SEQ (COLOR_BG_RED));
2963 else if (count * 5 > maximum_count) /* > 20%. */
2964 linestr.insert (0, SGR_SEQ (COLOR_BG_YELLOW));
2965 else if (count * 10 > maximum_count) /* > 10%. */
2966 linestr.insert (0, SGR_SEQ (COLOR_BG_GREEN));
2967 linestr += SGR_RESET;
2968 }
2969
2970 fprintf (f, "%s:%s", s.c_str (), linestr.c_str ());
2971 }
2972
2973 static void
2974 print_source_line (FILE *f, const vector<const char *> &source_lines,
2975 unsigned line)
2976 {
2977 gcc_assert (line >= 1);
2978 gcc_assert (line <= source_lines.size ());
2979
2980 fprintf (f, ":%s\n", source_lines[line - 1]);
2981 }
2982
2983 /* Output line details for LINE and print it to F file. LINE lives on
2984 LINE_NUM. */
2985
2986 static void
2987 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2988 {
2989 if (flag_all_blocks)
2990 {
2991 arc_info *arc;
2992 int ix, jx;
2993
2994 ix = jx = 0;
2995 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2996 it != line->blocks.end (); it++)
2997 {
2998 if (!(*it)->is_call_return)
2999 {
3000 output_line_beginning (f, line->exists,
3001 (*it)->exceptional, false,
3002 (*it)->count, line_num,
3003 "%%%%%", "$$$$$", 0);
3004 fprintf (f, "-block %2d", ix++);
3005 if (flag_verbose)
3006 fprintf (f, " (BB %u)", (*it)->id);
3007 fprintf (f, "\n");
3008 }
3009 if (flag_branches)
3010 for (arc = (*it)->succ; arc; arc = arc->succ_next)
3011 jx += output_branch_count (f, jx, arc);
3012 }
3013 }
3014 else if (flag_branches)
3015 {
3016 int ix;
3017
3018 ix = 0;
3019 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
3020 it != line->branches.end (); it++)
3021 ix += output_branch_count (f, ix, (*it));
3022 }
3023 }
3024
3025 /* Output detail statistics about function FN to file F. */
3026
3027 static void
3028 output_function_details (FILE *f, function_info *fn)
3029 {
3030 if (!flag_branches)
3031 return;
3032
3033 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
3034 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
3035 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
3036
3037 for (; arc; arc = arc->pred_next)
3038 if (arc->fake)
3039 return_count -= arc->count;
3040
3041 fprintf (f, "function %s", fn->get_name ());
3042 fprintf (f, " called %s",
3043 format_gcov (called_count, 0, -1));
3044 fprintf (f, " returned %s",
3045 format_gcov (return_count, called_count, 0));
3046 fprintf (f, " blocks executed %s",
3047 format_gcov (fn->blocks_executed, fn->get_block_count (), 0));
3048 fprintf (f, "\n");
3049 }
3050
3051 /* Read in the source file one line at a time, and output that line to
3052 the gcov file preceded by its execution count and other
3053 information. */
3054
3055 static void
3056 output_lines (FILE *gcov_file, const source_info *src)
3057 {
3058 #define DEFAULT_LINE_START " -: 0:"
3059 #define FN_SEPARATOR "------------------\n"
3060
3061 FILE *source_file;
3062 const char *retval;
3063
3064 /* Print colorization legend. */
3065 if (flag_use_colors)
3066 fprintf (gcov_file, "%s",
3067 DEFAULT_LINE_START "Colorization: profile count: " \
3068 SGR_SEQ (COLOR_BG_CYAN) "zero coverage (exceptional)" SGR_RESET \
3069 " " \
3070 SGR_SEQ (COLOR_BG_RED) "zero coverage (unexceptional)" SGR_RESET \
3071 " " \
3072 SGR_SEQ (COLOR_BG_MAGENTA) "unexecuted block" SGR_RESET "\n");
3073
3074 if (flag_use_hotness_colors)
3075 fprintf (gcov_file, "%s",
3076 DEFAULT_LINE_START "Colorization: line numbers: hotness: " \
3077 SGR_SEQ (COLOR_BG_RED) "> 50%" SGR_RESET " " \
3078 SGR_SEQ (COLOR_BG_YELLOW) "> 20%" SGR_RESET " " \
3079 SGR_SEQ (COLOR_BG_GREEN) "> 10%" SGR_RESET "\n");
3080
3081 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
3082 if (!multiple_files)
3083 {
3084 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
3085 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
3086 no_data_file ? "-" : da_file_name);
3087 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
3088 }
3089
3090 source_file = fopen (src->name, "r");
3091 if (!source_file)
3092 fnotice (stderr, "Cannot open source file %s\n", src->name);
3093 else if (src->file_time == 0)
3094 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
3095
3096 vector<const char *> source_lines;
3097 if (source_file)
3098 while ((retval = read_line (source_file)) != NULL)
3099 source_lines.push_back (xstrdup (retval));
3100
3101 unsigned line_start_group = 0;
3102 vector<function_info *> *fns;
3103
3104 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
3105 {
3106 if (line_num >= src->lines.size ())
3107 {
3108 fprintf (gcov_file, "%9s:%5u", "-", line_num);
3109 print_source_line (gcov_file, source_lines, line_num);
3110 continue;
3111 }
3112
3113 const line_info *line = &src->lines[line_num];
3114
3115 if (line_start_group == 0)
3116 {
3117 fns = src->get_functions_at_location (line_num);
3118 if (fns != NULL && fns->size () > 1)
3119 {
3120 /* It's possible to have functions that partially overlap,
3121 thus take the maximum end_line of functions starting
3122 at LINE_NUM. */
3123 for (unsigned i = 0; i < fns->size (); i++)
3124 if ((*fns)[i]->end_line > line_start_group)
3125 line_start_group = (*fns)[i]->end_line;
3126 }
3127 else if (fns != NULL && fns->size () == 1)
3128 {
3129 function_info *fn = (*fns)[0];
3130 output_function_details (gcov_file, fn);
3131 }
3132 }
3133
3134 /* For lines which don't exist in the .bb file, print '-' before
3135 the source line. For lines which exist but were never
3136 executed, print '#####' or '=====' before the source line.
3137 Otherwise, print the execution count before the source line.
3138 There are 16 spaces of indentation added before the source
3139 line so that tabs won't be messed up. */
3140 output_line_beginning (gcov_file, line->exists, line->unexceptional,
3141 line->has_unexecuted_block, line->count,
3142 line_num, "=====", "#####", src->maximum_count);
3143
3144 print_source_line (gcov_file, source_lines, line_num);
3145 output_line_details (gcov_file, line, line_num);
3146
3147 if (line_start_group == line_num)
3148 {
3149 for (vector<function_info *>::iterator it = fns->begin ();
3150 it != fns->end (); it++)
3151 {
3152 function_info *fn = *it;
3153 vector<line_info> &lines = fn->lines;
3154
3155 fprintf (gcov_file, FN_SEPARATOR);
3156
3157 string fn_name = fn->get_name ();
3158 if (flag_use_colors)
3159 {
3160 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
3161 fn_name += SGR_RESET;
3162 }
3163
3164 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
3165
3166 output_function_details (gcov_file, fn);
3167
3168 /* Print all lines covered by the function. */
3169 for (unsigned i = 0; i < lines.size (); i++)
3170 {
3171 line_info *line = &lines[i];
3172 unsigned l = fn->start_line + i;
3173
3174 /* For lines which don't exist in the .bb file, print '-'
3175 before the source line. For lines which exist but
3176 were never executed, print '#####' or '=====' before
3177 the source line. Otherwise, print the execution count
3178 before the source line.
3179 There are 16 spaces of indentation added before the source
3180 line so that tabs won't be messed up. */
3181 output_line_beginning (gcov_file, line->exists,
3182 line->unexceptional,
3183 line->has_unexecuted_block,
3184 line->count,
3185 l, "=====", "#####",
3186 src->maximum_count);
3187
3188 print_source_line (gcov_file, source_lines, l);
3189 output_line_details (gcov_file, line, l);
3190 }
3191 }
3192
3193 fprintf (gcov_file, FN_SEPARATOR);
3194 line_start_group = 0;
3195 }
3196 }
3197
3198 if (source_file)
3199 fclose (source_file);
3200 }