]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gcov.c
gcov*: collapse lisence header to 2 lines in --version.
[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-2020 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. */
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, " -i, --json-format Output JSON intermediate format into .gcov.json.gz file\n");
902 fnotice (file, " -j, --human-readable Output human readable numbers\n");
903 fnotice (file, " -k, --use-colors Emit colored output\n");
904 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
905 source files\n");
906 fnotice (file, " -m, --demangled-names Output demangled function names\n");
907 fnotice (file, " -n, --no-output Do not create an output file\n");
908 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
909 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
910 fnotice (file, " -q, --use-hotness-colors Emit perf-like colored output for hot lines\n");
911 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
912 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
913 fnotice (file, " -t, --stdout Output to stdout instead of a file\n");
914 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
915 fnotice (file, " -v, --version Print version number, then exit\n");
916 fnotice (file, " -w, --verbose Print verbose informations\n");
917 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
918 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
919 bug_report_url);
920 exit (status);
921 }
922
923 /* Print version information and exit. */
924
925 static void
926 print_version (void)
927 {
928 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
929 fprintf (stdout, "Copyright %s 2020 Free Software Foundation, Inc.\n",
930 _("(C)"));
931 fnotice (stdout,
932 _("This is free software; see the source for copying conditions. There is NO\n\
933 warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
934 exit (SUCCESS_EXIT_CODE);
935 }
936
937 static const struct option options[] =
938 {
939 { "help", no_argument, NULL, 'h' },
940 { "version", no_argument, NULL, 'v' },
941 { "verbose", no_argument, NULL, 'w' },
942 { "all-blocks", no_argument, NULL, 'a' },
943 { "branch-probabilities", no_argument, NULL, 'b' },
944 { "branch-counts", no_argument, NULL, 'c' },
945 { "json-format", no_argument, NULL, 'i' },
946 { "human-readable", no_argument, NULL, 'j' },
947 { "no-output", no_argument, NULL, 'n' },
948 { "long-file-names", no_argument, NULL, 'l' },
949 { "function-summaries", no_argument, NULL, 'f' },
950 { "demangled-names", no_argument, NULL, 'm' },
951 { "preserve-paths", no_argument, NULL, 'p' },
952 { "relative-only", no_argument, NULL, 'r' },
953 { "object-directory", required_argument, NULL, 'o' },
954 { "object-file", required_argument, NULL, 'o' },
955 { "source-prefix", required_argument, NULL, 's' },
956 { "stdout", no_argument, NULL, 't' },
957 { "unconditional-branches", no_argument, NULL, 'u' },
958 { "display-progress", no_argument, NULL, 'd' },
959 { "hash-filenames", no_argument, NULL, 'x' },
960 { "use-colors", no_argument, NULL, 'k' },
961 { "use-hotness-colors", no_argument, NULL, 'q' },
962 { 0, 0, 0, 0 }
963 };
964
965 /* Process args, return index to first non-arg. */
966
967 static int
968 process_args (int argc, char **argv)
969 {
970 int opt;
971
972 const char *opts = "abcdfhijklmno:pqrs:tuvwx";
973 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
974 {
975 switch (opt)
976 {
977 case 'a':
978 flag_all_blocks = 1;
979 break;
980 case 'b':
981 flag_branches = 1;
982 break;
983 case 'c':
984 flag_counts = 1;
985 break;
986 case 'f':
987 flag_function_summary = 1;
988 break;
989 case 'h':
990 print_usage (false);
991 /* print_usage will exit. */
992 case 'l':
993 flag_long_names = 1;
994 break;
995 case 'j':
996 flag_human_readable_numbers = 1;
997 break;
998 case 'k':
999 flag_use_colors = 1;
1000 break;
1001 case 'q':
1002 flag_use_hotness_colors = 1;
1003 break;
1004 case 'm':
1005 flag_demangled_names = 1;
1006 break;
1007 case 'n':
1008 flag_gcov_file = 0;
1009 break;
1010 case 'o':
1011 object_directory = optarg;
1012 break;
1013 case 's':
1014 source_prefix = optarg;
1015 source_length = strlen (source_prefix);
1016 break;
1017 case 'r':
1018 flag_relative_only = 1;
1019 break;
1020 case 'p':
1021 flag_preserve_paths = 1;
1022 break;
1023 case 'u':
1024 flag_unconditional = 1;
1025 break;
1026 case 'i':
1027 flag_json_format = 1;
1028 flag_gcov_file = 1;
1029 break;
1030 case 'd':
1031 flag_display_progress = 1;
1032 break;
1033 case 'x':
1034 flag_hash_filenames = 1;
1035 break;
1036 case 'w':
1037 flag_verbose = 1;
1038 break;
1039 case 't':
1040 flag_use_stdout = 1;
1041 break;
1042 case 'v':
1043 print_version ();
1044 /* print_version will exit. */
1045 default:
1046 print_usage (true);
1047 /* print_usage will exit. */
1048 }
1049 }
1050
1051 return optind;
1052 }
1053
1054 /* Output intermediate LINE sitting on LINE_NUM to JSON OBJECT.
1055 Add FUNCTION_NAME to the LINE. */
1056
1057 static void
1058 output_intermediate_json_line (json::array *object,
1059 line_info *line, unsigned line_num,
1060 const char *function_name)
1061 {
1062 if (!line->exists)
1063 return;
1064
1065 json::object *lineo = new json::object ();
1066 lineo->set ("line_number", new json::integer_number (line_num));
1067 if (function_name != NULL)
1068 lineo->set ("function_name", new json::string (function_name));
1069 lineo->set ("count", new json::integer_number (line->count));
1070 lineo->set ("unexecuted_block",
1071 new json::literal (line->has_unexecuted_block));
1072
1073 json::array *branches = new json::array ();
1074 lineo->set ("branches", branches);
1075
1076 vector<arc_info *>::const_iterator it;
1077 if (flag_branches)
1078 for (it = line->branches.begin (); it != line->branches.end ();
1079 it++)
1080 {
1081 if (!(*it)->is_unconditional && !(*it)->is_call_non_return)
1082 {
1083 json::object *branch = new json::object ();
1084 branch->set ("count", new json::integer_number ((*it)->count));
1085 branch->set ("throw", new json::literal ((*it)->is_throw));
1086 branch->set ("fallthrough",
1087 new json::literal ((*it)->fall_through));
1088 branches->append (branch);
1089 }
1090 }
1091
1092 object->append (lineo);
1093 }
1094
1095 /* Get the name of the gcov file. The return value must be free'd.
1096
1097 It appends the '.gcov' extension to the *basename* of the file.
1098 The resulting file name will be in PWD.
1099
1100 e.g.,
1101 input: foo.da, output: foo.da.gcov
1102 input: a/b/foo.cc, output: foo.cc.gcov */
1103
1104 static char *
1105 get_gcov_intermediate_filename (const char *file_name)
1106 {
1107 const char *gcov = ".gcov.json.gz";
1108 char *result;
1109 const char *cptr;
1110
1111 /* Find the 'basename'. */
1112 cptr = lbasename (file_name);
1113
1114 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
1115 sprintf (result, "%s%s", cptr, gcov);
1116
1117 return result;
1118 }
1119
1120 /* Output the result in JSON intermediate format.
1121 Source info SRC is dumped into JSON_FILES which is JSON array. */
1122
1123 static void
1124 output_json_intermediate_file (json::array *json_files, source_info *src)
1125 {
1126 json::object *root = new json::object ();
1127 json_files->append (root);
1128
1129 root->set ("file", new json::string (src->name));
1130
1131 json::array *functions = new json::array ();
1132 root->set ("functions", functions);
1133
1134 std::sort (src->functions.begin (), src->functions.end (),
1135 function_line_start_cmp ());
1136 for (vector<function_info *>::iterator it = src->functions.begin ();
1137 it != src->functions.end (); it++)
1138 {
1139 json::object *function = new json::object ();
1140 function->set ("name", new json::string ((*it)->m_name));
1141 function->set ("demangled_name",
1142 new json::string ((*it)->get_demangled_name ()));
1143 function->set ("start_line",
1144 new json::integer_number ((*it)->start_line));
1145 function->set ("start_column",
1146 new json::integer_number ((*it)->start_column));
1147 function->set ("end_line", new json::integer_number ((*it)->end_line));
1148 function->set ("end_column",
1149 new json::integer_number ((*it)->end_column));
1150 function->set ("blocks",
1151 new json::integer_number ((*it)->get_block_count ()));
1152 function->set ("blocks_executed",
1153 new json::integer_number ((*it)->blocks_executed));
1154 function->set ("execution_count",
1155 new json::integer_number ((*it)->blocks[0].count));
1156
1157 functions->append (function);
1158 }
1159
1160 json::array *lineso = new json::array ();
1161 root->set ("lines", lineso);
1162
1163 function_info *last_non_group_fn = NULL;
1164
1165 for (unsigned line_num = 1; line_num <= src->lines.size (); line_num++)
1166 {
1167 vector<function_info *> *fns = src->get_functions_at_location (line_num);
1168
1169 if (fns != NULL)
1170 /* Print first group functions that begin on the line. */
1171 for (vector<function_info *>::iterator it2 = fns->begin ();
1172 it2 != fns->end (); it2++)
1173 {
1174 if (!(*it2)->is_group)
1175 last_non_group_fn = *it2;
1176
1177 vector<line_info> &lines = (*it2)->lines;
1178 for (unsigned i = 0; i < lines.size (); i++)
1179 {
1180 line_info *line = &lines[i];
1181 output_intermediate_json_line (lineso, line, line_num + i,
1182 (*it2)->m_name);
1183 }
1184 }
1185
1186 /* Follow with lines associated with the source file. */
1187 if (line_num < src->lines.size ())
1188 output_intermediate_json_line (lineso, &src->lines[line_num], line_num,
1189 (last_non_group_fn != NULL
1190 ? last_non_group_fn->m_name : NULL));
1191 }
1192 }
1193
1194 /* Function start pair. */
1195 struct function_start
1196 {
1197 unsigned source_file_idx;
1198 unsigned start_line;
1199 };
1200
1201 /* Traits class for function start hash maps below. */
1202
1203 struct function_start_pair_hash : typed_noop_remove <function_start>
1204 {
1205 typedef function_start value_type;
1206 typedef function_start compare_type;
1207
1208 static hashval_t
1209 hash (const function_start &ref)
1210 {
1211 inchash::hash hstate (0);
1212 hstate.add_int (ref.source_file_idx);
1213 hstate.add_int (ref.start_line);
1214 return hstate.end ();
1215 }
1216
1217 static bool
1218 equal (const function_start &ref1, const function_start &ref2)
1219 {
1220 return (ref1.source_file_idx == ref2.source_file_idx
1221 && ref1.start_line == ref2.start_line);
1222 }
1223
1224 static void
1225 mark_deleted (function_start &ref)
1226 {
1227 ref.start_line = ~1U;
1228 }
1229
1230 static const bool empty_zero_p = false;
1231
1232 static void
1233 mark_empty (function_start &ref)
1234 {
1235 ref.start_line = ~2U;
1236 }
1237
1238 static bool
1239 is_deleted (const function_start &ref)
1240 {
1241 return ref.start_line == ~1U;
1242 }
1243
1244 static bool
1245 is_empty (const function_start &ref)
1246 {
1247 return ref.start_line == ~2U;
1248 }
1249 };
1250
1251 /* Process a single input file. */
1252
1253 static void
1254 process_file (const char *file_name)
1255 {
1256 create_file_names (file_name);
1257
1258 for (unsigned i = 0; i < processed_files.size (); i++)
1259 if (strcmp (da_file_name, processed_files[i]) == 0)
1260 {
1261 fnotice (stderr, "'%s' file is already processed\n",
1262 file_name);
1263 return;
1264 }
1265
1266 processed_files.push_back (xstrdup (da_file_name));
1267
1268 read_graph_file ();
1269 read_count_file ();
1270 }
1271
1272 /* Process all functions in all files. */
1273
1274 static void
1275 process_all_functions (void)
1276 {
1277 hash_map<function_start_pair_hash, function_info *> fn_map;
1278
1279 /* Identify group functions. */
1280 for (vector<function_info *>::iterator it = functions.begin ();
1281 it != functions.end (); it++)
1282 if (!(*it)->artificial)
1283 {
1284 function_start needle;
1285 needle.source_file_idx = (*it)->src;
1286 needle.start_line = (*it)->start_line;
1287
1288 function_info **slot = fn_map.get (needle);
1289 if (slot)
1290 {
1291 (*slot)->is_group = 1;
1292 (*it)->is_group = 1;
1293 }
1294 else
1295 fn_map.put (needle, *it);
1296 }
1297
1298 /* Remove all artificial function. */
1299 functions.erase (remove_if (functions.begin (), functions.end (),
1300 function_info::is_artificial), functions.end ());
1301
1302 for (vector<function_info *>::iterator it = functions.begin ();
1303 it != functions.end (); it++)
1304 {
1305 function_info *fn = *it;
1306 unsigned src = fn->src;
1307
1308 if (!fn->counts.empty () || no_data_file)
1309 {
1310 source_info *s = &sources[src];
1311 s->add_function (fn);
1312
1313 /* Mark last line in files touched by function. */
1314 for (unsigned block_no = 0; block_no != fn->blocks.size ();
1315 block_no++)
1316 {
1317 block_info *block = &fn->blocks[block_no];
1318 for (unsigned i = 0; i < block->locations.size (); i++)
1319 {
1320 /* Sort lines of locations. */
1321 sort (block->locations[i].lines.begin (),
1322 block->locations[i].lines.end ());
1323
1324 if (!block->locations[i].lines.empty ())
1325 {
1326 s = &sources[block->locations[i].source_file_idx];
1327 unsigned last_line
1328 = block->locations[i].lines.back ();
1329
1330 /* Record new lines for the function. */
1331 if (last_line >= s->lines.size ())
1332 {
1333 s = &sources[block->locations[i].source_file_idx];
1334 unsigned last_line
1335 = block->locations[i].lines.back ();
1336
1337 /* Record new lines for the function. */
1338 if (last_line >= s->lines.size ())
1339 {
1340 /* Record new lines for a source file. */
1341 s->lines.resize (last_line + 1);
1342 }
1343 }
1344 }
1345 }
1346 }
1347
1348 /* Allocate lines for group function, following start_line
1349 and end_line information of the function. */
1350 if (fn->is_group)
1351 fn->lines.resize (fn->end_line - fn->start_line + 1);
1352
1353 solve_flow_graph (fn);
1354 if (fn->has_catch)
1355 find_exception_blocks (fn);
1356 }
1357 else
1358 {
1359 /* The function was not in the executable -- some other
1360 instance must have been selected. */
1361 }
1362 }
1363 }
1364
1365 static void
1366 output_gcov_file (const char *file_name, source_info *src)
1367 {
1368 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
1369
1370 if (src->coverage.lines)
1371 {
1372 FILE *gcov_file = fopen (gcov_file_name, "w");
1373 if (gcov_file)
1374 {
1375 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
1376 output_lines (gcov_file, src);
1377 if (ferror (gcov_file))
1378 fnotice (stderr, "Error writing output file '%s'\n",
1379 gcov_file_name);
1380 fclose (gcov_file);
1381 }
1382 else
1383 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
1384 }
1385 else
1386 {
1387 unlink (gcov_file_name);
1388 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
1389 }
1390 free (gcov_file_name);
1391 }
1392
1393 static void
1394 generate_results (const char *file_name)
1395 {
1396 char *gcov_intermediate_filename;
1397
1398 for (vector<function_info *>::iterator it = functions.begin ();
1399 it != functions.end (); it++)
1400 {
1401 function_info *fn = *it;
1402 coverage_info coverage;
1403
1404 memset (&coverage, 0, sizeof (coverage));
1405 coverage.name = fn->get_name ();
1406 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1407 if (flag_function_summary)
1408 {
1409 function_summary (&coverage);
1410 fnotice (stdout, "\n");
1411 }
1412 }
1413
1414 name_map needle;
1415 needle.name = file_name;
1416 vector<name_map>::iterator it
1417 = std::find (names.begin (), names.end (), needle);
1418 if (it != names.end ())
1419 file_name = sources[it->src].coverage.name;
1420 else
1421 file_name = canonicalize_name (file_name);
1422
1423 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1424
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));
1428
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));
1432
1433 json::array *json_files = new json::array ();
1434 root->set ("files", json_files);
1435
1436 for (vector<source_info>::iterator it = sources.begin ();
1437 it != sources.end (); it++)
1438 {
1439 source_info *src = &(*it);
1440 if (flag_relative_only)
1441 {
1442 /* Ignore this source, if it is an absolute path (after
1443 source prefix removal). */
1444 char first = src->coverage.name[0];
1445
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;
1452 }
1453
1454 accumulate_line_counts (src);
1455
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)
1461 {
1462 if (flag_json_format)
1463 {
1464 output_json_intermediate_file (json_files, src);
1465 if (!flag_use_stdout)
1466 fnotice (stdout, "\n");
1467 }
1468 else
1469 {
1470 if (flag_use_stdout)
1471 {
1472 if (src->coverage.lines)
1473 output_lines (stdout, src);
1474 }
1475 else
1476 {
1477 output_gcov_file (file_name, src);
1478 fnotice (stdout, "\n");
1479 }
1480 }
1481 }
1482 }
1483
1484 if (flag_gcov_file && flag_json_format)
1485 {
1486 if (flag_use_stdout)
1487 {
1488 root->dump (stdout);
1489 printf ("\n");
1490 }
1491 else
1492 {
1493 pretty_printer pp;
1494 root->print (&pp);
1495 pp_formatted_text (&pp);
1496
1497 gzFile output = gzopen (gcov_intermediate_filename, "w");
1498 if (output == NULL)
1499 {
1500 fnotice (stderr, "Cannot open JSON output file %s\n",
1501 gcov_intermediate_filename);
1502 return;
1503 }
1504
1505 if (gzputs (output, pp_formatted_text (&pp)) == EOF
1506 || gzclose (output))
1507 {
1508 fnotice (stderr, "Error writing JSON output file %s\n",
1509 gcov_intermediate_filename);
1510 return;
1511 }
1512 }
1513 }
1514 }
1515
1516 /* Release all memory used. */
1517
1518 static void
1519 release_structures (void)
1520 {
1521 for (vector<function_info *>::iterator it = functions.begin ();
1522 it != functions.end (); it++)
1523 delete (*it);
1524
1525 sources.resize (0);
1526 names.resize (0);
1527 functions.resize (0);
1528 ident_to_fn.clear ();
1529 }
1530
1531 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1532 is not specified, these are named from FILE_NAME sans extension. If
1533 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1534 directory, but named from the basename of the FILE_NAME, sans extension.
1535 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1536 and the data files are named from that. */
1537
1538 static void
1539 create_file_names (const char *file_name)
1540 {
1541 char *cptr;
1542 char *name;
1543 int length = strlen (file_name);
1544 int base;
1545
1546 /* Free previous file names. */
1547 free (bbg_file_name);
1548 free (da_file_name);
1549 da_file_name = bbg_file_name = NULL;
1550 bbg_file_time = 0;
1551 bbg_stamp = 0;
1552
1553 if (object_directory && object_directory[0])
1554 {
1555 struct stat status;
1556
1557 length += strlen (object_directory) + 2;
1558 name = XNEWVEC (char, length);
1559 name[0] = 0;
1560
1561 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1562 strcat (name, object_directory);
1563 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1564 strcat (name, "/");
1565 }
1566 else
1567 {
1568 name = XNEWVEC (char, length + 1);
1569 strcpy (name, file_name);
1570 base = 0;
1571 }
1572
1573 if (base)
1574 {
1575 /* Append source file name. */
1576 const char *cptr = lbasename (file_name);
1577 strcat (name, cptr ? cptr : file_name);
1578 }
1579
1580 /* Remove the extension. */
1581 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1582 if (cptr)
1583 *cptr = 0;
1584
1585 length = strlen (name);
1586
1587 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1588 strcpy (bbg_file_name, name);
1589 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1590
1591 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1592 strcpy (da_file_name, name);
1593 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1594
1595 free (name);
1596 return;
1597 }
1598
1599 /* Find or create a source file structure for FILE_NAME. Copies
1600 FILE_NAME on creation */
1601
1602 static unsigned
1603 find_source (const char *file_name)
1604 {
1605 char *canon;
1606 unsigned idx;
1607 struct stat status;
1608
1609 if (!file_name)
1610 file_name = "<unknown>";
1611
1612 name_map needle;
1613 needle.name = file_name;
1614
1615 vector<name_map>::iterator it = std::find (names.begin (), names.end (),
1616 needle);
1617 if (it != names.end ())
1618 {
1619 idx = it->src;
1620 goto check_date;
1621 }
1622
1623 /* Not found, try the canonical name. */
1624 canon = canonicalize_name (file_name);
1625 needle.name = canon;
1626 it = std::find (names.begin (), names.end (), needle);
1627 if (it == names.end ())
1628 {
1629 /* Not found with canonical name, create a new source. */
1630 source_info *src;
1631
1632 idx = sources.size ();
1633 needle = name_map (canon, idx);
1634 names.push_back (needle);
1635
1636 sources.push_back (source_info ());
1637 src = &sources.back ();
1638 src->name = canon;
1639 src->coverage.name = src->name;
1640 src->index = idx;
1641 if (source_length
1642 #if HAVE_DOS_BASED_FILE_SYSTEM
1643 /* You lose if separators don't match exactly in the
1644 prefix. */
1645 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1646 #else
1647 && !strncmp (source_prefix, src->coverage.name, source_length)
1648 #endif
1649 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1650 src->coverage.name += source_length + 1;
1651 if (!stat (src->name, &status))
1652 src->file_time = status.st_mtime;
1653 }
1654 else
1655 idx = it->src;
1656
1657 needle.name = file_name;
1658 if (std::find (names.begin (), names.end (), needle) == names.end ())
1659 {
1660 /* Append the non-canonical name. */
1661 names.push_back (name_map (xstrdup (file_name), idx));
1662 }
1663
1664 /* Resort the name map. */
1665 std::sort (names.begin (), names.end ());
1666
1667 check_date:
1668 if (sources[idx].file_time > bbg_file_time)
1669 {
1670 static int info_emitted;
1671
1672 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1673 file_name, bbg_file_name);
1674 if (!info_emitted)
1675 {
1676 fnotice (stderr,
1677 "(the message is displayed only once per source file)\n");
1678 info_emitted = 1;
1679 }
1680 sources[idx].file_time = 0;
1681 }
1682
1683 return idx;
1684 }
1685
1686 /* Read the notes file. Save functions to FUNCTIONS global vector. */
1687
1688 static void
1689 read_graph_file (void)
1690 {
1691 unsigned version;
1692 unsigned current_tag = 0;
1693 unsigned tag;
1694
1695 if (!gcov_open (bbg_file_name, 1))
1696 {
1697 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1698 return;
1699 }
1700 bbg_file_time = gcov_time ();
1701 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1702 {
1703 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1704 gcov_close ();
1705 return;
1706 }
1707
1708 version = gcov_read_unsigned ();
1709 if (version != GCOV_VERSION)
1710 {
1711 char v[4], e[4];
1712
1713 GCOV_UNSIGNED2STRING (v, version);
1714 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1715
1716 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1717 bbg_file_name, v, e);
1718 }
1719 bbg_stamp = gcov_read_unsigned ();
1720 bbg_cwd = xstrdup (gcov_read_string ());
1721 bbg_supports_has_unexecuted_blocks = gcov_read_unsigned ();
1722
1723 function_info *fn = NULL;
1724 while ((tag = gcov_read_unsigned ()))
1725 {
1726 unsigned length = gcov_read_unsigned ();
1727 gcov_position_t base = gcov_position ();
1728
1729 if (tag == GCOV_TAG_FUNCTION)
1730 {
1731 char *function_name;
1732 unsigned ident;
1733 unsigned lineno_checksum, cfg_checksum;
1734
1735 ident = gcov_read_unsigned ();
1736 lineno_checksum = gcov_read_unsigned ();
1737 cfg_checksum = gcov_read_unsigned ();
1738 function_name = xstrdup (gcov_read_string ());
1739 unsigned artificial = gcov_read_unsigned ();
1740 unsigned src_idx = find_source (gcov_read_string ());
1741 unsigned start_line = gcov_read_unsigned ();
1742 unsigned start_column = gcov_read_unsigned ();
1743 unsigned end_line = gcov_read_unsigned ();
1744 unsigned end_column = gcov_read_unsigned ();
1745
1746 fn = new function_info ();
1747 functions.push_back (fn);
1748 ident_to_fn[ident] = fn;
1749
1750 fn->m_name = function_name;
1751 fn->ident = ident;
1752 fn->lineno_checksum = lineno_checksum;
1753 fn->cfg_checksum = cfg_checksum;
1754 fn->src = src_idx;
1755 fn->start_line = start_line;
1756 fn->start_column = start_column;
1757 fn->end_line = end_line;
1758 fn->end_column = end_column;
1759 fn->artificial = artificial;
1760
1761 current_tag = tag;
1762 }
1763 else if (fn && tag == GCOV_TAG_BLOCKS)
1764 {
1765 if (!fn->blocks.empty ())
1766 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1767 bbg_file_name, fn->get_name ());
1768 else
1769 fn->blocks.resize (gcov_read_unsigned ());
1770 }
1771 else if (fn && tag == GCOV_TAG_ARCS)
1772 {
1773 unsigned src = gcov_read_unsigned ();
1774 fn->blocks[src].id = src;
1775 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1776 block_info *src_blk = &fn->blocks[src];
1777 unsigned mark_catches = 0;
1778 struct arc_info *arc;
1779
1780 if (src >= fn->blocks.size () || fn->blocks[src].succ)
1781 goto corrupt;
1782
1783 while (num_dests--)
1784 {
1785 unsigned dest = gcov_read_unsigned ();
1786 unsigned flags = gcov_read_unsigned ();
1787
1788 if (dest >= fn->blocks.size ())
1789 goto corrupt;
1790 arc = XCNEW (arc_info);
1791
1792 arc->dst = &fn->blocks[dest];
1793 arc->src = src_blk;
1794
1795 arc->count = 0;
1796 arc->count_valid = 0;
1797 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1798 arc->fake = !!(flags & GCOV_ARC_FAKE);
1799 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1800
1801 arc->succ_next = src_blk->succ;
1802 src_blk->succ = arc;
1803 src_blk->num_succ++;
1804
1805 arc->pred_next = fn->blocks[dest].pred;
1806 fn->blocks[dest].pred = arc;
1807 fn->blocks[dest].num_pred++;
1808
1809 if (arc->fake)
1810 {
1811 if (src)
1812 {
1813 /* Exceptional exit from this function, the
1814 source block must be a call. */
1815 fn->blocks[src].is_call_site = 1;
1816 arc->is_call_non_return = 1;
1817 mark_catches = 1;
1818 }
1819 else
1820 {
1821 /* Non-local return from a callee of this
1822 function. The destination block is a setjmp. */
1823 arc->is_nonlocal_return = 1;
1824 fn->blocks[dest].is_nonlocal_return = 1;
1825 }
1826 }
1827
1828 if (!arc->on_tree)
1829 fn->counts.push_back (0);
1830 }
1831
1832 if (mark_catches)
1833 {
1834 /* We have a fake exit from this block. The other
1835 non-fall through exits must be to catch handlers.
1836 Mark them as catch arcs. */
1837
1838 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1839 if (!arc->fake && !arc->fall_through)
1840 {
1841 arc->is_throw = 1;
1842 fn->has_catch = 1;
1843 }
1844 }
1845 }
1846 else if (fn && tag == GCOV_TAG_LINES)
1847 {
1848 unsigned blockno = gcov_read_unsigned ();
1849 block_info *block = &fn->blocks[blockno];
1850
1851 if (blockno >= fn->blocks.size ())
1852 goto corrupt;
1853
1854 while (true)
1855 {
1856 unsigned lineno = gcov_read_unsigned ();
1857
1858 if (lineno)
1859 block->locations.back ().lines.push_back (lineno);
1860 else
1861 {
1862 const char *file_name = gcov_read_string ();
1863
1864 if (!file_name)
1865 break;
1866 block->locations.push_back (block_location_info
1867 (find_source (file_name)));
1868 }
1869 }
1870 }
1871 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1872 {
1873 fn = NULL;
1874 current_tag = 0;
1875 }
1876 gcov_sync (base, length);
1877 if (gcov_is_error ())
1878 {
1879 corrupt:;
1880 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1881 break;
1882 }
1883 }
1884 gcov_close ();
1885
1886 if (functions.empty ())
1887 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1888 }
1889
1890 /* Reads profiles from the count file and attach to each
1891 function. Return nonzero if fatal error. */
1892
1893 static int
1894 read_count_file (void)
1895 {
1896 unsigned ix;
1897 unsigned version;
1898 unsigned tag;
1899 function_info *fn = NULL;
1900 int error = 0;
1901 map<unsigned, function_info *>::iterator it;
1902
1903 if (!gcov_open (da_file_name, 1))
1904 {
1905 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1906 da_file_name);
1907 no_data_file = 1;
1908 return 0;
1909 }
1910 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1911 {
1912 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1913 cleanup:;
1914 gcov_close ();
1915 return 1;
1916 }
1917 version = gcov_read_unsigned ();
1918 if (version != GCOV_VERSION)
1919 {
1920 char v[4], e[4];
1921
1922 GCOV_UNSIGNED2STRING (v, version);
1923 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1924
1925 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1926 da_file_name, v, e);
1927 }
1928 tag = gcov_read_unsigned ();
1929 if (tag != bbg_stamp)
1930 {
1931 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1932 goto cleanup;
1933 }
1934
1935 while ((tag = gcov_read_unsigned ()))
1936 {
1937 unsigned length = gcov_read_unsigned ();
1938 unsigned long base = gcov_position ();
1939
1940 if (tag == GCOV_TAG_OBJECT_SUMMARY)
1941 {
1942 struct gcov_summary summary;
1943 gcov_read_summary (&summary);
1944 object_runs = summary.runs;
1945 }
1946 else if (tag == GCOV_TAG_FUNCTION && !length)
1947 ; /* placeholder */
1948 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1949 {
1950 unsigned ident;
1951 ident = gcov_read_unsigned ();
1952 fn = NULL;
1953 it = ident_to_fn.find (ident);
1954 if (it != ident_to_fn.end ())
1955 fn = it->second;
1956
1957 if (!fn)
1958 ;
1959 else if (gcov_read_unsigned () != fn->lineno_checksum
1960 || gcov_read_unsigned () != fn->cfg_checksum)
1961 {
1962 mismatch:;
1963 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1964 da_file_name, fn->get_name ());
1965 goto cleanup;
1966 }
1967 }
1968 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1969 {
1970 if (length != GCOV_TAG_COUNTER_LENGTH (fn->counts.size ()))
1971 goto mismatch;
1972
1973 for (ix = 0; ix != fn->counts.size (); ix++)
1974 fn->counts[ix] += gcov_read_counter ();
1975 }
1976 gcov_sync (base, length);
1977 if ((error = gcov_is_error ()))
1978 {
1979 fnotice (stderr,
1980 error < 0
1981 ? N_("%s:overflowed\n")
1982 : N_("%s:corrupted\n"),
1983 da_file_name);
1984 goto cleanup;
1985 }
1986 }
1987
1988 gcov_close ();
1989 return 0;
1990 }
1991
1992 /* Solve the flow graph. Propagate counts from the instrumented arcs
1993 to the blocks and the uninstrumented arcs. */
1994
1995 static void
1996 solve_flow_graph (function_info *fn)
1997 {
1998 unsigned ix;
1999 arc_info *arc;
2000 gcov_type *count_ptr = &fn->counts.front ();
2001 block_info *blk;
2002 block_info *valid_blocks = NULL; /* valid, but unpropagated blocks. */
2003 block_info *invalid_blocks = NULL; /* invalid, but inferable blocks. */
2004
2005 /* The arcs were built in reverse order. Fix that now. */
2006 for (ix = fn->blocks.size (); ix--;)
2007 {
2008 arc_info *arc_p, *arc_n;
2009
2010 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
2011 arc_p = arc, arc = arc_n)
2012 {
2013 arc_n = arc->succ_next;
2014 arc->succ_next = arc_p;
2015 }
2016 fn->blocks[ix].succ = arc_p;
2017
2018 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
2019 arc_p = arc, arc = arc_n)
2020 {
2021 arc_n = arc->pred_next;
2022 arc->pred_next = arc_p;
2023 }
2024 fn->blocks[ix].pred = arc_p;
2025 }
2026
2027 if (fn->blocks.size () < 2)
2028 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
2029 bbg_file_name, fn->get_name ());
2030 else
2031 {
2032 if (fn->blocks[ENTRY_BLOCK].num_pred)
2033 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
2034 bbg_file_name, fn->get_name ());
2035 else
2036 /* We can't deduce the entry block counts from the lack of
2037 predecessors. */
2038 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
2039
2040 if (fn->blocks[EXIT_BLOCK].num_succ)
2041 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
2042 bbg_file_name, fn->get_name ());
2043 else
2044 /* Likewise, we can't deduce exit block counts from the lack
2045 of its successors. */
2046 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
2047 }
2048
2049 /* Propagate the measured counts, this must be done in the same
2050 order as the code in profile.c */
2051 for (unsigned i = 0; i < fn->blocks.size (); i++)
2052 {
2053 blk = &fn->blocks[i];
2054 block_info const *prev_dst = NULL;
2055 int out_of_order = 0;
2056 int non_fake_succ = 0;
2057
2058 for (arc = blk->succ; arc; arc = arc->succ_next)
2059 {
2060 if (!arc->fake)
2061 non_fake_succ++;
2062
2063 if (!arc->on_tree)
2064 {
2065 if (count_ptr)
2066 arc->count = *count_ptr++;
2067 arc->count_valid = 1;
2068 blk->num_succ--;
2069 arc->dst->num_pred--;
2070 }
2071 if (prev_dst && prev_dst > arc->dst)
2072 out_of_order = 1;
2073 prev_dst = arc->dst;
2074 }
2075 if (non_fake_succ == 1)
2076 {
2077 /* If there is only one non-fake exit, it is an
2078 unconditional branch. */
2079 for (arc = blk->succ; arc; arc = arc->succ_next)
2080 if (!arc->fake)
2081 {
2082 arc->is_unconditional = 1;
2083 /* If this block is instrumenting a call, it might be
2084 an artificial block. It is not artificial if it has
2085 a non-fallthrough exit, or the destination of this
2086 arc has more than one entry. Mark the destination
2087 block as a return site, if none of those conditions
2088 hold. */
2089 if (blk->is_call_site && arc->fall_through
2090 && arc->dst->pred == arc && !arc->pred_next)
2091 arc->dst->is_call_return = 1;
2092 }
2093 }
2094
2095 /* Sort the successor arcs into ascending dst order. profile.c
2096 normally produces arcs in the right order, but sometimes with
2097 one or two out of order. We're not using a particularly
2098 smart sort. */
2099 if (out_of_order)
2100 {
2101 arc_info *start = blk->succ;
2102 unsigned changes = 1;
2103
2104 while (changes)
2105 {
2106 arc_info *arc, *arc_p, *arc_n;
2107
2108 changes = 0;
2109 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
2110 {
2111 if (arc->dst > arc_n->dst)
2112 {
2113 changes = 1;
2114 if (arc_p)
2115 arc_p->succ_next = arc_n;
2116 else
2117 start = arc_n;
2118 arc->succ_next = arc_n->succ_next;
2119 arc_n->succ_next = arc;
2120 arc_p = arc_n;
2121 }
2122 else
2123 {
2124 arc_p = arc;
2125 arc = arc_n;
2126 }
2127 }
2128 }
2129 blk->succ = start;
2130 }
2131
2132 /* Place it on the invalid chain, it will be ignored if that's
2133 wrong. */
2134 blk->invalid_chain = 1;
2135 blk->chain = invalid_blocks;
2136 invalid_blocks = blk;
2137 }
2138
2139 while (invalid_blocks || valid_blocks)
2140 {
2141 while ((blk = invalid_blocks))
2142 {
2143 gcov_type total = 0;
2144 const arc_info *arc;
2145
2146 invalid_blocks = blk->chain;
2147 blk->invalid_chain = 0;
2148 if (!blk->num_succ)
2149 for (arc = blk->succ; arc; arc = arc->succ_next)
2150 total += arc->count;
2151 else if (!blk->num_pred)
2152 for (arc = blk->pred; arc; arc = arc->pred_next)
2153 total += arc->count;
2154 else
2155 continue;
2156
2157 blk->count = total;
2158 blk->count_valid = 1;
2159 blk->chain = valid_blocks;
2160 blk->valid_chain = 1;
2161 valid_blocks = blk;
2162 }
2163 while ((blk = valid_blocks))
2164 {
2165 gcov_type total;
2166 arc_info *arc, *inv_arc;
2167
2168 valid_blocks = blk->chain;
2169 blk->valid_chain = 0;
2170 if (blk->num_succ == 1)
2171 {
2172 block_info *dst;
2173
2174 total = blk->count;
2175 inv_arc = NULL;
2176 for (arc = blk->succ; arc; arc = arc->succ_next)
2177 {
2178 total -= arc->count;
2179 if (!arc->count_valid)
2180 inv_arc = arc;
2181 }
2182 dst = inv_arc->dst;
2183 inv_arc->count_valid = 1;
2184 inv_arc->count = total;
2185 blk->num_succ--;
2186 dst->num_pred--;
2187 if (dst->count_valid)
2188 {
2189 if (dst->num_pred == 1 && !dst->valid_chain)
2190 {
2191 dst->chain = valid_blocks;
2192 dst->valid_chain = 1;
2193 valid_blocks = dst;
2194 }
2195 }
2196 else
2197 {
2198 if (!dst->num_pred && !dst->invalid_chain)
2199 {
2200 dst->chain = invalid_blocks;
2201 dst->invalid_chain = 1;
2202 invalid_blocks = dst;
2203 }
2204 }
2205 }
2206 if (blk->num_pred == 1)
2207 {
2208 block_info *src;
2209
2210 total = blk->count;
2211 inv_arc = NULL;
2212 for (arc = blk->pred; arc; arc = arc->pred_next)
2213 {
2214 total -= arc->count;
2215 if (!arc->count_valid)
2216 inv_arc = arc;
2217 }
2218 src = inv_arc->src;
2219 inv_arc->count_valid = 1;
2220 inv_arc->count = total;
2221 blk->num_pred--;
2222 src->num_succ--;
2223 if (src->count_valid)
2224 {
2225 if (src->num_succ == 1 && !src->valid_chain)
2226 {
2227 src->chain = valid_blocks;
2228 src->valid_chain = 1;
2229 valid_blocks = src;
2230 }
2231 }
2232 else
2233 {
2234 if (!src->num_succ && !src->invalid_chain)
2235 {
2236 src->chain = invalid_blocks;
2237 src->invalid_chain = 1;
2238 invalid_blocks = src;
2239 }
2240 }
2241 }
2242 }
2243 }
2244
2245 /* If the graph has been correctly solved, every block will have a
2246 valid count. */
2247 for (unsigned i = 0; ix < fn->blocks.size (); i++)
2248 if (!fn->blocks[i].count_valid)
2249 {
2250 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
2251 bbg_file_name, fn->get_name ());
2252 break;
2253 }
2254 }
2255
2256 /* Mark all the blocks only reachable via an incoming catch. */
2257
2258 static void
2259 find_exception_blocks (function_info *fn)
2260 {
2261 unsigned ix;
2262 block_info **queue = XALLOCAVEC (block_info *, fn->blocks.size ());
2263
2264 /* First mark all blocks as exceptional. */
2265 for (ix = fn->blocks.size (); ix--;)
2266 fn->blocks[ix].exceptional = 1;
2267
2268 /* Now mark all the blocks reachable via non-fake edges */
2269 queue[0] = &fn->blocks[0];
2270 queue[0]->exceptional = 0;
2271 for (ix = 1; ix;)
2272 {
2273 block_info *block = queue[--ix];
2274 const arc_info *arc;
2275
2276 for (arc = block->succ; arc; arc = arc->succ_next)
2277 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
2278 {
2279 arc->dst->exceptional = 0;
2280 queue[ix++] = arc->dst;
2281 }
2282 }
2283 }
2284 \f
2285
2286 /* Increment totals in COVERAGE according to arc ARC. */
2287
2288 static void
2289 add_branch_counts (coverage_info *coverage, const arc_info *arc)
2290 {
2291 if (arc->is_call_non_return)
2292 {
2293 coverage->calls++;
2294 if (arc->src->count)
2295 coverage->calls_executed++;
2296 }
2297 else if (!arc->is_unconditional)
2298 {
2299 coverage->branches++;
2300 if (arc->src->count)
2301 coverage->branches_executed++;
2302 if (arc->count)
2303 coverage->branches_taken++;
2304 }
2305 }
2306
2307 /* Format COUNT, if flag_human_readable_numbers is set, return it human
2308 readable format. */
2309
2310 static char const *
2311 format_count (gcov_type count)
2312 {
2313 static char buffer[64];
2314 const char *units = " kMGTPEZY";
2315
2316 if (count < 1000 || !flag_human_readable_numbers)
2317 {
2318 sprintf (buffer, "%" PRId64, count);
2319 return buffer;
2320 }
2321
2322 unsigned i;
2323 gcov_type divisor = 1;
2324 for (i = 0; units[i+1]; i++, divisor *= 1000)
2325 {
2326 if (count + divisor / 2 < 1000 * divisor)
2327 break;
2328 }
2329 float r = 1.0f * count / divisor;
2330 sprintf (buffer, "%.1f%c", r, units[i]);
2331 return buffer;
2332 }
2333
2334 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2335 count. If DECIMAL_PLACES >= 0, format TOP/BOTTOM * 100 to DECIMAL_PLACES.
2336 If DECIMAL_PLACES is zero, no decimal point is printed. Only print 100% when
2337 TOP==BOTTOM and only print 0% when TOP=0. If DECIMAL_PLACES < 0, then simply
2338 format TOP. Return pointer to a static string. */
2339
2340 static char const *
2341 format_gcov (gcov_type top, gcov_type bottom, int decimal_places)
2342 {
2343 static char buffer[20];
2344
2345 if (decimal_places >= 0)
2346 {
2347 float ratio = bottom ? 100.0f * top / bottom: 0;
2348
2349 /* Round up to 1% if there's a small non-zero value. */
2350 if (ratio > 0.0f && ratio < 0.5f && decimal_places == 0)
2351 ratio = 1.0f;
2352 sprintf (buffer, "%.*f%%", decimal_places, ratio);
2353 }
2354 else
2355 return format_count (top);
2356
2357 return buffer;
2358 }
2359
2360 /* Summary of execution */
2361
2362 static void
2363 executed_summary (unsigned lines, unsigned executed)
2364 {
2365 if (lines)
2366 fnotice (stdout, "Lines executed:%s of %d\n",
2367 format_gcov (executed, lines, 2), lines);
2368 else
2369 fnotice (stdout, "No executable lines\n");
2370 }
2371
2372 /* Output summary info for a function. */
2373
2374 static void
2375 function_summary (const coverage_info *coverage)
2376 {
2377 fnotice (stdout, "%s '%s'\n", "Function", coverage->name);
2378 executed_summary (coverage->lines, coverage->lines_executed);
2379 }
2380
2381 /* Output summary info for a file. */
2382
2383 static void
2384 file_summary (const coverage_info *coverage)
2385 {
2386 fnotice (stdout, "%s '%s'\n", "File", coverage->name);
2387 executed_summary (coverage->lines, coverage->lines_executed);
2388
2389 if (flag_branches)
2390 {
2391 if (coverage->branches)
2392 {
2393 fnotice (stdout, "Branches executed:%s of %d\n",
2394 format_gcov (coverage->branches_executed,
2395 coverage->branches, 2),
2396 coverage->branches);
2397 fnotice (stdout, "Taken at least once:%s of %d\n",
2398 format_gcov (coverage->branches_taken,
2399 coverage->branches, 2),
2400 coverage->branches);
2401 }
2402 else
2403 fnotice (stdout, "No branches\n");
2404 if (coverage->calls)
2405 fnotice (stdout, "Calls executed:%s of %d\n",
2406 format_gcov (coverage->calls_executed, coverage->calls, 2),
2407 coverage->calls);
2408 else
2409 fnotice (stdout, "No calls\n");
2410 }
2411 }
2412
2413 /* Canonicalize the filename NAME by canonicalizing directory
2414 separators, eliding . components and resolving .. components
2415 appropriately. Always returns a unique string. */
2416
2417 static char *
2418 canonicalize_name (const char *name)
2419 {
2420 /* The canonical name cannot be longer than the incoming name. */
2421 char *result = XNEWVEC (char, strlen (name) + 1);
2422 const char *base = name, *probe;
2423 char *ptr = result;
2424 char *dd_base;
2425 int slash = 0;
2426
2427 #if HAVE_DOS_BASED_FILE_SYSTEM
2428 if (base[0] && base[1] == ':')
2429 {
2430 result[0] = base[0];
2431 result[1] = ':';
2432 base += 2;
2433 ptr += 2;
2434 }
2435 #endif
2436 for (dd_base = ptr; *base; base = probe)
2437 {
2438 size_t len;
2439
2440 for (probe = base; *probe; probe++)
2441 if (IS_DIR_SEPARATOR (*probe))
2442 break;
2443
2444 len = probe - base;
2445 if (len == 1 && base[0] == '.')
2446 /* Elide a '.' directory */
2447 ;
2448 else if (len == 2 && base[0] == '.' && base[1] == '.')
2449 {
2450 /* '..', we can only elide it and the previous directory, if
2451 we're not a symlink. */
2452 struct stat ATTRIBUTE_UNUSED buf;
2453
2454 *ptr = 0;
2455 if (dd_base == ptr
2456 #if defined (S_ISLNK)
2457 /* S_ISLNK is not POSIX.1-1996. */
2458 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2459 #endif
2460 )
2461 {
2462 /* Cannot elide, or unreadable or a symlink. */
2463 dd_base = ptr + 2 + slash;
2464 goto regular;
2465 }
2466 while (ptr != dd_base && *ptr != '/')
2467 ptr--;
2468 slash = ptr != result;
2469 }
2470 else
2471 {
2472 regular:
2473 /* Regular pathname component. */
2474 if (slash)
2475 *ptr++ = '/';
2476 memcpy (ptr, base, len);
2477 ptr += len;
2478 slash = 1;
2479 }
2480
2481 for (; IS_DIR_SEPARATOR (*probe); probe++)
2482 continue;
2483 }
2484 *ptr = 0;
2485
2486 return result;
2487 }
2488
2489 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2490
2491 static void
2492 md5sum_to_hex (const char *sum, char *buffer)
2493 {
2494 for (unsigned i = 0; i < 16; i++)
2495 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2496 }
2497
2498 /* Generate an output file name. INPUT_NAME is the canonicalized main
2499 input file and SRC_NAME is the canonicalized file name.
2500 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2501 long_output_names we prepend the processed name of the input file
2502 to each output name (except when the current source file is the
2503 input file, so you don't get a double concatenation). The two
2504 components are separated by '##'. With preserve_paths we create a
2505 filename from all path components of the source file, replacing '/'
2506 with '#', and .. with '^', without it we simply take the basename
2507 component. (Remember, the canonicalized name will already have
2508 elided '.' components and converted \\ separators.) */
2509
2510 static char *
2511 make_gcov_file_name (const char *input_name, const char *src_name)
2512 {
2513 char *ptr;
2514 char *result;
2515
2516 if (flag_long_names && input_name && strcmp (src_name, input_name))
2517 {
2518 /* Generate the input filename part. */
2519 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2520
2521 ptr = result;
2522 ptr = mangle_name (input_name, ptr);
2523 ptr[0] = ptr[1] = '#';
2524 ptr += 2;
2525 }
2526 else
2527 {
2528 result = XNEWVEC (char, strlen (src_name) + 10);
2529 ptr = result;
2530 }
2531
2532 ptr = mangle_name (src_name, ptr);
2533 strcpy (ptr, ".gcov");
2534
2535 /* When hashing filenames, we shorten them by only using the filename
2536 component and appending a hash of the full (mangled) pathname. */
2537 if (flag_hash_filenames)
2538 {
2539 md5_ctx ctx;
2540 char md5sum[16];
2541 char md5sum_hex[33];
2542
2543 md5_init_ctx (&ctx);
2544 md5_process_bytes (src_name, strlen (src_name), &ctx);
2545 md5_finish_ctx (&ctx, md5sum);
2546 md5sum_to_hex (md5sum, md5sum_hex);
2547 free (result);
2548
2549 result = XNEWVEC (char, strlen (src_name) + 50);
2550 ptr = result;
2551 ptr = mangle_name (src_name, ptr);
2552 ptr[0] = ptr[1] = '#';
2553 ptr += 2;
2554 memcpy (ptr, md5sum_hex, 32);
2555 ptr += 32;
2556 strcpy (ptr, ".gcov");
2557 }
2558
2559 return result;
2560 }
2561
2562 /* Mangle BASE name, copy it at the beginning of PTR buffer and
2563 return address of the \0 character of the buffer. */
2564
2565 static char *
2566 mangle_name (char const *base, char *ptr)
2567 {
2568 size_t len;
2569
2570 /* Generate the source filename part. */
2571 if (!flag_preserve_paths)
2572 base = lbasename (base);
2573 else
2574 base = mangle_path (base);
2575
2576 len = strlen (base);
2577 memcpy (ptr, base, len);
2578 ptr += len;
2579
2580 return ptr;
2581 }
2582
2583 /* Scan through the bb_data for each line in the block, increment
2584 the line number execution count indicated by the execution count of
2585 the appropriate basic block. */
2586
2587 static void
2588 add_line_counts (coverage_info *coverage, function_info *fn)
2589 {
2590 bool has_any_line = false;
2591 /* Scan each basic block. */
2592 for (unsigned ix = 0; ix != fn->blocks.size (); ix++)
2593 {
2594 line_info *line = NULL;
2595 block_info *block = &fn->blocks[ix];
2596 if (block->count && ix && ix + 1 != fn->blocks.size ())
2597 fn->blocks_executed++;
2598 for (unsigned i = 0; i < block->locations.size (); i++)
2599 {
2600 unsigned src_idx = block->locations[i].source_file_idx;
2601 vector<unsigned> &lines = block->locations[i].lines;
2602
2603 block->cycle.arc = NULL;
2604 block->cycle.ident = ~0U;
2605
2606 for (unsigned j = 0; j < lines.size (); j++)
2607 {
2608 unsigned ln = lines[j];
2609
2610 /* Line belongs to a function that is in a group. */
2611 if (fn->group_line_p (ln, src_idx))
2612 {
2613 gcc_assert (lines[j] - fn->start_line < fn->lines.size ());
2614 line = &(fn->lines[lines[j] - fn->start_line]);
2615 line->exists = 1;
2616 if (!block->exceptional)
2617 {
2618 line->unexceptional = 1;
2619 if (block->count == 0)
2620 line->has_unexecuted_block = 1;
2621 }
2622 line->count += block->count;
2623 }
2624 else
2625 {
2626 gcc_assert (ln < sources[src_idx].lines.size ());
2627 line = &(sources[src_idx].lines[ln]);
2628 if (coverage)
2629 {
2630 if (!line->exists)
2631 coverage->lines++;
2632 if (!line->count && block->count)
2633 coverage->lines_executed++;
2634 }
2635 line->exists = 1;
2636 if (!block->exceptional)
2637 {
2638 line->unexceptional = 1;
2639 if (block->count == 0)
2640 line->has_unexecuted_block = 1;
2641 }
2642 line->count += block->count;
2643 }
2644 }
2645
2646 has_any_line = true;
2647
2648 if (!ix || ix + 1 == fn->blocks.size ())
2649 /* Entry or exit block. */;
2650 else if (line != NULL)
2651 {
2652 line->blocks.push_back (block);
2653
2654 if (flag_branches)
2655 {
2656 arc_info *arc;
2657
2658 for (arc = block->succ; arc; arc = arc->succ_next)
2659 line->branches.push_back (arc);
2660 }
2661 }
2662 }
2663 }
2664
2665 if (!has_any_line)
2666 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name,
2667 fn->get_name ());
2668 }
2669
2670 /* Accumulate info for LINE that belongs to SRC source file. If ADD_COVERAGE
2671 is set to true, update source file summary. */
2672
2673 static void accumulate_line_info (line_info *line, source_info *src,
2674 bool add_coverage)
2675 {
2676 if (add_coverage)
2677 for (vector<arc_info *>::iterator it = line->branches.begin ();
2678 it != line->branches.end (); it++)
2679 add_branch_counts (&src->coverage, *it);
2680
2681 if (!line->blocks.empty ())
2682 {
2683 /* The user expects the line count to be the number of times
2684 a line has been executed. Simply summing the block count
2685 will give an artificially high number. The Right Thing
2686 is to sum the entry counts to the graph of blocks on this
2687 line, then find the elementary cycles of the local graph
2688 and add the transition counts of those cycles. */
2689 gcov_type count = 0;
2690
2691 /* Cycle detection. */
2692 for (vector<block_info *>::iterator it = line->blocks.begin ();
2693 it != line->blocks.end (); it++)
2694 {
2695 for (arc_info *arc = (*it)->pred; arc; arc = arc->pred_next)
2696 if (!line->has_block (arc->src))
2697 count += arc->count;
2698 for (arc_info *arc = (*it)->succ; arc; arc = arc->succ_next)
2699 arc->cs_count = arc->count;
2700 }
2701
2702 /* Now, add the count of loops entirely on this line. */
2703 count += get_cycles_count (*line);
2704 line->count = count;
2705
2706 if (line->count > src->maximum_count)
2707 src->maximum_count = line->count;
2708 }
2709
2710 if (line->exists && add_coverage)
2711 {
2712 src->coverage.lines++;
2713 if (line->count)
2714 src->coverage.lines_executed++;
2715 }
2716 }
2717
2718 /* Accumulate the line counts of a file. */
2719
2720 static void
2721 accumulate_line_counts (source_info *src)
2722 {
2723 /* First work on group functions. */
2724 for (vector<function_info *>::iterator it = src->functions.begin ();
2725 it != src->functions.end (); it++)
2726 {
2727 function_info *fn = *it;
2728
2729 if (fn->src != src->index || !fn->is_group)
2730 continue;
2731
2732 for (vector<line_info>::iterator it2 = fn->lines.begin ();
2733 it2 != fn->lines.end (); it2++)
2734 {
2735 line_info *line = &(*it2);
2736 accumulate_line_info (line, src, false);
2737 }
2738 }
2739
2740 /* Work on global lines that line in source file SRC. */
2741 for (vector<line_info>::iterator it = src->lines.begin ();
2742 it != src->lines.end (); it++)
2743 accumulate_line_info (&(*it), src, true);
2744
2745 /* If not using intermediate mode, sum lines of group functions and
2746 add them to lines that live in a source file. */
2747 if (!flag_json_format)
2748 for (vector<function_info *>::iterator it = src->functions.begin ();
2749 it != src->functions.end (); it++)
2750 {
2751 function_info *fn = *it;
2752
2753 if (fn->src != src->index || !fn->is_group)
2754 continue;
2755
2756 for (unsigned i = 0; i < fn->lines.size (); i++)
2757 {
2758 line_info *fn_line = &fn->lines[i];
2759 if (fn_line->exists)
2760 {
2761 unsigned ln = fn->start_line + i;
2762 line_info *src_line = &src->lines[ln];
2763
2764 if (!src_line->exists)
2765 src->coverage.lines++;
2766 if (!src_line->count && fn_line->count)
2767 src->coverage.lines_executed++;
2768
2769 src_line->count += fn_line->count;
2770 src_line->exists = 1;
2771
2772 if (fn_line->has_unexecuted_block)
2773 src_line->has_unexecuted_block = 1;
2774
2775 if (fn_line->unexceptional)
2776 src_line->unexceptional = 1;
2777 }
2778 }
2779 }
2780 }
2781
2782 /* Output information about ARC number IX. Returns nonzero if
2783 anything is output. */
2784
2785 static int
2786 output_branch_count (FILE *gcov_file, int ix, const arc_info *arc)
2787 {
2788 if (arc->is_call_non_return)
2789 {
2790 if (arc->src->count)
2791 {
2792 fnotice (gcov_file, "call %2d returned %s\n", ix,
2793 format_gcov (arc->src->count - arc->count,
2794 arc->src->count, -flag_counts));
2795 }
2796 else
2797 fnotice (gcov_file, "call %2d never executed\n", ix);
2798 }
2799 else if (!arc->is_unconditional)
2800 {
2801 if (arc->src->count)
2802 fnotice (gcov_file, "branch %2d taken %s%s", ix,
2803 format_gcov (arc->count, arc->src->count, -flag_counts),
2804 arc->fall_through ? " (fallthrough)"
2805 : arc->is_throw ? " (throw)" : "");
2806 else
2807 fnotice (gcov_file, "branch %2d never executed", ix);
2808
2809 if (flag_verbose)
2810 fnotice (gcov_file, " (BB %d)", arc->dst->id);
2811
2812 fnotice (gcov_file, "\n");
2813 }
2814 else if (flag_unconditional && !arc->dst->is_call_return)
2815 {
2816 if (arc->src->count)
2817 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2818 format_gcov (arc->count, arc->src->count, -flag_counts));
2819 else
2820 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2821 }
2822 else
2823 return 0;
2824 return 1;
2825 }
2826
2827 static const char *
2828 read_line (FILE *file)
2829 {
2830 static char *string;
2831 static size_t string_len;
2832 size_t pos = 0;
2833 char *ptr;
2834
2835 if (!string_len)
2836 {
2837 string_len = 200;
2838 string = XNEWVEC (char, string_len);
2839 }
2840
2841 while ((ptr = fgets (string + pos, string_len - pos, file)))
2842 {
2843 size_t len = strlen (string + pos);
2844
2845 if (len && string[pos + len - 1] == '\n')
2846 {
2847 string[pos + len - 1] = 0;
2848 return string;
2849 }
2850 pos += len;
2851 /* If the file contains NUL characters or an incomplete
2852 last line, which can happen more than once in one run,
2853 we have to avoid doubling the STRING_LEN unnecessarily. */
2854 if (pos > string_len / 2)
2855 {
2856 string_len *= 2;
2857 string = XRESIZEVEC (char, string, string_len);
2858 }
2859 }
2860
2861 return pos ? string : NULL;
2862 }
2863
2864 /* Pad string S with spaces from left to have total width equal to 9. */
2865
2866 static void
2867 pad_count_string (string &s)
2868 {
2869 if (s.size () < 9)
2870 s.insert (0, 9 - s.size (), ' ');
2871 }
2872
2873 /* Print GCOV line beginning to F stream. If EXISTS is set to true, the
2874 line exists in source file. UNEXCEPTIONAL indicated that it's not in
2875 an exceptional statement. The output is printed for LINE_NUM of given
2876 COUNT of executions. EXCEPTIONAL_STRING and UNEXCEPTIONAL_STRING are
2877 used to indicate non-executed blocks. */
2878
2879 static void
2880 output_line_beginning (FILE *f, bool exists, bool unexceptional,
2881 bool has_unexecuted_block,
2882 gcov_type count, unsigned line_num,
2883 const char *exceptional_string,
2884 const char *unexceptional_string,
2885 unsigned int maximum_count)
2886 {
2887 string s;
2888 if (exists)
2889 {
2890 if (count > 0)
2891 {
2892 s = format_gcov (count, 0, -1);
2893 if (has_unexecuted_block
2894 && bbg_supports_has_unexecuted_blocks)
2895 {
2896 if (flag_use_colors)
2897 {
2898 pad_count_string (s);
2899 s.insert (0, SGR_SEQ (COLOR_BG_MAGENTA
2900 COLOR_SEPARATOR COLOR_FG_WHITE));
2901 s += SGR_RESET;
2902 }
2903 else
2904 s += "*";
2905 }
2906 pad_count_string (s);
2907 }
2908 else
2909 {
2910 if (flag_use_colors)
2911 {
2912 s = "0";
2913 pad_count_string (s);
2914 if (unexceptional)
2915 s.insert (0, SGR_SEQ (COLOR_BG_RED
2916 COLOR_SEPARATOR COLOR_FG_WHITE));
2917 else
2918 s.insert (0, SGR_SEQ (COLOR_BG_CYAN
2919 COLOR_SEPARATOR COLOR_FG_WHITE));
2920 s += SGR_RESET;
2921 }
2922 else
2923 {
2924 s = unexceptional ? unexceptional_string : exceptional_string;
2925 pad_count_string (s);
2926 }
2927 }
2928 }
2929 else
2930 {
2931 s = "-";
2932 pad_count_string (s);
2933 }
2934
2935 /* Format line number in output. */
2936 char buffer[16];
2937 sprintf (buffer, "%5u", line_num);
2938 string linestr (buffer);
2939
2940 if (flag_use_hotness_colors && maximum_count)
2941 {
2942 if (count * 2 > maximum_count) /* > 50%. */
2943 linestr.insert (0, SGR_SEQ (COLOR_BG_RED));
2944 else if (count * 5 > maximum_count) /* > 20%. */
2945 linestr.insert (0, SGR_SEQ (COLOR_BG_YELLOW));
2946 else if (count * 10 > maximum_count) /* > 10%. */
2947 linestr.insert (0, SGR_SEQ (COLOR_BG_GREEN));
2948 linestr += SGR_RESET;
2949 }
2950
2951 fprintf (f, "%s:%s", s.c_str (), linestr.c_str ());
2952 }
2953
2954 static void
2955 print_source_line (FILE *f, const vector<const char *> &source_lines,
2956 unsigned line)
2957 {
2958 gcc_assert (line >= 1);
2959 gcc_assert (line <= source_lines.size ());
2960
2961 fprintf (f, ":%s\n", source_lines[line - 1]);
2962 }
2963
2964 /* Output line details for LINE and print it to F file. LINE lives on
2965 LINE_NUM. */
2966
2967 static void
2968 output_line_details (FILE *f, const line_info *line, unsigned line_num)
2969 {
2970 if (flag_all_blocks)
2971 {
2972 arc_info *arc;
2973 int ix, jx;
2974
2975 ix = jx = 0;
2976 for (vector<block_info *>::const_iterator it = line->blocks.begin ();
2977 it != line->blocks.end (); it++)
2978 {
2979 if (!(*it)->is_call_return)
2980 {
2981 output_line_beginning (f, line->exists,
2982 (*it)->exceptional, false,
2983 (*it)->count, line_num,
2984 "%%%%%", "$$$$$", 0);
2985 fprintf (f, "-block %2d", ix++);
2986 if (flag_verbose)
2987 fprintf (f, " (BB %u)", (*it)->id);
2988 fprintf (f, "\n");
2989 }
2990 if (flag_branches)
2991 for (arc = (*it)->succ; arc; arc = arc->succ_next)
2992 jx += output_branch_count (f, jx, arc);
2993 }
2994 }
2995 else if (flag_branches)
2996 {
2997 int ix;
2998
2999 ix = 0;
3000 for (vector<arc_info *>::const_iterator it = line->branches.begin ();
3001 it != line->branches.end (); it++)
3002 ix += output_branch_count (f, ix, (*it));
3003 }
3004 }
3005
3006 /* Output detail statistics about function FN to file F. */
3007
3008 static void
3009 output_function_details (FILE *f, function_info *fn)
3010 {
3011 if (!flag_branches)
3012 return;
3013
3014 arc_info *arc = fn->blocks[EXIT_BLOCK].pred;
3015 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
3016 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
3017
3018 for (; arc; arc = arc->pred_next)
3019 if (arc->fake)
3020 return_count -= arc->count;
3021
3022 fprintf (f, "function %s", fn->get_name ());
3023 fprintf (f, " called %s",
3024 format_gcov (called_count, 0, -1));
3025 fprintf (f, " returned %s",
3026 format_gcov (return_count, called_count, 0));
3027 fprintf (f, " blocks executed %s",
3028 format_gcov (fn->blocks_executed, fn->get_block_count (), 0));
3029 fprintf (f, "\n");
3030 }
3031
3032 /* Read in the source file one line at a time, and output that line to
3033 the gcov file preceded by its execution count and other
3034 information. */
3035
3036 static void
3037 output_lines (FILE *gcov_file, const source_info *src)
3038 {
3039 #define DEFAULT_LINE_START " -: 0:"
3040 #define FN_SEPARATOR "------------------\n"
3041
3042 FILE *source_file;
3043 const char *retval;
3044
3045 /* Print colorization legend. */
3046 if (flag_use_colors)
3047 fprintf (gcov_file, "%s",
3048 DEFAULT_LINE_START "Colorization: profile count: " \
3049 SGR_SEQ (COLOR_BG_CYAN) "zero coverage (exceptional)" SGR_RESET \
3050 " " \
3051 SGR_SEQ (COLOR_BG_RED) "zero coverage (unexceptional)" SGR_RESET \
3052 " " \
3053 SGR_SEQ (COLOR_BG_MAGENTA) "unexecuted block" SGR_RESET "\n");
3054
3055 if (flag_use_hotness_colors)
3056 fprintf (gcov_file, "%s",
3057 DEFAULT_LINE_START "Colorization: line numbers: hotness: " \
3058 SGR_SEQ (COLOR_BG_RED) "> 50%" SGR_RESET " " \
3059 SGR_SEQ (COLOR_BG_YELLOW) "> 20%" SGR_RESET " " \
3060 SGR_SEQ (COLOR_BG_GREEN) "> 10%" SGR_RESET "\n");
3061
3062 fprintf (gcov_file, DEFAULT_LINE_START "Source:%s\n", src->coverage.name);
3063 if (!multiple_files)
3064 {
3065 fprintf (gcov_file, DEFAULT_LINE_START "Graph:%s\n", bbg_file_name);
3066 fprintf (gcov_file, DEFAULT_LINE_START "Data:%s\n",
3067 no_data_file ? "-" : da_file_name);
3068 fprintf (gcov_file, DEFAULT_LINE_START "Runs:%u\n", object_runs);
3069 }
3070
3071 source_file = fopen (src->name, "r");
3072 if (!source_file)
3073 fnotice (stderr, "Cannot open source file %s\n", src->name);
3074 else if (src->file_time == 0)
3075 fprintf (gcov_file, DEFAULT_LINE_START "Source is newer than graph\n");
3076
3077 vector<const char *> source_lines;
3078 if (source_file)
3079 while ((retval = read_line (source_file)) != NULL)
3080 source_lines.push_back (xstrdup (retval));
3081
3082 unsigned line_start_group = 0;
3083 vector<function_info *> *fns;
3084
3085 for (unsigned line_num = 1; line_num <= source_lines.size (); line_num++)
3086 {
3087 if (line_num >= src->lines.size ())
3088 {
3089 fprintf (gcov_file, "%9s:%5u", "-", line_num);
3090 print_source_line (gcov_file, source_lines, line_num);
3091 continue;
3092 }
3093
3094 const line_info *line = &src->lines[line_num];
3095
3096 if (line_start_group == 0)
3097 {
3098 fns = src->get_functions_at_location (line_num);
3099 if (fns != NULL && fns->size () > 1)
3100 {
3101 /* It's possible to have functions that partially overlap,
3102 thus take the maximum end_line of functions starting
3103 at LINE_NUM. */
3104 for (unsigned i = 0; i < fns->size (); i++)
3105 if ((*fns)[i]->end_line > line_start_group)
3106 line_start_group = (*fns)[i]->end_line;
3107 }
3108 else if (fns != NULL && fns->size () == 1)
3109 {
3110 function_info *fn = (*fns)[0];
3111 output_function_details (gcov_file, fn);
3112 }
3113 }
3114
3115 /* For lines which don't exist in the .bb file, print '-' before
3116 the source line. For lines which exist but were never
3117 executed, print '#####' or '=====' before the source line.
3118 Otherwise, print the execution count before the source line.
3119 There are 16 spaces of indentation added before the source
3120 line so that tabs won't be messed up. */
3121 output_line_beginning (gcov_file, line->exists, line->unexceptional,
3122 line->has_unexecuted_block, line->count,
3123 line_num, "=====", "#####", src->maximum_count);
3124
3125 print_source_line (gcov_file, source_lines, line_num);
3126 output_line_details (gcov_file, line, line_num);
3127
3128 if (line_start_group == line_num)
3129 {
3130 for (vector<function_info *>::iterator it = fns->begin ();
3131 it != fns->end (); it++)
3132 {
3133 function_info *fn = *it;
3134 vector<line_info> &lines = fn->lines;
3135
3136 fprintf (gcov_file, FN_SEPARATOR);
3137
3138 string fn_name = fn->get_name ();
3139 if (flag_use_colors)
3140 {
3141 fn_name.insert (0, SGR_SEQ (COLOR_FG_CYAN));
3142 fn_name += SGR_RESET;
3143 }
3144
3145 fprintf (gcov_file, "%s:\n", fn_name.c_str ());
3146
3147 output_function_details (gcov_file, fn);
3148
3149 /* Print all lines covered by the function. */
3150 for (unsigned i = 0; i < lines.size (); i++)
3151 {
3152 line_info *line = &lines[i];
3153 unsigned l = fn->start_line + i;
3154
3155 /* For lines which don't exist in the .bb file, print '-'
3156 before the source line. For lines which exist but
3157 were never executed, print '#####' or '=====' before
3158 the source line. Otherwise, print the execution count
3159 before the source line.
3160 There are 16 spaces of indentation added before the source
3161 line so that tabs won't be messed up. */
3162 output_line_beginning (gcov_file, line->exists,
3163 line->unexceptional,
3164 line->has_unexecuted_block,
3165 line->count,
3166 l, "=====", "#####",
3167 src->maximum_count);
3168
3169 print_source_line (gcov_file, source_lines, l);
3170 output_line_details (gcov_file, line, l);
3171 }
3172 }
3173
3174 fprintf (gcov_file, FN_SEPARATOR);
3175 line_start_group = 0;
3176 }
3177 }
3178
3179 if (source_file)
3180 fclose (source_file);
3181 }