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