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