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