[ARM] Add source mode to coprocessor pattern SETs
[official-gcc.git] / gcc / gcov.c
blob320b81263f88227b2dd2ea73addce1f7377cb0a0
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>
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.
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.
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/>. */
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. */
27 /* ??? Should have an option to print the number of basic blocks, and the
28 percent of them that are covered. */
30 /* Need an option to show individual block counts, and show
31 probabilities of fall through arcs. */
33 #include "config.h"
34 #define INCLUDE_ALGORITHM
35 #define INCLUDE_VECTOR
36 #include "system.h"
37 #include "coretypes.h"
38 #include "tm.h"
39 #include "intl.h"
40 #include "diagnostic.h"
41 #include "version.h"
42 #include "demangle.h"
44 #include <getopt.h>
46 #include "md5.h"
48 using namespace std;
50 #define IN_GCOV 1
51 #include "gcov-io.h"
52 #include "gcov-io.c"
54 /* The gcno file is generated by -ftest-coverage option. The gcda file is
55 generated by a program compiled with -fprofile-arcs. Their formats
56 are documented in gcov-io.h. */
58 /* The functions in this file for creating and solution program flow graphs
59 are very similar to functions in the gcc source file profile.c. In
60 some places we make use of the knowledge of how profile.c works to
61 select particular algorithms here. */
63 /* The code validates that the profile information read in corresponds
64 to the code currently being compiled. Rather than checking for
65 identical files, the code below compares a checksum on the CFG
66 (based on the order of basic blocks and the arcs in the CFG). If
67 the CFG checksum in the gcda file match the CFG checksum in the
68 gcno file, the profile data will be used. */
70 /* This is the size of the buffer used to read in source file lines. */
72 struct function_info;
73 struct block_info;
74 struct source_info;
76 /* Describes an arc between two basic blocks. */
78 typedef struct arc_info
80 /* source and destination blocks. */
81 struct block_info *src;
82 struct block_info *dst;
84 /* transition counts. */
85 gcov_type count;
86 /* used in cycle search, so that we do not clobber original counts. */
87 gcov_type cs_count;
89 unsigned int count_valid : 1;
90 unsigned int on_tree : 1;
91 unsigned int fake : 1;
92 unsigned int fall_through : 1;
94 /* Arc to a catch handler. */
95 unsigned int is_throw : 1;
97 /* Arc is for a function that abnormally returns. */
98 unsigned int is_call_non_return : 1;
100 /* Arc is for catch/setjmp. */
101 unsigned int is_nonlocal_return : 1;
103 /* Is an unconditional branch. */
104 unsigned int is_unconditional : 1;
106 /* Loop making arc. */
107 unsigned int cycle : 1;
109 /* Next branch on line. */
110 struct arc_info *line_next;
112 /* Links to next arc on src and dst lists. */
113 struct arc_info *succ_next;
114 struct arc_info *pred_next;
115 } arc_t;
117 /* Describes a basic block. Contains lists of arcs to successor and
118 predecessor blocks. */
120 typedef struct block_info
122 /* Chain of exit and entry arcs. */
123 arc_t *succ;
124 arc_t *pred;
126 /* Number of unprocessed exit and entry arcs. */
127 gcov_type num_succ;
128 gcov_type num_pred;
130 /* Block execution count. */
131 gcov_type count;
132 unsigned flags : 12;
133 unsigned count_valid : 1;
134 unsigned valid_chain : 1;
135 unsigned invalid_chain : 1;
136 unsigned exceptional : 1;
138 /* Block is a call instrumenting site. */
139 unsigned is_call_site : 1; /* Does the call. */
140 unsigned is_call_return : 1; /* Is the return. */
142 /* Block is a landing pad for longjmp or throw. */
143 unsigned is_nonlocal_return : 1;
145 union
147 struct
149 /* Array of line numbers and source files. source files are
150 introduced by a linenumber of zero, the next 'line number' is
151 the number of the source file. Always starts with a source
152 file. */
153 unsigned *encoding;
154 unsigned num;
155 } line; /* Valid until blocks are linked onto lines */
156 struct
158 /* Single line graph cycle workspace. Used for all-blocks
159 mode. */
160 arc_t *arc;
161 unsigned ident;
162 } cycle; /* Used in all-blocks mode, after blocks are linked onto
163 lines. */
164 } u;
166 /* Temporary chain for solving graph, and for chaining blocks on one
167 line. */
168 struct block_info *chain;
170 } block_t;
172 /* Describes a single function. Contains an array of basic blocks. */
174 typedef struct function_info
176 /* Name of function. */
177 char *name;
178 char *demangled_name;
179 unsigned ident;
180 unsigned lineno_checksum;
181 unsigned cfg_checksum;
183 /* The graph contains at least one fake incoming edge. */
184 unsigned has_catch : 1;
186 /* Array of basic blocks. Like in GCC, the entry block is
187 at blocks[0] and the exit block is at blocks[1]. */
188 #define ENTRY_BLOCK (0)
189 #define EXIT_BLOCK (1)
190 block_t *blocks;
191 unsigned num_blocks;
192 unsigned blocks_executed;
194 /* Raw arc coverage counts. */
195 gcov_type *counts;
196 unsigned num_counts;
198 /* First line number & file. */
199 unsigned line;
200 unsigned src;
202 /* Next function in same source file. */
203 struct function_info *next_file_fn;
205 /* Next function. */
206 struct function_info *next;
207 } function_t;
209 /* Describes coverage of a file or function. */
211 typedef struct coverage_info
213 int lines;
214 int lines_executed;
216 int branches;
217 int branches_executed;
218 int branches_taken;
220 int calls;
221 int calls_executed;
223 char *name;
224 } coverage_t;
226 /* Describes a single line of source. Contains a chain of basic blocks
227 with code on it. */
229 typedef struct line_info
231 /* Return true when NEEDLE is one of basic blocks the line belongs to. */
232 bool has_block (block_t *needle);
234 gcov_type count; /* execution count */
235 union
237 arc_t *branches; /* branches from blocks that end on this
238 line. Used for branch-counts when not
239 all-blocks mode. */
240 block_t *blocks; /* blocks which start on this line. Used
241 in all-blocks mode. */
242 } u;
243 unsigned exists : 1;
244 unsigned unexceptional : 1;
245 } line_t;
247 bool
248 line_t::has_block (block_t *needle)
250 for (block_t *n = u.blocks; n; n = n->chain)
251 if (n == needle)
252 return true;
254 return false;
257 /* Describes a file mentioned in the block graph. Contains an array
258 of line info. */
260 typedef struct source_info
262 /* Canonical name of source file. */
263 char *name;
264 time_t file_time;
266 /* Array of line information. */
267 line_t *lines;
268 unsigned num_lines;
270 coverage_t coverage;
272 /* Functions in this source file. These are in ascending line
273 number order. */
274 function_t *functions;
275 } source_t;
277 typedef struct name_map
279 char *name; /* Source file name */
280 unsigned src; /* Source file */
281 } name_map_t;
283 /* Holds a list of function basic block graphs. */
285 static function_t *functions;
286 static function_t **fn_end = &functions;
288 static source_t *sources; /* Array of source files */
289 static unsigned n_sources; /* Number of sources */
290 static unsigned a_sources; /* Allocated sources */
292 static name_map_t *names; /* Mapping of file names to sources */
293 static unsigned n_names; /* Number of names */
294 static unsigned a_names; /* Allocated names */
296 /* This holds data summary information. */
298 static unsigned object_runs;
299 static unsigned program_count;
301 static unsigned total_lines;
302 static unsigned total_executed;
304 /* Modification time of graph file. */
306 static time_t bbg_file_time;
308 /* Name of the notes (gcno) output file. The "bbg" prefix is for
309 historical reasons, when the notes file contained only the
310 basic block graph notes. */
312 static char *bbg_file_name;
314 /* Stamp of the bbg file */
315 static unsigned bbg_stamp;
317 /* Name and file pointer of the input file for the count data (gcda). */
319 static char *da_file_name;
321 /* Data file is missing. */
323 static int no_data_file;
325 /* If there is several input files, compute and display results after
326 reading all data files. This way if two or more gcda file refer to
327 the same source file (eg inline subprograms in a .h file), the
328 counts are added. */
330 static int multiple_files = 0;
332 /* Output branch probabilities. */
334 static int flag_branches = 0;
336 /* Show unconditional branches too. */
337 static int flag_unconditional = 0;
339 /* Output a gcov file if this is true. This is on by default, and can
340 be turned off by the -n option. */
342 static int flag_gcov_file = 1;
344 /* Output progress indication if this is true. This is off by default
345 and can be turned on by the -d option. */
347 static int flag_display_progress = 0;
349 /* Output *.gcov file in intermediate format used by 'lcov'. */
351 static int flag_intermediate_format = 0;
353 /* Output demangled function names. */
355 static int flag_demangled_names = 0;
357 /* For included files, make the gcov output file name include the name
358 of the input source file. For example, if x.h is included in a.c,
359 then the output file name is a.c##x.h.gcov instead of x.h.gcov. */
361 static int flag_long_names = 0;
363 /* For situations when a long name can potentially hit filesystem path limit,
364 let's calculate md5sum of the path and append it to a file name. */
366 static int flag_hash_filenames = 0;
368 /* Output count information for every basic block, not merely those
369 that contain line number information. */
371 static int flag_all_blocks = 0;
373 /* Output summary info for each function. */
375 static int flag_function_summary = 0;
377 /* Object directory file prefix. This is the directory/file where the
378 graph and data files are looked for, if nonzero. */
380 static char *object_directory = 0;
382 /* Source directory prefix. This is removed from source pathnames
383 that match, when generating the output file name. */
385 static char *source_prefix = 0;
386 static size_t source_length = 0;
388 /* Only show data for sources with relative pathnames. Absolute ones
389 usually indicate a system header file, which although it may
390 contain inline functions, is usually uninteresting. */
391 static int flag_relative_only = 0;
393 /* Preserve all pathname components. Needed when object files and
394 source files are in subdirectories. '/' is mangled as '#', '.' is
395 elided and '..' mangled to '^'. */
397 static int flag_preserve_paths = 0;
399 /* Output the number of times a branch was taken as opposed to the percentage
400 of times it was taken. */
402 static int flag_counts = 0;
404 /* Forward declarations. */
405 static int process_args (int, char **);
406 static void print_usage (int) ATTRIBUTE_NORETURN;
407 static void print_version (void) ATTRIBUTE_NORETURN;
408 static void process_file (const char *);
409 static void generate_results (const char *);
410 static void create_file_names (const char *);
411 static int name_search (const void *, const void *);
412 static int name_sort (const void *, const void *);
413 static char *canonicalize_name (const char *);
414 static unsigned find_source (const char *);
415 static function_t *read_graph_file (void);
416 static int read_count_file (function_t *);
417 static void solve_flow_graph (function_t *);
418 static void find_exception_blocks (function_t *);
419 static void add_branch_counts (coverage_t *, const arc_t *);
420 static void add_line_counts (coverage_t *, function_t *);
421 static void executed_summary (unsigned, unsigned);
422 static void function_summary (const coverage_t *, const char *);
423 static const char *format_gcov (gcov_type, gcov_type, int);
424 static void accumulate_line_counts (source_t *);
425 static void output_gcov_file (const char *, source_t *);
426 static int output_branch_count (FILE *, int, const arc_t *);
427 static void output_lines (FILE *, const source_t *);
428 static char *make_gcov_file_name (const char *, const char *);
429 static char *mangle_name (const char *, char *);
430 static void release_structures (void);
431 static void release_function (function_t *);
432 extern int main (int, char **);
434 /* Cycle detection!
435 There are a bajillion algorithms that do this. Boost's function is named
436 hawick_cycles, so I used the algorithm by K. A. Hawick and H. A. James in
437 "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
438 (url at <http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf>).
440 The basic algorithm is simple: effectively, we're finding all simple paths
441 in a subgraph (that shrinks every iteration). Duplicates are filtered by
442 "blocking" a path when a node is added to the path (this also prevents non-
443 simple paths)--the node is unblocked only when it participates in a cycle.
446 typedef vector<arc_t *> arc_vector_t;
447 typedef vector<const block_t *> block_vector_t;
449 /* Enum with types of loop in CFG. */
451 enum loop_type
453 NO_LOOP = 0,
454 LOOP = 1,
455 NEGATIVE_LOOP = 3
458 /* Loop_type operator that merges two values: A and B. */
460 inline loop_type& operator |= (loop_type& a, loop_type b)
462 return a = static_cast<loop_type> (a | b);
465 /* Handle cycle identified by EDGES, where the function finds minimum cs_count
466 and subtract the value from all counts. The subtracted value is added
467 to COUNT. Returns type of loop. */
469 static loop_type
470 handle_cycle (const arc_vector_t &edges, int64_t &count)
472 /* Find the minimum edge of the cycle, and reduce all nodes in the cycle by
473 that amount. */
474 int64_t cycle_count = INTTYPE_MAXIMUM (int64_t);
475 for (unsigned i = 0; i < edges.size (); i++)
477 int64_t ecount = edges[i]->cs_count;
478 if (cycle_count > ecount)
479 cycle_count = ecount;
481 count += cycle_count;
482 for (unsigned i = 0; i < edges.size (); i++)
483 edges[i]->cs_count -= cycle_count;
485 return cycle_count < 0 ? NEGATIVE_LOOP : LOOP;
488 /* Unblock a block U from BLOCKED. Apart from that, iterate all blocks
489 blocked by U in BLOCK_LISTS. */
491 static void
492 unblock (const block_t *u, block_vector_t &blocked,
493 vector<block_vector_t > &block_lists)
495 block_vector_t::iterator it = find (blocked.begin (), blocked.end (), u);
496 if (it == blocked.end ())
497 return;
499 unsigned index = it - blocked.begin ();
500 blocked.erase (it);
502 for (block_vector_t::iterator it2 = block_lists[index].begin ();
503 it2 != block_lists[index].end (); it2++)
504 unblock (*it2, blocked, block_lists);
505 for (unsigned j = 0; j < block_lists[index].size (); j++)
506 unblock (u, blocked, block_lists);
508 block_lists.erase (block_lists.begin () + index);
511 /* Find circuit going to block V, PATH is provisional seen cycle.
512 BLOCKED is vector of blocked vertices, BLOCK_LISTS contains vertices
513 blocked by a block. COUNT is accumulated count of the current LINE.
514 Returns what type of loop it contains. */
516 static loop_type
517 circuit (block_t *v, arc_vector_t &path, block_t *start,
518 block_vector_t &blocked, vector<block_vector_t> &block_lists,
519 line_t &linfo, int64_t &count)
521 loop_type result = NO_LOOP;
523 /* Add v to the block list. */
524 gcc_assert (find (blocked.begin (), blocked.end (), v) == blocked.end ());
525 blocked.push_back (v);
526 block_lists.push_back (block_vector_t ());
528 for (arc_t *arc = v->succ; arc; arc = arc->succ_next)
530 block_t *w = arc->dst;
531 if (w < start || !linfo.has_block (w))
532 continue;
534 path.push_back (arc);
535 if (w == start)
536 /* Cycle has been found. */
537 result |= handle_cycle (path, count);
538 else if (find (blocked.begin (), blocked.end (), w) == blocked.end ())
539 result |= circuit (w, path, start, blocked, block_lists, linfo, count);
541 path.pop_back ();
544 if (result != NO_LOOP)
545 unblock (v, blocked, block_lists);
546 else
547 for (arc_t *arc = v->succ; arc; arc = arc->succ_next)
549 block_t *w = arc->dst;
550 if (w < start || !linfo.has_block (w))
551 continue;
553 size_t index
554 = find (blocked.begin (), blocked.end (), w) - blocked.begin ();
555 gcc_assert (index < blocked.size ());
556 block_vector_t &list = block_lists[index];
557 if (find (list.begin (), list.end (), v) == list.end ())
558 list.push_back (v);
561 return result;
564 /* Find cycles for a LINFO. If HANDLE_NEGATIVE_CYCLES is set and the line
565 contains a negative loop, then perform the same function once again. */
567 static gcov_type
568 get_cycles_count (line_t &linfo, bool handle_negative_cycles = true)
570 /* Note that this algorithm works even if blocks aren't in sorted order.
571 Each iteration of the circuit detection is completely independent
572 (except for reducing counts, but that shouldn't matter anyways).
573 Therefore, operating on a permuted order (i.e., non-sorted) only
574 has the effect of permuting the output cycles. */
576 loop_type result = NO_LOOP;
577 gcov_type count = 0;
578 for (block_t *block = linfo.u.blocks; block; block = block->chain)
580 arc_vector_t path;
581 block_vector_t blocked;
582 vector<block_vector_t > block_lists;
583 result |= circuit (block, path, block, blocked, block_lists, linfo,
584 count);
587 /* If we have a negative cycle, repeat the find_cycles routine. */
588 if (result == NEGATIVE_LOOP && handle_negative_cycles)
589 count += get_cycles_count (linfo, false);
591 return count;
595 main (int argc, char **argv)
597 int argno;
598 int first_arg;
599 const char *p;
601 p = argv[0] + strlen (argv[0]);
602 while (p != argv[0] && !IS_DIR_SEPARATOR (p[-1]))
603 --p;
604 progname = p;
606 xmalloc_set_program_name (progname);
608 /* Unlock the stdio streams. */
609 unlock_std_streams ();
611 gcc_init_libintl ();
613 diagnostic_initialize (global_dc, 0);
615 /* Handle response files. */
616 expandargv (&argc, &argv);
618 a_names = 10;
619 names = XNEWVEC (name_map_t, a_names);
620 a_sources = 10;
621 sources = XNEWVEC (source_t, a_sources);
623 argno = process_args (argc, argv);
624 if (optind == argc)
625 print_usage (true);
627 if (argc - argno > 1)
628 multiple_files = 1;
630 first_arg = argno;
632 for (; argno != argc; argno++)
634 if (flag_display_progress)
635 printf ("Processing file %d out of %d\n", argno - first_arg + 1,
636 argc - first_arg);
637 process_file (argv[argno]);
640 generate_results (multiple_files ? NULL : argv[argc - 1]);
642 release_structures ();
644 return 0;
647 /* Print a usage message and exit. If ERROR_P is nonzero, this is an error,
648 otherwise the output of --help. */
650 static void
651 print_usage (int error_p)
653 FILE *file = error_p ? stderr : stdout;
654 int status = error_p ? FATAL_EXIT_CODE : SUCCESS_EXIT_CODE;
656 fnotice (file, "Usage: gcov [OPTION]... SOURCE|OBJ...\n\n");
657 fnotice (file, "Print code coverage information.\n\n");
658 fnotice (file, " -h, --help Print this help, then exit\n");
659 fnotice (file, " -a, --all-blocks Show information for every basic block\n");
660 fnotice (file, " -b, --branch-probabilities Include branch probabilities in output\n");
661 fnotice (file, " -c, --branch-counts Output counts of branches taken\n\
662 rather than percentages\n");
663 fnotice (file, " -d, --display-progress Display progress information\n");
664 fnotice (file, " -f, --function-summaries Output summaries for each function\n");
665 fnotice (file, " -i, --intermediate-format Output .gcov file in intermediate text format\n");
666 fnotice (file, " -l, --long-file-names Use long output file names for included\n\
667 source files\n");
668 fnotice (file, " -m, --demangled-names Output demangled function names\n");
669 fnotice (file, " -n, --no-output Do not create an output file\n");
670 fnotice (file, " -o, --object-directory DIR|FILE Search for object files in DIR or called FILE\n");
671 fnotice (file, " -p, --preserve-paths Preserve all pathname components\n");
672 fnotice (file, " -r, --relative-only Only show data for relative sources\n");
673 fnotice (file, " -s, --source-prefix DIR Source prefix to elide\n");
674 fnotice (file, " -u, --unconditional-branches Show unconditional branch counts too\n");
675 fnotice (file, " -v, --version Print version number, then exit\n");
676 fnotice (file, " -x, --hash-filenames Hash long pathnames\n");
677 fnotice (file, "\nFor bug reporting instructions, please see:\n%s.\n",
678 bug_report_url);
679 exit (status);
682 /* Print version information and exit. */
684 static void
685 print_version (void)
687 fnotice (stdout, "gcov %s%s\n", pkgversion_string, version_string);
688 fprintf (stdout, "Copyright %s 2017 Free Software Foundation, Inc.\n",
689 _("(C)"));
690 fnotice (stdout,
691 _("This is free software; see the source for copying conditions.\n"
692 "There is NO warranty; not even for MERCHANTABILITY or \n"
693 "FITNESS FOR A PARTICULAR PURPOSE.\n\n"));
694 exit (SUCCESS_EXIT_CODE);
697 static const struct option options[] =
699 { "help", no_argument, NULL, 'h' },
700 { "version", no_argument, NULL, 'v' },
701 { "all-blocks", no_argument, NULL, 'a' },
702 { "branch-probabilities", no_argument, NULL, 'b' },
703 { "branch-counts", no_argument, NULL, 'c' },
704 { "intermediate-format", no_argument, NULL, 'i' },
705 { "no-output", no_argument, NULL, 'n' },
706 { "long-file-names", no_argument, NULL, 'l' },
707 { "function-summaries", no_argument, NULL, 'f' },
708 { "demangled-names", no_argument, NULL, 'm' },
709 { "preserve-paths", no_argument, NULL, 'p' },
710 { "relative-only", no_argument, NULL, 'r' },
711 { "object-directory", required_argument, NULL, 'o' },
712 { "object-file", required_argument, NULL, 'o' },
713 { "source-prefix", required_argument, NULL, 's' },
714 { "unconditional-branches", no_argument, NULL, 'u' },
715 { "display-progress", no_argument, NULL, 'd' },
716 { "hash-filenames", no_argument, NULL, 'x' },
717 { 0, 0, 0, 0 }
720 /* Process args, return index to first non-arg. */
722 static int
723 process_args (int argc, char **argv)
725 int opt;
727 const char *opts = "abcdfhilmno:prs:uvx";
728 while ((opt = getopt_long (argc, argv, opts, options, NULL)) != -1)
730 switch (opt)
732 case 'a':
733 flag_all_blocks = 1;
734 break;
735 case 'b':
736 flag_branches = 1;
737 break;
738 case 'c':
739 flag_counts = 1;
740 break;
741 case 'f':
742 flag_function_summary = 1;
743 break;
744 case 'h':
745 print_usage (false);
746 /* print_usage will exit. */
747 case 'l':
748 flag_long_names = 1;
749 break;
750 case 'm':
751 flag_demangled_names = 1;
752 break;
753 case 'n':
754 flag_gcov_file = 0;
755 break;
756 case 'o':
757 object_directory = optarg;
758 break;
759 case 's':
760 source_prefix = optarg;
761 source_length = strlen (source_prefix);
762 break;
763 case 'r':
764 flag_relative_only = 1;
765 break;
766 case 'p':
767 flag_preserve_paths = 1;
768 break;
769 case 'u':
770 flag_unconditional = 1;
771 break;
772 case 'i':
773 flag_intermediate_format = 1;
774 flag_gcov_file = 1;
775 break;
776 case 'd':
777 flag_display_progress = 1;
778 break;
779 case 'x':
780 flag_hash_filenames = 1;
781 break;
782 case 'v':
783 print_version ();
784 /* print_version will exit. */
785 default:
786 print_usage (true);
787 /* print_usage will exit. */
791 return optind;
794 /* Get the name of the gcov file. The return value must be free'd.
796 It appends the '.gcov' extension to the *basename* of the file.
797 The resulting file name will be in PWD.
799 e.g.,
800 input: foo.da, output: foo.da.gcov
801 input: a/b/foo.cc, output: foo.cc.gcov */
803 static char *
804 get_gcov_intermediate_filename (const char *file_name)
806 const char *gcov = ".gcov";
807 char *result;
808 const char *cptr;
810 /* Find the 'basename'. */
811 cptr = lbasename (file_name);
813 result = XNEWVEC (char, strlen (cptr) + strlen (gcov) + 1);
814 sprintf (result, "%s%s", cptr, gcov);
816 return result;
819 /* Output the result in intermediate format used by 'lcov'.
821 The intermediate format contains a single file named 'foo.cc.gcov',
822 with no source code included. A sample output is
824 file:foo.cc
825 function:5,1,_Z3foov
826 function:13,1,main
827 function:19,1,_GLOBAL__sub_I__Z3foov
828 function:19,1,_Z41__static_initialization_and_destruction_0ii
829 lcount:5,1
830 lcount:7,9
831 lcount:9,8
832 lcount:11,1
833 file:/.../iostream
834 lcount:74,1
835 file:/.../basic_ios.h
836 file:/.../ostream
837 file:/.../ios_base.h
838 function:157,0,_ZStorSt12_Ios_IostateS_
839 lcount:157,0
840 file:/.../char_traits.h
841 function:258,0,_ZNSt11char_traitsIcE6lengthEPKc
842 lcount:258,0
845 The default gcov outputs multiple files: 'foo.cc.gcov',
846 'iostream.gcov', 'ios_base.h.gcov', etc. with source code
847 included. Instead the intermediate format here outputs only a single
848 file 'foo.cc.gcov' similar to the above example. */
850 static void
851 output_intermediate_file (FILE *gcov_file, source_t *src)
853 unsigned line_num; /* current line number. */
854 const line_t *line; /* current line info ptr. */
855 function_t *fn; /* current function info ptr. */
857 fprintf (gcov_file, "file:%s\n", src->name); /* source file name */
859 for (fn = src->functions; fn; fn = fn->next_file_fn)
861 /* function:<name>,<line_number>,<execution_count> */
862 fprintf (gcov_file, "function:%d,%s,%s\n", fn->line,
863 format_gcov (fn->blocks[0].count, 0, -1),
864 flag_demangled_names ? fn->demangled_name : fn->name);
867 for (line_num = 1, line = &src->lines[line_num];
868 line_num < src->num_lines;
869 line_num++, line++)
871 arc_t *arc;
872 if (line->exists)
873 fprintf (gcov_file, "lcount:%u,%s\n", line_num,
874 format_gcov (line->count, 0, -1));
875 if (flag_branches)
876 for (arc = line->u.branches; arc; arc = arc->line_next)
878 if (!arc->is_unconditional && !arc->is_call_non_return)
880 const char *branch_type;
881 /* branch:<line_num>,<branch_coverage_type>
882 branch_coverage_type
883 : notexec (Branch not executed)
884 : taken (Branch executed and taken)
885 : nottaken (Branch executed, but not taken)
887 if (arc->src->count)
888 branch_type = (arc->count > 0) ? "taken" : "nottaken";
889 else
890 branch_type = "notexec";
891 fprintf (gcov_file, "branch:%d,%s\n", line_num, branch_type);
897 /* Process a single input file. */
899 static void
900 process_file (const char *file_name)
902 function_t *fns;
904 create_file_names (file_name);
905 fns = read_graph_file ();
906 if (!fns)
907 return;
909 read_count_file (fns);
910 while (fns)
912 function_t *fn = fns;
914 fns = fn->next;
915 fn->next = NULL;
916 if (fn->counts || no_data_file)
918 unsigned src = fn->src;
919 unsigned line = fn->line;
920 unsigned block_no;
921 function_t *probe, **prev;
923 /* Now insert it into the source file's list of
924 functions. Normally functions will be encountered in
925 ascending order, so a simple scan is quick. Note we're
926 building this list in reverse order. */
927 for (prev = &sources[src].functions;
928 (probe = *prev); prev = &probe->next_file_fn)
929 if (probe->line <= line)
930 break;
931 fn->next_file_fn = probe;
932 *prev = fn;
934 /* Mark last line in files touched by function. */
935 for (block_no = 0; block_no != fn->num_blocks; block_no++)
937 unsigned *enc = fn->blocks[block_no].u.line.encoding;
938 unsigned num = fn->blocks[block_no].u.line.num;
940 for (; num--; enc++)
941 if (!*enc)
943 if (enc[1] != src)
945 if (line >= sources[src].num_lines)
946 sources[src].num_lines = line + 1;
947 line = 0;
948 src = enc[1];
950 enc++;
951 num--;
953 else if (*enc > line)
954 line = *enc;
956 if (line >= sources[src].num_lines)
957 sources[src].num_lines = line + 1;
959 solve_flow_graph (fn);
960 if (fn->has_catch)
961 find_exception_blocks (fn);
962 *fn_end = fn;
963 fn_end = &fn->next;
965 else
966 /* The function was not in the executable -- some other
967 instance must have been selected. */
968 release_function (fn);
972 static void
973 output_gcov_file (const char *file_name, source_t *src)
975 char *gcov_file_name = make_gcov_file_name (file_name, src->coverage.name);
977 if (src->coverage.lines)
979 FILE *gcov_file = fopen (gcov_file_name, "w");
980 if (gcov_file)
982 fnotice (stdout, "Creating '%s'\n", gcov_file_name);
983 output_lines (gcov_file, src);
984 if (ferror (gcov_file))
985 fnotice (stderr, "Error writing output file '%s'\n", gcov_file_name);
986 fclose (gcov_file);
988 else
989 fnotice (stderr, "Could not open output file '%s'\n", gcov_file_name);
991 else
993 unlink (gcov_file_name);
994 fnotice (stdout, "Removing '%s'\n", gcov_file_name);
996 free (gcov_file_name);
999 static void
1000 generate_results (const char *file_name)
1002 unsigned ix;
1003 source_t *src;
1004 function_t *fn;
1005 FILE *gcov_intermediate_file = NULL;
1006 char *gcov_intermediate_filename = NULL;
1008 for (ix = n_sources, src = sources; ix--; src++)
1009 if (src->num_lines)
1010 src->lines = XCNEWVEC (line_t, src->num_lines);
1012 for (fn = functions; fn; fn = fn->next)
1014 coverage_t coverage;
1016 memset (&coverage, 0, sizeof (coverage));
1017 coverage.name = flag_demangled_names ? fn->demangled_name : fn->name;
1018 add_line_counts (flag_function_summary ? &coverage : NULL, fn);
1019 if (flag_function_summary)
1021 function_summary (&coverage, "Function");
1022 fnotice (stdout, "\n");
1026 if (file_name)
1028 name_map_t *name_map = (name_map_t *)bsearch
1029 (file_name, names, n_names, sizeof (*names), name_search);
1030 if (name_map)
1031 file_name = sources[name_map->src].coverage.name;
1032 else
1033 file_name = canonicalize_name (file_name);
1036 if (flag_gcov_file && flag_intermediate_format)
1038 /* Open the intermediate file. */
1039 gcov_intermediate_filename = get_gcov_intermediate_filename (file_name);
1040 gcov_intermediate_file = fopen (gcov_intermediate_filename, "w");
1041 if (!gcov_intermediate_file)
1043 fnotice (stderr, "Cannot open intermediate output file %s\n",
1044 gcov_intermediate_filename);
1045 return;
1049 for (ix = n_sources, src = sources; ix--; src++)
1051 if (flag_relative_only)
1053 /* Ignore this source, if it is an absolute path (after
1054 source prefix removal). */
1055 char first = src->coverage.name[0];
1057 #if HAVE_DOS_BASED_FILE_SYSTEM
1058 if (first && src->coverage.name[1] == ':')
1059 first = src->coverage.name[2];
1060 #endif
1061 if (IS_DIR_SEPARATOR (first))
1062 continue;
1065 accumulate_line_counts (src);
1066 function_summary (&src->coverage, "File");
1067 total_lines += src->coverage.lines;
1068 total_executed += src->coverage.lines_executed;
1069 if (flag_gcov_file)
1071 if (flag_intermediate_format)
1072 /* Output the intermediate format without requiring source
1073 files. This outputs a section to a *single* file. */
1074 output_intermediate_file (gcov_intermediate_file, src);
1075 else
1076 output_gcov_file (file_name, src);
1077 fnotice (stdout, "\n");
1081 if (flag_gcov_file && flag_intermediate_format)
1083 /* Now we've finished writing the intermediate file. */
1084 fclose (gcov_intermediate_file);
1085 XDELETEVEC (gcov_intermediate_filename);
1088 if (!file_name)
1089 executed_summary (total_lines, total_executed);
1092 /* Release a function structure */
1094 static void
1095 release_function (function_t *fn)
1097 unsigned ix;
1098 block_t *block;
1100 for (ix = fn->num_blocks, block = fn->blocks; ix--; block++)
1102 arc_t *arc, *arc_n;
1104 for (arc = block->succ; arc; arc = arc_n)
1106 arc_n = arc->succ_next;
1107 free (arc);
1110 free (fn->blocks);
1111 free (fn->counts);
1112 if (flag_demangled_names && fn->demangled_name != fn->name)
1113 free (fn->demangled_name);
1114 free (fn->name);
1117 /* Release all memory used. */
1119 static void
1120 release_structures (void)
1122 unsigned ix;
1123 function_t *fn;
1125 for (ix = n_sources; ix--;)
1126 free (sources[ix].lines);
1127 free (sources);
1129 for (ix = n_names; ix--;)
1130 free (names[ix].name);
1131 free (names);
1133 while ((fn = functions))
1135 functions = fn->next;
1136 release_function (fn);
1140 /* Generate the names of the graph and data files. If OBJECT_DIRECTORY
1141 is not specified, these are named from FILE_NAME sans extension. If
1142 OBJECT_DIRECTORY is specified and is a directory, the files are in that
1143 directory, but named from the basename of the FILE_NAME, sans extension.
1144 Otherwise OBJECT_DIRECTORY is taken to be the name of the object *file*
1145 and the data files are named from that. */
1147 static void
1148 create_file_names (const char *file_name)
1150 char *cptr;
1151 char *name;
1152 int length = strlen (file_name);
1153 int base;
1155 /* Free previous file names. */
1156 free (bbg_file_name);
1157 free (da_file_name);
1158 da_file_name = bbg_file_name = NULL;
1159 bbg_file_time = 0;
1160 bbg_stamp = 0;
1162 if (object_directory && object_directory[0])
1164 struct stat status;
1166 length += strlen (object_directory) + 2;
1167 name = XNEWVEC (char, length);
1168 name[0] = 0;
1170 base = !stat (object_directory, &status) && S_ISDIR (status.st_mode);
1171 strcat (name, object_directory);
1172 if (base && (!IS_DIR_SEPARATOR (name[strlen (name) - 1])))
1173 strcat (name, "/");
1175 else
1177 name = XNEWVEC (char, length + 1);
1178 strcpy (name, file_name);
1179 base = 0;
1182 if (base)
1184 /* Append source file name. */
1185 const char *cptr = lbasename (file_name);
1186 strcat (name, cptr ? cptr : file_name);
1189 /* Remove the extension. */
1190 cptr = strrchr (CONST_CAST (char *, lbasename (name)), '.');
1191 if (cptr)
1192 *cptr = 0;
1194 length = strlen (name);
1196 bbg_file_name = XNEWVEC (char, length + strlen (GCOV_NOTE_SUFFIX) + 1);
1197 strcpy (bbg_file_name, name);
1198 strcpy (bbg_file_name + length, GCOV_NOTE_SUFFIX);
1200 da_file_name = XNEWVEC (char, length + strlen (GCOV_DATA_SUFFIX) + 1);
1201 strcpy (da_file_name, name);
1202 strcpy (da_file_name + length, GCOV_DATA_SUFFIX);
1204 free (name);
1205 return;
1208 /* A is a string and B is a pointer to name_map_t. Compare for file
1209 name orderability. */
1211 static int
1212 name_search (const void *a_, const void *b_)
1214 const char *a = (const char *)a_;
1215 const name_map_t *b = (const name_map_t *)b_;
1217 #if HAVE_DOS_BASED_FILE_SYSTEM
1218 return strcasecmp (a, b->name);
1219 #else
1220 return strcmp (a, b->name);
1221 #endif
1224 /* A and B are a pointer to name_map_t. Compare for file name
1225 orderability. */
1227 static int
1228 name_sort (const void *a_, const void *b_)
1230 const name_map_t *a = (const name_map_t *)a_;
1231 return name_search (a->name, b_);
1234 /* Find or create a source file structure for FILE_NAME. Copies
1235 FILE_NAME on creation */
1237 static unsigned
1238 find_source (const char *file_name)
1240 name_map_t *name_map;
1241 char *canon;
1242 unsigned idx;
1243 struct stat status;
1245 if (!file_name)
1246 file_name = "<unknown>";
1247 name_map = (name_map_t *)bsearch
1248 (file_name, names, n_names, sizeof (*names), name_search);
1249 if (name_map)
1251 idx = name_map->src;
1252 goto check_date;
1255 if (n_names + 2 > a_names)
1257 /* Extend the name map array -- we'll be inserting one or two
1258 entries. */
1259 a_names *= 2;
1260 name_map = XNEWVEC (name_map_t, a_names);
1261 memcpy (name_map, names, n_names * sizeof (*names));
1262 free (names);
1263 names = name_map;
1266 /* Not found, try the canonical name. */
1267 canon = canonicalize_name (file_name);
1268 name_map = (name_map_t *) bsearch (canon, names, n_names, sizeof (*names),
1269 name_search);
1270 if (!name_map)
1272 /* Not found with canonical name, create a new source. */
1273 source_t *src;
1275 if (n_sources == a_sources)
1277 a_sources *= 2;
1278 src = XNEWVEC (source_t, a_sources);
1279 memcpy (src, sources, n_sources * sizeof (*sources));
1280 free (sources);
1281 sources = src;
1284 idx = n_sources;
1286 name_map = &names[n_names++];
1287 name_map->name = canon;
1288 name_map->src = idx;
1290 src = &sources[n_sources++];
1291 memset (src, 0, sizeof (*src));
1292 src->name = canon;
1293 src->coverage.name = src->name;
1294 if (source_length
1295 #if HAVE_DOS_BASED_FILE_SYSTEM
1296 /* You lose if separators don't match exactly in the
1297 prefix. */
1298 && !strncasecmp (source_prefix, src->coverage.name, source_length)
1299 #else
1300 && !strncmp (source_prefix, src->coverage.name, source_length)
1301 #endif
1302 && IS_DIR_SEPARATOR (src->coverage.name[source_length]))
1303 src->coverage.name += source_length + 1;
1304 if (!stat (src->name, &status))
1305 src->file_time = status.st_mtime;
1307 else
1308 idx = name_map->src;
1310 if (name_search (file_name, name_map))
1312 /* Append the non-canonical name. */
1313 name_map = &names[n_names++];
1314 name_map->name = xstrdup (file_name);
1315 name_map->src = idx;
1318 /* Resort the name map. */
1319 qsort (names, n_names, sizeof (*names), name_sort);
1321 check_date:
1322 if (sources[idx].file_time > bbg_file_time)
1324 static int info_emitted;
1326 fnotice (stderr, "%s:source file is newer than notes file '%s'\n",
1327 file_name, bbg_file_name);
1328 if (!info_emitted)
1330 fnotice (stderr,
1331 "(the message is displayed only once per source file)\n");
1332 info_emitted = 1;
1334 sources[idx].file_time = 0;
1337 return idx;
1340 /* Read the notes file. Return list of functions read -- in reverse order. */
1342 static function_t *
1343 read_graph_file (void)
1345 unsigned version;
1346 unsigned current_tag = 0;
1347 function_t *fn = NULL;
1348 function_t *fns = NULL;
1349 function_t **fns_end = &fns;
1350 unsigned src_idx = 0;
1351 unsigned ix;
1352 unsigned tag;
1354 if (!gcov_open (bbg_file_name, 1))
1356 fnotice (stderr, "%s:cannot open notes file\n", bbg_file_name);
1357 return fns;
1359 bbg_file_time = gcov_time ();
1360 if (!gcov_magic (gcov_read_unsigned (), GCOV_NOTE_MAGIC))
1362 fnotice (stderr, "%s:not a gcov notes file\n", bbg_file_name);
1363 gcov_close ();
1364 return fns;
1367 version = gcov_read_unsigned ();
1368 if (version != GCOV_VERSION)
1370 char v[4], e[4];
1372 GCOV_UNSIGNED2STRING (v, version);
1373 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1375 fnotice (stderr, "%s:version '%.4s', prefer '%.4s'\n",
1376 bbg_file_name, v, e);
1378 bbg_stamp = gcov_read_unsigned ();
1380 while ((tag = gcov_read_unsigned ()))
1382 unsigned length = gcov_read_unsigned ();
1383 gcov_position_t base = gcov_position ();
1385 if (tag == GCOV_TAG_FUNCTION)
1387 char *function_name;
1388 unsigned ident, lineno;
1389 unsigned lineno_checksum, cfg_checksum;
1391 ident = gcov_read_unsigned ();
1392 lineno_checksum = gcov_read_unsigned ();
1393 cfg_checksum = gcov_read_unsigned ();
1394 function_name = xstrdup (gcov_read_string ());
1395 src_idx = find_source (gcov_read_string ());
1396 lineno = gcov_read_unsigned ();
1398 fn = XCNEW (function_t);
1399 fn->name = function_name;
1400 if (flag_demangled_names)
1402 fn->demangled_name = cplus_demangle (fn->name, DMGL_PARAMS);
1403 if (!fn->demangled_name)
1404 fn->demangled_name = fn->name;
1406 fn->ident = ident;
1407 fn->lineno_checksum = lineno_checksum;
1408 fn->cfg_checksum = cfg_checksum;
1409 fn->src = src_idx;
1410 fn->line = lineno;
1412 fn->next_file_fn = NULL;
1413 fn->next = NULL;
1414 *fns_end = fn;
1415 fns_end = &fn->next;
1416 current_tag = tag;
1418 else if (fn && tag == GCOV_TAG_BLOCKS)
1420 if (fn->blocks)
1421 fnotice (stderr, "%s:already seen blocks for '%s'\n",
1422 bbg_file_name, fn->name);
1423 else
1425 unsigned ix, num_blocks = GCOV_TAG_BLOCKS_NUM (length);
1426 fn->num_blocks = num_blocks;
1428 fn->blocks = XCNEWVEC (block_t, fn->num_blocks);
1429 for (ix = 0; ix != num_blocks; ix++)
1430 fn->blocks[ix].flags = gcov_read_unsigned ();
1433 else if (fn && tag == GCOV_TAG_ARCS)
1435 unsigned src = gcov_read_unsigned ();
1436 unsigned num_dests = GCOV_TAG_ARCS_NUM (length);
1437 block_t *src_blk = &fn->blocks[src];
1438 unsigned mark_catches = 0;
1439 struct arc_info *arc;
1441 if (src >= fn->num_blocks || fn->blocks[src].succ)
1442 goto corrupt;
1444 while (num_dests--)
1446 unsigned dest = gcov_read_unsigned ();
1447 unsigned flags = gcov_read_unsigned ();
1449 if (dest >= fn->num_blocks)
1450 goto corrupt;
1451 arc = XCNEW (arc_t);
1453 arc->dst = &fn->blocks[dest];
1454 arc->src = src_blk;
1456 arc->count = 0;
1457 arc->count_valid = 0;
1458 arc->on_tree = !!(flags & GCOV_ARC_ON_TREE);
1459 arc->fake = !!(flags & GCOV_ARC_FAKE);
1460 arc->fall_through = !!(flags & GCOV_ARC_FALLTHROUGH);
1462 arc->succ_next = src_blk->succ;
1463 src_blk->succ = arc;
1464 src_blk->num_succ++;
1466 arc->pred_next = fn->blocks[dest].pred;
1467 fn->blocks[dest].pred = arc;
1468 fn->blocks[dest].num_pred++;
1470 if (arc->fake)
1472 if (src)
1474 /* Exceptional exit from this function, the
1475 source block must be a call. */
1476 fn->blocks[src].is_call_site = 1;
1477 arc->is_call_non_return = 1;
1478 mark_catches = 1;
1480 else
1482 /* Non-local return from a callee of this
1483 function. The destination block is a setjmp. */
1484 arc->is_nonlocal_return = 1;
1485 fn->blocks[dest].is_nonlocal_return = 1;
1489 if (!arc->on_tree)
1490 fn->num_counts++;
1493 if (mark_catches)
1495 /* We have a fake exit from this block. The other
1496 non-fall through exits must be to catch handlers.
1497 Mark them as catch arcs. */
1499 for (arc = src_blk->succ; arc; arc = arc->succ_next)
1500 if (!arc->fake && !arc->fall_through)
1502 arc->is_throw = 1;
1503 fn->has_catch = 1;
1507 else if (fn && tag == GCOV_TAG_LINES)
1509 unsigned blockno = gcov_read_unsigned ();
1510 unsigned *line_nos = XCNEWVEC (unsigned, length - 1);
1512 if (blockno >= fn->num_blocks || fn->blocks[blockno].u.line.encoding)
1513 goto corrupt;
1515 for (ix = 0; ; )
1517 unsigned lineno = gcov_read_unsigned ();
1519 if (lineno)
1521 if (!ix)
1523 line_nos[ix++] = 0;
1524 line_nos[ix++] = src_idx;
1526 line_nos[ix++] = lineno;
1528 else
1530 const char *file_name = gcov_read_string ();
1532 if (!file_name)
1533 break;
1534 src_idx = find_source (file_name);
1535 line_nos[ix++] = 0;
1536 line_nos[ix++] = src_idx;
1540 fn->blocks[blockno].u.line.encoding = line_nos;
1541 fn->blocks[blockno].u.line.num = ix;
1543 else if (current_tag && !GCOV_TAG_IS_SUBTAG (current_tag, tag))
1545 fn = NULL;
1546 current_tag = 0;
1548 gcov_sync (base, length);
1549 if (gcov_is_error ())
1551 corrupt:;
1552 fnotice (stderr, "%s:corrupted\n", bbg_file_name);
1553 break;
1556 gcov_close ();
1558 if (!fns)
1559 fnotice (stderr, "%s:no functions found\n", bbg_file_name);
1561 return fns;
1564 /* Reads profiles from the count file and attach to each
1565 function. Return nonzero if fatal error. */
1567 static int
1568 read_count_file (function_t *fns)
1570 unsigned ix;
1571 unsigned version;
1572 unsigned tag;
1573 function_t *fn = NULL;
1574 int error = 0;
1576 if (!gcov_open (da_file_name, 1))
1578 fnotice (stderr, "%s:cannot open data file, assuming not executed\n",
1579 da_file_name);
1580 no_data_file = 1;
1581 return 0;
1583 if (!gcov_magic (gcov_read_unsigned (), GCOV_DATA_MAGIC))
1585 fnotice (stderr, "%s:not a gcov data file\n", da_file_name);
1586 cleanup:;
1587 gcov_close ();
1588 return 1;
1590 version = gcov_read_unsigned ();
1591 if (version != GCOV_VERSION)
1593 char v[4], e[4];
1595 GCOV_UNSIGNED2STRING (v, version);
1596 GCOV_UNSIGNED2STRING (e, GCOV_VERSION);
1598 fnotice (stderr, "%s:version '%.4s', prefer version '%.4s'\n",
1599 da_file_name, v, e);
1601 tag = gcov_read_unsigned ();
1602 if (tag != bbg_stamp)
1604 fnotice (stderr, "%s:stamp mismatch with notes file\n", da_file_name);
1605 goto cleanup;
1608 while ((tag = gcov_read_unsigned ()))
1610 unsigned length = gcov_read_unsigned ();
1611 unsigned long base = gcov_position ();
1613 if (tag == GCOV_TAG_PROGRAM_SUMMARY)
1615 struct gcov_summary summary;
1616 gcov_read_summary (&summary);
1617 object_runs += summary.ctrs[GCOV_COUNTER_ARCS].runs;
1618 program_count++;
1620 else if (tag == GCOV_TAG_FUNCTION && !length)
1621 ; /* placeholder */
1622 else if (tag == GCOV_TAG_FUNCTION && length == GCOV_TAG_FUNCTION_LENGTH)
1624 unsigned ident;
1625 struct function_info *fn_n;
1627 /* Try to find the function in the list. To speed up the
1628 search, first start from the last function found. */
1629 ident = gcov_read_unsigned ();
1630 fn_n = fns;
1631 for (fn = fn ? fn->next : NULL; ; fn = fn->next)
1633 if (fn)
1635 else if ((fn = fn_n))
1636 fn_n = NULL;
1637 else
1639 fnotice (stderr, "%s:unknown function '%u'\n",
1640 da_file_name, ident);
1641 break;
1643 if (fn->ident == ident)
1644 break;
1647 if (!fn)
1649 else if (gcov_read_unsigned () != fn->lineno_checksum
1650 || gcov_read_unsigned () != fn->cfg_checksum)
1652 mismatch:;
1653 fnotice (stderr, "%s:profile mismatch for '%s'\n",
1654 da_file_name, fn->name);
1655 goto cleanup;
1658 else if (tag == GCOV_TAG_FOR_COUNTER (GCOV_COUNTER_ARCS) && fn)
1660 if (length != GCOV_TAG_COUNTER_LENGTH (fn->num_counts))
1661 goto mismatch;
1663 if (!fn->counts)
1664 fn->counts = XCNEWVEC (gcov_type, fn->num_counts);
1666 for (ix = 0; ix != fn->num_counts; ix++)
1667 fn->counts[ix] += gcov_read_counter ();
1669 gcov_sync (base, length);
1670 if ((error = gcov_is_error ()))
1672 fnotice (stderr,
1673 error < 0
1674 ? N_("%s:overflowed\n")
1675 : N_("%s:corrupted\n"),
1676 da_file_name);
1677 goto cleanup;
1681 gcov_close ();
1682 return 0;
1685 /* Solve the flow graph. Propagate counts from the instrumented arcs
1686 to the blocks and the uninstrumented arcs. */
1688 static void
1689 solve_flow_graph (function_t *fn)
1691 unsigned ix;
1692 arc_t *arc;
1693 gcov_type *count_ptr = fn->counts;
1694 block_t *blk;
1695 block_t *valid_blocks = NULL; /* valid, but unpropagated blocks. */
1696 block_t *invalid_blocks = NULL; /* invalid, but inferable blocks. */
1698 /* The arcs were built in reverse order. Fix that now. */
1699 for (ix = fn->num_blocks; ix--;)
1701 arc_t *arc_p, *arc_n;
1703 for (arc_p = NULL, arc = fn->blocks[ix].succ; arc;
1704 arc_p = arc, arc = arc_n)
1706 arc_n = arc->succ_next;
1707 arc->succ_next = arc_p;
1709 fn->blocks[ix].succ = arc_p;
1711 for (arc_p = NULL, arc = fn->blocks[ix].pred; arc;
1712 arc_p = arc, arc = arc_n)
1714 arc_n = arc->pred_next;
1715 arc->pred_next = arc_p;
1717 fn->blocks[ix].pred = arc_p;
1720 if (fn->num_blocks < 2)
1721 fnotice (stderr, "%s:'%s' lacks entry and/or exit blocks\n",
1722 bbg_file_name, fn->name);
1723 else
1725 if (fn->blocks[ENTRY_BLOCK].num_pred)
1726 fnotice (stderr, "%s:'%s' has arcs to entry block\n",
1727 bbg_file_name, fn->name);
1728 else
1729 /* We can't deduce the entry block counts from the lack of
1730 predecessors. */
1731 fn->blocks[ENTRY_BLOCK].num_pred = ~(unsigned)0;
1733 if (fn->blocks[EXIT_BLOCK].num_succ)
1734 fnotice (stderr, "%s:'%s' has arcs from exit block\n",
1735 bbg_file_name, fn->name);
1736 else
1737 /* Likewise, we can't deduce exit block counts from the lack
1738 of its successors. */
1739 fn->blocks[EXIT_BLOCK].num_succ = ~(unsigned)0;
1742 /* Propagate the measured counts, this must be done in the same
1743 order as the code in profile.c */
1744 for (ix = 0, blk = fn->blocks; ix != fn->num_blocks; ix++, blk++)
1746 block_t const *prev_dst = NULL;
1747 int out_of_order = 0;
1748 int non_fake_succ = 0;
1750 for (arc = blk->succ; arc; arc = arc->succ_next)
1752 if (!arc->fake)
1753 non_fake_succ++;
1755 if (!arc->on_tree)
1757 if (count_ptr)
1758 arc->count = *count_ptr++;
1759 arc->count_valid = 1;
1760 blk->num_succ--;
1761 arc->dst->num_pred--;
1763 if (prev_dst && prev_dst > arc->dst)
1764 out_of_order = 1;
1765 prev_dst = arc->dst;
1767 if (non_fake_succ == 1)
1769 /* If there is only one non-fake exit, it is an
1770 unconditional branch. */
1771 for (arc = blk->succ; arc; arc = arc->succ_next)
1772 if (!arc->fake)
1774 arc->is_unconditional = 1;
1775 /* If this block is instrumenting a call, it might be
1776 an artificial block. It is not artificial if it has
1777 a non-fallthrough exit, or the destination of this
1778 arc has more than one entry. Mark the destination
1779 block as a return site, if none of those conditions
1780 hold. */
1781 if (blk->is_call_site && arc->fall_through
1782 && arc->dst->pred == arc && !arc->pred_next)
1783 arc->dst->is_call_return = 1;
1787 /* Sort the successor arcs into ascending dst order. profile.c
1788 normally produces arcs in the right order, but sometimes with
1789 one or two out of order. We're not using a particularly
1790 smart sort. */
1791 if (out_of_order)
1793 arc_t *start = blk->succ;
1794 unsigned changes = 1;
1796 while (changes)
1798 arc_t *arc, *arc_p, *arc_n;
1800 changes = 0;
1801 for (arc_p = NULL, arc = start; (arc_n = arc->succ_next);)
1803 if (arc->dst > arc_n->dst)
1805 changes = 1;
1806 if (arc_p)
1807 arc_p->succ_next = arc_n;
1808 else
1809 start = arc_n;
1810 arc->succ_next = arc_n->succ_next;
1811 arc_n->succ_next = arc;
1812 arc_p = arc_n;
1814 else
1816 arc_p = arc;
1817 arc = arc_n;
1821 blk->succ = start;
1824 /* Place it on the invalid chain, it will be ignored if that's
1825 wrong. */
1826 blk->invalid_chain = 1;
1827 blk->chain = invalid_blocks;
1828 invalid_blocks = blk;
1831 while (invalid_blocks || valid_blocks)
1833 while ((blk = invalid_blocks))
1835 gcov_type total = 0;
1836 const arc_t *arc;
1838 invalid_blocks = blk->chain;
1839 blk->invalid_chain = 0;
1840 if (!blk->num_succ)
1841 for (arc = blk->succ; arc; arc = arc->succ_next)
1842 total += arc->count;
1843 else if (!blk->num_pred)
1844 for (arc = blk->pred; arc; arc = arc->pred_next)
1845 total += arc->count;
1846 else
1847 continue;
1849 blk->count = total;
1850 blk->count_valid = 1;
1851 blk->chain = valid_blocks;
1852 blk->valid_chain = 1;
1853 valid_blocks = blk;
1855 while ((blk = valid_blocks))
1857 gcov_type total;
1858 arc_t *arc, *inv_arc;
1860 valid_blocks = blk->chain;
1861 blk->valid_chain = 0;
1862 if (blk->num_succ == 1)
1864 block_t *dst;
1866 total = blk->count;
1867 inv_arc = NULL;
1868 for (arc = blk->succ; arc; arc = arc->succ_next)
1870 total -= arc->count;
1871 if (!arc->count_valid)
1872 inv_arc = arc;
1874 dst = inv_arc->dst;
1875 inv_arc->count_valid = 1;
1876 inv_arc->count = total;
1877 blk->num_succ--;
1878 dst->num_pred--;
1879 if (dst->count_valid)
1881 if (dst->num_pred == 1 && !dst->valid_chain)
1883 dst->chain = valid_blocks;
1884 dst->valid_chain = 1;
1885 valid_blocks = dst;
1888 else
1890 if (!dst->num_pred && !dst->invalid_chain)
1892 dst->chain = invalid_blocks;
1893 dst->invalid_chain = 1;
1894 invalid_blocks = dst;
1898 if (blk->num_pred == 1)
1900 block_t *src;
1902 total = blk->count;
1903 inv_arc = NULL;
1904 for (arc = blk->pred; arc; arc = arc->pred_next)
1906 total -= arc->count;
1907 if (!arc->count_valid)
1908 inv_arc = arc;
1910 src = inv_arc->src;
1911 inv_arc->count_valid = 1;
1912 inv_arc->count = total;
1913 blk->num_pred--;
1914 src->num_succ--;
1915 if (src->count_valid)
1917 if (src->num_succ == 1 && !src->valid_chain)
1919 src->chain = valid_blocks;
1920 src->valid_chain = 1;
1921 valid_blocks = src;
1924 else
1926 if (!src->num_succ && !src->invalid_chain)
1928 src->chain = invalid_blocks;
1929 src->invalid_chain = 1;
1930 invalid_blocks = src;
1937 /* If the graph has been correctly solved, every block will have a
1938 valid count. */
1939 for (ix = 0; ix < fn->num_blocks; ix++)
1940 if (!fn->blocks[ix].count_valid)
1942 fnotice (stderr, "%s:graph is unsolvable for '%s'\n",
1943 bbg_file_name, fn->name);
1944 break;
1948 /* Mark all the blocks only reachable via an incoming catch. */
1950 static void
1951 find_exception_blocks (function_t *fn)
1953 unsigned ix;
1954 block_t **queue = XALLOCAVEC (block_t *, fn->num_blocks);
1956 /* First mark all blocks as exceptional. */
1957 for (ix = fn->num_blocks; ix--;)
1958 fn->blocks[ix].exceptional = 1;
1960 /* Now mark all the blocks reachable via non-fake edges */
1961 queue[0] = fn->blocks;
1962 queue[0]->exceptional = 0;
1963 for (ix = 1; ix;)
1965 block_t *block = queue[--ix];
1966 const arc_t *arc;
1968 for (arc = block->succ; arc; arc = arc->succ_next)
1969 if (!arc->fake && !arc->is_throw && arc->dst->exceptional)
1971 arc->dst->exceptional = 0;
1972 queue[ix++] = arc->dst;
1978 /* Increment totals in COVERAGE according to arc ARC. */
1980 static void
1981 add_branch_counts (coverage_t *coverage, const arc_t *arc)
1983 if (arc->is_call_non_return)
1985 coverage->calls++;
1986 if (arc->src->count)
1987 coverage->calls_executed++;
1989 else if (!arc->is_unconditional)
1991 coverage->branches++;
1992 if (arc->src->count)
1993 coverage->branches_executed++;
1994 if (arc->count)
1995 coverage->branches_taken++;
1999 /* Format a GCOV_TYPE integer as either a percent ratio, or absolute
2000 count. If dp >= 0, format TOP/BOTTOM * 100 to DP decimal places.
2001 If DP is zero, no decimal point is printed. Only print 100% when
2002 TOP==BOTTOM and only print 0% when TOP=0. If dp < 0, then simply
2003 format TOP. Return pointer to a static string. */
2005 static char const *
2006 format_gcov (gcov_type top, gcov_type bottom, int dp)
2008 static char buffer[20];
2010 if (dp >= 0)
2012 float ratio = bottom ? (float)top / bottom : 0;
2013 int ix;
2014 unsigned limit = 100;
2015 unsigned percent;
2017 for (ix = dp; ix--; )
2018 limit *= 10;
2020 percent = (unsigned) (ratio * limit + (float)0.5);
2021 if (percent <= 0 && top)
2022 percent = 1;
2023 else if (percent >= limit && top != bottom)
2024 percent = limit - 1;
2025 ix = sprintf (buffer, "%.*u%%", dp + 1, percent);
2026 if (dp)
2028 dp++;
2031 buffer[ix+1] = buffer[ix];
2032 ix--;
2034 while (dp--);
2035 buffer[ix + 1] = '.';
2038 else
2039 sprintf (buffer, "%" PRId64, (int64_t)top);
2041 return buffer;
2044 /* Summary of execution */
2046 static void
2047 executed_summary (unsigned lines, unsigned executed)
2049 if (lines)
2050 fnotice (stdout, "Lines executed:%s of %d\n",
2051 format_gcov (executed, lines, 2), lines);
2052 else
2053 fnotice (stdout, "No executable lines\n");
2056 /* Output summary info for a function or file. */
2058 static void
2059 function_summary (const coverage_t *coverage, const char *title)
2061 fnotice (stdout, "%s '%s'\n", title, coverage->name);
2062 executed_summary (coverage->lines, coverage->lines_executed);
2064 if (flag_branches)
2066 if (coverage->branches)
2068 fnotice (stdout, "Branches executed:%s of %d\n",
2069 format_gcov (coverage->branches_executed,
2070 coverage->branches, 2),
2071 coverage->branches);
2072 fnotice (stdout, "Taken at least once:%s of %d\n",
2073 format_gcov (coverage->branches_taken,
2074 coverage->branches, 2),
2075 coverage->branches);
2077 else
2078 fnotice (stdout, "No branches\n");
2079 if (coverage->calls)
2080 fnotice (stdout, "Calls executed:%s of %d\n",
2081 format_gcov (coverage->calls_executed, coverage->calls, 2),
2082 coverage->calls);
2083 else
2084 fnotice (stdout, "No calls\n");
2088 /* Canonicalize the filename NAME by canonicalizing directory
2089 separators, eliding . components and resolving .. components
2090 appropriately. Always returns a unique string. */
2092 static char *
2093 canonicalize_name (const char *name)
2095 /* The canonical name cannot be longer than the incoming name. */
2096 char *result = XNEWVEC (char, strlen (name) + 1);
2097 const char *base = name, *probe;
2098 char *ptr = result;
2099 char *dd_base;
2100 int slash = 0;
2102 #if HAVE_DOS_BASED_FILE_SYSTEM
2103 if (base[0] && base[1] == ':')
2105 result[0] = base[0];
2106 result[1] = ':';
2107 base += 2;
2108 ptr += 2;
2110 #endif
2111 for (dd_base = ptr; *base; base = probe)
2113 size_t len;
2115 for (probe = base; *probe; probe++)
2116 if (IS_DIR_SEPARATOR (*probe))
2117 break;
2119 len = probe - base;
2120 if (len == 1 && base[0] == '.')
2121 /* Elide a '.' directory */
2123 else if (len == 2 && base[0] == '.' && base[1] == '.')
2125 /* '..', we can only elide it and the previous directory, if
2126 we're not a symlink. */
2127 struct stat ATTRIBUTE_UNUSED buf;
2129 *ptr = 0;
2130 if (dd_base == ptr
2131 #if defined (S_ISLNK)
2132 /* S_ISLNK is not POSIX.1-1996. */
2133 || stat (result, &buf) || S_ISLNK (buf.st_mode)
2134 #endif
2137 /* Cannot elide, or unreadable or a symlink. */
2138 dd_base = ptr + 2 + slash;
2139 goto regular;
2141 while (ptr != dd_base && *ptr != '/')
2142 ptr--;
2143 slash = ptr != result;
2145 else
2147 regular:
2148 /* Regular pathname component. */
2149 if (slash)
2150 *ptr++ = '/';
2151 memcpy (ptr, base, len);
2152 ptr += len;
2153 slash = 1;
2156 for (; IS_DIR_SEPARATOR (*probe); probe++)
2157 continue;
2159 *ptr = 0;
2161 return result;
2164 /* Print hex representation of 16 bytes from SUM and write it to BUFFER. */
2166 static void
2167 md5sum_to_hex (const char *sum, char *buffer)
2169 for (unsigned i = 0; i < 16; i++)
2170 sprintf (buffer + (2 * i), "%02x", (unsigned char)sum[i]);
2173 /* Generate an output file name. INPUT_NAME is the canonicalized main
2174 input file and SRC_NAME is the canonicalized file name.
2175 LONG_OUTPUT_NAMES and PRESERVE_PATHS affect name generation. With
2176 long_output_names we prepend the processed name of the input file
2177 to each output name (except when the current source file is the
2178 input file, so you don't get a double concatenation). The two
2179 components are separated by '##'. With preserve_paths we create a
2180 filename from all path components of the source file, replacing '/'
2181 with '#', and .. with '^', without it we simply take the basename
2182 component. (Remember, the canonicalized name will already have
2183 elided '.' components and converted \\ separators.) */
2185 static char *
2186 make_gcov_file_name (const char *input_name, const char *src_name)
2188 char *ptr;
2189 char *result;
2191 if (flag_long_names && input_name && strcmp (src_name, input_name))
2193 /* Generate the input filename part. */
2194 result = XNEWVEC (char, strlen (input_name) + strlen (src_name) + 10);
2196 ptr = result;
2197 ptr = mangle_name (input_name, ptr);
2198 ptr[0] = ptr[1] = '#';
2199 ptr += 2;
2201 else
2203 result = XNEWVEC (char, strlen (src_name) + 10);
2204 ptr = result;
2207 ptr = mangle_name (src_name, ptr);
2208 strcpy (ptr, ".gcov");
2210 /* When hashing filenames, we shorten them by only using the filename
2211 component and appending a hash of the full (mangled) pathname. */
2212 if (flag_hash_filenames)
2214 md5_ctx ctx;
2215 char md5sum[16];
2216 char md5sum_hex[33];
2218 md5_init_ctx (&ctx);
2219 md5_process_bytes (src_name, strlen (src_name), &ctx);
2220 md5_finish_ctx (&ctx, md5sum);
2221 md5sum_to_hex (md5sum, md5sum_hex);
2222 free (result);
2224 result = XNEWVEC (char, strlen (src_name) + 50);
2225 ptr = result;
2226 ptr = mangle_name (src_name, ptr);
2227 ptr[0] = ptr[1] = '#';
2228 ptr += 2;
2229 memcpy (ptr, md5sum_hex, 32);
2230 ptr += 32;
2231 strcpy (ptr, ".gcov");
2234 return result;
2237 static char *
2238 mangle_name (char const *base, char *ptr)
2240 size_t len;
2242 /* Generate the source filename part. */
2243 if (!flag_preserve_paths)
2245 base = lbasename (base);
2246 len = strlen (base);
2247 memcpy (ptr, base, len);
2248 ptr += len;
2250 else
2252 /* Convert '/' to '#', convert '..' to '^',
2253 convert ':' to '~' on DOS based file system. */
2254 const char *probe;
2256 #if HAVE_DOS_BASED_FILE_SYSTEM
2257 if (base[0] && base[1] == ':')
2259 ptr[0] = base[0];
2260 ptr[1] = '~';
2261 ptr += 2;
2262 base += 2;
2264 #endif
2265 for (; *base; base = probe)
2267 size_t len;
2269 for (probe = base; *probe; probe++)
2270 if (*probe == '/')
2271 break;
2272 len = probe - base;
2273 if (len == 2 && base[0] == '.' && base[1] == '.')
2274 *ptr++ = '^';
2275 else
2277 memcpy (ptr, base, len);
2278 ptr += len;
2280 if (*probe)
2282 *ptr++ = '#';
2283 probe++;
2288 return ptr;
2291 /* Scan through the bb_data for each line in the block, increment
2292 the line number execution count indicated by the execution count of
2293 the appropriate basic block. */
2295 static void
2296 add_line_counts (coverage_t *coverage, function_t *fn)
2298 unsigned ix;
2299 line_t *line = NULL; /* This is propagated from one iteration to the
2300 next. */
2302 /* Scan each basic block. */
2303 for (ix = 0; ix != fn->num_blocks; ix++)
2305 block_t *block = &fn->blocks[ix];
2306 unsigned *encoding;
2307 const source_t *src = NULL;
2308 unsigned jx;
2310 if (block->count && ix && ix + 1 != fn->num_blocks)
2311 fn->blocks_executed++;
2312 for (jx = 0, encoding = block->u.line.encoding;
2313 jx != block->u.line.num; jx++, encoding++)
2314 if (!*encoding)
2316 src = &sources[*++encoding];
2317 jx++;
2319 else
2321 line = &src->lines[*encoding];
2323 if (coverage)
2325 if (!line->exists)
2326 coverage->lines++;
2327 if (!line->count && block->count)
2328 coverage->lines_executed++;
2330 line->exists = 1;
2331 if (!block->exceptional)
2332 line->unexceptional = 1;
2333 line->count += block->count;
2335 free (block->u.line.encoding);
2336 block->u.cycle.arc = NULL;
2337 block->u.cycle.ident = ~0U;
2339 if (!ix || ix + 1 == fn->num_blocks)
2340 /* Entry or exit block */;
2341 else if (flag_all_blocks)
2343 line_t *block_line = line;
2345 if (!block_line)
2346 block_line = &sources[fn->src].lines[fn->line];
2348 block->chain = block_line->u.blocks;
2349 block_line->u.blocks = block;
2351 else if (flag_branches)
2353 arc_t *arc;
2355 for (arc = block->succ; arc; arc = arc->succ_next)
2357 arc->line_next = line->u.branches;
2358 line->u.branches = arc;
2359 if (coverage && !arc->is_unconditional)
2360 add_branch_counts (coverage, arc);
2364 if (!line)
2365 fnotice (stderr, "%s:no lines for '%s'\n", bbg_file_name, fn->name);
2368 /* Accumulate the line counts of a file. */
2370 static void
2371 accumulate_line_counts (source_t *src)
2373 line_t *line;
2374 function_t *fn, *fn_p, *fn_n;
2375 unsigned ix;
2377 /* Reverse the function order. */
2378 for (fn = src->functions, fn_p = NULL; fn; fn_p = fn, fn = fn_n)
2380 fn_n = fn->next_file_fn;
2381 fn->next_file_fn = fn_p;
2383 src->functions = fn_p;
2385 for (ix = src->num_lines, line = src->lines; ix--; line++)
2387 if (!flag_all_blocks)
2389 arc_t *arc, *arc_p, *arc_n;
2391 /* Total and reverse the branch information. */
2392 for (arc = line->u.branches, arc_p = NULL; arc;
2393 arc_p = arc, arc = arc_n)
2395 arc_n = arc->line_next;
2396 arc->line_next = arc_p;
2398 add_branch_counts (&src->coverage, arc);
2400 line->u.branches = arc_p;
2402 else if (line->u.blocks)
2404 /* The user expects the line count to be the number of times
2405 a line has been executed. Simply summing the block count
2406 will give an artificially high number. The Right Thing
2407 is to sum the entry counts to the graph of blocks on this
2408 line, then find the elementary cycles of the local graph
2409 and add the transition counts of those cycles. */
2410 block_t *block, *block_p, *block_n;
2411 gcov_type count = 0;
2413 /* Reverse the block information. */
2414 for (block = line->u.blocks, block_p = NULL; block;
2415 block_p = block, block = block_n)
2417 block_n = block->chain;
2418 block->chain = block_p;
2419 block->u.cycle.ident = ix;
2421 line->u.blocks = block_p;
2423 /* Sum the entry arcs. */
2424 for (block = line->u.blocks; block; block = block->chain)
2426 arc_t *arc;
2428 for (arc = block->pred; arc; arc = arc->pred_next)
2429 if (flag_branches)
2430 add_branch_counts (&src->coverage, arc);
2433 /* Cycle detection. */
2434 for (block = line->u.blocks; block; block = block->chain)
2436 for (arc_t *arc = block->pred; arc; arc = arc->pred_next)
2437 if (!line->has_block (arc->src))
2438 count += arc->count;
2439 for (arc_t *arc = block->succ; arc; arc = arc->succ_next)
2440 arc->cs_count = arc->count;
2443 /* Now, add the count of loops entirely on this line. */
2444 count += get_cycles_count (*line);
2445 line->count = count;
2448 if (line->exists)
2450 src->coverage.lines++;
2451 if (line->count)
2452 src->coverage.lines_executed++;
2457 /* Output information about ARC number IX. Returns nonzero if
2458 anything is output. */
2460 static int
2461 output_branch_count (FILE *gcov_file, int ix, const arc_t *arc)
2463 if (arc->is_call_non_return)
2465 if (arc->src->count)
2467 fnotice (gcov_file, "call %2d returned %s\n", ix,
2468 format_gcov (arc->src->count - arc->count,
2469 arc->src->count, -flag_counts));
2471 else
2472 fnotice (gcov_file, "call %2d never executed\n", ix);
2474 else if (!arc->is_unconditional)
2476 if (arc->src->count)
2477 fnotice (gcov_file, "branch %2d taken %s%s\n", ix,
2478 format_gcov (arc->count, arc->src->count, -flag_counts),
2479 arc->fall_through ? " (fallthrough)"
2480 : arc->is_throw ? " (throw)" : "");
2481 else
2482 fnotice (gcov_file, "branch %2d never executed\n", ix);
2484 else if (flag_unconditional && !arc->dst->is_call_return)
2486 if (arc->src->count)
2487 fnotice (gcov_file, "unconditional %2d taken %s\n", ix,
2488 format_gcov (arc->count, arc->src->count, -flag_counts));
2489 else
2490 fnotice (gcov_file, "unconditional %2d never executed\n", ix);
2492 else
2493 return 0;
2494 return 1;
2497 static const char *
2498 read_line (FILE *file)
2500 static char *string;
2501 static size_t string_len;
2502 size_t pos = 0;
2503 char *ptr;
2505 if (!string_len)
2507 string_len = 200;
2508 string = XNEWVEC (char, string_len);
2511 while ((ptr = fgets (string + pos, string_len - pos, file)))
2513 size_t len = strlen (string + pos);
2515 if (len && string[pos + len - 1] == '\n')
2517 string[pos + len - 1] = 0;
2518 return string;
2520 pos += len;
2521 /* If the file contains NUL characters or an incomplete
2522 last line, which can happen more than once in one run,
2523 we have to avoid doubling the STRING_LEN unnecessarily. */
2524 if (pos > string_len / 2)
2526 string_len *= 2;
2527 string = XRESIZEVEC (char, string, string_len);
2531 return pos ? string : NULL;
2534 /* Read in the source file one line at a time, and output that line to
2535 the gcov file preceded by its execution count and other
2536 information. */
2538 static void
2539 output_lines (FILE *gcov_file, const source_t *src)
2541 FILE *source_file;
2542 unsigned line_num; /* current line number. */
2543 const line_t *line; /* current line info ptr. */
2544 const char *retval = ""; /* status of source file reading. */
2545 function_t *fn = NULL;
2547 fprintf (gcov_file, "%9s:%5d:Source:%s\n", "-", 0, src->coverage.name);
2548 if (!multiple_files)
2550 fprintf (gcov_file, "%9s:%5d:Graph:%s\n", "-", 0, bbg_file_name);
2551 fprintf (gcov_file, "%9s:%5d:Data:%s\n", "-", 0,
2552 no_data_file ? "-" : da_file_name);
2553 fprintf (gcov_file, "%9s:%5d:Runs:%u\n", "-", 0, object_runs);
2555 fprintf (gcov_file, "%9s:%5d:Programs:%u\n", "-", 0, program_count);
2557 source_file = fopen (src->name, "r");
2558 if (!source_file)
2560 fnotice (stderr, "Cannot open source file %s\n", src->name);
2561 retval = NULL;
2563 else if (src->file_time == 0)
2564 fprintf (gcov_file, "%9s:%5d:Source is newer than graph\n", "-", 0);
2566 if (flag_branches)
2567 fn = src->functions;
2569 for (line_num = 1, line = &src->lines[line_num];
2570 line_num < src->num_lines; line_num++, line++)
2572 for (; fn && fn->line == line_num; fn = fn->next_file_fn)
2574 arc_t *arc = fn->blocks[EXIT_BLOCK].pred;
2575 gcov_type return_count = fn->blocks[EXIT_BLOCK].count;
2576 gcov_type called_count = fn->blocks[ENTRY_BLOCK].count;
2578 for (; arc; arc = arc->pred_next)
2579 if (arc->fake)
2580 return_count -= arc->count;
2582 fprintf (gcov_file, "function %s", flag_demangled_names ?
2583 fn->demangled_name : fn->name);
2584 fprintf (gcov_file, " called %s",
2585 format_gcov (called_count, 0, -1));
2586 fprintf (gcov_file, " returned %s",
2587 format_gcov (return_count, called_count, 0));
2588 fprintf (gcov_file, " blocks executed %s",
2589 format_gcov (fn->blocks_executed, fn->num_blocks - 2, 0));
2590 fprintf (gcov_file, "\n");
2593 if (retval)
2594 retval = read_line (source_file);
2596 /* For lines which don't exist in the .bb file, print '-' before
2597 the source line. For lines which exist but were never
2598 executed, print '#####' or '=====' before the source line.
2599 Otherwise, print the execution count before the source line.
2600 There are 16 spaces of indentation added before the source
2601 line so that tabs won't be messed up. */
2602 fprintf (gcov_file, "%9s:%5u:%s\n",
2603 !line->exists ? "-" : line->count
2604 ? format_gcov (line->count, 0, -1)
2605 : line->unexceptional ? "#####" : "=====", line_num,
2606 retval ? retval : "/*EOF*/");
2608 if (flag_all_blocks)
2610 block_t *block;
2611 arc_t *arc;
2612 int ix, jx;
2614 for (ix = jx = 0, block = line->u.blocks; block;
2615 block = block->chain)
2617 if (!block->is_call_return)
2618 fprintf (gcov_file, "%9s:%5u-block %2d\n",
2619 !line->exists ? "-" : block->count
2620 ? format_gcov (block->count, 0, -1)
2621 : block->exceptional ? "%%%%%" : "$$$$$",
2622 line_num, ix++);
2623 if (flag_branches)
2624 for (arc = block->succ; arc; arc = arc->succ_next)
2625 jx += output_branch_count (gcov_file, jx, arc);
2628 else if (flag_branches)
2630 int ix;
2631 arc_t *arc;
2633 for (ix = 0, arc = line->u.branches; arc; arc = arc->line_next)
2634 ix += output_branch_count (gcov_file, ix, arc);
2638 /* Handle all remaining source lines. There may be lines after the
2639 last line of code. */
2640 if (retval)
2642 for (; (retval = read_line (source_file)); line_num++)
2643 fprintf (gcov_file, "%9s:%5u:%s\n", "-", line_num, retval);
2646 if (source_file)
2647 fclose (source_file);