Debian Codegraph @

bin/geninfo

raw
1 #!/usr/bin/env perl
2 #
3 # Copyright (c) International Business Machines Corp., 2002,2012
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or (at
8 # your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, see
17 # <http://www.gnu.org/licenses/>.
18 #
19 #
20 # geninfo
21 #
22 # This script generates .info files from data files as created by code
23 # instrumented with gcc's built-in profiling mechanism. Call it with
24 # --help and refer to the geninfo man page to get information on usage
25 # and available options.
26 #
27 #
28 # Authors:
29 # 2002-08-23 created by Peter Oberparleiter <[email protected]>
30 # IBM Lab Boeblingen
31 # based on code by Manoj Iyer <[email protected]> and
32 # Megan Bock <[email protected]>
33 # IBM Austin
34 # 2002-09-05 / Peter Oberparleiter: implemented option that allows file list
35 # 2003-04-16 / Peter Oberparleiter: modified read_gcov so that it can also
36 # parse the new gcov format which is to be introduced in gcc 3.3
37 # 2003-04-30 / Peter Oberparleiter: made info write to STDERR, not STDOUT
38 # 2003-07-03 / Peter Oberparleiter: added line checksum support, added
39 # --no-checksum
40 # 2003-09-18 / Nigel Hinds: capture branch coverage data from GCOV
41 # 2003-12-11 / Laurent Deniel: added --follow option
42 # workaround gcov (<= 3.2.x) bug with empty .da files
43 # 2004-01-03 / Laurent Deniel: Ignore empty .bb files
44 # 2004-02-16 / Andreas Krebbel: Added support for .gcno/.gcda files and
45 # gcov versioning
46 # 2004-08-09 / Peter Oberparleiter: added configuration file support
47 # 2008-07-14 / Tom Zoerner: added --function-coverage command line option
48 # 2008-08-13 / Peter Oberparleiter: modified function coverage
49 # implementation (now enabled per default)
50 # July 2020 / Henry Cox: [email protected]
51 # Refactor to use common lcovutil package.
52 # Add filters to suppress certain line and branch coverpoints
53 # Sept 2020 / Henry Cox: modify to use common lcov package for coverage
54 # data representation.
55
56 use strict;
57 use warnings;
58 use File::Basename qw(basename dirname fileparse);
59 use File::Spec::Functions qw /abs2rel catdir file_name_is_absolute splitdir
60 splitpath catpath catfile/;
61 use File::Temp;
62 use File::Copy qw(copy move);
63 use File::Path;
64 use Cwd qw/abs_path getcwd realpath/;
65 use Time::HiRes; # for profiling
66 use Capture::Tiny;
67 use FindBin;
68 use Storable;
69 use POSIX;
70
71 use lib "$FindBin::RealBin/../lib";
72 use lcovutil qw (define_errors parse_ignore_errors
73 $tool_name $tool_dir $lcov_version $lcov_url
74 ignorable_error ignorable_warning is_ignored
75 set_info_callback info init_verbose_flag $verbose
76 debug $debug
77 $br_coverage $func_coverage
78 system_no_output $devnull $dirseparator
79 die_handler warn_handler
80 parse_cov_filters summarize_cov_filters
81 $EXCL_START $EXCL_STOP $EXCL_BR_START $EXCL_BR_STOP
82 $EXCL_EXCEPTION_BR_START $EXCL_EXCEPTION_BR_STOP
83 $EXCL_LINE $EXCL_BR_LINE $EXCL_EXCEPTION_LINE
84
85 %excluded_files
86 warn_file_patterns
87 @extractVersionScript
88
89 $ERROR_GCOV $ERROR_GRAPH $ERROR_PACKAGE $ERROR_CHILD
90 $ERROR_EMPTY $ERROR_PARALLEL $ERROR_UNSUPPORTED $ERROR_PATH
91 $ERROR_INCONSISTENT_DATA $ERROR_UTILITY $ERROR_FORMAT
92 report_parallel_error check_parent_process
93 summarize_messages
94 is_external @internal_dirs
95 parseOptions
96 @comments
97 $maxParallelism init_parallel_params $maxMemory
98 );
99
100 if ($^O eq "msys") {
101 require File::Spec::Win32;
102 }
103
104 our @gcov_tool;
105
106 # Constants
107
108 our $GCOV_VERSION_8_0_0 = 0x80000;
109 our $GCOV_VERSION_4_7_0 = 0x40700;
110 our $GCOV_VERSION_4_2_0 = 0x40200; # llvm/11
111
112 # Compatibility mode values
113 our $COMPAT_VALUE_OFF = 0;
114 our $COMPAT_VALUE_ON = 1;
115 our $COMPAT_VALUE_AUTO = 2;
116
117 # Compatibility mode value names
118 our %COMPAT_NAME_TO_VALUE = ("off" => $COMPAT_VALUE_OFF,
119 "on" => $COMPAT_VALUE_ON,
120 "auto" => $COMPAT_VALUE_AUTO,);
121
122 # Compatibility modes
123 our $COMPAT_MODE_LIBTOOL = 1 << 0;
124 our $COMPAT_MODE_HAMMER = 1 << 1;
125 our $COMPAT_MODE_SPLIT_CRC = 1 << 2;
126
127 # Compatibility mode names
128 our %COMPAT_NAME_TO_MODE = ("libtool" => $COMPAT_MODE_LIBTOOL,
129 "hammer" => $COMPAT_MODE_HAMMER,
130 "split_crc" => $COMPAT_MODE_SPLIT_CRC,
131 "android_4_4_0" => $COMPAT_MODE_SPLIT_CRC,);
132
133 # Map modes to names
134 our %COMPAT_MODE_TO_NAME = ($COMPAT_MODE_LIBTOOL => "libtool",
135 $COMPAT_MODE_HAMMER => "hammer",
136 $COMPAT_MODE_SPLIT_CRC => "split_crc",);
137
138 # Compatibility mode default values
139 our %COMPAT_MODE_DEFAULTS = ($COMPAT_MODE_LIBTOOL => $COMPAT_VALUE_ON,
140 $COMPAT_MODE_HAMMER => $COMPAT_VALUE_AUTO,
141 $COMPAT_MODE_SPLIT_CRC => $COMPAT_VALUE_AUTO,);
142
143 # Compatibility mode auto-detection routines
144 our %COMPAT_MODE_AUTO = ($COMPAT_MODE_HAMMER => 0, # no gcc/3.3 support
145 $COMPAT_MODE_SPLIT_CRC => 1, # will be done later
146 );
147
148 our $UNNAMED_BLOCK = -1;
149
150 our $trace_data;
151
152 # Prototypes
153 sub print_usage(*);
154 sub gen_info(@);
155 sub process_dafile($$$$);
156 sub match_filename($@);
157 sub solve_ambiguous_match($$$);
158 sub split_filename($);
159 sub solve_relative_path($$);
160 sub compute_internal_directories(@);
161 sub read_gcov_header($);
162 sub read_gcov_file($$$);
163 sub my_info(@);
164 set_info_callback(\&my_info);
165 sub process_intermediate($$$$);
166 sub map_llvm_version($);
167 sub version_to_str($);
168 sub get_gcov_version();
169 sub apply_exclusion_data($$$);
170 sub process_graphfile($$);
171 sub filter_fn_name($$);
172 sub graph_error($$);
173 sub graph_read(*$;$$);
174 sub graph_skip(*$;$);
175 sub uniq(@);
176 sub sort_uniq(@);
177 sub graph_cleanup($);
178 sub graph_find_base($);
179 sub graph_from_bb($$$$);
180 sub graph_add_order($$$);
181 sub read_gcno_word(*;$$);
182 sub read_gcno_value(*$;$$);
183 sub read_gcno_string(*$);
184 sub read_gcno_lines_record(*$$$$$$);
185 sub read_gcno_function_record(*$$$$$);
186 sub read_gcno($);
187 sub get_gcov_capabilities();
188 sub int_handler();
189 sub compat_name($);
190 sub parse_compat_modes($);
191 sub is_compat($);
192 sub which($);
193
194 # Global variables
195 our $gcov_version;
196 our $gcov_version_string;
197 our $graph_file_extension = '.gcno';
198 our $data_file_extension = '.gcda';
199 our @data_directory;
200 our $buildDirSearchPath;
201 our $test_name = "";
202 our $help;
203 our $output_filename;
204 our $single_file; # Write result into single merged file or not
205 our $files_created = 0; # Number of output files created
206 our $base_directory;
207 our $version;
208 our $opt_no_compat_libtool;
209 our $initial;
210 our $no_recursion = 0;
211 our $maxdepth;
212 our $no_markers = 0;
213 our $opt_derive_func_data = 0;
214 our $gcov_caps;
215 our %compat_value;
216 our $intermediate;
217 our $intervalMonitor; # class for progress reporting
218 our $totalChildCpuTime = 0;
219 our $intervalChildCpuTime = 0; # since last updata
220
221 # for performance tweaking/tuning
222 our $defaultChunkSize;
223 our $defaultInterval;
224 our %childRetryCounts;
225 our @large_files;
226
227 our $cwd = getcwd();
228 chomp($cwd);
229
230 lcovutil::save_cmd_line(\@ARGV, "$FindBin::RealBin");
231
232 #
233 # Code entry point
234 #
235
236 # Register handler routine to be called when interrupted
237 $SIG{"INT"} = \&int_handler;
238 $SIG{__WARN__} = \&warn_handler;
239 $SIG{__DIE__} = \&die_handler;
240
241 # Set LC_ALL so that gcov output will be in a unified format
242 $ENV{"LC_ALL"} = "C";
243
244 # retrieve settings from RC file - use these if not overridden on command line
245 my %geninfo_opts = ("test-name|t=s" => \$test_name,
246 "output-filename|o=s" => \$output_filename,
247 "base-directory|b=s" => \$base_directory,
248 "follow|f" => \$lcovutil::opt_follow,
249 "compat-libtool" => \$lcovutil::opt_compat_libtool,
250 "no-compat-libtool" => \$opt_no_compat_libtool,
251 "gcov-tool=s" => \@gcov_tool,
252 "initial|i" => \$initial,
253 "all" => \$lcovutil::geninfo_captureAll,
254 "no-recursion" => \$no_recursion,
255 "no-markers" => \$no_markers,
256 "derive-func-data" => \$opt_derive_func_data,
257 "external|e" => \$lcovutil::opt_external,
258 "no-external" => \$lcovutil::opt_no_external,
259 "compat=s" => \$lcovutil::geninfo_opt_compat,
260 'large-file=s' => \@large_files);
261
262 # Parse command line options
263 if (!lcovutil::parseOptions(\%lcovutil::geninfo_rc_opts, \%geninfo_opts,
264 \$output_filename)) {
265 print(STDERR "Use $tool_name --help to get usage information\n");
266 exit(1);
267 }
268
269 $buildDirSearchPath =
270 SearchPath->new('build directory', @lcovutil::build_directory);
271 @gcov_tool = @lcovutil::rc_gcov_tool unless @gcov_tool;
272
273 eval {
274 map { qr($_) } @large_files;
275 };
276 die("invalid 'large-file' regexp: $@")
277 if ($@);
278
279 # Check regexp
280 if (defined($lcovutil::rc_adjust_src_path)) {
281 my ($pattern, $replace) = split(/\s*=>\s*/, $lcovutil::rc_adjust_src_path);
282 # If no replacement is specified, simply remove pattern
283 $replace = '' unless defined($replace);
284 my $p = "s#$pattern#$replace#g";
285 $p .= 'i' if $lcovutil::case_insensitive;
286 my $text = 'abc';
287 my $str = eval { '$test =~ ' . $p . ';' };
288 if ($@) {
289 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
290 "Invalid 'geninfo_adjust_src_path=$lcovutil::rc_adjust_src_path' syntax: '$@'"
291 );
292 } else {
293 push(@lcovutil::file_subst_patterns, [$p, 0]);
294 }
295 }
296
297 if ($lcovutil::geninfo_captureAll && $initial) {
298 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
299 "'--all' ignored when '--initial' is used");
300 $lcovutil::geninfo_captureAll = undef;
301 }
302
303 if (defined($lcovutil::tempdirname)) {
304 $lcovutil::tmp_dir = $lcovutil::tempdirname;
305 File::Path::make_path($lcovutil::tmp_dir) or
306 die("unable to mkdir $lcovutil::tmp_dir: $!")
307 unless (-d $lcovutil::tmp_dir);
308 }
309
310 # Merge options
311 if (defined($opt_no_compat_libtool)) {
312 $lcovutil::opt_compat_libtool = ($opt_no_compat_libtool ? 0 : 1);
313 $opt_no_compat_libtool = undef;
314 }
315
316 if (defined($lcovutil::opt_external)) {
317 $lcovutil::opt_no_external = !$lcovutil::opt_external;
318 $lcovutil::opt_external = undef;
319 }
320
321 my $start = Time::HiRes::gettimeofday();
322
323 @data_directory = @ARGV;
324
325 debug("$lcov_version\n");
326
327 if (0 == scalar(@gcov_tool)) {
328 # not specified - use gcov by default - expected to be in user's path
329 push(@gcov_tool, 'gcov');
330 } else {
331 @gcov_tool =
332 split($lcovutil::split_char, join($lcovutil::split_char, @gcov_tool));
333 my $tool = $gcov_tool[0];
334 my (undef, $dir, $file) = splitpath($tool);
335
336 if ($dir eq "") {
337 $tool = which($tool);
338 } elsif (!file_name_is_absolute($tool)) {
339 $tool = abs_path($tool);
340 }
341 if (!-x $tool) {
342 die("cannot access gcov tool '$gcov_tool[0]'");
343 }
344 $gcov_tool[0] = $tool;
345 if (scalar(@gcov_tool) > 1) {
346 foreach my $e (@gcov_tool) {
347 $e = "'$e'" if ($e =~ /\s/);
348 }
349 }
350 }
351 if (scalar(@lcovutil::extractVersionScript) > 1) {
352 foreach my $e (@lcovutil::extractVersionScript) {
353 $e = "'$e'" if ($e =~ /\s/);
354 }
355 }
356
357 # Check gcov tool
358 if (system_no_output(3, @gcov_tool, "--help") == -1) {
359 die("failed execution of gcov_tool \"" .
360 join(' ', @gcov_tool) . " --help\": $!");
361 }
362
363 ($gcov_version, $gcov_version_string) = get_gcov_version();
364 $gcov_caps = get_gcov_capabilities();
365
366 # Determine intermediate mode
367 if ($lcovutil::rc_intermediate eq "0") {
368 $intermediate = 0;
369 } elsif ($lcovutil::rc_intermediate eq "1") {
370 $intermediate = 1;
371 } elsif (lc($lcovutil::rc_intermediate) eq "auto") {
372 # Use intermediate format if supported by gcov and not conflicting with
373 # exception branch exclusion
374 $intermediate = (($gcov_caps->{'intermediate-format'} &&
375 !$lcovutil::exclude_exception_branch) ||
376 $gcov_caps->{'json-format'}) ? 1 : 0;
377 } else {
378 die("invalid value for geninfo_intermediate: " .
379 "'$lcovutil::rc_intermediate'\n");
380 }
381
382 if ($gcov_version >= (9 << 16) &&
383 !$intermediate) {
384 lcovutil::ignorable_error($ERROR_UNSUPPORTED,
385 "geninfo does not support text format for gcov/9 or higher (your version appears to be '$gcov_version_string').\n Please remove config file entry 'geninfo_intermdediate = 0'."
386 );
387 $intermediate = 1;
388 }
389
390 if ($intermediate) {
391 info("Using intermediate gcov format\n");
392 if ($opt_derive_func_data) {
393 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
394 "--derive-func-data is not compatible with intermediate format");
395 $opt_derive_func_data = 0;
396 }
397 if ($lcovutil::exclude_exception_branch && !$gcov_caps->{'json-format'}) {
398 die("excluding exception branches is not compatible with " .
399 "text intermediate format\n");
400 }
401 }
402
403 # Determine gcov options
404 push(@gcov_tool, "-b")
405 if ($gcov_caps->{'branch-probabilities'} &&
406 ($lcovutil::br_coverage ||
407 $lcovutil::func_coverage ||
408 $lcovutil::opt_adjust_unexecuted_blocks));
409 push(@gcov_tool, "-c")
410 if ($gcov_caps->{'branch-counts'} &&
411 $lcovutil::br_coverage);
412 push(@gcov_tool, "-a")
413 if ($gcov_caps->{'all-blocks'} &&
414 $lcovutil::opt_gcov_all_blocks &&
415 $lcovutil::br_coverage &&
416 !$intermediate);
417 if ($gcov_caps->{'hash-filenames'}) {
418 push(@gcov_tool, "-x");
419 } else {
420 push(@gcov_tool, "-p") if ($gcov_caps->{'preserve-paths'});
421 }
422 push(@gcov_tool, '-i') if $intermediate;
423
424 if ($lcovutil::mcdc_coverage) {
425 if ($gcov_caps->{'conditions'}) {
426 push(@gcov_tool, '--conditions');
427 } else {
428 $lcovutil::mcdc_coverage = 0;
429 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
430 "MC/DC coverage enabled but \"$gcov_tool[0]\" does not support the '--conditions' option."
431 );
432 }
433 }
434
435 # Determine compatibility modes
436 parse_compat_modes($lcovutil::geninfo_opt_compat);
437
438 if ($no_markers) {
439 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
440 "use new '--filter' option or old '--no-markers' - not both")
441 if (@lcovutil::opt_filter);
442 } elsif (!@lcovutil::opt_filter) {
443 # don't apply the backward-compatible options if user specifies any filters
444 lcovutil::info(1,
445 "$lcovutil::tool_name: applying '--filter region,branch_region' by default - see the '--no-markers' section in the man page for more information.\n"
446 );
447 push(@lcovutil::opt_filter, "region");
448 push(@lcovutil::opt_filter, "branch_region") if $br_coverage;
449 } else {
450 lcovutil::info(
451 "Note: 'region' and 'branch_region' filters are not applied by default when '--filter' is specified. See the '--no-markers section in the man page for more information.\n"
452 ) unless grep({ /(region|branch_region)/ } @lcovutil::opt_filter);
453 }
454 parse_cov_filters(@lcovutil::opt_filter);
455
456 # Make sure test names only contain valid characters
457 if ($test_name =~ s/\W/_/g) {
458 lcovutil::ignorable_warning($lcovutil::ERROR_FORMAT,
459 "invalid characters removed from testname");
460 }
461
462 # Adjust test name to include uname output if requested
463 if ($lcovutil::geninfo_adjust_testname) {
464 $test_name .= "__" . `uname -a`;
465 $test_name =~ s/\W/_/g;
466 }
467
468 # Make sure base_directory contains an absolute path specification
469 if ($base_directory) {
470 $base_directory = solve_relative_path($cwd, $base_directory);
471 push(@ReadCurrentSource::source_directories, $base_directory);
472 }
473
474 # Determine checksum mode - normalize to boolean
475 $lcovutil::verify_checksum =
476 defined($lcovutil::verify_checksum) && $lcovutil::verify_checksum;
477
478 # Determine max depth for recursion
479 if ($no_recursion) {
480 $maxdepth = "-maxdepth 1";
481 } else {
482 $maxdepth = "";
483 }
484
485 # Check for directory name
486 if (!@data_directory) {
487 die("No directory specified\n" .
488 "Use $tool_name --help to get usage information\n");
489 } else {
490 my @dirs;
491 foreach my $pattern (@data_directory) {
492 if (-d $pattern) {
493 $pattern =~
494 s#$lcovutil::dirseparator$##; # remove trailing slash - if any
495 push(@dirs, $pattern);
496 next;
497 }
498 $pattern =~ s/([^\\]) /$1\\ /g # explicitly escape spaces
499 unless $^O =~ /Win/;
500
501 my @glob = glob($pattern);
502
503 my $count = 0;
504 foreach (@glob) {
505
506 stat($_);
507 if (!-r _) {
508 ignorable_error($ERROR_GCOV, "cannot read $_!");
509 } else {
510 push(@dirs, $_);
511 $count++;
512 }
513 }
514 if (0 == $count) {
515 ignorable_error($ERROR_EMPTY, "$pattern does not match anything.");
516 }
517 }
518 @data_directory = @dirs;
519 }
520
521 if ($gcov_version < $GCOV_VERSION_4_2_0) {
522 die("Your toolchain version is too old and is no longer supported by lcov. Please upgrade - or use an older lcov release."
523 );
524 }
525
526 # Check output filename
527 $single_file = defined($output_filename);
528
529 # use absolute path: we change directories while processing files
530 $output_filename = catfile($cwd, $output_filename)
531 if (defined($output_filename) &&
532 ($output_filename ne "-") &&
533 !file_name_is_absolute($output_filename));
534
535 # Build list of directories to identify external files
536 compute_internal_directories(@data_directory, $base_directory);
537
538 if ($initial && $lcovutil::br_coverage && !$intermediate) {
539 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
540 "--initial cannot generate branch coverage data with this compiler/toolchain version."
541 );
542 }
543
544 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
545 "--fail_under_lines not supported unless output file specified")
546 if (defined($lcovutil::fail_under_lines) && !$single_file);
547
548 # where to write parallel child data
549 my $tempFileDir =
550 defined($lcovutil::tempdirname) ? $lcovutil::tempdirname :
551 File::Temp->newdir("geninfo_datXXXX",
552 DIR => $lcovutil::tmp_dir,
553 CLEANUP => !defined($lcovutil::preserve_intermediates));
554
555 lcovutil::info("Writing temporary data to $tempFileDir\n");
556 # Do something
557 my $processedFiles = 0;
558 my $exit_code = 0;
559 eval { $processedFiles += gen_info(@data_directory); };
560 if ($@) {
561 $exit_code = 1;
562 print(STDERR $@);
563 }
564
565 if (0 == $exit_code) {
566 eval {
567 my $now = Time::HiRes::gettimeofday();
568 # have to check the loaded input data for exclusion markers because the
569 # data was generated directly from the gcov files - did not go through
570 # TraceFile::load which explicitly checks
571 if ($single_file && defined($trace_data)) {
572 $trace_data->applyFilters();
573 my $f = Time::HiRes::gettimeofday();
574 $trace_data->add_comments(@lcovutil::comments);
575 $trace_data->write_info_file($output_filename,
576 $lcovutil::verify_checksum);
577 $files_created++;
578 my $then = Time::HiRes::gettimeofday();
579 $lcovutil::profileData{filter} = $f - $now;
580 $lcovutil::profileData{write} = $then - $f;
581 }
582 if ($files_created == 0) {
583 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
584 "no data generated\n");
585 }
586 my $then = Time::HiRes::gettimeofday();
587 $lcovutil::profileData{emit} = $then - $now;
588 if (defined($trace_data)) {
589 info("Finished .info-file creation\n");
590 $trace_data->print_summary()
591 if ($lcovutil::verbose >= 0);
592 }
593 summarize_cov_filters();
594 # print warnings
595 lcovutil::warn_file_patterns();
596 $buildDirSearchPath->warn_unused(
597 @lcovutil::build_directory ? '--build-directory' :
598 'build_directory = ');
599 ReadCurrentSource::warn_sourcedir_patterns();
600 };
601 if ($@) {
602 # eval of filter application failed - set error return code, but
603 # still try to emit profile
604 print(STDERR $@);
605 $exit_code = 1;
606 }
607 }
608 # $trace_data may be undef if no non-empty GCDA files found and the
609 # 'empty' warning is ignored
610 if (0 == $exit_code &&
611 defined($trace_data) &&
612 $single_file) {
613
614 $trace_data->checkCoverageCriteria();
615 CoverageCriteria::summarize();
616 $exit_code = 1 if $CoverageCriteria::coverageCriteriaStatus;
617 }
618 summarize_messages();
619 my $end = Time::HiRes::gettimeofday();
620 $lcovutil::profileData{total} = $end - $start;
621
622 lcovutil::cleanup_callbacks();
623
624 lcovutil::save_profile(
625 (defined($output_filename) && '-' ne $output_filename) ? $output_filename :
626 "geninfo");
627
628 # exit with non-zero status if --keep-going and some errors detected
629 $exit_code = 1
630 if (0 == $exit_code &&
631 (!(defined($trace_data) && $single_file) ||
632 lcovutil::saw_error()));
633 exit($exit_code);
634
635 #
636 # print_usage(handle)
637 #
638 # Print usage information.
639 #
640
641 sub print_usage(*)
642 {
643 local *HANDLE = $_[0];
644
645 print(HANDLE <<END_OF_USAGE);
646 Usage: $tool_name [OPTIONS] DIRECTORY
647
648 Traverse DIRECTORY and create a tracefile for each compiler coverage data file
649 found (.gcda/.gcno). Note that you may specify more than one directory, all of
650 which are then processed sequentially.
651
652 COMMON OPTIONS
653 -h, --help Print this help, then exit
654 --version Print version number, then exit
655 -v, --verbose Increase verbosity level
656 -q, --quiet Decrease verbosity level (e.g. to turn off
657 progress messages)
658 --debug Increase debug verbosity level
659 --config-file FILENAME Specify configuration file location
660 --rc SETTING=VALUE Override configuration file setting
661 --ignore-errors ERRORS Continue after ERRORS (see man page for full
662 list of errors and their meaning)
663 --keep-going Do not stop if an error occurs
664 --tempdir DIRNAME Write temporary and intermediate data here
665 --preserve Keep intermediate files for debugging
666
667 OPTIONS
668 -i, --initial Capture initial zero coverage data
669 --all Capture both .gcda and lone .gcno data
670 -t, --test-name NAME Use test case NAME for resulting data
671 -o, --output-filename OUTFILE Write data only to OUTFILE
672 -f, --follow Follow links when searching .da/.gcda files
673 -b, --base-directory DIR Use DIR as base directory for relative paths
674 --build-directory DIR Search DIR for .gcno files (if not found
675 with .gcda)
676 --(no-)function-coverage Enable (disable) function coverage
677 --(no)-branch-coverage Enable (disable) branch coverage
678 --mcdc Enable MC/DC coverage
679 --(no-)checksum Enable (disable) line checksumming
680 --(no-)compat-libtool Enable (disable) libtool compatibility mode
681 --gcov-tool TOOL Specify gcov tool location
682 --ignore-errors ERROR Continue after ERROR (gcov, source, graph)
683 --keep-going Do not stop if error occurs. Try to
684 produce a result
685 --filter TYPE Apply FILTERS to input data (see man page
686 for full list of filters and their effects)
687 --demangle-cpp [PARAM] Demangle C++ function names
688 --no-recursion Exclude subdirectories from processing
689 --no-markers Ignore exclusion markers in source code
690 --derive-func-data Generate function data from line data
691 --(no-)external Include (ignore) data for external files
692 --compat MODE=on|off|auto Set compat MODE (libtool, hammer, split_crc)
693 --include PATTERN Include files matching PATTERN
694 --exclude PATTERN Exclude files matching PATTERN
695 --substitute REGEXP Change source file names according to REGEXP
696 --erase-functions REGEXP Exclude data for functions matching REGEXP
697 --omit-lines REGEXP Ignore data in lines matching REGEXP
698 --forget-test-names Merge data for all tests names
699 --version-script SCRIPTNAME Call script to find revision control version
700 ID of source file
701 --resolve-script SCRIPTNAME Call script to find source file frpm path
702 -j, --parallel [N] Use parallel processing with at most N jobs
703 --memory MB Use at most MB memory in parallel processing
704 --profile [FILENAME] Write performance statistics to FILENAME
705 (default: OUTPUT_FILENAME.json)
706
707 For more information see the geninfo man page.
708 END_OF_USAGE
709
710 }
711
712 package IntervalMonitor;
713
714 use constant {
715 TOTAL_FILES => 0,
716 TOTAL_CHUNKS => 1,
717 CHUNK_SIZE => 2,
718 PROCESSED_CHUNKS => 3,
719 INTERVAL_LENGTH => 4,
720 START_TIME => 5, # start processing worklist
721 LAST_UPDATE => 6, # number files processed at last update
722 INTERVAL_START => 7,
723 INTERVAL_COUNTS =>
724 8, # source files and coverpoints found since update
725
726 FILE_COUNT => 0,
727 LINE_COUNT => 1,
728 BRANCH_COUNT => 2,
729 FUNCTION_COUNT => 3,
730 };
731
732 sub new
733 {
734 my ($class, $totalFiles, $nChunks, $chunkSize, $intervalLength) = @_;
735 my $start = Time::HiRes::gettimeofday();
736 my $self = [$totalFiles, $nChunks, $chunkSize, 0,
737 $intervalLength, $start, 0, $start,
738 [0, 0, 0, 0]
739 ];
740 bless $self, $class;
741 return $self;
742 }
743
744 sub checkUpdate
745 {
746 my ($self, $processedFiles) = @_;
747
748 if ($self->[INTERVAL_LENGTH] &&
749 $self->[INTERVAL_LENGTH] <= ($processedFiles - $self->[LAST_UPDATE])) {
750 my $filesLastInterval = $processedFiles - $self->[LAST_UPDATE];
751 $self->[LAST_UPDATE] = $processedFiles;
752 my $now = Time::HiRes::gettimeofday();
753 my $elapsed = $now - $self->[START_TIME];
754 my $intervalTime = $now - $self->[INTERVAL_START];
755 my $rate = ($processedFiles) / $elapsed;
756 my $average = $totalChildCpuTime / ($processedFiles);
757 my $interval = $intervalChildCpuTime / $filesLastInterval;
758 $intervalChildCpuTime = 0;
759 $self->[INTERVAL_START] = $now;
760 # compute average wall clock files/s and individual s/file (actual CPU)
761 # for overall processing of all files and for files during this
762 # interval. Might be useful to observe performance issues during
763 # execution.
764 my $total = $self->[TOTAL_FILES];
765 lcovutil::info(
766 "elapsed:%0.1fm: remaining:%d files %0.1fm: %0.2f files/s %0.2f s/file (interval:%0.2f f/s %0.2f s/f)\n",
767 $elapsed / 60,
768 $total - $processedFiles,
769 ($total - $processedFiles) / ($rate * 60),
770 $rate,
771 $average,
772 $filesLastInterval / $intervalTime,
773 $interval);
774 # how many new source files and new coverpoints have been found
775 # in this interval?
776 if (defined($trace_data)) {
777 my @counts = $trace_data->count_totals();
778 my $intervalData = $self->[INTERVAL_COUNTS];
779 if ($counts[0] !=
780 $intervalData->[FILE_COUNT] || # number source files
781 $counts[1]->[0] !=
782 $intervalData->[LINE_COUNT] || # line coverpoints
783 $counts[2]->[0] !=
784 $intervalData->[BRANCH_COUNT] || # branch coverpoints
785 $counts[3]->[0] != $intervalData->[FUNCTION_COUNT]
786 ) # function coverpoints
787 {
788 lcovutil::info(1,
789 " added files:%d ln:%d br:%d fn:%d\n",
790 $counts[0] - $intervalData->[FILE_COUNT],
791 $counts[1]->[0] - $intervalData->[LINE_COUNT],
792 $counts[2]->[0] - $intervalData->[BRANCH_COUNT],
793 $counts[3]->[0] - $intervalData->[FUNCTION_COUNT]
794 );
795 $self->[INTERVAL_COUNTS] = [$counts[0], $counts[1]->[0],
796 $counts[2]->[0], $counts[3]->[0]
797 ];
798 }
799 }
800 }
801 }
802
803 package BuildWorkList;
804
805 sub new
806 {
807 my $class = shift;
808 my $self = [[], {}, {}]; # [worklist, processedFiles, messages]
809 return bless $self, $class;
810 }
811
812 sub worklist
813 {
814 my $self = shift;
815 # we saved the messages for the end...
816 foreach my $msg (values %{$self->[2]}) {
817 lcovutil::ignorable_error($msg->[0], $msg->[1]);
818 }
819 return $self->[0];
820 }
821
822 sub find_corresponding_gcno_file
823 {
824 my ($gcda_file, $searchdir) = @_;
825 my ($name, $d, $e) = File::Basename::fileparse($gcda_file, qr/\.[^.]*/);
826 my $gcno_file = File::Spec->catfile($d, $name . ".gcno");
827 foreach ($gcno_file) {
828 return $gcno_file if (-f $gcno_file || -l $gcno_file);
829
830 my $alt = lcovutil::subst_file_name($gcno_file);
831 my $prefix = "looking for GCNO matching '$gcda_file':\n";
832 if ($alt ne $gcno_file) {
833 $gcno_file = $alt;
834 lcovutil::info(1, "$prefix at '$gcno_file'\n");
835 $prefix = '';
836 return $gcno_file if (-f $gcno_file || -l $gcno_file);
837 }
838 # check to see if this file is in a different directory
839 my $dir = $d;
840 $dir =~ s#^$searchdir##g;
841 $prefix = "looking for GCNO matching '$gcda_file' prefix:'$dir':\n";
842 # handle case that gcda and gcno are in different directories
843 # - say, where is the gcda that we found, then see if gcno is
844 # in the same directory. If not, then look in a gcno path and
845 # link both gcda and gcno into this tempdir, run gcov, then
846 # unlink
847 # from the directory where the gcda file is found:
848 # strip off the directory where we start the search
849 # then strip off the GCOV_PREFIX (if there is one)
850 # then append the remaining path the the GCDA file, to the
851 # 'GCNO_PATH' that we were provided.
852 # - if there is a file there: use it.
853 foreach my $d (@$buildDirSearchPath) {
854 # is the GCNO in the relative path from build_dir?
855 my $build_directory = $d->[0];
856 $gcno_file =
857 File::Spec->catfile($build_directory, $dir, $name . ".gcno");
858
859 lcovutil::info(1, "$prefix at '$gcno_file'\n");
860 $prefix = '';
861 if (-f $gcno_file || -l $gcno_file) {
862 ++$d->[1];
863 return $gcno_file;
864 }
865
866 # is the GCNO in the relative path after we apply substitutions?
867 $alt = lcovutil::subst_file_name($gcno_file);
868 if ($alt ne $gcno_file) {
869 $gcno_file = $alt;
870 lcovutil::info(1, "$prefix at '$gcno_file'\n");
871 $prefix = '';
872 if (-f $gcno_file || -l $gcno_file) {
873 ++$d->[1];
874 return $gcno_file;
875 }
876 }
877 } # foreach build_directory
878
879 if (@lcovutil::resolveCallback) {
880 $gcno_file = File::Spec->catfile($d, $name . ".gcno");
881
882 $gcno_file = SearchPath::resolveCallback($gcno_file, 1);
883 return $gcno_file if (-f $gcno_file || -l $gcno_file);
884 }
885 } # foreach switch
886
887 # skip the .gcda file if there is no .gcno
888 lcovutil::ignorable_error(
889 $lcovutil::ERROR_PATH,
890 (lcovutil::is_ignored($lcovutil::ERROR_PATH) ? 'skipping' :
891 'cannot process') .
892 " .gcda file $gcda_file because corresponding .gcno file '$gcno_file' is missing"
893 .
894 (
895 $lcovutil::verbose ||
896 lcovutil::message_count($lcovutil::ERROR_PATH) == 0 ?
897 " (see the '--build-directory' entry in 'man geninfo' for suggestions)"
898 :
899 '') .
900 '.');
901
902 return undef;
903 }
904
905 sub add_worklist_entry
906 {
907 my ($self, $filename, $directory) = @_;
908 if (exists($self->[1]->{$filename})) {
909 lcovutil::ignorable_error(
910 $lcovutil::ERROR_USAGE,
911 "duplicate file $filename in both " .
912 $self->[1]->{$filename} . " and $directory"
913 .
914 (lcovutil::is_ignored(
915 $lcovutil::ERROR_USAGE) ?
916 ' (skip latter)' :
917 ''));
918 return;
919 }
920 $self->[1]->{$filename} = $directory;
921
922 my ($gcda_file, $gcno_file);
923 if ($filename !~ /$data_file_extension$/) {
924 $gcno_file = $filename;
925 } else {
926 $gcda_file = $filename;
927 $gcno_file = find_corresponding_gcno_file($filename, $directory);
928 return unless $gcno_file; # would have errored out
929
930 my ($vol, $dir, $name) = File::Spec->splitpath($gcno_file);
931 # remove trailing slash
932 $self->[1]->{$gcno_file} = substr($dir, 0, -1);
933 }
934 push(@{$self->[0]}, [$directory, $gcda_file, $gcno_file]);
935 }
936
937 sub find_files
938 {
939 my $self = shift;
940 my $processGcno = shift;
941 my ($type, $ext);
942
943 if ($processGcno) {
944 $type = "graph";
945 $ext = $graph_file_extension;
946 } else {
947 $type = "data";
948 $ext = $data_file_extension;
949 }
950 foreach my $directory (@_) {
951 unless (-e $directory) {
952 # hold error until the end of processing - we might be looking
953 # for both .gcno and .gcda files - and don't want to generate
954 # the same 'no such directory' message twice. Nor do we want
955 # to produce an error if only one type of file is in this
956 # directory
957 $self->[2]->{$directory} = [$lcovutil::ERROR_USAGE,
958 "no such file or directory '$directory'"
959 ];
960 next;
961 }
962 if (-d $directory) {
963 lcovutil::info("Scanning $directory for $ext files ...\n");
964
965 my $now = Time::HiRes::gettimeofday();
966 my $follow = $lcovutil::opt_follow ? '-follow' : '';
967 my ($stdout, $stderr, $code) = Capture::Tiny::capture {
968 system(
969 "find '$directory' $maxdepth $follow -name \\*$ext -type f -o -name \\*$ext -type l"
970 );
971 };
972 lcovutil::ignorable_error($lcovutil::ERROR_UTILITY,
973 "error in 'find \"$directory\" ...': $stderr")
974 if ($code);
975
976 my $time = Time::HiRes::gettimeofday() - $now;
977 if (exists($lcovutil::profileData{find}) &&
978 exists($lcovutil::profileData{find}{$directory})) {
979 $lcovutil::profileData{find}{$directory} += $time;
980 } else {
981 $lcovutil::profileData{find}{$directory} = $time;
982 }
983 # split on crlf
984 my @found = split(/[\x0A\x0D]/, $stdout);
985 if (!@found) {
986 if (!defined($processGcno) || $processGcno != 2) {
987 # delay message: might be a file of other type here
988 $self->[2]->{$directory} = [
989 $lcovutil::ERROR_EMPTY,
990 "no $ext files found in $directory"
991 ];
992 }
993
994 next;
995 }
996 # we found something here - remove the pending error message, if any
997 delete($self->[2]->{$directory})
998 ; # if exists($self->[2]->{$directory});
999 lcovutil::info("Found %d %s files in %s\n",
1000 scalar(@found), $type, $directory);
1001 # keep track of directory where we found the file
1002 foreach my $entry (@found) {
1003 # don't add gcno file again, if we already handled the .gcda
1004 $self->add_worklist_entry($entry, $directory)
1005 unless (defined($processGcno) &&
1006 $processGcno == 2 &&
1007 exists($self->[1]->{$entry}));
1008 }
1009 } elsif (!defined($processGcno) || $processGcno == 1) {
1010 my ($name, $d, $e) =
1011 File::Basename::fileparse($directory, qr/\.[^.]*/);
1012 if ($e ne $ext &&
1013 (!$lcovutil::geninfo_captureAll || $e ne $graph_file_extension)
1014 ) {
1015 $self->[2]->{$directory} = [
1016 $lcovutil::ERROR_USAGE,
1017 "$directory has unsupported extension: expected '$ext'" .
1018 ($initial ? " for initial capture" : "")
1019 ];
1020 next;
1021 }
1022 delete($self->[2]->{$directory});
1023 # use the directory where we find the file as the base dir
1024 $self->add_worklist_entry($directory, $d);
1025 }
1026 }
1027 }
1028
1029 package main;
1030
1031 #
1032 # gen_info(directory_list)
1033 #
1034 # Traverse each DIRECTORY in list and create a .info file for each data file found.
1035 # The .info file contains TEST_NAME in the following format:
1036 #
1037 # TN:<test name>
1038 #
1039 # For each source file name referenced in the data file, there is a section
1040 # containing source code and coverage data. See geninfo(1) man page for
1041 # more details.
1042 #
1043 # In addition to the main source code file there are sections for each
1044 # #included file containing executable code. Note that the absolute path
1045 # of a source file is generated by interpreting the contents of the respective
1046 # graph file. Relative filenames are prefixed with the directory in which the
1047 # graph file is found. Note also that symbolic links to the graph file will be
1048 # resolved so that the actual file path is used instead of the path to a link.
1049 # This approach is necessary for the mechanism to work with the /proc/gcov
1050 # files.
1051 #
1052 # Die on error.
1053 #
1054
1055 my $chunkSize;
1056
1057 sub _process_one_chunk($$$$)
1058 {
1059 my ($chunk, $chunkId, $combined, $pid) = @_;
1060
1061 my $start = Time::HiRes::gettimeofday();
1062
1063 my $idx = 0;
1064 foreach my $data (@$chunk) {
1065 my $now = Time::HiRes::gettimeofday();
1066 if (defined($pid) &&
1067 0 != $pid) {
1068 # if parent died, then time for me to go
1069 lcovutil::check_parent_process();
1070 }
1071
1072 my ($searchdir, $gcda_file, $gcno_file) = @$data;
1073
1074 # "name" will be .gcno if "$initial" else will be $gcda
1075 my $name = defined($gcda_file) ? $gcda_file : $gcno_file;
1076 info(1,
1077 "Processing $name%s\n",
1078 defined($pid) ? " in child $pid" : "" . "\n");
1079 my $context = MessageContext->new("capturing from $name");
1080
1081 # multiple gcda files may refer to the same source - so generate the
1082 # same 'source.gcda' output file - so they each need a different directory
1083 # This is necessary to preserve intermediates, and if we are running
1084 # in parallel; we don't want to overwrite and don't want multiple children to
1085 # conflict.
1086 my $tmp = File::Temp->newdir(
1087 "geninfo_XXXXX",
1088 DIR => $tempFileDir,
1089 CLEANUP => !defined($lcovutil::preserve_intermediates)
1090 ) if ($intermediate || defined($gcda_file));
1091
1092 # keep track of order - so we can estimate which files were processed
1093 # at same time
1094 $lcovutil::profileData{order}{$name} =
1095 ($chunkId * $chunkSize) + $idx;
1096 ++$idx;
1097
1098 my $trace;
1099 if ($intermediate) {
1100 $trace =
1101 process_intermediate($searchdir, $gcda_file,
1102 $gcno_file, $tmp->dirname);
1103 } elsif (!defined($gcda_file)) {
1104 # just read the gcno file and set all the counters to zero
1105 $trace = process_graphfile($searchdir, $gcno_file);
1106 } else {
1107 $trace =
1108 process_dafile($searchdir, $gcda_file,
1109 $gcno_file, $tmp->dirname);
1110 }
1111 my $then = Time::HiRes::gettimeofday();
1112 $lcovutil::profileData{parse}{$name} = $then - $now;
1113
1114 if (defined($trace)) {
1115
1116 if (!$single_file) {
1117 # Create one .info file per input file
1118 $trace->applyFilters();
1119 $trace->add_comments(@lcovutil::comments);
1120 $trace->write_info_file(solve_relative_path(
1121 $cwd, $name . ".info"
1122 ),
1123 $lcovutil::verify_checksum);
1124 my $then = Time::HiRes::gettimeofday();
1125 $lcovutil::profileData{filter_file}{$name} = $then - $now;
1126 $files_created++;
1127 } else {
1128 if (defined($combined)) {
1129 $combined->merge_tracefile($trace, TraceInfo::UNION);
1130 } else {
1131 $combined = $trace;
1132 }
1133 my $end = Time::HiRes::gettimeofday();
1134 $lcovutil::profileData{append}{$name} = $end - $then;
1135 }
1136 }
1137 my $done = Time::HiRes::gettimeofday();
1138 die("unexpected duplicate file '$name'")
1139 if exists($lcovutil::profileData{file}{$name});
1140 $lcovutil::profileData{file}{$name} = $done - $now;
1141 }
1142 my $end = Time::HiRes::gettimeofday();
1143
1144 return $combined;
1145 }
1146
1147 sub _merge_one_child($$$)
1148 {
1149 my ($children, $tempFileExt, $worklist) = @_;
1150
1151 my $child = wait();
1152 my $start = Time::HiRes::gettimeofday();
1153 my $childstatus = $?;
1154 unless (exists($children->{$child})) {
1155 lcovutil::report_unknown_child($child);
1156 return 0;
1157 }
1158
1159 debug(
1160 "_merge_one_child: $child (parent $$) status $childstatus from $tempFileDir\n"
1161 );
1162 my ($chunk, $forkAt, $chunkId) = @{$children->{$child}};
1163 my $dumped = File::Spec->catfile($tempFileDir, "dumper_$child");
1164 my $childLog = File::Spec->catfile($tempFileDir, "geninfo_$child.log");
1165 my $childErr = File::Spec->catfile($tempFileDir, "geninfo_$child.err");
1166
1167 foreach my $f ($childLog, $childErr) {
1168 if (!-f $f) {
1169 # no data was printed..
1170 $f = '';
1171 next;
1172 }
1173 if (open(RESTORE, "<", $f)) {
1174 # slurp into a string and eval..
1175 my $str = do { local $/; <RESTORE> }; # slurp whole thing
1176 close(RESTORE) or die("unable to close $f: $!\n");
1177 unlink $f;
1178 $f = $str;
1179 } else {
1180 $f = "unable to open $f: $!";
1181 if (0 == $childstatus) {
1182 report_parallel_error('geninfo', $ERROR_PARALLEL, $child, 0,
1183 $f, keys(%$children));
1184 }
1185 }
1186 }
1187 my $signal = $childstatus & 0xFF;
1188 print(STDOUT $childLog)
1189 if ((0 != $childstatus &&
1190 $signal != POSIX::SIGKILL &&
1191 $lcovutil::max_fork_fails != 0) ||
1192 $lcovutil::verbose);
1193 print(STDERR $childErr);
1194 # look for spaceout message in the gcov log
1195 if (0 == $signal &&
1196 0 != $childstatus &&
1197 0 != $lcovutil::max_fork_fails &&
1198 lcovutil::is_ignored($lcovutil::ERROR_FORK) &&
1199 grep(
1200 { /(std::bad_alloc|annot allocate memory|out of memory|integretity check failed for compressed file)/
1201 } ($childLog, $childErr))
1202 ) {
1203
1204 # pretend it was killed so we retry
1205 $signal = POSIX::SIGKILL;
1206 }
1207 my $data = Storable::retrieve($dumped)
1208 if (-f $dumped && 0 == $childstatus);
1209 # note that $data will not be defined (no data dumped) if there was
1210 # no child data extracted (e.g., all files excluded)
1211 if (defined($data)) {
1212 eval {
1213 my ($childInfo, $buildDirCounts, $counts, $updates) = @$data;
1214 lcovutil::update_state(@$updates);
1215 $files_created += $counts->[0];
1216 $processedFiles += $counts->[1];
1217 my $childFinish = $counts->[2];
1218 $buildDirSearchPath->update_count(@$buildDirCounts);
1219 my $childCpuTime = $lcovutil::profileData{child}{$chunkId};
1220 $totalChildCpuTime += $childCpuTime;
1221 $intervalChildCpuTime += $childCpuTime;
1222
1223 my $now = Time::HiRes::gettimeofday();
1224 $lcovutil::profileData{undump}{$chunkId} = $now - $start;
1225 if (defined($childInfo)) {
1226 if (defined($trace_data)) {
1227 $trace_data->merge_tracefile($childInfo, TraceInfo::UNION);
1228 my $final = Time::HiRes::gettimeofday();
1229 $lcovutil::profileData{append}{$chunkId} = $final - $now;
1230 } else {
1231 $trace_data = $childInfo;
1232 }
1233 my $end = Time::HiRes::gettimeofday();
1234 $lcovutil::profileData{merge}{$chunkId} = $end - $now;
1235 $lcovutil::profileData{queue}{$chunkId} = $start - $childFinish;
1236 }
1237 $intervalMonitor->checkUpdate($processedFiles);
1238 };
1239 if ($@) {
1240 $childstatus = 1 << 8 unless $childstatus;
1241 print STDOUT $@;
1242 report_parallel_error('geninfo', $ERROR_PARALLEL, $child,
1243 $childstatus, "unable to deserialize $dumped: $@",
1244 keys(%$children));
1245 }
1246 }
1247 if ($childstatus != 0) {
1248 if (POSIX::SIGKILL == $signal) {
1249 if (exists($childRetryCounts{$chunkId})) {
1250 $childRetryCounts{$chunkId} += 1;
1251 } else {
1252 $childRetryCounts{$chunkId} = 1;
1253 }
1254 lcovutil::report_fork_failure(
1255 "compute job $chunkId",
1256 "killed by OS - possibly due to out-of-memory",
1257 $childRetryCounts{$chunkId});
1258 push(@$worklist, $chunk);
1259 } else {
1260 report_parallel_error('geninfo', $ERROR_CHILD, $child, $childstatus,
1261 "ignoring data in chunk $chunkId",
1262 keys(%$children));
1263 }
1264 }
1265 foreach my $f ($dumped) {
1266 unlink $f
1267 if -f $f;
1268 }
1269 my $to = Time::HiRes::gettimeofday();
1270 $lcovutil::profileData{chunk}{$chunkId} = $to - $forkAt;
1271 if (exists($lcovutil::profileData{process}{$chunkId}) &&
1272 exists($lcovutil::profileData{merge}{$chunkId})) {
1273 $lcovutil::profileData{work}{$chunkId} =
1274 $lcovutil::profileData{process}{$chunkId} +
1275 $lcovutil::profileData{merge}{$chunkId};
1276 }
1277 return 0 == $childstatus;
1278 }
1279
1280 sub gen_info(@)
1281 {
1282 my $builder = BuildWorkList->new();
1283
1284 $builder->find_files($initial, @_);
1285 if (!defined($initial) &&
1286 defined($lcovutil::geninfo_captureAll) &&
1287 $lcovutil::geninfo_captureAll) {
1288 $builder->find_files(2, @_);
1289 }
1290 my $filelist = $builder->worklist();
1291 my @sorted_filelist;
1292 if ($lcovutil::sort_inputs) {
1293 @sorted_filelist = sort({
1294 my $na = $a->[0] .
1295 (defined($a->[1]) ? $a->[1] : $a->[2]);
1296 my $nb = $b->[0] .
1297 (defined($b->[1]) ? $b->[1] : $b->[2]);
1298 $na cmp $nb
1299 } @$filelist);
1300 $filelist = \@sorted_filelist;
1301 }
1302 my $total = scalar(@$filelist);
1303 if (1 < $lcovutil::maxParallelism) {
1304 my $floor =
1305 $lcovutil::maxParallelism ?
1306 (int($total / $lcovutil::maxParallelism)) :
1307 1;
1308 if (defined($lcovutil::defaultChunkSize)) {
1309 if ($lcovutil::defaultChunkSize =~ /^(\d+)\s*(%?)$/) {
1310 if (defined($2) && $2) {
1311 # a percentage
1312 $chunkSize = int($total * $1 / 100);
1313 } else {
1314 # an absolute value
1315 $chunkSize = $1;
1316 }
1317 } else {
1318 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
1319 "geninfo_chunk_size '$lcovutil::defaultChunkSize' is not recognized"
1320 );
1321 }
1322 }
1323 # Need to balance time in child vs. time to merge child data -
1324 # - if we have too many children, then they finish and wait in the
1325 # queue to be merged.
1326 # - if we have too few, then the merge time in child gets long
1327 # build up in set to 80% of
1328 $chunkSize = int(0.8 * $floor) unless defined($chunkSize);
1329
1330 $chunkSize = 1 if $chunkSize < 2;
1331 } else {
1332 $chunkSize = 1;
1333 }
1334 my @worklist;
1335 my $serialChunk = [1, []];
1336 my $chunk = [0, []]; # [isSerial, [fileList]]
1337 FILE: foreach my $j (@$filelist) {
1338 my ($dir, $gcda, $gcno) = @$j;
1339 foreach my $f ($gcda, $gcno) {
1340 next unless defined($f); # might not be a GCDA file
1341 my $filename = $dir . $lcovutil::dirseparator . $f;
1342 if (grep({ $filename =~ $_ } @main::large_files)) {
1343 lcovutil::info(1, "large file: $filename\n");
1344 push(@{$serialChunk->[1]}, $j);
1345 next FILE;
1346 }
1347 }
1348 push(@{$chunk->[1]}, $j);
1349 if (scalar(@{$chunk->[1]}) == $chunkSize) {
1350 push(@worklist, $chunk);
1351 $chunk = [0, []];
1352 }
1353 } #foreach DATA_FILE
1354 push(@worklist, $chunk) if @{$chunk->[1]};
1355 # serial chunk is at the top of the stack - so serial processing
1356 # happens before we fork multiple processes
1357 push(@worklist, $serialChunk)
1358 if (@{$serialChunk->[1]});
1359
1360 # Process all files in list
1361 my $currentParallel = 0;
1362 my %children;
1363 my $tempFileExt = '';
1364 $tempFileExt = ".gz"
1365 if (defined $output_filename) && $output_filename =~ /\.gz$/;
1366
1367 my $totalChunks = scalar(@worklist);
1368 my $processedChunks = 0;
1369
1370 # process at least 5% of files before printing stats
1371 $lcovutil::defaultInterval = 5 unless defined($lcovutil::defaultInterval);
1372
1373 my $intervalLength = int($total * $lcovutil::defaultInterval / 100);
1374 my $start = Time::HiRes::gettimeofday();
1375
1376 $intervalMonitor =
1377 IntervalMonitor->new($total, $totalChunks, $chunkSize, $intervalLength);
1378
1379 lcovutil::info("using: chunkSize: %d, nchunks:%d, intervalLength:%d\n",
1380 $chunkSize, $totalChunks, $intervalLength);
1381 $lcovutil::profileData{chunkSize} = $chunkSize;
1382 $lcovutil::profileData{nChunks} = $totalChunks;
1383 $lcovutil::profileData{interval} = $intervalLength;
1384 $lcovutil::profileData{nFiles} = $total;
1385 $lcovutil::maxParallelism = 1 unless scalar(@worklist) > 1;
1386
1387 my $failedAttempts = 0;
1388 do {
1389 CHUNK: while (@worklist) {
1390
1391 my $chunk = pop(@worklist);
1392 ++$processedChunks;
1393
1394 if (1 < $lcovutil::maxParallelism &&
1395 1 != $chunk->[0]) {
1396
1397 my $currentSize = 0;
1398 if (0 != $lcovutil::maxMemory) {
1399 $currentSize = lcovutil::current_process_size();
1400 }
1401 if ($currentParallel >= $lcovutil::maxParallelism ||
1402 ($currentParallel > 1 &&
1403 (($currentParallel + 1) * $currentSize) >
1404 $lcovutil::maxMemory)
1405 ) {
1406 lcovutil::info(1,
1407 "memory constraint ($currentParallel + 1) * $currentSize > $lcovutil::maxMemory violated: waiting. "
1408 . ($total + 1)
1409 . " remaining\n")
1410 if ((($currentParallel + 1) * $currentSize) >
1411 $lcovutil::maxMemory);
1412
1413 $currentParallel -=
1414 _merge_one_child(\%children, $tempFileExt, \@worklist);
1415 # put the job back in the list
1416 --$processedChunks;
1417 push(@worklist, $chunk);
1418 next CHUNK;
1419 }
1420
1421 $lcovutil::deferWarnings = 1;
1422 my $now = Time::HiRes::gettimeofday();
1423 my $pid = fork();
1424 if (!defined($pid)) {
1425 # fork failed
1426 ++$failedAttempts;
1427 lcovutil::report_fork_failure("process chunk",
1428 $!, $failedAttempts);
1429 --$processedChunks;
1430 push(@worklist, $chunk);
1431 next CHUNK;
1432 }
1433 $failedAttempts = 0;
1434 if (0 == $pid) {
1435 # I'm the child...
1436 # set my output file to temp location so my dump won't
1437 # collide with another child - then merge at the end...
1438 # would be better if the various gcov data readers would
1439 # build a datastructure that we could dump - rather than
1440 # printing a .info file that we have to parse....but so
1441 # be it.
1442 my $childStart = Time::HiRes::gettimeofday();
1443 my $currentState = lcovutil::initial_state();
1444 $buildDirSearchPath->reset();
1445 $output_filename =
1446 File::Spec->catfile($tempFileDir,
1447 "geninfo_$$.info" . $tempFileExt);
1448 my $childInfo;
1449 # set count to zero so we know how many got created in
1450 # the child process
1451 $files_created = 0;
1452 my $now = Time::HiRes::gettimeofday();
1453 # using 'capture' here so that we can both capture/redirect geninfo
1454 # messages from a child process during parallel execution AND
1455 # redirect stdout/stderr from gcov calls.
1456 # It does not work to directly open/reopen the STDOUT and STDERR
1457 # descriptors due to interactions between the child and parent
1458 # processes (see the Capture::Tiny doc for some details)
1459 my $status = 0;
1460 my ($stdout, $stderr, $code) = Capture::Tiny::capture {
1461 eval {
1462 $childInfo =
1463 _process_one_chunk($chunk->[1],
1464 $processedChunks, $childInfo, $$);
1465 };
1466 if ($@) {
1467 $status = 1; # error
1468 print(STDERR $@); # capture messages in $stderr
1469 }
1470 };
1471 # parent might have already caught an error, cleaned up and
1472 # removed the tempdir and exited.
1473 lcovutil::check_parent_process();
1474
1475 # print stdout and stderr ...
1476 foreach my $d (['kog', $stdout], ['err', $stderr]) {
1477 my ($ext, $str) = @$d;
1478 # only print if there is something to print
1479 next
1480 unless ($str);
1481 my $tmpf =
1482 File::Spec->catfile($tempFileDir,
1483 "geninfo_$$.$ext");
1484 my $f = InOutFile->out($tmpf);
1485 my $h = $f->hdl();
1486 print($h $str);
1487 }
1488 my $dumpf = File::Spec->catfile($tempFileDir, "dumper_$$");
1489 foreach my $f ($output_filename) {
1490 unlink $f
1491 if -f $f && !$lcovutil::preserve_intermediates;
1492 }
1493 my $buildDirCounts = $buildDirSearchPath->current_count();
1494
1495 my $then = Time::HiRes::gettimeofday();
1496 # keep separate timestamp for when this child block was entered
1497 # vs when fork() was called - lest this job waited in queue for
1498 # a while
1499 $lcovutil::profileData{process}{$processedChunks} =
1500 $then - $now;
1501
1502 $lcovutil::profileData{child}{$processedChunks} =
1503 $then - $childStart;
1504 # dump parsed data - then read back and merge
1505 my $data;
1506 eval {
1507 # NOTE: not storing anything if we extracted nothing/
1508 # there is no childInfo data
1509 $data =
1510 Storable::store(
1511 [$single_file ? $childInfo : undef,
1512 $buildDirCounts,
1513 [$files_created, scalar(@{$chunk->[1]}),
1514 $then
1515 ],
1516 lcovutil::compute_update($currentState)
1517 ],
1518 $dumpf) if defined($childInfo);
1519 };
1520 if ($@ || (defined($childInfo) && !defined($data))) {
1521 lcovutil::ignorable_error($lcovutil::ERROR_PARALLEL,
1522 "Child $$ serialize failed" . ($@ ? ": $@" : ''));
1523 }
1524 exit($status);
1525 } else {
1526 # I'm the parent
1527 $children{$pid} = [$chunk, $now, $processedChunks];
1528 ++$currentParallel;
1529 }
1530 } else {
1531 # not parallel..
1532 my $saveParallel = $lcovutil::maxParallelism;
1533 $lcovutil::maxParallelism = 1;
1534 if ($chunk->[0]) {
1535 my $num = scalar(@{$chunk->[1]});
1536 lcovutil::info(
1537 "Processing $num file" . ($num == 1 ? '' : 's') .
1538 " from chunk 0 serially\n");
1539 }
1540 my $now = Time::HiRes::gettimeofday();
1541 $trace_data =
1542 _process_one_chunk($chunk->[1], $processedChunks,
1543 $trace_data, undef);
1544 $processedFiles += scalar(@{$chunk->[1]});
1545 if ($chunk->[0]) {
1546 lcovutil::info("Finished processing chunk 0\n");
1547 }
1548 my $then = Time::HiRes::gettimeofday();
1549 $lcovutil::maxParallelism = $saveParallel;
1550 $lcovutil::profileData{process}{$processedChunks} =
1551 $then - $now;
1552 }
1553 } # end foreach
1554
1555 while ($currentParallel != 0) {
1556 $currentParallel -=
1557 _merge_one_child(\%children, $tempFileExt, \@worklist);
1558 }
1559 # wrap in outer loop in case we get a spaceout/child failure
1560 # during 'tail' processing.
1561 } while (@worklist);
1562
1563 info("Finished processing %d "
1564 .
1565 ($initial ? 'GCNO' :
1566 ($lcovutil::geninfo_captureAll ? 'GCDA/GCNO' : 'GCDA')) .
1567 " file%s\n",
1568 $processedFiles,
1569 1 == $processedFiles ? '' : 's');
1570 # Report whether files were excluded.
1571 if (%lcovutil::excluded_files) {
1572 my $count = scalar keys %lcovutil::excluded_files;
1573
1574 info("Excluded data for %d file%s due to include/exclude options\n",
1575 $count, 1 == $count ? '' : 's');
1576 }
1577 return $processedFiles;
1578 }
1579
1580 #
1581 # derive_data(contentdata, funcdata, bbdata)
1582 #
1583 # Calculate function coverage data by combining line coverage data and the
1584 # list of lines belonging to a function.
1585 #
1586 # contentdata: [ instr1, count1, source1, instr2, count2, source2, ... ]
1587 # instr<n>: Instrumentation flag for line n
1588 # count<n>: Execution count for line n
1589 # source<n>: Source code for line n
1590 #
1591 # funcdata: [ count1, func1, count2, func2, ... ]
1592 # count<n>: Execution count for function number n
1593 # func<n>: Function name for function number n
1594 #
1595 # bbdata: function_name -> [ line1, line2, ... ]
1596 # line<n>: Line number belonging to the corresponding function
1597 #
1598
1599 sub derive_data($$$)
1600 {
1601 my ($contentdata, $funcdata, $bbdata) = @_;
1602 my @gcov_content = @{$contentdata};
1603 my @gcov_functions = @{$funcdata};
1604 my %fn_count;
1605
1606 if (!defined($bbdata)) {
1607 return @gcov_functions;
1608 }
1609
1610 # First add existing function data
1611 while (@gcov_functions) {
1612 my $count = shift(@gcov_functions);
1613 my $fn = shift(@gcov_functions);
1614
1615 $fn_count{$fn} = $count;
1616 }
1617
1618 # Convert line coverage data to function data
1619 foreach my $fn (keys(%{$bbdata})) {
1620 my $line_data = $bbdata->{$fn};
1621 my $line;
1622 my $fninstr = 0;
1623
1624 if ($fn eq "") {
1625 next;
1626 }
1627 # Find the lowest line count for this function
1628 my $count = 0;
1629 foreach my $line (@$line_data) {
1630 my $linstr = $gcov_content[($line - 1) * 3 + 0];
1631 my $lcount = $gcov_content[($line - 1) * 3 + 1];
1632
1633 next if (!$linstr);
1634 $fninstr = 1;
1635 if (($lcount > 0) &&
1636 (($count == 0) || ($lcount < $count))) {
1637 $count = $lcount;
1638 }
1639 }
1640 next if (!$fninstr);
1641 $fn_count{$fn} = $count;
1642 }
1643
1644 # Convert hash to list in @gcov_functions format
1645 foreach my $fn (sort(keys(%fn_count))) {
1646 push(@gcov_functions, $fn_count{$fn}, $fn);
1647 }
1648
1649 return @gcov_functions;
1650 }
1651
1652 #
1653 # process_dafile(dirname, da_filename, gcno_filename, tempdir)
1654 #
1655 # Create a .info file for a single data file.
1656 #
1657 # Die on error.
1658 #
1659
1660 sub process_dafile($$$$)
1661 {
1662 my ($dirname, $gcda_file, $gcno_file, $tempdir) = @_;
1663 my $da_filename; # Name of data file to process
1664 my $da_dir; # Directory of data file
1665 my $source_dir; # Directory of source file
1666 my $da_basename; # data filename without ".da/.gcda" extension
1667 my $bb_filename; # Name of respective graph file
1668 my $bb_basename; # Basename of the original graph file
1669 my $graph; # Contents of graph file
1670 my $instr; # Contents of graph file part 2
1671 my $object_dir; # Directory containing all object files
1672 my $source_filename; # Name of a source code file
1673 my $gcov_file; # Name of a .gcov file
1674 my @gcov_content; # Content of a .gcov file
1675 my $gcov_branches; # Branch content of a .gcov file
1676 my @gcov_functions; # Function calls of a .gcov file
1677 my $line_number; # Line number count
1678 my @matches; # List of absolute paths matching filename
1679 my $base_dir; # Base directory for current file
1680
1681 # Get path to data file in absolute and normalized form (begins with /,
1682 # contains no more ../ or ./)
1683 $da_filename = solve_relative_path($cwd, $gcda_file);
1684 my $gcno_filename = solve_relative_path($cwd, $gcno_file);
1685
1686 # Get directory and basename of data file
1687 ($da_dir, $da_basename) = split_filename($da_filename);
1688
1689 $source_dir = $da_dir;
1690 if (is_compat($COMPAT_MODE_LIBTOOL)) {
1691 # Avoid files from .libs dirs
1692 $source_dir =~ s/\.libs$//;
1693 }
1694
1695 # Construct base_dir for current file
1696 if ($base_directory) {
1697 $base_dir = $base_directory;
1698 } else {
1699 $base_dir = $source_dir;
1700 }
1701
1702 # Construct name of graph file
1703 $bb_filename = solve_relative_path($cwd, $gcno_file);
1704
1705 # Find out the real location of graph file in case we're just looking at
1706 # a link
1707 while (readlink($bb_filename)) {
1708 my $last_dir = dirname($bb_filename);
1709
1710 $bb_filename = readlink($bb_filename);
1711 $bb_filename = solve_relative_path($last_dir, $bb_filename);
1712 }
1713
1714 # Ignore empty graph file (e.g. source file with no statement)
1715 if (-z $bb_filename) {
1716 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY, "empty $bb_filename");
1717 chdir($cwd) or die("can't cd back to $cwd: $!");
1718 return undef;
1719 }
1720
1721 # Read contents of graph file into hash. We need it later to find out
1722 # the absolute path to each .gcov file created as well as for
1723 # information about functions and their source code positions.
1724 ($instr, $graph) = read_gcno($bb_filename);
1725
1726 # Try to find base directory automatically if requested by user
1727 if ($lcovutil::rc_auto_base) {
1728 $base_dir = find_base_from_source($base_dir,
1729 [keys(%{$instr}), keys(%{$graph})]);
1730 }
1731
1732 adjust_source_filenames($instr, $base_dir);
1733 adjust_source_filenames($graph, $base_dir);
1734
1735 # Set $object_dir to real location of object files. This may differ
1736 # from $da_dir if the graph file is just a link to the "real" object
1737 # file location.
1738 $object_dir = dirname($bb_filename);
1739 my $da_arg = File::Spec->catfile($base_dir, $da_filename);
1740 # Is the data file in a different directory? (this happens e.g. with
1741 # the gcov-kernel patch).
1742 if ($object_dir ne $da_dir) {
1743 # Use links in tempdir
1744 $da_arg = File::Basename::basename($da_filename);
1745 my $gcda = File::Spec->catfile($tempdir, $da_arg);
1746 symlink($da_filename, $gcda) or
1747 die("cannot create link $gcda: $!\n");
1748 my $gcno = File::Spec->catfile($tempdir,
1749 File::Basename::basename($bb_filename));
1750 symlink($bb_filename, $gcno) or
1751 die("cannot create link $gcno: $!\n");
1752 $object_dir = '.';
1753 }
1754
1755 chdir($tempdir) or die("can't cd to $tempdir: $!");
1756 # Execute gcov command and suppress standard output
1757 # also redirect stderr to /dev/null if 'quiet'
1758 # HGC: what we really want to do is to redirect stdout/stderr
1759 # unless verbose - but echo them for non-zero exit status.
1760 my $now = Time::HiRes::gettimeofday();
1761 debug("call gcov: " . join(' ', @gcov_tool) . " $da_arg -o $object_dir\n");
1762 lcovutil::info(2,
1763 "process $da_arg (for $base_dir/$da_filename in $tempdir\n");
1764 my ($out, $err, $code) =
1765 system_no_output(1 + 2 + 4, @gcov_tool, $da_arg, "-o", $object_dir);
1766 my $then = Time::HiRes::gettimeofday();
1767 $lcovutil::profileData{exec}{$dirname}{$gcda_file} = $then - $now;
1768
1769 if (0 != $code) {
1770 check_gcov_fail($err, $da_filename);
1771 }
1772 print_gcov_warnings('stdout', $out, 0, {})
1773 if ('' ne $out &&
1774 (0 != $code ||
1775 $lcovutil::verbose > 1));
1776 print_gcov_warnings('stderr', $err, 0, {})
1777 if ('' ne $err &&
1778 (0 != $code ||
1779 $lcovutil::verbose));
1780
1781 # Change back to initial directory
1782 debug(2, "chdir back to $cwd\n");
1783 chdir($cwd) or die("can't cd back to $cwd: $!");
1784 # Collect data from resulting .gcov files and create .info file
1785 # this version of gcov wrote the files to "." - but we want to
1786 # save them in tempdir
1787 my @gcov_list;
1788 foreach my $f (glob("$tempdir/*.gcov $tempdir/.*.gcov")) {
1789 # Skip gcov file for gcc built-in code
1790 push(@gcov_list, $f) unless ($f eq "<built-in>.gcov");
1791 }
1792
1793 # Check for files
1794 if (!@gcov_list) {
1795 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
1796 "gcov did not create any files for " . "$da_filename!\n");
1797 }
1798
1799 if ($code) {
1800 ignorable_error($ERROR_UTILITY,
1801 "GCOV command failed for $da_filename!");
1802 return undef;
1803 }
1804
1805 my $traceFile = TraceFile->new();
1806 # Traverse the list of generated .gcov files and combine them into a
1807 # single .info file
1808 foreach $gcov_file (@gcov_list) {
1809 GCOV_FILE_LOOP: {
1810 next unless -f $gcov_file; # skp if we didn't copy it over
1811
1812 my ($source, $object) = read_gcov_header($gcov_file);
1813 if (!defined($source)) {
1814 # Derive source file name from gcov file name if
1815 # header format could not be parsed
1816 $source = $gcov_file;
1817 $source =~ s/\.gcov$//;
1818 }
1819
1820 $source = solve_relative_path($base_dir, $source);
1821
1822 # apply more patterns here
1823 $source = ReadCurrentSource::resolve_path($source, 1);
1824
1825 @matches = match_filename($source, keys(%{$instr}));
1826
1827 # Skip files that are not mentioned in the graph file
1828 if (!@matches) {
1829 lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
1830 "cannot find an entry for " .
1831 $gcov_file . " in $graph_file_extension file");
1832 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1833 next;
1834 }
1835
1836 # Read in contents of gcov file
1837 my @result = read_gcov_file($gcov_file, $da_filename, $source);
1838 if (!defined($result[0])) {
1839 lcovutil::ignorable_error($lcovutil::ERROR_CORRUPT,
1840 "$gcov_file is unreadable");
1841 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1842 next;
1843 }
1844 @gcov_content = @{$result[0]};
1845 my $branchData = $result[1];
1846 @gcov_functions = @{$result[2]};
1847
1848 # Skip empty files
1849 if (!@gcov_content) {
1850 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
1851 "$gcov_file is empty");
1852 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1853 next;
1854 }
1855
1856 if (scalar(@matches) == 1) {
1857 # Just one match
1858 $source_filename = $matches[0];
1859 } else {
1860 # Try to solve the ambiguity
1861 $source_filename = solve_ambiguous_match($gcov_file, \@matches,
1862 \@gcov_content);
1863 }
1864 $source_filename =
1865 ReadCurrentSource::resolve_path($source_filename, 1);
1866
1867 if (TraceFile::skipCurrentFile($source_filename)) {
1868 $lcovutil::excluded_files{$source_filename} = 1;
1869 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1870 next GCOV_FILE_LOOP;
1871 }
1872
1873 # Skip external files if requested
1874 if (is_external($source_filename)) {
1875 info(" ignoring data for external file $source_filename\n");
1876 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1877 next;
1878 }
1879
1880 my $fileData = $traceFile->data($source_filename);
1881 my $functionMap = $fileData->testfnc($test_name);
1882 my $branchMap = $fileData->testbr($test_name);
1883 my $lineMap = $fileData->test($test_name);
1884
1885 if (@lcovutil::extractVersionScript) {
1886 my $version = lcovutil::extractFileVersion($source_filename);
1887 $fileData->version($version)
1888 if (defined($version) && $version ne "");
1889 }
1890
1891 # If requested, derive function coverage data from
1892 # line coverage data of the first line of a function
1893 if ($opt_derive_func_data) {
1894 @gcov_functions =
1895 derive_data(\@gcov_content, \@gcov_functions,
1896 $graph->{$source_filename});
1897 }
1898
1899 # Hold function-related information
1900 my %functionData;
1901 if (defined($graph->{$source_filename})) {
1902 my $fn_data = $graph->{$source_filename};
1903
1904 while (my ($fn, $ln_data) = each(%$fn_data)) {
1905 next if ($fn eq "");
1906 my $line = $ln_data->[0];
1907
1908 # Normalize function name - need to demangle here because
1909 # the graph data came from reading the gcno file and isn't
1910 # demangled already
1911 $fn = filter_fn_name($fn,
1912 defined($lcovutil::demangle_cpp_cmd));
1913 $functionData{$fn} =
1914 $functionMap->define_function($fn, $line);
1915 }
1916 }
1917
1918 while (@gcov_functions) {
1919 my $count = shift(@gcov_functions);
1920 my $fn = shift(@gcov_functions);
1921
1922 # don't need to demangle here because this came from reading
1923 # the gcov result - and we demangled that.
1924 $fn = filter_fn_name($fn, 0);
1925 next unless exists($functionData{$fn});
1926 $functionData{$fn}->addAlias($fn, $count);
1927 }
1928
1929 # Coverage information for each instrumented branch:
1930 foreach my $line ($branchData->keylist()) {
1931
1932 my $branchEntry = $branchData->value($line);
1933
1934 # gcov extraction block numbers can be strange - so
1935 # just renumber them.
1936 my $blockRenumber = 0;
1937 foreach my $blockId ($branchEntry->blocks()) {
1938 my $blockData = $branchEntry->getBlock($blockId);
1939 foreach my $br (@$blockData) {
1940 $branchMap->append($line, $blockRenumber,
1941 $br, $source_filename);
1942 }
1943 ++$blockRenumber;
1944 }
1945 } # end for each branch
1946
1947 # Reset line counters
1948 $line_number = 0;
1949
1950 # Write coverage information for each instrumented line
1951 # Note: @gcov_content contains a list of (flag, count, source)
1952 # tuple for each source code line
1953 while (@gcov_content) {
1954
1955 $line_number++;
1956
1957 # Check for instrumented line
1958 if ($gcov_content[0]) {
1959 my $hit = $gcov_content[1];
1960 # do we have branch data on this line?
1961 # if no branch data and this line was marked as
1962 # 'unexecuted' - then set its hit count to zero
1963 if ('ARRAY' eq ref($hit)) {
1964 die("unexpected 'unexec' count") unless $hit->[1] == 1;
1965 $hit = $hit->[0];
1966 if ($hit != 0 &&
1967 !defined($branchMap->value($line_number))) {
1968 lcovutil::debug(
1969 "$source_filename:$line_number: unexecuted block on non-branch line with count=$hit\n"
1970 );
1971 if ($lcovutil::opt_adjust_unexecuted_blocks) {
1972 $hit = 0;
1973 } elsif (lcovutil::warn_once(
1974 "unexecuted block",
1975 $ERROR_INCONSISTENT_DATA
1976 )) {
1977 lcovutil::ignorable_warning(
1978 $ERROR_INCONSISTENT_DATA,
1979 "$source_filename:$line_number: unexecuted block on non-branch line with non-zero hit count. Use \"geninfo --rc geninfo_unexecuted_blocks=1 to set count to zero."
1980 );
1981 }
1982 }
1983 }
1984 $lineMap->append($line_number, $hit);
1985 }
1986 # Remove already processed data from array
1987 splice(@gcov_content, 0, 3);
1988 }
1989 # now go through lines, functions, branches - append to test_name data
1990 $fileData->sum()->union($lineMap);
1991 $fileData->sumbr()->union($branchMap);
1992 $fileData->func()->union($functionMap);
1993
1994 # Remove .gcov file after processing
1995 unlink($gcov_file) unless $lcovutil::preserve_intermediates;
1996 }
1997 }
1998
1999 return $traceFile;
2000 }
2001
2002 #
2003 # compute_internal_directories(list)
2004 #
2005 # Walk directory tree to find set of 'internal' directories
2006 # - soft links within the 'internal' tree which point to directories outside
2007 # the tree cause those target directories to be considered 'internal' if
2008 # the "--follow" flag is specified - else, 'external'
2009 #
2010
2011 sub compute_internal_directories(@)
2012 {
2013 my @dirstack;
2014 foreach my $entry (@_) {
2015 next unless (defined($entry));
2016 # do not apply substitution patterns to the dir name -
2017 # if user really wants that, they can specify a substitution and/or
2018 # include/exclude patterns
2019 my $p = solve_relative_path($cwd, $entry);
2020 push(@dirstack, $p)
2021 if $lcovutil::opt_follow && !grep($p eq $_, @dirstack);
2022 push(@lcovutil::internal_dirs, $p)
2023 unless
2024 grep($p eq $_ || ($lcovutil::case_insensitive && lc($p) eq lc($_)),
2025 @lcovutil::internal_dirs);
2026 if (!file_name_is_absolute($entry) &&
2027 $entry ne $p) {
2028 push(@lcovutil::internal_dirs, $entry)
2029 unless grep($entry eq $_ || ($lcovutil::case_insensitive &&
2030 lc($entry) eq lc($_)),
2031 @lcovutil::internal_dirs);
2032 }
2033 }
2034
2035 my %visited;
2036 while (@dirstack) {
2037 my $top = pop(@dirstack);
2038 if (-l $top) {
2039 my $t = Cwd::realpath($top);
2040 die("expected directory found '$t'") unless -d $t;
2041 unless (exists($visited{$t})) {
2042 lcovutil::info(1,
2043 "internal directory: target '$t' of link '$top'\n");
2044 $visited{$t} = $top;
2045 push(@dirstack, $t);
2046 push(@lcovutil::internal_dirs, $t)
2047 if lcovutil::is_external($t);
2048 }
2049 next;
2050 }
2051 opendir(my $dh, $top) or die("can't open directory: $!");
2052 while (my $e = readdir($dh)) {
2053 next if $e eq '.' || $e eq '..';
2054 my $p = File::Spec->catfile($top, $e);
2055 if (-l $p) {
2056 my $l = Cwd::realpath($p);
2057 push(@dirstack, $p) if (-d $l);
2058 } elsif (-d $p) {
2059 push(@dirstack, $p) unless exists($visited{$p});
2060 $visited{$p} = $top;
2061 }
2062 } # while
2063 closedir($dh);
2064 }
2065
2066 if (@lcovutil::internal_dirs) {
2067 lcovutil::info("Recording 'internal' directories:\n\t" .
2068 join("\n\t", @lcovutil::internal_dirs) . "\n");
2069 }
2070
2071 # Function is_external() requires all internal_dirs to end with a slash
2072 foreach my $dir (@lcovutil::internal_dirs) {
2073 $dir =~ s#$lcovutil::dirseparator*$#$lcovutil::dirseparator#;
2074 }
2075 }
2076
2077 #
2078 # solve_relative_path(path, dir)
2079 #
2080 # Solve relative path components of DIR which, if not absolute, resides in PATH.
2081 #
2082
2083 sub solve_relative_path($$)
2084 {
2085 my ($path, $dir) = @_;
2086
2087 # Convert from Windows path to msys path
2088 if ($^O eq "msys") {
2089 # search for a windows drive letter at the beginning
2090 my ($volume, $directories, $filename) =
2091 File::Spec::Win32->splitpath($dir);
2092 if ($volume ne '') {
2093 my $uppercase_volume;
2094 # transform c/d\../e/f\g to Windows style c\d\..\e\f\g
2095 $dir = File::Spec::Win32->canonpath($dir);
2096 # use Win32 module to retrieve path components
2097 # $uppercase_volume is not used any further
2098 ($uppercase_volume, $directories, $filename) =
2099 File::Spec::Win32->splitpath($dir);
2100 my @dirs = File::Spec::Win32->splitdir($directories);
2101
2102 # prepend volume, since in msys C: is always mounted to /c
2103 $volume =~ s|^([a-zA-Z]+):|/\L$1\E|;
2104 unshift(@dirs, $volume);
2105
2106 # transform to Unix style '/' path
2107 $directories = File::Spec->catdir(@dirs);
2108 $dir = File::Spec->catpath('', $directories, $filename);
2109 } else {
2110 # eliminate '\' path separators
2111 $dir = File::Spec->canonpath($dir);
2112 }
2113 }
2114
2115 my $result = $dir;
2116 # Prepend path if not absolute
2117 if (!File::Spec->file_name_is_absolute($dir)) {
2118 $result = File::Spec->catfile($path, $result);
2119 }
2120 # can't just use Cwd::abs_path on the pathname because it understands
2121 # soft links and resolves them - so we end up pointing to the actual file
2122 # and not to the carefully constructed linked-build paths that the user
2123 # wanted. Have to do it the hard way
2124 # return Cwd::abs_path($result);
2125
2126 # Remove // in favor of /
2127 my $d = $lcovutil::dirseparator;
2128 $result =~ s#$d$d#$d#g;
2129
2130 # Remove . in middle or at end of path
2131 while ($result =~ s#$d\.($d|$)#$d#) {
2132 }
2133
2134 # Remove trailing /
2135 $result =~ s#$d$##g if ($result ne $d);
2136
2137 # change "X/dirname/../Y" into "X/Y"
2138 while ($result =~ s#$d[^$d]+$d\.\.($d|$)#$d#) {
2139 }
2140 # change "dirname/../Y" into "./Y" (i.e,, at head of path)
2141 $result =~ s#^[^$d]+\/\.\.$d#.$d#;
2142
2143 # Remove preceding ..
2144 $result =~ s#^$d\.\.$d#$d#g;
2145
2146 return $result;
2147 }
2148
2149 #
2150 # match_filename(gcov_filename, list)
2151 #
2152 # Return a list of those entries of LIST which match the relative filename
2153 # GCOV_FILENAME.
2154 #
2155
2156 sub match_filename($@)
2157 {
2158 my ($filename, @list) = @_;
2159 my ($vol, $dir, $file) = splitpath($filename);
2160 my @comp = splitdir($dir);
2161 my $comps = scalar(@comp);
2162 my $entry;
2163 my @result;
2164
2165 entry:
2166 foreach $entry (@list) {
2167 my ($evol, $edir, $efile) = splitpath($entry);
2168 # Filename component must match
2169 if ($efile ne $file) {
2170 next;
2171 }
2172 # Check directory components last to first for match
2173 my @ecomp = splitdir($edir);
2174 my $ecomps = scalar(@ecomp);
2175 if ($ecomps < $comps) {
2176 next;
2177 }
2178 for (my $i = 0; $i < $comps; $i++) {
2179 if ($comp[$comps - $i - 1] ne $ecomp[$ecomps - $i - 1]) {
2180 next entry;
2181 }
2182 }
2183 push(@result, $entry);
2184 }
2185
2186 return @result;
2187 }
2188
2189 #
2190 # solve_ambiguous_match(rel_filename, matches_ref, gcov_content_ref)
2191 #
2192 # Try to solve ambiguous matches of mapping (gcov file) -> (source code) file
2193 # by comparing source code provided in the GCOV file with that of the files
2194 # in MATCHES. REL_FILENAME identifies the relative filename of the gcov
2195 # file.
2196 #
2197 # Return the one real match or die if there is none.
2198 #
2199
2200 sub solve_ambiguous_match($$$)
2201 {
2202 my $rel_name = $_[0];
2203 my $matches = $_[1];
2204 my $content = $_[2];
2205 local *SOURCE;
2206
2207 # Check the list of matches
2208 foreach my $filename (@$matches) {
2209
2210 # Compare file contents
2211 open(SOURCE, "<", $filename) or
2212 die("cannot read $filename: $!\n");
2213
2214 my $no_match = 0;
2215 for (my $index = 2; <SOURCE>; $index += 3) {
2216 chomp;
2217
2218 # Also remove CR from line-end
2219 s/\015$//;
2220
2221 if ($_ ne @$content[$index]) {
2222 $no_match = 1;
2223 last;
2224 }
2225 }
2226
2227 close(SOURCE) or die("unable to close $filename: $!\n");
2228
2229 if (!$no_match) {
2230 info("Solved source file ambiguity for $rel_name\n");
2231 return $filename;
2232 }
2233 }
2234
2235 die("could not match gcov data for $rel_name!\n");
2236 }
2237
2238 #
2239 # split_filename(filename)
2240 #
2241 # Return (path, filename, extension) for a given FILENAME.
2242 #
2243
2244 sub split_filename($)
2245 {
2246 my ($vol, $dir, $name) = File::Spec->splitpath($_[0]);
2247
2248 my @file_components = split('\.', $name);
2249 my $extension = pop(@file_components);
2250
2251 return ($vol . $dir, join(".", @file_components), $extension);
2252 }
2253
2254 #
2255 # read_gcov_header(gcov_filename)
2256 #
2257 # Parse file GCOV_FILENAME and return a list containing the following
2258 # information:
2259 #
2260 # (source, object)
2261 #
2262 # where:
2263 #
2264 # source: complete relative path of the source code file (gcc >= 3.3 only)
2265 # object: name of associated graph file
2266 #
2267 # Die on error.
2268 #
2269
2270 sub read_gcov_header($)
2271 {
2272 my $source;
2273 my $object;
2274 local *INPUT;
2275
2276 if (!open(INPUT, "<", $_[0])) {
2277 ignorable_error($ERROR_GCOV, "cannot read $_[0]: $!");
2278 return (undef, undef);
2279 }
2280
2281 while (<INPUT>) {
2282 chomp($_);
2283
2284 # Also remove CR from line-end
2285 s/\015$//;
2286
2287 if (/^\s+-:\s+0:Source:(.*)$/) {
2288 # Source: header entry
2289 $source = $1;
2290 } elsif (/^\s+-:\s+0:Object:(.*)$/) {
2291 # Object: header entry
2292 $object = $1;
2293 } else {
2294 last;
2295 }
2296 }
2297
2298 close(INPUT) or die("unable to close $_[0]: $!\n");
2299
2300 return ($source, $object);
2301 }
2302
2303 #
2304 # read_gcov_file(gcov_filename, gcda_filename, source_filename)
2305 #
2306 # Parse file GCOV_FILENAME (.gcov file format) and return the list:
2307 # (reference to gcov_content, reference to gcov_branch, reference to gcov_func)
2308 #
2309 # gcov_content is a list of 3 elements
2310 # (flag, count, source) for each source code line:
2311 #
2312 # $result[($line_number-1)*3+0] = instrumentation flag for line $line_number
2313 # $result[($line_number-1)*3+1] = execution count for line $line_number
2314 # $result[($line_number-1)*3+2] = source code text for line $line_number
2315 #
2316 # gcov_branch is a BranchData instance - see lcovutil.pm
2317 #
2318 # gcov_func is a list of 2 elements
2319 # (number of calls, function name) for each function
2320 #
2321 # Die on error.
2322 #
2323
2324 sub read_gcov_file($$$)
2325 {
2326 my ($filename, $da_filename, $source_filename) = @_;
2327 my @result = ();
2328 my $branchData = BranchData->new();
2329 my @functions = ();
2330 my $number;
2331 my $last_block = $UNNAMED_BLOCK;
2332 my $last_line = 0;
2333 my $branchId;
2334 my $unexec;
2335
2336 my $f = InOutFile->in($filename, $lcovutil::demangle_cpp_cmd);
2337 my $input = $f->hdl();
2338
2339 my $currentBlock;
2340
2341 # Expect gcov format as used in gcc >= 3.3
2342 debug("reading $filename\n");
2343 # line content "/*EOF*/" occurs when gcov knows the
2344 # number of lines in the file but can't find the source code -
2345 # most of the time, that is deliberate because we run gcov in a
2346 # temp directory in order to avoid conflicts from parallel execution
2347 # we do a bit of error checking that the content is not inconsistent
2348 # - e.g., if we find the file due to fully qualified paths, and find
2349 # a non-EOF line following an EOF line.
2350 my $foundEOF = 0;
2351 while (<$input>) {
2352 chomp($_);
2353 # Also remove CR from line-end
2354 s/\015$//;
2355
2356 if (/^\s*(\d+|\$+|\%+):\s*(\d+)-block\s+(\d+)\s*$/) {
2357 # Block information - used to group related branches
2358 $branchId = 0;
2359 $last_line = $2;
2360 $last_block = $3;
2361 } elsif (/^branch\s+(\d+)\s+taken\s+(\d+)(?:\s+\(([^)]*)\))?/) {
2362 next unless $lcovutil::br_coverage;
2363 # $1 is block ID, $2 is hit count
2364 my $count = $2;
2365 my $br = BranchBlock->new($branchId, $count, undef,
2366 defined($3) && $3 eq 'throw');
2367 $branchData->append($last_line, $last_block, $br, $filename);
2368 ++$branchId;
2369 } elsif (/^branch\s+(\d+)\s+never\s+executed/) {
2370 next unless $lcovutil::br_coverage;
2371 # this branch not taken
2372 my $br = BranchBlock->new($branchId, '-');
2373 $branchData->append($last_line, $last_block, $br, $filename);
2374 ++$branchId;
2375 } elsif (/^function\s+(.+)\s+called\s+(\d+)\s+/) {
2376 next unless $lcovutil::func_coverage;
2377 my $name = $1;
2378 my $count = $2;
2379 push(@functions, $count, $name);
2380 } elsif (/^call/) {
2381 # Function call return data
2382 } elsif (/^\s*([^:]+):\s*([^:]+):(.*)$/) {
2383 my ($count, $line, $code) = ($1, $2, $3);
2384 # Skip instance-specific counts
2385 next if ($line <= (scalar(@result) / 3));
2386 # skip fake line inserted by gcov
2387 if ($code eq '/*EOF*/') {
2388 $foundEOF = 1;
2389 } elsif ($foundEOF) {
2390 # data looks inconsistent...we started finding some EOF entries
2391 # and now we found a following entry which claims not to be EOF
2392 lcovutil::ignorable_error($ERROR_FORMAT,
2393 "non-EOF for $source_filename:$line at $filename:$. while processing $da_filename: '$code'"
2394 );
2395 }
2396 $branchId = 0; # if $last_line != $line;
2397 $last_line = $line;
2398 $last_block = $UNNAMED_BLOCK;
2399 # Strip unexecuted basic block marker
2400 if ($count =~ /^([^*]+)\*$/) {
2401 # need to do something about lines which have non-zero count
2402 # but unexecuted block. If there are no branches associated
2403 # with this line, then we should mark the line as not hit.
2404 # Otherwise, result is misleading because we can see
2405 # (for example) a non-zero hit could for the the 'if' clause
2406 # of an untaken branch.
2407 $unexec = 1;
2408 $count = $1;
2409 } else {
2410 $unexec = 0;
2411 }
2412
2413 # <exec count>:<line number>:<source code>
2414 if ($line eq "0") {
2415 # Extra data
2416 } elsif ($count eq "-") {
2417 # Uninstrumented line
2418 push(@result, 0, 0, $code);
2419 } else {
2420 # Check for zero count
2421 if ($count =~ /^[#=]/) {
2422 $count = 0;
2423 }
2424 push(@result, 1, $unexec ? [$count, $unexec] : $count, $code);
2425 }
2426 }
2427 }
2428 return (\@result, $branchData, \@functions);
2429 }
2430
2431 #
2432 # read_intermediate_text(gcov_filename, data)
2433 #
2434 # Read gcov intermediate text format in GCOV_FILENAME and add the resulting
2435 # data to DATA in the following format:
2436 #
2437 # data: source_filename -> file_data
2438 # file_data: concatenated lines of intermediate text data
2439 #
2440
2441 sub read_intermediate_text($$)
2442 {
2443 my ($gcov_filename, $data) = @_;
2444 my $filename;
2445
2446 my $f = InOutFile->in($gcov_filename, $lcovutil::demangle_cpp_cmd);
2447 my $h = $f->hdl();
2448 while (my $line = <$h>) {
2449 if ($line =~ /^file:(.*)$/) {
2450 $filename = $1;
2451 $filename =~ s/[\r\n]$//g;
2452 #filename will be simplified/sustituted in 'adjust_source_filenames'
2453 } elsif (defined($filename)) {
2454 $data->{$filename} .= $line;
2455 }
2456 }
2457 }
2458
2459 #
2460 # read_intermediate_json(gcov_filename, data, basedir_ref)
2461 #
2462 # Read gcov intermediate JSON format in GCOV_FILENAME and add the resulting
2463 # data to DATA in the following format:
2464 #
2465 # data: source_filename -> file_data
2466 # file_data: GCOV JSON data for file
2467 #
2468 # Also store the value for current_working_directory to BASEDIR_REF.
2469 #
2470
2471 sub read_intermediate_json($$$)
2472 {
2473 my ($gcov_filename, $data, $basedir_ref) = @_;
2474 # intermediate JSON contains the demangled name
2475 my $json = JsonSupport::load($gcov_filename); # imported from lcovutil.pm
2476 if (!defined($json) ||
2477 !exists($json->{"files"}) ||
2478 ref($json->{"files"} ne "ARRAY")) {
2479 die("Unrecognized JSON output format in $gcov_filename\n");
2480 }
2481
2482 $$basedir_ref = $json->{"current_working_directory"};
2483
2484 # Workaround for bug in MSYS GCC 9.x that encodes \ as \n in gcov JSON
2485 # output
2486 if ($^O eq "msys" && $$basedir_ref =~ /\n/) {
2487 $$basedir_ref =~ s#\n#/#g;
2488 }
2489
2490 for my $file (@{$json->{"files"}}) {
2491 # decode_json() is decoding UTF-8 strings from the JSON file into
2492 # Perl's internal encoding, but filenames on the filesystem are
2493 # usually UTF-8 encoded, so the filename strings need to be
2494 # converted back to UTF-8 so that they actually match the name
2495 # on the filesystem.
2496 utf8::encode($file->{"file"});
2497
2498 my $filename = $file->{"file"};
2499 $data->{$filename} = $file;
2500 }
2501 }
2502
2503 #
2504 # intermediate_text_to_info(data)
2505 #
2506 # Write DATA in info format to file descriptor FD.
2507 #
2508 # data: filename -> file_data:
2509 # file_data: concatenated lines of intermediate text data
2510 #
2511 # Note: To simplify processing, gcov data is not combined here, that is counts
2512 # that appear multiple times for the same lines/branches are not added.
2513 # This is done by lcov/genhtml when reading the data files.
2514 #
2515
2516 sub intermediate_text_to_info($)
2517 {
2518 my $data = shift;
2519 my $branch_num = 0;
2520
2521 return if (!%{$data});
2522
2523 my $traceFile = TraceFile->new();
2524
2525 while (my ($filename, $fileStr) = each(%$data)) {
2526 # note that we already substituted the source file name and handled
2527 # include/exclude directives - so no need to check here
2528 # see 'adjust_source_filenames() and 'filter_source_files()
2529
2530 lcovutil::info(1, "emit data for $filename\n");
2531
2532 # there is no meaningful parse location for this data
2533 my $fileData = $traceFile->data($filename);
2534 my $functionMap = $fileData->testfnc($test_name);
2535 my $branchMap = $fileData->testbr($test_name);
2536 my $lineMap = $fileData->test($test_name);
2537
2538 if (@lcovutil::extractVersionScript) {
2539 my $version = lcovutil::extractFileVersion($filename);
2540 $fileData->version($version)
2541 if (defined($version) && $version ne "");
2542 }
2543 for my $line (split(/\n/, $fileStr)) {
2544 if ($line =~ /^lcount:(\d+),(\d+),?/) {
2545 # lcount:<line>,<count>
2546 # lcount:<line>,<count>,<has_unexecuted_blocks>
2547 my $lineNo = $1;
2548 my $hit = $2;
2549 $lineMap->append($lineNo, $hit);
2550
2551 # Intermediate text format does not provide
2552 # branch numbers, and the same branch may appear
2553 # multiple times on the same line (e.g. in
2554 # template instances). Synthesize a branch
2555 # number based on the assumptions:
2556 # a) the order of branches is fixed across
2557 # instances
2558 # b) an instance starts with an lcount line
2559 $branch_num = 0;
2560 } elsif ($line =~ /^function:((\d+)(,(\d+))?),(\d+),(.+)$/) {
2561 next unless $lcovutil::func_coverage;
2562
2563 # function:<line>,<endline,>?<count>,<name>
2564 my ($lineNo, $endline, $hit, $name) = ($2, $4, $5, $6);
2565 my $func =
2566 $functionMap->define_function($name, $lineNo, $endline);
2567 $func->addAlias($name, $hit);
2568 } elsif ($line =~ /^branch:(\d+),(taken|nottaken|notexec)/) {
2569 my $lineNo = $1;
2570 next
2571 unless $lcovutil::br_coverage;
2572 my $c;
2573 # branch:<line>,taken|nottaken|notexec
2574 if ($2 eq "taken") {
2575 $c = 1;
2576 } elsif ($2 eq "nottaken") {
2577 $c = 0;
2578 } else {
2579 $c = "-";
2580 }
2581 my $br = BranchBlock->new($branch_num, $c);
2582 # "block" is always zero for intermedaite text
2583 $branchMap->append($lineNo, 0, $br, $filename);
2584 ++$branch_num;
2585 }
2586 }
2587 # now go through lines, functions, branches - append to test_name data
2588 $fileData->sum()->union($lineMap);
2589 $fileData->sumbr()->union($branchMap);
2590 $fileData->func()->union($functionMap);
2591 }
2592 return $traceFile;
2593 }
2594
2595 #
2596 # intermediate_json_to_info(data)
2597 #
2598 # Write DATA in info format to file descriptor FD.
2599 #
2600 # data: filename -> file_data:
2601 # file_data: GCOV JSON data for file
2602 #
2603 # Note: To simplify processing, gcov data is not combined here, that is counts
2604 # that appear multiple times for the same lines/branches are not added.
2605 # This is done by lcov/genhtml when reading the data files.
2606 #
2607
2608 sub intermediate_json_to_info($)
2609 {
2610 my $data = shift;
2611 my $branch_num = 0;
2612
2613 return if (!%{$data});
2614
2615 my $traceFile = TraceFile->new();
2616 lcovutil::debug(1,
2617 "called intermediate_json_to_info " . join(' ', keys(%$data)) . "\n");
2618 while (my ($filename, $file_data) = each(%$data)) {
2619 # note that we already substituted the source file name and handled
2620 # include/exclude directives - so no need to check here
2621 # see 'adjust_source_filenames() and 'filter_source_files()
2622 # there is no meaningful parse location for this data
2623 my $fileData = $traceFile->data($filename);
2624 my $functionMap = $fileData->testfnc($test_name);
2625 my $branchMap = $fileData->testbr($test_name);
2626 my $lineMap = $fileData->test($test_name);
2627 my $mcdcMap = $fileData->testcase_mcdc($test_name);
2628 lcovutil::debug(1, "parse $filename\n");
2629
2630 if (@lcovutil::extractVersionScript) {
2631 my $version = lcovutil::extractFileVersion($filename);
2632 $fileData->version($version)
2633 if (defined($version) && $version ne "");
2634 }
2635
2636 # Function data
2637 if ($lcovutil::func_coverage) {
2638 for my $d (@{$file_data->{"functions"}}) {
2639 my $start_line = $d->{"start_line"};
2640 my $end_line = $d->{"end_line"}
2641 if exists($d->{end_line});
2642 my $count = $d->{"execution_count"};
2643 my $name = $lcovutil::demangle_cpp_cmd ? $d->{demangled_name} :
2644 $d->{"name"};
2645 my $func =
2646 $functionMap->define_function($name, $start_line,
2647 $end_line);
2648 $func->addAlias($name, $count);
2649 }
2650 }
2651 for my $d (@{$file_data->{"lines"}}) {
2652 my $line = $d->{"line_number"};
2653 my $count = $d->{"count"};
2654
2655 my $branches = $d->{"branches"};
2656 my $unexec = $d->{"unexecuted_block"};
2657 my $conditions = $d->{'conditions'}
2658 if $lcovutil::mcdc_coverage && exists($d->{'conditions'});
2659
2660 next
2661 if (!defined($line) || !defined($count));
2662
2663 if (0 == scalar(@$branches) && $unexec && $count != 0) {
2664 lcovutil::debug(
2665 "$filename:$line: unexecuted block on non-branch line with count=$count\n"
2666 );
2667 if ($lcovutil::opt_adjust_unexecuted_blocks) {
2668 $count = 0;
2669 } elsif (
2670 lcovutil::warn_once("unexecuted block",
2671 $ERROR_INCONSISTENT_DATA)
2672 ) {
2673 lcovutil::ignorable_warning($ERROR_INCONSISTENT_DATA,
2674 "$filename:$line: unexecuted block on non-branch line with non-zero hit count. Use \"geninfo --rc geninfo_unexecuted_blocks=1 to set count to zero."
2675 );
2676 }
2677 }
2678
2679 # just add the line - worry about filtering later
2680 $lineMap->append($line, $count);
2681
2682 # Branch data
2683 if ($lcovutil::br_coverage) {
2684
2685 # there may be compiler-generated branch data on
2686 # the closing brace of the function...
2687 $branch_num = 0;
2688 $unexec = (defined($unexec) && $unexec && $count == 0);
2689
2690 for my $b (@$branches) {
2691 my $brcount = $b->{"count"};
2692 my $is_exception = $b->{"throw"};
2693 # need to keep track of whether compiler thinks this
2694 # branch is an exception - so we can skip it later.
2695
2696 if (!defined($brcount) || $unexec) {
2697 $brcount = "-";
2698 }
2699 my $entry =
2700 BranchBlock->new($branch_num, $brcount, undef,
2701 defined($is_exception) && $is_exception != 0);
2702 # "block" is always zero for intermediate JSON data
2703 $branchMap->append($line, 0, $entry, $filename);
2704 ++$branch_num;
2705 }
2706 }
2707 if ($conditions && @$conditions) {
2708 #die("unexpected multiple conditions at $line") if scalar(@$conditions) > 1;
2709 #lcovutil::debug(1, "MCDC at $filename:$line\n");
2710 my $mcdc = $mcdcMap->new_mcdc($fileData, $line);
2711
2712 foreach my $c (@$conditions) {
2713 my $count = $c->{count};
2714 my $exprs = $count / 2;
2715 my $coverage = $c->{covered};
2716 my $false = $c->{not_covered_false};
2717 my $true = $c->{not_covered_true};
2718 die("expected even condition count: $count") if $count % 2;
2719 my @true;
2720 my @false;
2721
2722 foreach my $m (sort @$false) {
2723 $false[$m] = 0;
2724 }
2725 foreach my $m (sort @$true) {
2726 $true[$m] = 0;
2727 }
2728 for (my $i = 0; $i < $exprs; ++$i) {
2729 $mcdc->insertExpr($filename, $exprs, 0,
2730 !defined($false[$i]),
2731 $i, $i);
2732 $mcdc->insertExpr($filename, $exprs, 1,
2733 !defined($true[$i]),
2734 $i, $i);
2735 }
2736 }
2737 $mcdcMap->close_mcdcBlock($mcdc);
2738 }
2739 }
2740 # now go through lines, functions, branches - append to test_name data
2741 $fileData->sum()->union($lineMap);
2742 $fileData->sumbr()->union($branchMap);
2743 $fileData->mcdc()->union($mcdcMap);
2744 $fileData->func()->union($functionMap);
2745 }
2746 return $traceFile;
2747 }
2748
2749 sub which($)
2750 {
2751 my $filename = shift;
2752
2753 return $filename if (file_name_is_absolute($filename));
2754 foreach my $dir (File::Spec->path()) {
2755 my $p = catfile($dir, $filename);
2756 return $p if (-x $p);
2757 }
2758 return $filename;
2759 }
2760
2761 sub check_gcov_fail($$)
2762 {
2763 my ($msg, $filename) = @_;
2764
2765 if ($msg =~ /version\s+'([^']+)',\s+prefer\s+'([^']+)'/) {
2766 my $have = $1;
2767 my $want = $2;
2768 foreach my $f (\$have, \$want) {
2769 if ($$f =~ /^(.)0(.)\*$/) {
2770 # version ID numbering in the gcda/gcno file is not entirely
2771 # clear to me - but it appears to be "major.0.minor" - where
2772 # major is integral for versions older than gcc/10, and hex +1
2773 # for versions after gcc/10.
2774 my $major =
2775 (ord($1) >= ord('A')) ? (ord($1) - ord('A') + 9) : $1;
2776 $$f = sprintf("%d.%d", $major, $2);
2777 }
2778 }
2779 my $path = which($gcov_tool[0]);
2780 lcovutil::ignorable_error($lcovutil::ERROR_VERSION,
2781 "Incompatible GCC/GCOV version found while processing $filename:\n\tYour test was built with '$have'.\n\tYou are trying to capture with gcov tool '$path' which is version '$want'."
2782 );
2783 return 1;
2784 }
2785 return 0;
2786 }
2787
2788 #
2789 # print_gcov_warnings(type, stderr_file, is_graph, map)
2790 #
2791 # Print GCOV warnings in file STDERR_FILE to STDERR. If IS_GRAPH is non-zero,
2792 # suppress warnings about missing as these are expected. Replace keys found
2793 # in MAP with their values.
2794 #
2795
2796 sub print_gcov_warnings($$$$)
2797 {
2798 my ($type, $data, $is_graph, $map) = @_;
2799
2800 my $leader = "$type:\n ";
2801 foreach my $line (split('\n', $data)) {
2802 next if ($is_graph && $line =~ /cannot open data file/);
2803
2804 for my $key (keys(%{$map})) {
2805 $line =~ s/\Q$key\E/$map->{$key}/g;
2806 }
2807
2808 print(STDERR $leader, $line, "\n");
2809 $leader = ' ';
2810 }
2811 }
2812
2813 #
2814 # process_intermediate(directory, file, gcno_file, tempdir)
2815 #
2816 # Create output for a single file (either a data file or a graph file) using
2817 # gcov's intermediate option.
2818 #
2819
2820 sub process_intermediate($$$$)
2821 {
2822 my ($searchdir, $file, $gcno_file, $tempdir) = @_;
2823 my $data_file;
2824 my $errmsg;
2825 my $errorType = $lcovutil::ERROR_GCOV;
2826 my %data;
2827 my $base;
2828 my $json_basedir;
2829 my $json_format;
2830
2831 my $filename = defined($file) ? $file : $gcno_file;
2832 $file = solve_relative_path($cwd, $filename);
2833 my ($fdir, $fbase, $fext) = split_filename($file);
2834
2835 my $is_graph = (".$fext" eq $graph_file_extension);
2836
2837 if ($is_graph) {
2838 # Process graph file - copy to temp directory to prevent
2839 # accidental processing of associated data file
2840 $data_file =
2841 File::Spec->catfile($tempdir, "$fbase$graph_file_extension");
2842 if (!copy($file, $data_file)) {
2843 $errmsg = "ERROR: Could not copy file $file: $!";
2844 $errorType = $lcovutil::ERROR_PATH;
2845 goto err;
2846 }
2847 } else {
2848 $gcno_file = solve_relative_path($cwd, $gcno_file);
2849 foreach my $f ($file, $gcno_file) {
2850 my $p = -l $f ? Cwd::abs_path($f) : $f;
2851 if (!-r $p) {
2852 $errmsg = "$f does not exist/is not readable";
2853 $errorType = $lcovutil::ERROR_PATH;
2854 goto err;
2855 }
2856 }
2857 # if .gcda and .gcno files are in the same directory, then simply
2858 # process in place - otherwise, link the .gcda and .gcno files
2859 # into tempdir and run from here
2860 if (dirname($file) eq dirname($gcno_file)) {
2861 # Process data file in place
2862 $data_file = $file;
2863 } else {
2864 $data_file = basename($file);
2865 foreach my $f ($file, $gcno_file) {
2866 my $l = File::Spec->catfile($tempdir, basename($f));
2867 debug("create links to process $f in $tempdir\n");
2868 symlink($f, $l);
2869 # unclear why symlink returns an error code when it actually
2870 # created the link
2871 if ($? && !-l $l) {
2872 $errmsg = "unable to create link for $f: $!";
2873 goto err;
2874 }
2875 }
2876 }
2877 }
2878
2879 # Change directory
2880 debug(2, "chdir to tempdir $tempdir\n");
2881 if (!chdir($tempdir)) {
2882 $errmsg = "Could not change to directory $tempdir: $!";
2883 goto err;
2884 }
2885
2886 # Run gcov on data file
2887 debug("gcov: " . join(' ', @gcov_tool) . " $data_file\n");
2888 my $now = Time::HiRes::gettimeofday();
2889 my ($out, $err, $rc) = system_no_output(1 + 2 + 4, @gcov_tool, $data_file);
2890 my $then = Time::HiRes::gettimeofday();
2891 $lcovutil::profileData{exec}{$filename} = $then - $now;
2892 print_gcov_warnings('stdout', $out, $is_graph, {$data_file => $file,})
2893 if ('' ne $out &&
2894 (0 != $rc ||
2895 $lcovutil::verbose > 1));
2896 unlink($out);
2897 debug(2, "chdir back to '$cwd'\n");
2898 chdir($cwd) or die("can't cd back to $cwd: $!");
2899 print_gcov_warnings('stderr', $err, $is_graph, {$data_file => $file,})
2900 if ('' ne $err &&
2901 (0 != $rc ||
2902 $lcovutil::verbose));
2903
2904 my $gcovOutGlobPattern =
2905 "$tempdir/*.gcov $tempdir/.*.gcov $tempdir/*.gcov.json.gz $tempdir/.*gcov.json.gz";
2906
2907 if (0 != $rc) {
2908 if (check_gcov_fail($err, $file)) {
2909 return;
2910 }
2911 $errmsg = "GCOV failed for $file";
2912 # can parse the error log to see if it spaced out - then return
2913 # code so parent can catch it
2914 if ($err =~ /out of memory allocating/) {
2915 lcovutil::info("spaceout calling gcov for '$data_file'\n");
2916 $errmsg .= ' out of memory';
2917 $errorType = $lcovutil::ERROR_CHILD
2918 if 1 != $lcovutil::maxParallelism;
2919 }
2920 goto err;
2921 }
2922
2923 if ($is_graph) {
2924 # Remove graph file copy
2925 unlink($data_file) unless $lcovutil::preserve_intermediates;
2926 }
2927
2928 # Parse resulting file(s)
2929 # 'meson' build system likes to use "." as leading character in generated
2930 # files. Seems an unfortunate decision.
2931 my $start = Time::HiRes::gettimeofday();
2932 for my $gcov_filename (glob($gcovOutGlobPattern)) {
2933 eval {
2934 if ($gcov_filename =~ /\.gcov\.json/) {
2935 read_intermediate_json($gcov_filename, \%data, \$json_basedir);
2936 $json_format = 1;
2937 } else {
2938 read_intermediate_text($gcov_filename, \%data);
2939 }
2940 if ($lcovutil::preserve_intermediates) {
2941 File::Copy::move($gcov_filename, $fdir) or
2942 die("cannot rename $gcov_filename: $!");
2943 } else {
2944 unlink($gcov_filename);
2945 }
2946 };
2947 if ($@) {
2948 if (1 != $lcovutil::maxParallelism &&
2949 $@ =~ /(integrity check failed|cannot start)/) {
2950 # looks like we ran out of memory..
2951 # maybe need new error type ERROR_MEMORY
2952 #$errorType = $lcovutil::ERROR_GCOV;
2953 $errmsg = $@;
2954 goto err;
2955 } else {
2956 die("read_intermediate failed: $@");
2957 }
2958 }
2959 }
2960 my $end = Time::HiRes::gettimeofday();
2961 $lcovutil::profileData{read}{$filename} = $end - $start;
2962
2963 if (!%data) {
2964 ignorable_warning($ERROR_GCOV,
2965 "GCOV did not produce any data for $file");
2966 return;
2967 }
2968
2969 # Determine base directory
2970 if (defined($base_directory)) {
2971 $base = $base_directory;
2972 } elsif (defined($json_basedir)) {
2973 $base = $json_basedir;
2974 } else {
2975 $base = $fdir;
2976
2977 if (is_compat($COMPAT_MODE_LIBTOOL)) {
2978 # Avoid files from .libs dirs
2979 $base =~ s/\.libs$//;
2980 }
2981
2982 # Try to find base directory automatically if requested by user
2983 if ($lcovutil::rc_auto_base) {
2984 $base = find_base_from_source($base, [keys(%data)]);
2985 }
2986 }
2987
2988 # Apply base file name to relative source files
2989 adjust_source_filenames(\%data, $base);
2990
2991 # Remove excluded source files
2992 filter_source_files(\%data);
2993
2994 # Generate output
2995 my $trace =
2996 $json_format ? intermediate_json_to_info(\%data) :
2997 intermediate_text_to_info(\%data);
2998 my $done = Time::HiRes::gettimeofday();
2999 $lcovutil::profileData{translate}{$filename} = $done - $end;
3000
3001 return $trace;
3002
3003 err:
3004 unlink(glob($gcovOutGlobPattern)); # clean up - in case gcov died
3005 ignorable_error($errorType, "$errmsg!");
3006 return undef;
3007 }
3008
3009 # Map LLVM versions to the version of GCC gcov which they emulate.
3010
3011 sub map_llvm_version($)
3012 {
3013 my $ver = shift;
3014
3015 return 0x040200 if ($ver >= 0x030400);
3016
3017 warn("This version of LLVM's gcov is unknown. " .
3018 "Assuming it emulates GCC gcov version 4.2.\n");
3019
3020 return 0x040200;
3021 }
3022
3023 # Return a readable version of encoded gcov version.
3024
3025 sub version_to_str($)
3026 {
3027 my $ver = shift;
3028
3029 my $a = $ver >> 16 & 0xff;
3030 my $b = $ver >> 8 & 0xff;
3031 my $c = $ver & 0xff;
3032
3033 return "$a.$b.$c";
3034 }
3035
3036 #
3037 # Get the GCOV tool version. Return an integer number which represents the
3038 # GCOV version. Version numbers can be compared using standard integer
3039 # operations.
3040 #
3041
3042 sub get_gcov_version()
3043 {
3044 local *HANDLE;
3045 my ($a, $b, $c) = (4, 2, 0); # Fallback version
3046
3047 # Examples for gcov version output:
3048 #
3049 # gcov (GCC) 4.4.7 20120313 (Red Hat 4.4.7-3)
3050 #
3051 # gcov (crosstool-NG 1.18.0) 4.7.2
3052 #
3053 # LLVM (http://llvm.org/):
3054 # LLVM version 3.4svn
3055 #
3056 # Apple LLVM version 8.0.0 (clang-800.0.38)
3057 # Optimized build.
3058 # Default target: x86_64-apple-darwin16.0.0
3059 # Host CPU: haswell
3060
3061 if ($lcovutil::verbose) {
3062 my $which = which($gcov_tool[0]);
3063 lcovutil::info("gcov is '$which'\n");
3064 }
3065
3066 open(GCOV_PIPE, "-|", "\"$gcov_tool[0]\" --version") or
3067 die("cannot retrieve gcov version: $!\n");
3068 local $/;
3069 my $version_string = <GCOV_PIPE>;
3070 close(GCOV_PIPE) or die("unable to close gcov pipe: $!\n");
3071
3072 # Remove all bracketed information
3073 $version_string =~ s/\([^\)]*\)//g;
3074
3075 if ($version_string =~ /(\d+)\.(\d+)(\.(\d+))?/) {
3076 ($a, $b, $c) = ($1, $2, $4);
3077 $c = 0 if (!defined($c));
3078 $version_string = (split('\n', $version_string))[0];
3079 chomp($version_string);
3080 } else {
3081 warn("cannot determine gcov version - assuming $a.$b.$c\n");
3082 }
3083 my $result = $a << 16 | $b << 8 | $c;
3084
3085 if ($version_string =~ /LLVM/) {
3086 $result = map_llvm_version($result);
3087 info("Found LLVM gcov version $a.$b.$c, which emulates gcov " .
3088 "version " . version_to_str($result) . "\n");
3089 } else {
3090 info("Found gcov version: " . version_to_str($result) . "\n");
3091 }
3092
3093 return ($result, $version_string);
3094 }
3095
3096 #
3097 # info(printf_parameter)
3098 #
3099 # Use printf to write PRINTF_PARAMETER to stdout only when not --quiet
3100 #
3101
3102 sub my_info(@)
3103 {
3104 # Print info string
3105 if (defined($output_filename) && ($output_filename eq "-")) {
3106 # Don't interfere with the .info output to STDOUT
3107 printf(STDERR @_);
3108 } else {
3109 printf(@_);
3110 }
3111 }
3112
3113 #
3114 # int_handler()
3115 #
3116 # Called when the script was interrupted by an INT signal (e.g. CTRl-C)
3117 #
3118
3119 sub int_handler()
3120 {
3121 if ($cwd) { chdir($cwd); }
3122 info("Aborted.\n");
3123 exit(1);
3124 }
3125
3126 sub process_graphfile($$)
3127 {
3128 my ($dirname, $file) = @_;
3129 my $graph_filename = $file;
3130 my $source_dir;
3131 my $base_dir;
3132
3133 # Get path to data file in absolute and normalized form (begins with /,
3134 # contains no more ../ or ./)
3135 $graph_filename = solve_relative_path($cwd, $graph_filename);
3136
3137 # Get directory and basename of data file
3138 my ($graph_dir, $graph_basename) = split_filename($graph_filename);
3139
3140 $source_dir = $graph_dir;
3141 if (is_compat($COMPAT_MODE_LIBTOOL)) {
3142 # Avoid files from .libs dirs
3143 $source_dir =~ s/\.libs$//;
3144 }
3145
3146 # Construct base_dir for current file
3147 if ($base_directory) {
3148 $base_dir = $base_directory;
3149 } else {
3150 $base_dir = $source_dir;
3151 }
3152
3153 # Ignore empty graph file (e.g. source file with no statement)
3154 if (-z $graph_filename) {
3155 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
3156 "empty $graph_filename");
3157 return undef;
3158 }
3159
3160 my ($instr, $graph) = read_gcno($graph_filename);
3161
3162 # Try to find base directory automatically if requested by user
3163 if ($lcovutil::rc_auto_base) {
3164 $base_dir = find_base_from_source($base_dir,
3165 [keys(%{$instr}), keys(%{$graph})]);
3166 }
3167
3168 adjust_source_filenames($instr, $base_dir);
3169 adjust_source_filenames($graph, $base_dir);
3170
3171 my $traceFile = TraceFile->new();
3172 foreach my $filename (sort(keys(%{$instr}))) {
3173 my $funcdata = $graph->{$filename};
3174 my $line;
3175 my $linedata;
3176
3177 # Skip external files if requested
3178 if (is_external($filename)) {
3179 info(" ignoring data for external file $filename\n");
3180 next;
3181 }
3182 # there is no meaningful parse location for this data
3183 my $fileData = $traceFile->data($filename);
3184 my $functionMap = $fileData->testfnc($test_name);
3185 my $lineMap = $fileData->test($test_name);
3186
3187 if (@lcovutil::extractVersionScript) {
3188 my $version = lcovutil::extractFileVersion($filename);
3189 $fileData->version($version)
3190 if (defined($version) && $version ne "");
3191 }
3192 if (defined($funcdata) && $lcovutil::func_coverage) {
3193 my @functions =
3194 sort({ $funcdata->{$a}->[0] <=> $funcdata->{$b}->[0] }
3195 keys(%{$funcdata}));
3196 # Gather list of instrumented lines and functions
3197 foreach my $func (@functions) {
3198 $linedata = $funcdata->{$func};
3199 my $lineNo = $linedata->[0];
3200 my $fnName =
3201 filter_fn_name($func, defined($lcovutil::demangle_cpp_cmd));
3202 my $func = $functionMap->define_function($fnName, $lineNo);
3203 $func->addAlias($fnName, 0);
3204 }
3205 }
3206 # Print zero line coverage data
3207 foreach $line (@{$instr->{$filename}}) {
3208 $lineMap->append($line, 0);
3209 }
3210 # now go through lines, functions, branches - append to test_name data
3211 $fileData->sum()->union($lineMap);
3212 $fileData->func()->union($functionMap);
3213 }
3214 return $traceFile;
3215 }
3216
3217 sub filter_fn_name($$)
3218 {
3219 my ($fn, $demangle) = @_;
3220 my $f;
3221 if ($demangle) {
3222 $f = `$lcovutil::demangle_cpp_cmd $fn`;
3223 chomp($f);
3224 die("unable to demangle '$fn': $!") if ($?);
3225 } else {
3226 $f = $fn;
3227 }
3228 # Remove characters used internally as function name delimiters
3229 $f =~ s/[,=]/_/g;
3230
3231 return $f;
3232 }
3233
3234 #
3235 # graph_error(filename, message)
3236 #
3237 # Print message about error in graph file. If ignore_graph_error is set, return.
3238 # Otherwise abort.
3239 #
3240
3241 sub graph_error($$)
3242 {
3243 my ($filename, $msg) = @_;
3244
3245 ignorable_error($ERROR_GRAPH,
3246 "$filename: $msg"
3247 .
3248 (lcovutil::is_ignored($ERROR_GRAPH) ? ' - skipping' : ''
3249 ) .
3250 '.');
3251 }
3252
3253 #
3254 # graph_read(handle, bytes[, description, peek])
3255 #
3256 # Read and return the specified number of bytes from handle. Return undef
3257 # if the number of bytes could not be read. If PEEK is non-zero, reset
3258 # file position after read.
3259 #
3260
3261 sub graph_read(*$;$$)
3262 {
3263 my ($handle, $length, $desc, $peek) = @_;
3264 my $data;
3265 my $pos;
3266
3267 lcovutil::debug(2, $desc);
3268 if ($peek) {
3269 $pos = tell($handle);
3270 if ($pos == -1) {
3271 lcovutil::ignorable_error($lcovutil::ERROR_CORRUPT,
3272 "Could not get current file position: $!");
3273 return undef;
3274 }
3275 }
3276 my $result = read($handle, $data, $length);
3277 # LCOV_EXCL_START
3278 if ($debug &&
3279 $debug >= 2) {
3280 my $op = $peek ? "peek" : "read";
3281 my $ascii = "";
3282 my $hex = "";
3283 my $i;
3284
3285 my $msg = "$op($length)=$result: ";
3286 for ($i = 0; $i < length($data); $i++) {
3287 my $c = substr($data, $i, 1);
3288 my $n = ord($c);
3289
3290 $hex .= sprintf("%02x ", $n);
3291 if ($n >= 32 && $n <= 127) {
3292 $ascii .= $c;
3293 } else {
3294 $ascii .= ".";
3295 }
3296 }
3297 lcovutil::debug(2, "$msg$hex |$ascii|\n");
3298 }
3299 # LCOV_EXCL_STOP
3300 if ($peek) {
3301 if (!seek($handle, $pos, 0)) {
3302 lcovutil::ignorable_error($lcovutil::ERROR_CORRUPT,
3303 "Could not set file position: $!");
3304 return undef;
3305 }
3306 }
3307 if ($result != $length) {
3308 return undef;
3309 }
3310 return $data;
3311 }
3312
3313 #
3314 # graph_skip(handle, bytes[, description])
3315 #
3316 # Read and discard the specified number of bytes from handle. Return non-zero
3317 # if bytes could be read, zero otherwise.
3318 #
3319
3320 sub graph_skip(*$;$)
3321 {
3322 my ($handle, $length, $desc) = @_;
3323
3324 return defined(graph_read($handle, $length, $desc));
3325 }
3326
3327 #
3328 # uniq(list)
3329 #
3330 # Return list without duplicate entries.
3331 #
3332
3333 sub uniq(@)
3334 {
3335 my @new_list;
3336 my %known;
3337
3338 foreach my $item (@_) {
3339 next if ($known{$item});
3340 $known{$item} = 1;
3341 push(@new_list, $item);
3342 }
3343
3344 return @new_list;
3345 }
3346
3347 #
3348 # sort_uniq(list)
3349 #
3350 # Return list in numerically ascending order and without duplicate entries.
3351 #
3352
3353 sub sort_uniq(@)
3354 {
3355 my %hash;
3356
3357 foreach (@_) {
3358 $hash{$_} = 1;
3359 }
3360 return sort { $a <=> $b } keys(%hash);
3361 }
3362
3363 #
3364 # parent_dir(dir)
3365 #
3366 # Return parent directory for DIR. DIR must not contain relative path
3367 # components.
3368 #
3369
3370 sub parent_dir($)
3371 {
3372 my $dir = shift;
3373 my ($v, $d, $f) = splitpath($dir, 1);
3374 my @dirs = splitdir($d);
3375
3376 pop(@dirs);
3377
3378 return catpath($v, catdir(@dirs), $f);
3379 }
3380
3381 #
3382 # find_base_from_source(base_dir, source_files)
3383 #
3384 # Try to determine the base directory of the object file built from
3385 # SOURCE_FILES. The base directory is the base for all relative filenames in
3386 # the gcov data. It is defined by the current working directory at time
3387 # of compiling the source file.
3388 #
3389 # This function implements a heuristic which relies on the following
3390 # assumptions:
3391 # - all files used for compilation are still present at their location
3392 # - the base directory is either BASE_DIR or one of its parent directories
3393 # - files by the same name are not present in multiple parent directories
3394 #
3395
3396 sub find_base_from_source($$)
3397 {
3398 my ($base_dir, $source_files) = @_;
3399 my $old_base;
3400 my $best_miss;
3401 my $best_base;
3402 my %rel_files;
3403
3404 # Determine list of relative paths
3405 foreach my $filename (@$source_files) {
3406 next if (file_name_is_absolute($filename));
3407
3408 $rel_files{$filename} = 1;
3409 }
3410
3411 # Early exit if there are no relative paths
3412 return $base_dir if (!%rel_files);
3413
3414 do {
3415 my $miss = 0;
3416
3417 foreach my $filename (keys(%rel_files)) {
3418 if (!-e solve_relative_path($base_dir, $filename)) {
3419 $miss++;
3420 }
3421 }
3422
3423 debug("base_dir=$base_dir miss=$miss\n");
3424
3425 # Exit if we find an exact match with no misses
3426 return $base_dir if ($miss == 0);
3427
3428 # No exact match, aim for the one with the least source file
3429 # misses
3430 if (!defined($best_base) || $miss < $best_miss) {
3431 $best_base = $base_dir;
3432 $best_miss = $miss;
3433 }
3434
3435 # Repeat until there's no more parent directory
3436 $old_base = $base_dir;
3437 $base_dir = parent_dir($base_dir);
3438 } while ($old_base ne $base_dir);
3439
3440 return $best_base;
3441 }
3442
3443 #
3444 # adjust_source_filenames(hash, base_dir)
3445 #
3446 # Transform all keys of HASH to absolute form and apply requested
3447 # transformations.
3448 #
3449
3450 sub adjust_source_filenames($$$)
3451 {
3452 my ($hash, $base_dir) = @_;
3453
3454 foreach my $filename (keys(%{$hash})) {
3455 my $old_filename = $filename;
3456
3457 # Convert to absolute canonical form
3458 $filename = solve_relative_path($base_dir, $filename);
3459
3460 # Apply adjustment
3461 $filename = ReadCurrentSource::resolve_path($filename, 1);
3462 if ($lcovutil::opt_follow && $lcovutil::opt_follow_file_links) {
3463 $filename = Cwd::realpath($filename);
3464 }
3465
3466 if ($filename ne $old_filename) {
3467 $hash->{$filename} = delete($hash->{$old_filename});
3468 }
3469 }
3470 }
3471
3472 #
3473 # filter_source_files(hash)
3474 #
3475 # Remove unwanted source file data from HASH.
3476 #
3477
3478 sub filter_source_files($)
3479 {
3480 my $hash = shift;
3481
3482 foreach my $filename (keys(%{$hash})) {
3483 # Skip external files if requested
3484 my $external = is_external($filename);
3485 if ($external ||
3486 TraceFile::skipCurrentFile($filename)) {
3487 if ($external) {
3488 lcovutil::info("Dropping 'external' file '$filename'\n");
3489 } else {
3490 lcovutil::info("Excluding file '$filename'\n");
3491 }
3492 # Remove file data
3493 delete($hash->{$filename});
3494 $lcovutil::excluded_files{$filename} = 1;
3495 }
3496 }
3497 }
3498
3499 #
3500 # graph_cleanup(graph)
3501 #
3502 # Remove entries for functions with no lines. Remove duplicate line numbers.
3503 # Sort list of line numbers numerically ascending.
3504 #
3505
3506 sub graph_cleanup($)
3507 {
3508 my $graph = shift;
3509 my $filename;
3510
3511 foreach $filename (keys(%{$graph})) {
3512 my $per_file = $graph->{$filename};
3513 my $function;
3514
3515 foreach $function (keys(%{$per_file})) {
3516 my $lines = $per_file->{$function};
3517
3518 if (scalar(@$lines) == 0) {
3519 # Remove empty function
3520 delete($per_file->{$function});
3521 next;
3522 }
3523 # Normalize list
3524 $per_file->{$function} = [uniq(@$lines)];
3525 }
3526 if (scalar(keys(%{$per_file})) == 0) {
3527 # Remove empty file
3528 delete($graph->{$filename});
3529 }
3530 }
3531 }
3532
3533 #
3534 # graph_find_base(bb)
3535 #
3536 # Try to identify the filename which is the base source file for the
3537 # specified bb data.
3538 #
3539
3540 sub graph_find_base($)
3541 {
3542 my $bb = shift;
3543 my %file_count;
3544 my $basefile;
3545
3546 # Identify base name for this bb data.
3547 foreach my $func (keys(%{$bb})) {
3548 my $filedata = $bb->{$func};
3549
3550 foreach my $file (keys(%{$filedata})) {
3551 my $count = $file_count{$file};
3552
3553 # Count file occurrence
3554 $file_count{$file} = defined($count) ? $count + 1 : 1;
3555 }
3556 }
3557 my $count = 0;
3558 foreach my $file (keys(%file_count)) {
3559 if ($file_count{$file} > $count) {
3560 # The file that contains code for the most functions
3561 # is likely the base file
3562 $count = $file_count{$file};
3563 $basefile = $file;
3564 } elsif ($file_count{$file} == $count) {
3565 # If more than one file could be the basefile, we
3566 # don't have a basefile
3567 $basefile = undef;
3568 }
3569 }
3570
3571 return $basefile;
3572 }
3573
3574 #
3575 # graph_from_bb(bb, fileorder, bb_filename, fileorder_first)
3576 #
3577 # Convert data from bb to the graph format and list of instrumented lines.
3578 #
3579 # If FILEORDER_FIRST is set, use fileorder data to determine a functions
3580 # base source file.
3581 #
3582 # Returns (instr, graph).
3583 #
3584 # bb : function name -> file data
3585 # : undef -> file order
3586 # file data : filename -> line data
3587 # line data : [ line1, line2, ... ]
3588 #
3589 # file order : function name -> [ filename1, filename2, ... ]
3590 #
3591 # graph : file name -> function data
3592 # function data : function name -> line data
3593 # line data : [ line1, line2, ... ]
3594 #
3595 # instr : filename -> line data
3596 # line data : [ line1, line2, ... ]
3597 #
3598
3599 sub graph_from_bb($$$$)
3600 {
3601 my ($bb, $fileorder, $bb_filename, $fileorder_first) = @_;
3602 my $graph = {};
3603 my $instr = {};
3604
3605 my $basefile = graph_find_base($bb);
3606 # Create graph structure
3607 foreach my $func (keys(%{$bb})) {
3608 my $filedata = $bb->{$func};
3609 my $order = $fileorder->{$func};
3610
3611 # Account for lines in functions
3612 if (defined($basefile) &&
3613 defined($filedata->{$basefile}) &&
3614 !$fileorder_first) {
3615 # If the basefile contributes to this function,
3616 # account this function to the basefile.
3617 $graph->{$basefile}->{$func} = $filedata->{$basefile};
3618 } else {
3619 # If the basefile does not contribute to this function,
3620 # account this function to the first file contributing
3621 # lines.
3622 $graph->{$order->[0]}->{$func} =
3623 $filedata->{$order->[0]};
3624 }
3625
3626 foreach my $file (keys(%{$filedata})) {
3627 # Account for instrumented lines
3628 my $linedata = $filedata->{$file};
3629 push(@{$instr->{$file}}, @$linedata);
3630 }
3631 }
3632 # Clean up array of instrumented lines
3633 foreach my $file (keys(%{$instr})) {
3634 $instr->{$file} = [sort_uniq(@{$instr->{$file}})];
3635 }
3636
3637 return ($instr, $graph);
3638 }
3639
3640 #
3641 # graph_add_order(fileorder, function, filename)
3642 #
3643 # Add an entry for filename to the fileorder data set for function.
3644 #
3645
3646 sub graph_add_order($$$)
3647 {
3648 my ($fileorder, $function, $filename) = @_;
3649
3650 my $list = $fileorder->{$function};
3651 foreach my $item (@$list) {
3652 if ($item eq $filename) {
3653 return;
3654 }
3655 }
3656 push(@$list, $filename);
3657 $fileorder->{$function} = $list;
3658 }
3659
3660 #
3661 # read_gcno_word(handle[, description, peek])
3662 #
3663 # Read and return a word in .gcno format.
3664 #
3665
3666 sub read_gcno_word(*;$$)
3667 {
3668 my ($handle, $desc, $peek) = @_;
3669
3670 return graph_read($handle, 4, $desc, $peek);
3671 }
3672
3673 #
3674 # read_gcno_value(handle, big_endian[, description, peek])
3675 #
3676 # Read a word in .gcno format from handle and return its integer value
3677 # according to the specified endianness. If PEEK is non-zero, reset file
3678 # position after read.
3679 #
3680
3681 sub read_gcno_value(*$;$$)
3682 {
3683 my ($handle, $big_endian, $desc, $peek) = @_;
3684
3685 my $word = read_gcno_word($handle, $desc, $peek);
3686 return undef unless defined($word);
3687 return unpack($big_endian ? 'N' : 'V', $word);
3688 }
3689
3690 #
3691 # read_gcno_string(handle, big_endian)
3692 #
3693 # Read and return a string in .gcno format.
3694 #
3695
3696 sub read_gcno_string(*$)
3697 {
3698 my ($handle, $big_endian) = @_;
3699
3700 lcovutil::debug(2, "string");
3701 # Read string length
3702 my $length = read_gcno_value($handle, $big_endian, "string length");
3703 return undef if (!defined($length));
3704 if ($length == 0) {
3705 return "";
3706 }
3707 $length *= 4;
3708 # Read string
3709 my $string = graph_read($handle, $length, "string and padding");
3710 return undef if (!defined($string));
3711 $string =~ s/\0//g;
3712
3713 return $string;
3714 }
3715
3716 #
3717 # read_gcno_lines_record(handle, gcno_filename, bb, fileorder, filename,
3718 # function, big_endian)
3719 #
3720 # Read a gcno format lines record from handle and add the relevant data to
3721 # bb and fileorder. Return filename on success, undef on error.
3722 #
3723
3724 sub read_gcno_lines_record(*$$$$$$)
3725 {
3726 my ($handle, $gcno_filename, $bb, $fileorder, $filename, $function,
3727 $big_endian)
3728 = @_;
3729
3730 lcovutil::debug(2, "lines record");
3731 # Skip basic block index
3732 graph_skip($handle, 4, "basic block index") or return undef;
3733 while (1) {
3734 # Read line number
3735 my $lineno = read_gcno_value($handle, $big_endian, "line number");
3736 return undef if (!defined($lineno));
3737 if ($lineno == 0) {
3738 # Got a marker for a new filename
3739 lcovutil::debug(2, "filename");
3740 my $string = read_gcno_string($handle, $big_endian);
3741 return undef if (!defined($string));
3742 # Check for end of record
3743 if ($string eq "") {
3744 return $filename;
3745 }
3746 $filename = $string;
3747 if (!exists($bb->{$function}->{$filename})) {
3748 $bb->{$function}->{$filename} = [];
3749 }
3750 next;
3751 }
3752 # Got an actual line number
3753 if (!defined($filename)) {
3754 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
3755 "unassigned line number in $gcno_filename");
3756 next;
3757 }
3758 # Add to list
3759 push(@{$bb->{$function}->{$filename}}, $lineno);
3760 graph_add_order($fileorder, $function, $filename);
3761 }
3762 }
3763
3764 #
3765 # read_gcno_function_record(handle, graph, big_endian, rec_length, version)
3766 #
3767 # Read a gcno format function record from handle and add the relevant data
3768 # to graph. Return (filename, function, artificial) on success, undef on error.
3769 #
3770
3771 sub read_gcno_function_record(*$$$$$)
3772 {
3773 my ($handle, $bb, $fileorder, $big_endian, $rec_length, $version) = @_;
3774 my $artificial;
3775
3776 lcovutil::debug(2, "function record");
3777 # Skip ident and checksum
3778 graph_skip($handle, 8, "function ident and checksum") or return undef;
3779 # must be gcc > 4 - so only split checksum exists
3780 graph_skip($handle, 4, "function cfg checksum");
3781 # Read function name
3782 lcovutil::debug(2, "function name");
3783 my $function = read_gcno_string($handle, $big_endian);
3784 return undef if (!defined($function));
3785 if ($version >= $GCOV_VERSION_8_0_0) {
3786 $artificial = read_gcno_value($handle, $big_endian,
3787 "compiler-generated entity flag");
3788 return undef if (!defined($artificial));
3789 }
3790 # Read filename
3791 lcovutil::debug(2, "filename");
3792 my $filename = read_gcno_string($handle, $big_endian);
3793 return undef if (!defined($filename));
3794 # Read first line number
3795 my $lineno = read_gcno_value($handle, $big_endian, "initial line number");
3796 return undef if (!defined($lineno));
3797 # Skip column and ending line number
3798 if ($version >= $GCOV_VERSION_8_0_0) {
3799 graph_skip($handle, 4, "column number") or return undef;
3800 graph_skip($handle, 4, "ending line number") or return undef;
3801 }
3802 # Add to list
3803 push(@{$bb->{$function}->{$filename}}, $lineno);
3804 graph_add_order($fileorder, $function, $filename);
3805
3806 return ($filename, $function, $artificial);
3807 }
3808
3809 #
3810 # map_gcno_version
3811 #
3812 # Map version number as found in .gcno files to the format used in geninfo.
3813 #
3814
3815 sub map_gcno_version($)
3816 {
3817 my $version = shift;
3818 my ($major, $minor);
3819
3820 my $a = $version >> 24;
3821 my $b = $version >> 16 & 0xff;
3822 my $c = $version >> 8 & 0xff;
3823
3824 if ($a < ord('A')) {
3825 $major = $a - ord('0');
3826 $minor = ($b - ord('0')) * 10 + $c - ord('0');
3827 } else {
3828 $major = ($a - ord('A')) * 10 + $b - ord('0');
3829 $minor = $c - ord('0');
3830 }
3831
3832 return $major << 16 | $minor << 8;
3833 }
3834
3835 sub remove_fn_from_hash($$)
3836 {
3837 my ($hash, $fns) = @_;
3838
3839 foreach my $fn (@$fns) {
3840 delete($hash->{$fn});
3841 }
3842 }
3843
3844 #
3845 # read_gcno(filename)
3846 #
3847 # Read the contents of the specified .gcno file and return the following
3848 # mapping:
3849 # graph: filename -> file_data
3850 # file_data: function name -> line_data
3851 # line_data: [ line1, line2, ... ]
3852 #
3853 # See the gcov-io.h file in the gcc 3.3 source code for a description of
3854 # the .gcno format.
3855 #
3856
3857 sub read_gcno($)
3858 {
3859 my ($gcno_filename) = @_;
3860 my $file_magic = 0x67636e6f;
3861 my $tag_function = 0x01000000;
3862 my $tag_lines = 0x01450000;
3863 my $big_endian;
3864 my $word;
3865 my $tag;
3866 my $length;
3867 my $filename;
3868 my $function;
3869 my $bb = {};
3870 my $fileorder = {};
3871 my $instr;
3872 my $graph;
3873 my $filelength;
3874 my $version;
3875 my $artificial;
3876 my @artificial_fns;
3877 local *HANDLE;
3878
3879 open(HANDLE, "<", $gcno_filename) or goto open_error;
3880 $filelength = (stat(HANDLE))[7];
3881 binmode(HANDLE);
3882 # Read magic
3883 $word = read_gcno_word(*HANDLE, "file magic");
3884 goto incomplete if (!defined($word));
3885 # Determine file endianness
3886 if (unpack("N", $word) == $file_magic) {
3887 $big_endian = 1;
3888 } elsif (unpack("V", $word) == $file_magic) {
3889 $big_endian = 0;
3890 } else {
3891 goto magic_error;
3892 }
3893 # Read version
3894 $version = read_gcno_value(*HANDLE, $big_endian, "compiler version");
3895 $version = map_gcno_version($version);
3896 debug(sprintf("found version 0x%08x\n", $version));
3897 # Skip stamp
3898 graph_skip(*HANDLE, 4, "file timestamp") or goto incomplete;
3899 if ($version >= $GCOV_VERSION_8_0_0) {
3900 graph_skip(*HANDLE, 4, "support unexecuted blocks flag") or
3901 goto incomplete;
3902 }
3903 while (!eof(HANDLE)) {
3904 my $next_pos;
3905 my $curr_pos;
3906
3907 # Read record tag
3908 $tag = read_gcno_value(*HANDLE, $big_endian, "record tag");
3909 goto incomplete if (!defined($tag));
3910 # Read record length
3911 $length = read_gcno_value(*HANDLE, $big_endian, "record length");
3912 goto incomplete if (!defined($length));
3913 # Convert length to bytes
3914 $length *= 4;
3915 # Calculate start of next record
3916 $next_pos = tell(HANDLE);
3917 goto tell_error if ($next_pos == -1);
3918 $next_pos += $length;
3919 # Catch garbage at the end of a gcno file
3920 if ($next_pos > $filelength) {
3921 debug("Overlong record: file_length=$filelength " .
3922 "rec_length=$length\n");
3923 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
3924 "$gcno_filename: Overlong record at end of file");
3925 last;
3926 }
3927 # Process record
3928 if ($tag == $tag_function) {
3929 ($filename, $function, $artificial) =
3930 read_gcno_function_record(*HANDLE, $bb, $fileorder, $big_endian,
3931 $length, $version);
3932 goto incomplete if (!defined($function));
3933 push(@artificial_fns, $function) if ($artificial);
3934 } elsif ($tag == $tag_lines) {
3935 # Read lines record
3936 $filename =
3937 read_gcno_lines_record(*HANDLE, $gcno_filename, $bb, $fileorder,
3938 $filename, $function, $big_endian);
3939 goto incomplete if (!defined($filename));
3940 } else {
3941 # Skip record contents
3942 graph_skip(*HANDLE, $length, "unhandled record") or
3943 goto incomplete;
3944 }
3945 # Ensure that we are at the start of the next record
3946 $curr_pos = tell(HANDLE);
3947 goto tell_error if ($curr_pos == -1);
3948 next if ($curr_pos == $next_pos);
3949 goto record_error if ($curr_pos > $next_pos);
3950 graph_skip(*HANDLE, $next_pos - $curr_pos, "unhandled record content")
3951 or
3952 goto incomplete;
3953 }
3954 close(HANDLE) or die("unable to close $gcno_filename: $!\n");
3955
3956 # Remove artificial functions from result data
3957 remove_fn_from_hash($bb, \@artificial_fns);
3958 remove_fn_from_hash($fileorder, \@artificial_fns);
3959
3960 ($instr, $graph) = graph_from_bb($bb, $fileorder, $gcno_filename, 1);
3961 graph_cleanup($graph);
3962
3963 return ($instr, $graph);
3964
3965 open_error:
3966 graph_error($gcno_filename, "could not open file: $!");
3967 return undef;
3968 incomplete:
3969 graph_error($gcno_filename, "reached unexpected end of file");
3970 return undef;
3971 magic_error:
3972 graph_error($gcno_filename, "found unrecognized gcno file magic");
3973 return undef;
3974 tell_error:
3975 graph_error($gcno_filename, "could not determine file position");
3976 return undef;
3977 record_error:
3978 graph_error($gcno_filename, "found unrecognized record format");
3979 return undef;
3980 }
3981
3982 #
3983 # get_gcov_capabilities
3984 #
3985 # Determine the list of available gcov options.
3986 #
3987
3988 sub get_gcov_capabilities()
3989 {
3990 my $help = join(' ', @gcov_tool) . ' --help';
3991 $help = `$help`;
3992 die("return code from '\"$gcov_tool[0]\" --help': $!")
3993 if ($?);
3994 my %capabilities;
3995 my %short_option_translations = ('a' => 'all-blocks',
3996 'b' => 'branch-probabilities',
3997 'c' => 'branch-counts',
3998 'f' => 'function-summaries',
3999 'h' => 'help',
4000 'i' => 'intermediate-format',
4001 'l' => 'long-file-names',
4002 'n' => 'no-output',
4003 'o' => 'object-directory',
4004 'p' => 'preserve-paths',
4005 'u' => 'unconditional-branches',
4006 'v' => 'version',
4007 'x' => 'hash-filenames',);
4008
4009 foreach (split(/\n/, $help)) {
4010 my $capability;
4011 if (/--(\S+)/) {
4012 $capability = $1;
4013 } else {
4014 # If the line provides a short option, translate it.
4015 next if (!/^\s*-(\S)\s/);
4016 $capability = $short_option_translations{$1};
4017 next if not defined($capability);
4018 }
4019 next if ($capability eq 'help');
4020 next if ($capability eq 'version');
4021 next if ($capability eq 'object-directory');
4022
4023 $capabilities{$capability} = 1;
4024 debug("gcov has capability '$capability'\n");
4025 }
4026
4027 return \%capabilities;
4028 }
4029
4030 #
4031 # compat_name(mode)
4032 #
4033 # Return the name of compatibility mode MODE.
4034 #
4035
4036 sub compat_name($)
4037 {
4038 my $mode = shift;
4039 my $name = $COMPAT_MODE_TO_NAME{$mode};
4040
4041 return $name if (defined($name));
4042
4043 return "<unknown>";
4044 }
4045
4046 #
4047 # parse_compat_modes(opt)
4048 #
4049 # Determine compatibility mode settings.
4050 #
4051
4052 sub parse_compat_modes($)
4053 {
4054 my $opt = shift;
4055 my @opt_list;
4056 my %specified;
4057
4058 # Initialize with defaults
4059 %compat_value = %COMPAT_MODE_DEFAULTS;
4060
4061 # Add old style specifications
4062 if (defined($lcovutil::opt_compat_libtool)) {
4063 $compat_value{$COMPAT_MODE_LIBTOOL} =
4064 $lcovutil::opt_compat_libtool ? $COMPAT_VALUE_ON :
4065 $COMPAT_VALUE_OFF;
4066 }
4067
4068 # Parse settings
4069 if (defined($opt)) {
4070 @opt_list = split(/\s*,\s*/, $opt);
4071 }
4072 foreach my $directive (@opt_list) {
4073 my ($mode, $value);
4074
4075 # Either
4076 # mode=off|on|auto or
4077 # mode (implies on)
4078 if ($directive !~ /^(\w+)=(\w+)$/ &&
4079 $directive !~ /^(\w+)$/) {
4080 die("Unknown compatibility mode specification: " . "$directive!\n");
4081 }
4082 # Determine mode
4083 $mode = $COMPAT_NAME_TO_MODE{lc($1)};
4084 if (!defined($mode)) {
4085 die("Unknown compatibility mode '$1'!\n");
4086 }
4087 $specified{$mode} = 1;
4088 # Determine value
4089 if (defined($2)) {
4090 $value = $COMPAT_NAME_TO_VALUE{lc($2)};
4091 if (!defined($value)) {
4092 die("Unknown compatibility mode value '$2'!\n");
4093 }
4094 } else {
4095 $value = $COMPAT_VALUE_ON;
4096 }
4097 $compat_value{$mode} = $value;
4098 }
4099 # Perform auto-detection
4100 foreach my $mode (sort(keys(%compat_value))) {
4101 my $value = $compat_value{$mode};
4102 my $is_autodetect = "";
4103 my $name = compat_name($mode);
4104
4105 if ($value == $COMPAT_VALUE_AUTO) {
4106 my $autodetect = $COMPAT_MODE_AUTO{$mode};
4107
4108 if (!defined($autodetect)) {
4109 die("No auto-detection for " . "mode '$name' available!\n");
4110 }
4111
4112 if (ref($autodetect) eq "CODE") {
4113 $value = &$autodetect();
4114 $compat_value{$mode} = $value;
4115 $is_autodetect = " (auto-detected)";
4116 }
4117 }
4118
4119 if ($specified{$mode}) {
4120 if ($value == $COMPAT_VALUE_ON) {
4121 info("Enabling compatibility mode '$name'$is_autodetect\n");
4122 } elsif ($value == $COMPAT_VALUE_OFF) {
4123 info("Disabling compatibility mode '$name'$is_autodetect\n");
4124 } else {
4125 info("Using delayed auto-detection for " .
4126 "compatibility mode '$name'\n");
4127 }
4128 }
4129 }
4130 }
4131
4132 #
4133 # is_compat(mode)
4134 #
4135 # Return non-zero if compatibility mode MODE is enabled.
4136 #
4137
4138 sub is_compat($)
4139 {
4140 my $mode = shift;
4141
4142 return $compat_value{$mode} == $COMPAT_VALUE_ON;
4143 }