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