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