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