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