Debian Codegraph @

bin/genhtml

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 # genhtml
21 #
22 # This script generates HTML output from .info files as created by the
23 # geninfo script. Call it with --help and refer to the genhtml man page
24 # to get information on usage and available options.
25 #
26 #
27 # History:
28 # 2002-08-23 created by Peter Oberparleiter <[email protected]>
29 # IBM Lab Boeblingen
30 # based on code by Manoj Iyer <[email protected]> and
31 # Megan Bock <[email protected]>
32 # IBM Austin
33 # 2002-08-27 / Peter Oberparleiter: implemented frame view
34 # 2002-08-29 / Peter Oberparleiter: implemented test description filtering
35 # so that by default only descriptions for test cases which
36 # actually hit some source lines are kept
37 # 2002-09-05 / Peter Oberparleiter: implemented --no-sourceview
38 # 2002-09-05 / Mike Kobler: One of my source file paths includes a "+" in
39 # the directory name. I found that genhtml.pl died when it
40 # encountered it. I was able to fix the problem by modifying
41 # the string with the escape character before parsing it.
42 # 2002-10-26 / Peter Oberparleiter: implemented --num-spaces
43 # 2003-04-07 / Peter Oberparleiter: fixed bug which resulted in an error
44 # when trying to combine .info files containing data without
45 # a test name
46 # 2003-04-10 / Peter Oberparleiter: extended fix by Mike to also cover
47 # other special characters
48 # 2003-04-30 / Peter Oberparleiter: made info write to STDERR, not STDOUT
49 # 2003-07-10 / Peter Oberparleiter: added line checksum support
50 # 2004-08-09 / Peter Oberparleiter: added configuration file support
51 # 2005-03-04 / Cal Pierog: added legend to HTML output, fixed coloring of
52 # "good coverage" background
53 # 2006-03-18 / Marcus Boerger: added --custom-intro, --custom-outro and
54 # overwrite --no-prefix if --prefix is present
55 # 2006-03-20 / Peter Oberparleiter: changes to custom_* function (rename
56 # to html_prolog/_epilog, minor modifications to implementation),
57 # changed prefix/noprefix handling to be consistent with current
58 # logic
59 # 2006-03-20 / Peter Oberparleiter: added --html-extension option
60 # 2008-07-14 / Tom Zoerner: added --function-coverage command line option;
61 # added function table to source file page
62 # 2008-08-13 / Peter Oberparleiter: modified function coverage
63 # implementation (now enabled per default),
64 # introduced sorting option (enabled per default)
65 # April/May 2020 / Henry Cox/Steven Dovich - Mediatek, inc
66 # Add support for differential line coverage categorization,
67 # date- and owner- binning.
68 # June/July 2020 / Henry Cox - Mediatek, inc
69 # Add support for differential branch coverage categorization,
70 # Add a bunch of navigation features - href to next code block
71 # of type T, of type T in date- or owner bin B, etc.
72 # Add sorted tables for date/owner bin summaries.
73 # Ocober 2020 / Henry Cox - Mediatek, inc
74 # Add "--hierarchical" display option.
75 #
76
77 use strict;
78 use warnings;
79
80 use File::Basename;
81 use File::Copy;
82 use File::Path;
83 use File::Spec;
84 use File::Temp;
85 use Scalar::Util qw/looks_like_number/;
86 use Digest::MD5 qw(md5_base64);
87 use Cwd qw/abs_path realpath cwd/;
88 use DateTime;
89 #use Regexp::Common qw(time); # damn - not installed
90 use Date::Parse;
91 use FileHandle;
92 use Carp;
93 use Storable qw(dclone);
94 use FindBin;
95 use Time::HiRes; # for profiling
96 use Storable;
97 use POSIX;
98 use Data::Dumper;
99
100 use lib "$FindBin::RealBin/../lib";
101 use lcovutil qw (set_tool_name define_errors parse_ignore_errors
102 $tool_name $tool_dir $lcov_version $lcov_url
103 ignorable_error
104 $ERROR_MISMATCH $ERROR_SOURCE $ERROR_BRANCH $ERROR_FORMAT
105 $ERROR_EMPTY $ERROR_VERSION $ERROR_UNUSED $ERROR_PACKAGE
106 $ERROR_CORRUPT $ERROR_NEGATIVE $ERROR_COUNT $ERROR_UNSUPPORTED
107 $ERROR_DEPRECATED $ERROR_INCONSISTENT_DATA $ERROR_CALLBACK
108 $ERROR_RANGE $ERROR_PATH
109 $ERROR_PARALLEL $ERROR_CHILD report_parallel_error
110 report_exit_status
111 summarize_messages
112 $br_coverage $func_coverage
113 info $verbose init_verbose_flag debug $debug $devnull
114 parseOptions
115 strip_directories
116 parse_cov_filters summarize_cov_filters
117 $FILTER_BRANCH_NO_COND $FILTER_LINE_CLOSE_BRACE @cov_filter
118 rate get_overall_line $default_precision check_precision
119 die_handler warn_handler parse_w3cdtf);
120
121 # Global constants
122 our $title = "LCOV - differential code coverage report";
123 lcovutil::set_tool_name(basename($0));
124
125 our $debugScheduler = 0;
126
127 # if false, then keep track of only enough information to be able to
128 # produce a valid HTML report.
129 # - Do not keep track of everything - say, to enable serialize/deserialize
130 # of the complete coverage DB.
131 # - In practice: this means to throw away the 'FileDetails' structure after
132 # the source file HTML has been constructed. 'FileDetails' is the lion's
133 # share of the memory footprint.
134 # This has the effect of reducing memory footprint and improving parallel
135 # performance.
136 our $buildSerializableDatabase = 0;
137
138 # Specify coverage rate limits (in %) for classifying file entries
139 # HI: $hi_limit <= rate <= 100 graph color: green
140 # MED: $med_limit <= rate < $hi_limit graph color: orange
141 # LO: 0 <= rate < $med_limit graph color: red
142
143 # For line coverage/all coverage types if not specified
144 our $hi_limit = 90;
145 our $med_limit = 75;
146
147 # For line coverage
148 our $ln_hi_limit;
149 our $ln_med_limit;
150
151 # For function coverage
152 our $fn_hi_limit;
153 our $fn_med_limit;
154
155 # For branch coverage
156 our $br_hi_limit;
157 our $br_med_limit;
158
159 # For MC/DC coverage
160 our $mcdc_hi_limit;
161 our $mcdc_med_limit;
162
163 # Width of overview image
164 our $overview_width = 80;
165
166 # Resolution of overview navigation: this number specifies the maximum
167 # difference in lines between the position a user selected from the overview
168 # and the position the source code window is scrolled to.
169 our $nav_resolution = 4;
170
171 # Clicking a line in the overview image should show the source code view at
172 # a position a bit further up so that the requested line is not the first
173 # line in the window. This number specifies that offset in lines.
174 our $nav_offset = 10;
175
176 # Clicking on a function name should show the source code at a position a
177 # few lines before the first line of code of that function. This number
178 # specifies that offset in lines.
179 our $func_offset = 2;
180
181 our $overview_title = "top level";
182
183 # Width for line coverage information in the source code view
184 our $line_field_width = 12;
185
186 # Width for branch coverage information in the source code view
187 our $br_field_width = 16;
188
189 # Width for MC/DC coverage information in the source code view
190 our $mcdc_field_width = 14;
191
192 # Width for owner name in the source code view
193 our $owner_field_width = 20;
194
195 # Width for block age in the source code view
196 our $age_field_width = 5;
197
198 # Width for TLA entry in the source code view
199 our $tla_field_width = 3;
200
201 # Internal Constants
202
203 # Header types
204 our $HDR_DIR = 0;
205 our $HDR_FILE = 1;
206 our $HDR_SOURCE = 2;
207 our $HDR_TESTDESC = 3;
208 our $HDR_FUNC = 4;
209
210 # Sort types
211 our $SORT_FILE = 0;
212 our $SORT_LINE = 1;
213 our $SORT_FUNC = 2;
214 our $SORT_BRANCH = 3;
215 our $SORT_MCDC = 4;
216 # function detail sort types
217 our $SORT_MISSING_LINE = 5; # by number of not-hit lines in function
218 our $SORT_MISSING_BRANCH = 6; # by number of not-hit branches in function
219 our $SORT_MISSING_MCDC = 7; # by number of not-hit MC/DC expressions in function
220
221 # Fileview heading types
222 our $HEAD_NO_DETAIL = 1;
223 our $HEAD_DETAIL_HIDDEN = 2;
224 our $HEAD_DETAIL_SHOWN = 3;
225
226 # Additional offsets used when converting branch coverage data to HTML
227 our $BR_LEN = -3;
228 our $BR_OPEN = -2; # 2nd last element
229 our $BR_CLOSE = -1; # last element
230
231 # Data related prototypes
232 sub print_usage(*);
233 sub gen_html();
234 sub html_create($$);
235 sub process_file($$$$$);
236 sub compute_title($$);
237 sub get_prefix($@);
238 sub shorten_prefix($);
239 sub get_relative_base_path($);
240 sub read_testfile($);
241 sub get_date_string($);
242 sub remove_unused_descriptions();
243 sub get_affecting_tests($$$$);
244 sub apply_prefix($@);
245 sub get_html_prolog($);
246 sub get_html_epilog($);
247 #sub write_dir_page($$$$$$$;$);
248 sub write_summary_pages($$$$$$$$);
249 sub classify_rate($$$$);
250 sub parse_dir_prefix(@);
251
252 # HTML related prototypes
253 sub escape_html($);
254 sub escape_id($);
255 sub get_bar_graph_code($$$);
256
257 sub write_png_files();
258 sub write_htaccess_file();
259 sub write_css_file();
260 sub write_description_file($$);
261 sub write_function_table(*$$$$$$$$$$$$);
262
263 sub write_html(*$);
264 sub write_html_prolog(*$$);
265 sub write_html_epilog(*$;$);
266
267 sub write_header(*$$$$$$$);
268 sub write_header_prolog(*$);
269 sub write_header_line(*@);
270 sub write_header_epilog(*$);
271
272 sub write_file_table(*$$$$$$);
273 sub write_file_table_prolog(*$$$@);
274 sub write_file_table_entry(*$$@);
275 sub write_file_table_detail_entry(*$$$$@);
276 sub write_file_table_epilog(*);
277
278 sub write_test_table_prolog(*$);
279 sub write_test_table_entry(*$$);
280 sub write_test_table_epilog(*);
281
282 sub write_source($$$$$$$$);
283 sub write_source_prolog(*$$$);
284 sub write_source_line(*$$$$$$$);
285 sub write_source_epilog(*);
286
287 sub write_frameset(*$$$);
288 sub write_overview_line(*$$$);
289 sub write_overview(*$$$$);
290
291 # External prototype (defined in genpng)
292 sub gen_png($$$$$@);
293
294 package SummaryInfo;
295
296 our @selectCallbackScript;
297 our $selectCallback;
298 our @cleanDirectoryList;
299
300 our @tlaPriorityOrder = ("UNC",
301 "LBC",
302 "UIC",
303 "UBC",
304
305 "GBC",
306 "GIC",
307 "GNC",
308 "CBC",
309
310 "EUB",
311 "ECB",
312 "DUB",
313 "DCB",);
314
315 our %tlaLocation = ("UNC" => 1,
316 "LBC" => 3,
317 "UIC" => 3,
318 "UBC" => 3,
319
320 "GBC" => 3,
321 "GIC" => 3,
322 "GNC" => 1,
323 "CBC" => 3,
324
325 "EUB" => 3,
326 "ECB" => 3,
327 "DUB" => 2,
328 "DCB" => 2,);
329
330 our %tlaToTitle = ("UNC" => "Uncovered New Code (+ => 0):\n" .
331 "Newly added code is not tested",
332 "LBC" => "Lost Baseline Coverage (1 => 0):\n" .
333 "Unchanged code is no longer tested",
334 "UIC" => "Uncovered Included Code (# => 0):\n" .
335 "Previously unused code is untested",
336 "UBC" => "Uncovered Baseline Code (0 => 0):\n" .
337 "Unchanged code was untested before, is untested now",
338
339 "GBC" => "Gained Baseline Coverage (0 => 1):\n" .
340 "Unchanged code is tested now",
341 "GIC" => "Gained Included Coverage (# => 1):\n" .
342 "Previously unused code is tested now",
343 "GNC" => "Gained New Coverage (+ => 1):\n" .
344 "Newly added code is tested",
345 "CBC" => "Covered Baseline Code (1 => 1):\n" .
346 "Unchanged code was tested before and is still tested",
347
348 "EUB" => "Excluded Uncovered Baseline (0 => #):\n" .
349 "Previously untested code is unused now",
350 "ECB" => "Excluded Covered Baseline (1 => #):\n" .
351 "Previously tested code is unused now",
352 "DUB" => "Deleted Uncovered Baseline (0 => -):\n" .
353 "Previously untested code has been deleted",
354 "DCB" => "Deleted Covered Baseline (1 => -):\n" .
355 "Previously tested code has been deleted",);
356
357 our %tlaToLegacy = ("UNC" => "Missed",
358 "GNC" => "Hit",);
359
360 our %tlaToLegacySrcLabel = ("UNC" => "MIS",
361 "GNC" => "HIT",);
362
363 our @defaultCutpoints = (7, 30, 180);
364 our @cutpoints;
365 our @ageGroupHeader;
366 our %ageHeaderToBin;
367
368 our @truncateOwnerTableLevels; # default: truncate everywhere if enabled
369 our $ownerTableElements; # default: do not truncate
370 our $compactSummaryTables = 1; # on by default
371
372 use constant {
373 TYPE => 0,
374 NAME => 1,
375 PARENT => 2,
376 RELATIVE_DIR => 3,
377 FULL_DIR => 4,
378 LINE_DATA => 5,
379 BRANCH_DATA => 6,
380 MCDC_DATA => 7,
381 FUNCTION_DATA => 8,
382
383 FILE_DETAILS => 9, # SourceFile struct - only used for 'file' type
384 SOURCES => 9, # used by top and directory types
385 IS_ABSOLUTE => 10, # used by directory type only
386
387 # coverage data list for type
388 DATA => 0,
389 AGE => 1,
390 OWNERS => 2, # not used by Function coverage - no owner
391 };
392
393 sub type2str
394 {
395 my $t = shift;
396 return 'line' if ($t == LINE_DATA);
397 return 'branch' if ($t == BRANCH_DATA);
398 return 'MC/DC' if ($t == MCDC_DATA);
399 die("unexpected type '$t'") unless ($t == FUNCTION_DATA);
400 return 'function';
401 }
402
403 sub _initCounts
404 {
405 my %hash;
406 foreach my $key ('found', 'hit', 'GNC', 'UNC', 'CBC', 'GBC',
407 'LBC', 'UBC', 'ECB', 'EUB', 'GIC', 'UIC',
408 'DCB', 'DUB'
409 ) {
410 $hash{$key} = 0;
411 }
412 return \%hash;
413 }
414
415 sub noBaseline
416 {
417 # no baseline - so we will have only 'UIC' and 'GIC' code
418 # legacy display order is 'hit' followed by 'not hit'
419 @tlaPriorityOrder = ('GNC', 'UNC');
420 %tlaToTitle = ('UNC' => 'Not Hit',
421 'GNC' => 'Hit',);
422 }
423
424 sub setAgeGroups
425 {
426 #my $numGroups = scalar(@_) + 1;
427 @cutpoints = sort({ $a <=> $b } @_);
428 if (@ageGroupHeader) {
429 # labels were specified by user
430 @ageGroupHeader = split($lcovutil::split_char,
431 join($lcovutil::split_char, @ageGroupHeader));
432 goto done
433 if (scalar(@ageGroupHeader) == scalar(@cutpoints) + 1);
434 # mismatched number - generate warning
435 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
436 "expected number of 'age' labels to match 'date-bin' cutpoints");
437 # if message ignored, then assign default labels
438 }
439 @ageGroupHeader = ();
440 my $prefix = "[..";
441 foreach my $days (@cutpoints) {
442 my $header = $prefix . $days . "] days";
443 push(@ageGroupHeader, $header);
444 $prefix = "(" . $days . ",";
445 }
446 push(@ageGroupHeader, "(" . $cutpoints[-1] . "..) days");
447 done:
448 %ageHeaderToBin = ();
449 my $bin = 0;
450 foreach my $header (@ageGroupHeader) {
451 $ageHeaderToBin{$header} = $bin;
452 ++$bin;
453 }
454 }
455
456 sub findAgeBin
457 {
458 my $age = shift;
459 defined($age) or die("undefined age");
460 my $bin;
461 for ($bin = 0; $bin <= $#cutpoints; $bin++) {
462 last
463 if ($age <= $cutpoints[$bin]);
464 }
465 return $bin;
466 }
467
468 sub new
469 {
470 my ($class, $type, $name, $is_absolute_dir) = @_;
471 defined($name) || $type eq 'top' or
472 die("SummaryInfo name should be defined, except at top-level");
473 my $self = [$type, # 'type' expected to be one of 'file', 'directory', 'top'
474 $name,
475 undef, # parent
476 undef, # relative dir,
477 undef, # full directory path,
478 [undef, [], {}], # line data
479 [undef, [], {}], # branch data
480 [undef, [], {}], # MC/DC data
481 [undef, []] # function data
482 ];
483 if ($type eq 'file') {
484 $self->[FILE_DETAILS] = undef; # will be SourceFile object
485 } else {
486 $self->[SOURCES] = {};
487 $self->[IS_ABSOLUTE] = $is_absolute_dir
488 if ($type eq 'directory');
489 }
490
491 for my $type (LINE_DATA, BRANCH_DATA, MCDC_DATA, FUNCTION_DATA) {
492 $self->[$type]->[DATA] = _initCounts();
493 # no age data unless annotations are enabled
494 next unless @SourceFile::annotateScript;
495 my $ageList = $self->[$type]->[AGE];
496 foreach my $i (0 .. $#cutpoints + 1) {
497 my $h = _initCounts();
498 $h->{_LB} = ($i == 0) ? undef : $cutpoints[$i - 1];
499 $h->{_UB} = ($i == $#cutpoints + 1) ? undef : $cutpoints[$i];
500 $h->{_INDEX} = $i;
501 push(@$ageList, $h);
502 }
503 }
504
505 bless $self, $class;
506
507 return $self;
508 }
509
510 # deserialization: copy the coverage portion of the undumped data
511 sub copyGuts
512 {
513 my ($self, $that) = @_;
514 my @copy = (RELATIVE_DIR, FULL_DIR, LINE_DATA, BRANCH_DATA,
515 MCDC_DATA, FUNCTION_DATA);
516 if ($that->[TYPE] eq 'file') {
517 push(@copy, FILE_DETAILS);
518 } elsif ($that->[TYPE] eq 'directory') {
519 push(@copy, IS_ABSOLUTE);
520 }
521 for my $key (@copy) {
522 $self->[$key] = $that->[$key];
523 }
524 }
525
526 sub name
527 {
528 my $self = shift;
529 return $self->[NAME];
530 }
531
532 sub unsetDirs
533 {
534 my $self = shift;
535 # need to reset after fork failure - we set the values
536 # just before forking, but now have to put them back.
537 die('bad usage: unsetDirs()')
538 unless (defined($self->[FULL_DIR]) &&
539 defined($self->[RELATIVE_DIR]));
540 $self->[FULL_DIR] = undef;
541 $self->[RELATIVE_DIR] = undef;
542 }
543
544 sub relativeDir
545 {
546 my ($self, $dir_string) = @_;
547 die("bad usage: relativeDir(" .
548 (defined($dir_string) ? $dir_string : '') . ') current: '
549 .
550 (defined($self->[RELATIVE_DIR]) ? $self->[RELATIVE_DIR] : '<undef>')
551 )
552 unless ((!defined($dir_string) && defined($self->[RELATIVE_DIR])) ||
553 (defined($dir_string) && !defined($self->[RELATIVE_DIR])));
554 $self->[RELATIVE_DIR] = $dir_string
555 if defined($dir_string);
556 return $self->[RELATIVE_DIR];
557 }
558
559 sub fullDir
560 {
561 my ($self, $dir_string) = @_;
562 die("bad usage fullDir()")
563 unless ((!defined($dir_string) && defined($self->[FULL_DIR])) ||
564 (defined($dir_string) && !defined($self->[FULL_DIR])));
565 $self->[FULL_DIR] = $dir_string
566 if defined($dir_string);
567 return $self->[FULL_DIR];
568 }
569
570 sub type
571 {
572 my $self = shift;
573 return $self->[TYPE];
574 }
575
576 sub is_directory
577 {
578 my ($self, $is_absolute) = @_;
579 return (
580 $self->type() eq 'directory' ?
581 ((defined($is_absolute) && $is_absolute) ? $self->[IS_ABSOLUTE] : 1)
582 :
583 0);
584 }
585
586 sub parent
587 {
588 my $self = shift;
589 return $self->[PARENT];
590 }
591
592 sub setParent
593 {
594 my ($self, $parent) = @_;
595 die("expected parent dir")
596 unless (ref($parent) eq "SummaryInfo" &&
597 ($main::flat ? 'top' : 'directory') eq $parent->type());
598 $self->[PARENT] = $parent;
599 }
600
601 sub sources
602 {
603 my $self = shift;
604 die("bad usage") if $self->type() eq 'file';
605 return keys(%{$self->[SOURCES]});
606 }
607
608 sub fileDetails
609 {
610 my ($self, $data) = @_;
611 $self->type() eq 'file' or die("source details only available for file");
612 !(defined($data) && defined($self->[FILE_DETAILS])) or
613 die("attempt to set details in initialized struct");
614 !defined($data) || ref($data) eq 'SourceFile' or
615 die("unexpected data arg " . ref($data));
616 $self->[FILE_DETAILS] = $data
617 if defined($data);
618 return $self->[FILE_DETAILS];
619 }
620
621 sub get_sorted_keys
622 {
623 # sort_type in ($SORT_FILE, $SORT_LINE, $SORT_FUNC, $SORT_BRANC, $SORT_MCDC)
624 my ($self, $sort_type, $include_dirs) = @_;
625 die("invalid usage") if $self->type() eq 'file';
626
627 my $sources = $self->[SOURCES];
628
629 my @keys = $self->sources();
630 my @l;
631 foreach my $k (@keys) {
632 my $data = $sources->{$k};
633 next
634 if ($data->type() eq 'directory' &&
635 (!defined($include_dirs) ||
636 0 == $include_dirs));
637 push(@l, $k);
638 }
639 if ($sort_type == $SORT_FILE) {
640 # alphabetic
641 return sort(@l);
642 }
643 my $covtype;
644 if ($sort_type == $SORT_LINE) {
645 # Sort by number of instrumented lines without coverage
646 $covtype = LINE_DATA;
647 } elsif ($sort_type == $SORT_FUNC) {
648 # Sort by number of instrumented functions without coverage
649 $covtype = FUNCTION_DATA;
650 } elsif ($sort_type == $SORT_MCDC) {
651 # Sort by number of MC/DC points without coverage
652 $covtype = MCDC_DATA;
653 } else {
654 die("unexpected sort type $sort_type")
655 unless ($sort_type == $SORT_BRANCH);
656 # Sort by number of instrumented branches without coverage
657 $covtype = BRANCH_DATA;
658 }
659
660 if ($main::opt_missed) {
661 # sort by directory first then secondary key
662 return
663 sort({
664 my $da = $sources->{$a};
665 my $db = $sources->{$b};
666 # directories then files if list includes both
667 $da->type() cmp $db->type() or
668 $db->get_missed($covtype)
669 <=> $da->get_missed($covtype) or
670 # sort alphabetically in case of tie
671 $da->name() cmp $db->name()
672 } @l);
673 } else {
674 return
675 sort({
676 my $da = $sources->{$a};
677 my $db = $sources->{$b};
678 $da->type() cmp $db->type() or
679 $da->get_rate($covtype) <=> $db->get_rate($covtype) or
680 $da->name() cmp $db->name()
681 } @l);
682 }
683 }
684
685 sub get_source
686 {
687 my ($self, $name) = @_;
688 die("bad usage") if $self->type() eq 'file';
689 return
690 exists($self->[SOURCES]->{$name}) ? $self->[SOURCES]->{$name} : undef;
691 }
692
693 sub remove_source
694 {
695 my ($self, $name) = @_;
696 die("bad usage") if $self->type() eq 'file';
697 delete $self->[SOURCES]->{$name};
698 }
699
700 sub get
701 {
702 my ($self, $key, $type) = @_;
703 $type = LINE_DATA
704 if !defined($type);
705
706 my $hash = $self->[$type]->[DATA];
707 if ($key eq "missed") {
708 my $missed = 0;
709 foreach my $k ('UBC', 'UNC', 'UIC', 'LBC') {
710 $missed += $hash->{$k}
711 if (exists($hash->{$k}));
712 }
713 return $missed;
714 } else {
715 die("unexpected 'get' key $key")
716 unless exists($hash->{$key});
717 return $hash->{$key};
718 }
719 }
720
721 # Return a relative value for the specified found&hit values
722 # which is used for sorting the corresponding entries in a
723 # file list.
724 #
725 sub get_rate
726 {
727 my ($self, $covtype) = @_;
728
729 my $hash = $self->[$covtype]->[DATA];
730 my $found = $hash->{found};
731 my $hit = $hash->{hit};
732
733 if ($found == 0) {
734 #return 100;
735 return 1000;
736 }
737 #return (100.0 * $hit) / $found;
738 return int($hit * 1000 / $found) * 10 + 2 - (1 / $found);
739 }
740
741 sub get_missed
742 {
743 my ($self, $covtype) = @_;
744
745 my $hash = $self->[$covtype]->[DATA];
746 my $found = $hash->{found};
747 my $hit = $hash->{hit};
748
749 return $found - $hit;
750 }
751
752 sub contains_owner
753 {
754 my ($self, $owner) = @_;
755 return exists($self->[LINE_DATA]->[OWNERS]->{$owner});
756 }
757
758 sub owners
759 {
760 # return possibly empty list of line owners in this file
761 # - filter only those which have 'missed' lines
762 my ($self, $showAll, $covType) = @_;
763
764 (!defined($covType) ||
765 $covType == LINE_DATA ||
766 $covType == BRANCH_DATA ||
767 $covType eq MCDC_DATA) or
768 die("unsupported coverage type '$covType'");
769
770 my $hash = $self->[defined($covType) ? $covType : LINE_DATA]->[OWNERS];
771
772 return keys(%$hash)
773 if $showAll;
774
775 my @rtn;
776 OWNER:
777 foreach my $name (keys(%$hash)) {
778 my $h = $hash->{$name};
779 foreach my $tla ('UNC', 'UBC', 'UIC', 'LBC') {
780 if (exists($h->{$tla})) {
781 die("unexpected 0 (zero) value for $tla of $name in $self->path()"
782 ) if (0 == $h->{$tla});
783 push(@rtn, $name);
784 next OWNER;
785 }
786 }
787 }
788 return @rtn;
789 }
790
791 sub owner_tlaCount
792 {
793 my ($self, $name, $tla, $covType) = @_;
794 die("$name not found in owner data for $self->path()")
795 unless exists($self->[LINE_DATA]->[OWNERS]->{$name});
796
797 return 0 # not supported, yet
798 if $covType == FUNCTION_DATA;
799
800 (!defined($covType) ||
801 $covType == LINE_DATA ||
802 $covType == BRANCH_DATA ||
803 $covType == MCDC_DATA) or
804 die("unsupported coverage type '$covType'");
805
806 my $hash =
807 $self->[defined($covType) ? $covType : LINE_DATA]->[OWNERS]->{$name};
808 return $hash->{$tla}
809 if (exists($hash->{$tla}));
810
811 if ($tla eq "found") {
812 my $total = 0;
813 foreach my $k (keys(%$hash)) {
814 # count only code that can be hit (ie., not excluded)
815 $total += $hash->{$k}
816 if ('EUB' ne $k &&
817 'ECB' ne $k);
818 }
819 return $total;
820 } elsif ($tla eq "hit") {
821 my $hit = 0;
822 foreach my $k ('CBC', 'GBC', 'GIC', 'GNC') {
823 $hit += $hash->{$k}
824 if (exists($hash->{$k}));
825 }
826 return $hit;
827 } elsif ($tla eq "missed") {
828 my $missed = 0;
829 foreach my $k ('UBC', 'UNC', 'UIC', 'LBC') {
830 $missed += $hash->{$k}
831 if (exists($hash->{$k}));
832 }
833 return $tla eq "missed" ? $missed : -$missed;
834 }
835 die("unexpected TLA $tla")
836 unless exists($tlaLocation{$tla});
837 return 0;
838 }
839
840 sub hasOwnerInfo
841 {
842 my $self = shift;
843
844 return %{$self->[LINE_DATA]->[OWNERS]} ? 1 : 0;
845 }
846
847 sub hasDateInfo
848 {
849 my $self = shift;
850 # we get date- and owner information at the same time from the
851 # annotation-script - so, if we have owner info, then we have date info too.
852 return %{$self->[LINE_DATA]->[OWNERS]} ? 1 : 0;
853 }
854
855 sub findOwnerList
856 {
857 # return [ [owner, lineCovData, branchCovData, functionCov]] for each owner
858 # where lineCovData = [missedCount, totalCount]
859 # branchCovData = [missed, total] or undef if not enabled
860 # functionCov = [missed, total] or undef if not enabled
861 # - sorted in descending order number of missed lines
862 my ($self, $callback_type, $truncate_me, $all) = @_;
863
864 my @owners;
865 foreach my $owner (keys(%{$self->[LINE_DATA]->[OWNERS]})) {
866 my $lineMissed = $self->owner_tlaCount($owner, 'missed', LINE_DATA);
867 my $branchMissed =
868 $lcovutil::br_coverage ?
869 $self->owner_tlaCount($owner, 'missed', BRANCH_DATA) :
870 0;
871 my $funcMissed =
872 $lcovutil::func_coverage ?
873 $self->owner_tlaCount($owner, 'missed', FUNCTION_DATA) :
874 0;
875 my $mcdcMissed =
876 $lcovutil::mcdc_coverage ?
877 $self->owner_tlaCount($owner, 'missed', MCDC_DATA) :
878 0;
879 # filter owners who have unexercised code, if requested
880
881 if ($all ||
882 (0 != $lineMissed || 0 != $branchMissed || 0 != $funcMissed)) {
883 my $lineCb = OwnerDetailCallback->new($self, $owner, LINE_DATA);
884 my $branchCb = OwnerDetailCallback->new($self, $owner, BRANCH_DATA);
885 my $mcdcCb = OwnerDetailCallback->new($self, $owner, MCDC_DATA);
886 my $functionCb =
887 OwnerDetailCallback->new($self, $owner, FUNCTION_DATA);
888 my $lineTotal = $self->owner_tlaCount($owner, 'found', LINE_DATA);
889 my $branchTotal =
890 $lcovutil::br_coverage ?
891 $self->owner_tlaCount($owner, 'found', BRANCH_DATA) :
892 0;
893 my $mcdcTotal =
894 $lcovutil::mcdc_coverage ?
895 $self->owner_tlaCount($owner, 'found', MCDC_DATA) :
896 0;
897 my $funcTotal =
898 $lcovutil::func_coverage ?
899 $self->owner_tlaCount($owner, 'found', FUNCTION_DATA) :
900 0;
901 push(@owners,
902 [$owner,
903 [$lineMissed, $lineTotal, $lineCb],
904 [$branchMissed, $branchTotal, $branchCb],
905 [$funcMissed, $funcTotal, $functionCb],
906 [$mcdcMissed, $mcdcTotal, $mcdcCb]
907 ]);
908 }
909 }
910 @owners = sort({
911 $b->[1]->[0] <=> $a->[1]->[0] || # missed
912 $b->[1]->[1] <=> $a->[1]->[1] || # then total
913 $a->[0] cmp $b->[0]
914 } @owners); # then by name
915 my $truncated;
916 if ($truncate_me &&
917 defined($ownerTableElements) &&
918 $ownerTableElements < scalar(@owners) &&
919 (0 == scalar(@truncateOwnerTableLevels) ||
920 grep(/$callback_type/, @truncateOwnerTableLevels))
921 ) {
922 # don't truncate the 'primary' key owner table
923
924 $truncated = (scalar(@owners) - $ownerTableElements);
925 #lcovutil::info("truncating $truncated elements in header table\n");
926 splice(@owners, $ownerTableElements);
927 } else {
928 $truncated = 0;
929 }
930 return (scalar(@owners) ? \@owners : undef, $truncated);
931 }
932
933 sub append
934 {
935 my ($self, $record) = @_;
936
937 # keep track of the records that get merged into me..
938 defined($record->[NAME]) or
939 die("attempt to anonymous SummaryInfo record");
940 !exists($self->[SOURCES]->{$record->[NAME]}) or
941 die("duplicate merge record " . $record->[NAME]);
942 $self->[SOURCES]->{$record->[NAME]} = $record;
943
944 die($record->name() . " already has parent " . $record->parent()->name())
945 if (defined($record->parent()) && $record->[PARENT] != $self);
946 $record->[PARENT] = $self
947 if !defined($record->parent());
948
949 foreach my $group (LINE_DATA, FUNCTION_DATA, BRANCH_DATA, MCDC_DATA) {
950 my $mine = $self->[$group]->[DATA];
951 my $yours = $record->[$group]->[DATA];
952 while (my ($key, $value) = each(%$yours)) {
953 $mine->{$key} += $yours->{$key};
954 }
955 }
956
957 # there will be no date info if we didn't also collect owner data
958 # merge the date- and owner data, if if we aren't going to display it
959 # (In future, probably want to serialize the data for future processing)
960 if (%{$record->[LINE_DATA]->[OWNERS]}) {
961 foreach my $covType (LINE_DATA, FUNCTION_DATA, BRANCH_DATA, MCDC_DATA) {
962 for (my $bin = 0; $bin <= $#ageGroupHeader; ++$bin) {
963 foreach my $key (keys %{$self->[$covType]->[DATA]}) {
964 # duplicate line-coverage buckets
965 my $ageval = $self->age_sample($bin);
966 if ($covType == LINE_DATA) {
967 $self->lineCovCount($key, "age", $ageval,
968 $record->lineCovCount($key, "age", $ageval));
969 } elsif ($covType == BRANCH_DATA) {
970 $self->branchCovCount($key, "age", $ageval,
971 $record->branchCovCount($key, "age", $ageval));
972 } elsif ($covType == MCDC_DATA) {
973 $self->mcdcCovCount($key, "age", $ageval,
974 $record->branchCovCount($key, "age", $ageval));
975 } else {
976 $self->functionCovCount($key, 'age', $ageval,
977 $record->functionCovCount($key, "age", $ageval));
978 }
979 }
980 }
981
982 my $ownerList = $self->[$covType]->[OWNERS];
983 while (my ($name, $yours) = each(%{$record->[$covType]->[OWNERS]}))
984 {
985 if (!exists($ownerList->{$name})) {
986 $ownerList->{$name} = {};
987 }
988 my $mine = $ownerList->{$name};
989 while (my ($tla, $count) = each(%$yours)) {
990 if (exists($mine->{$tla})) {
991 $mine->{$tla} += $count;
992 } else {
993 $mine->{$tla} = $count;
994 }
995 }
996 }
997 }
998 }
999 return $self;
1000 }
1001
1002 sub age_sample
1003 {
1004 my ($self, $i) = @_;
1005 my $bin = $self->[LINE_DATA]->[AGE]->[$i];
1006 return ($i < $#ageGroupHeader) ? $bin->{_UB} : ($bin->{_LB} + 1);
1007 }
1008
1009 sub lineCovCount
1010 {
1011 my ($self, $key, $group, $age, $delta) = @_;
1012
1013 $delta = 0 unless defined($delta);
1014
1015 if ($key eq 'missed') {
1016 my $found = $self->lineCovCount('found', $group, $age);
1017 my $hit = $self->lineCovCount('hit', $group, $age);
1018 return $found - $hit;
1019 }
1020
1021 if ($group eq "age") {
1022 my $a = $self->[LINE_DATA]->[AGE];
1023 my $bin = SummaryInfo::findAgeBin($age);
1024 exists($a->[$bin]) && exists($a->[$bin]->{$key}) or
1025 die("unexpected key '$key' for bin '$bin'");
1026 $a->[$bin]->{$key} += $delta;
1027 return $a->[$bin]->{$key};
1028 }
1029
1030 my $d = $self->[$group]->[DATA];
1031 defined($d) or
1032 die("SummaryInfo::value: unrecognized group $group\n");
1033 defined($d->{$key}) or
1034 die("SummaryInfo::value: unrecognized key $key\n");
1035
1036 $d->{$key} += $delta;
1037 return $d->{$key};
1038 }
1039
1040 sub branchCovCount
1041 {
1042 my ($self, $key, $group, $age, $delta) = @_;
1043
1044 $delta = 0 unless defined($delta);
1045
1046 if ($key eq 'missed') {
1047 my $found = $self->branchCovCount('found', $group, $age);
1048 my $hit = $self->branchCovCount('hit', $group, $age);
1049 return $found - $hit;
1050 }
1051
1052 my $branch = $self->[BRANCH_DATA];
1053 if ($group eq "age") {
1054 my $a = $branch->[AGE];
1055 my $bin = SummaryInfo::findAgeBin($age);
1056 # LCOV_EXCL_START
1057 unless (exists($a->[$bin]) && exists($a->[$bin]->{$key})) {
1058 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
1059 "unexpected key '$key' for bin '$bin'");
1060 return;
1061 }
1062 # LCOV_EXCL_STOP
1063 $a->[$bin]->{$key} += $delta;
1064 return $a->[$bin]->{$key};
1065 }
1066 my $d = $branch->[DATA];
1067 defined($d) or
1068 die("SummaryInfo::value: unrecognized branch group $group\n");
1069 defined($d->{$key}) or
1070 die("SummaryInfo::value: unrecognized branch key $key\n");
1071
1072 $d->{$key} += $delta;
1073 return $d->{$key};
1074 }
1075
1076 sub mcdcCovCount
1077 {
1078 my ($self, $key, $group, $age, $delta) = @_;
1079
1080 $delta = 0 unless defined($delta);
1081
1082 if ($key eq 'missed') {
1083 my $found = $self->mcdcCovCount('found', $group, $age);
1084 my $hit = $self->mcdcCovCount('hit', $group, $age);
1085 return $found - $hit;
1086 }
1087
1088 my $mcdc = $self->[MCDC_DATA];
1089 if ($group eq "age") {
1090 my $a = $mcdc->[AGE];
1091 my $bin = SummaryInfo::findAgeBin($age);
1092 # LCOV_EXCL_START
1093 unless (exists($a->[$bin]) && exists($a->[$bin]->{$key})) {
1094 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
1095 "unexpected key '$key' for bin '$bin'");
1096 return;
1097 }
1098 # LCOV_EXCL_STOP
1099 $a->[$bin]->{$key} += $delta;
1100 return $a->[$bin]->{$key};
1101 }
1102 my $d = $mcdc->[DATA];
1103 defined($d) or
1104 die("SummaryInfo::value: unrecognized MC/DC group $group\n");
1105 defined($d->{$key}) or
1106 die("SummaryInfo::value: unrecognized MC/DC key $key\n");
1107
1108 $d->{$key} += $delta;
1109 return $d->{$key};
1110 }
1111
1112 sub functionCovCount
1113 {
1114 my ($self, $key, $group, $age, $delta) = @_;
1115
1116 $delta = 0 unless defined($delta);
1117
1118 if ($key eq 'missed') {
1119 my $found = $self->functionCovCount('found', $group, $age);
1120 my $hit = $self->functionCovCount('hit', $group, $age);
1121 return $found - $hit;
1122 }
1123
1124 my $func = $self->[FUNCTION_DATA];
1125 if ($group eq "age") {
1126 my $a = $func->[AGE];
1127 my $bin = SummaryInfo::findAgeBin($age);
1128 # LCOV_EXCL_START
1129 unless (exists($a->[$bin]) && exists($a->[$bin]->{$key})) {
1130 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
1131 "unexpected key '$key' for bin '$bin'");
1132 return;
1133 }
1134 # LCOV_EXCL_STOP
1135 $a->[$bin]->{$key} += $delta;
1136 return $a->[$bin]->{$key};
1137 }
1138 my $d = $func->[DATA];
1139 defined($d) or
1140 die("SummaryInfo::value: unrecognized function group $group\n");
1141 defined($d->{$key}) or
1142 die("SummaryInfo::value: unrecognized function key $key\n");
1143
1144 $d->{$key} += $delta;
1145 return $d->{$key};
1146 }
1147
1148 sub removeLine
1149 {
1150 my ($self, $lineData) = @_;
1151
1152 my $l = $self->[LINE_DATA]->[DATA];
1153 if ($lineData->in_curr()) {
1154 $l->{hit} -= $lineData->curr_count() != 0;
1155 $l->{found} -= 1;
1156 }
1157 if ($lcovutil::br_coverage) {
1158 my $b = $lineData->current_branch();
1159 if (defined($b)) {
1160 my ($found, $hit) = $b->totals();
1161 my $br = $self->[BRANCH_DATA]->[DATA];
1162 $br->{hit} -= $hit;
1163 $br->{found} -= $found;
1164 }
1165 }
1166 if ($lcovutil::mcdc_coverage) {
1167 my $b = $lineData->current_mcdc();
1168 if (defined($b)) {
1169 my ($found, $hit) = $b->totals();
1170 my $br = $self->[MCDC_DATA]->[DATA];
1171 $br->{hit} -= $hit;
1172 $br->{found} -= $found;
1173 }
1174 }
1175 if ($lcovutil::func_coverage) {
1176 my $f = $lineData->current_function();
1177 if (defined($f)) {
1178 my $fn = $self->[FUNCTION_DATA]->[DATA];
1179 $fn->{hit} -= $f->hit() != 0;
1180 $fn->{found} -= 1;
1181 }
1182 }
1183 }
1184
1185 sub is_empty
1186 {
1187 my $self = shift;
1188 my $t = $self->[LINE_DATA]->[DATA];
1189 foreach my $category (keys %$t) {
1190 return 0 if 0 != $t->{$category};
1191 }
1192 return 1;
1193 }
1194
1195 sub type_count
1196 {
1197 my ($type, $status, $self, $delta) = @_;
1198 my $l = $self->[$type]->[DATA];
1199 $l->{$status} += $delta if defined($delta);
1200 return $l->{$status};
1201 }
1202
1203 sub lines_found
1204 {
1205 return type_count(LINE_DATA, 'found', @_);
1206 }
1207
1208 sub lines_hit
1209 {
1210 return type_count(LINE_DATA, 'hit', @_);
1211 }
1212
1213 sub function_found
1214 {
1215 return type_count(FUNCTION_DATA, 'found', @_);
1216 }
1217
1218 sub function_hit
1219 {
1220 return type_count(FUNCTION_DATA, 'hit', @_);
1221 }
1222
1223 sub branch_found
1224 {
1225 return type_count(BRANCH_DATA, 'found', @_);
1226 }
1227
1228 sub branch_hit
1229 {
1230 return type_count(BRANCH_DATA, 'hit', @_);
1231 }
1232
1233 sub mcdc_found
1234 {
1235 return type_count(MCDC_DATA, 'found', @_);
1236 }
1237
1238 sub mcdc_hit
1239 {
1240 return type_count(MCDC_DATA, 'hit', @_);
1241 }
1242
1243 sub selected
1244 {
1245 my $rtn;
1246 eval { $rtn = $selectCallback->select(@_); };
1247 if ($@) {
1248 $rtn = 1; # return everything
1249 lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
1250 "select(..) failed: $@");
1251 }
1252 return $rtn;
1253 }
1254
1255 sub tlaSummary
1256 {
1257 my ($self, $t) = @_;
1258 my $type;
1259 if ($t eq 'line') {
1260 $type = LINE_DATA;
1261 } elsif ($t eq 'function') {
1262 $type = FUNCTION_DATA;
1263 } elsif ($t eq 'mcdc') {
1264 $type = MCDC_DATA;
1265 } else {
1266 die("unknown type $t") unless 'branch' eq $t;
1267 $type = BRANCH_DATA;
1268 }
1269 my $str = '';
1270 my $sep = '';
1271 my $d = $self->[$type]->[DATA];
1272 foreach my $tla (@tlaPriorityOrder) {
1273 my $count = $d->{$tla};
1274 next if $count == 0;
1275 $str .= $sep . $tla . ':' . $count;
1276 $sep = ' ';
1277 }
1278 return $str;
1279 }
1280
1281 sub checkCoverageCriteria
1282 {
1283 my $self = shift;
1284 my $type = $self->type();
1285
1286 if ($type eq 'top') {
1287 # simplistic top-level criteria..
1288 CoverageCriteria::check_failUnder($main::current_data);
1289 }
1290 return
1291 unless ($CoverageCriteria::criteriaCallback &&
1292 (0 == scalar(@CoverageCriteria::criteriaCallbackLevels) ||
1293 grep(/$type/, @CoverageCriteria::criteriaCallbackLevels)));
1294
1295 my $start = Time::HiRes::gettimeofday();
1296 my %data;
1297 foreach my $t (LINE_DATA, FUNCTION_DATA, BRANCH_DATA, MCDC_DATA) {
1298 my $key = type2str($t);
1299 my $d = $self->[$t]->[DATA];
1300 foreach my $k (keys %$d) {
1301 # $k will be 'hit', 'found' or one of the TLAs
1302 my $count = $d->{$k};
1303 next if $count == 0;
1304 if (exists $data{$key}) {
1305 $data{$key}->{$k} = $count;
1306 } else {
1307 $data{$key} = {$k => $count};
1308 }
1309 }
1310 }
1311 if (grep(/^date$/, @CoverageCriteria::criteriaCallbackTypes)) {
1312 foreach my $t (LINE_DATA, FUNCTION_DATA, BRANCH_DATA, MCDC_DATA) {
1313 my $key = type2str($t);
1314
1315 next unless exists($self->[$t]->[AGE]);
1316 my $ageBins = $self->[$t]->[AGE];
1317 foreach my $i (0 .. $#cutpoints + 1) {
1318 my $bin = $ageBins->[$i];
1319 foreach my $k (@tlaPriorityOrder, 'found', 'hit') {
1320 my $count = $bin->{$k};
1321 next if $count == 0;
1322 my $b;
1323 if (exists($data{$key})) {
1324 $b = $data{$key};
1325 } else {
1326 $b = {};
1327 $data{$key} = $b;
1328 }
1329 if (exists($b->{$i})) {
1330 $b->{$i}->{$k} = $count;
1331 } else {
1332 $b->{$i} = {$k => $count};
1333 }
1334 }
1335 }
1336 }
1337 }
1338 if (grep(/^owner$/, @CoverageCriteria::criteriaCallbackTypes)) {
1339 foreach my $t (LINE_DATA, BRANCH_DATA, MCDC_DATA) {
1340 my $key = type2str($t);
1341 next unless exists($self->[$t]->[OWNERS]);
1342 my $ownerBins = $self->[$t]->[OWNERS];
1343 while (my ($owner, $bin) = each(%$ownerBins)) {
1344 my $b;
1345 if (exists($data{$key})) {
1346 $b = $data{$key};
1347 } else {
1348 $b = {};
1349 $data{$key} = $b;
1350 }
1351 my $d = {};
1352 $b->{$owner} = $d;
1353 foreach my $k (@tlaPriorityOrder, 'found', 'hit') {
1354 next unless exists($bin->{$k});
1355 my $count = $bin->{$k};
1356 next if $count == 0;
1357 $d->{$k} = $count;
1358 }
1359 }
1360 }
1361 }
1362 my $name = $self->type() eq 'top' ? 'top' : $self->name();
1363 my $cmd =
1364 join(' ', @CoverageCriteria::coverageCriteriaScript) .
1365 ' \'' . $name . '\' ' . $self->type() . ' \'json_encoded_data\'';
1366 # command: script name (top|dir|file) jsonString args..
1367 lcovutil::info(1, "criteria: '$cmd'\n");
1368 CoverageCriteria::executeCallback($self->type(), $name, \%data);
1369 my $end = Time::HiRes::gettimeofday();
1370 $lcovutil::profileData{criteria}{$name} = $end - $start;
1371 }
1372
1373 package OwnerDetailCallback;
1374 # somewhat of a hack...I want a class which has a callback 'get'
1375 # that matches the SummaryInfo::get method - but returns owner-specific
1376 # information
1377
1378 use constant {
1379 SUMMARY => 0,
1380 OWNER => 1,
1381 TYPE => 2,
1382 };
1383
1384 sub new
1385 {
1386 my ($class, $summary, $owner, $covType) = @_;
1387 die("missing type") unless defined($covType);
1388
1389 my $self = [$summary, $owner, $covType];
1390 bless $self, $class;
1391 return $self;
1392 }
1393
1394 sub label
1395 {
1396 my $self = shift;
1397 return $self->owner();
1398 }
1399
1400 sub cb_type
1401 {
1402 my $self = shift;
1403 return 'owner';
1404 }
1405
1406 sub get
1407 {
1408 my ($self, $key, $type) = @_;
1409
1410 my ($summary, $owner, $covType) = @$self;
1411
1412 die("unexpected type $type")
1413 unless !defined($type) || ($type eq $covType);
1414
1415 return $summary->owner_tlaCount($owner, $key, $covType);
1416 }
1417
1418 sub owner
1419 {
1420 my $self = shift;
1421 return $self->[OWNER];
1422 }
1423
1424 sub covType
1425 {
1426 my $self = shift;
1427 return $self->[TYPE];
1428 }
1429
1430 package DateDetailCallback;
1431 # as above: callback class to return date-specific TLA counts
1432
1433 use constant {
1434 SUMMARY => 0,
1435 AGE => 1,
1436 TYPE => 2,
1437 BIN => 3,
1438 };
1439
1440 sub new
1441 {
1442 my ($class, $summary, $age, $covType) = @_;
1443 $covType = SummaryInfo::LINE_DATA unless defined($covType);
1444
1445 my $self = [$summary, $age, $covType, SummaryInfo::findAgeBin($age)];
1446 bless $self, $class;
1447 return $self;
1448 }
1449
1450 sub get
1451 {
1452 my ($self, $key, $type) = @_;
1453
1454 my ($summary, $age, $covType) = @$self;
1455
1456 die("unexpected type $type")
1457 unless (!defined($type) || ($type == $covType));
1458
1459 return $summary->lineCovCount($key, 'age', $age)
1460 if $covType == SummaryInfo::LINE_DATA;
1461
1462 return $summary->functionCovCount($key, 'age', $age)
1463 if $covType == SummaryInfo::FUNCTION_DATA;
1464
1465 return $summary->mcdcCovCount($key, 'age', $age)
1466 if $covType == SummaryInfo::MCDC_DATA;
1467
1468 die('$covType coverage not yet implemented')
1469 if $covType != SummaryInfo::BRANCH_DATA;
1470
1471 return $summary->branchCovCount($key, 'age', $age);
1472 }
1473
1474 sub label
1475 {
1476 my $self = shift;
1477 return $self->age();
1478 }
1479
1480 sub cb_type
1481 {
1482 my $self = shift;
1483 return 'date';
1484 }
1485
1486 sub age
1487 {
1488 my $self = shift;
1489 return $self->[AGE];
1490 }
1491
1492 sub bin
1493 {
1494 my $self = shift;
1495 return $self->[BIN];
1496 }
1497
1498 sub covType
1499 {
1500 my $self = shift;
1501 return $self->[TYPE];
1502 }
1503
1504 package FileOrDirectoryCallback;
1505 # callback class used by 'write_file_table' to retrieve count of the
1506 # various coverpoint categories in the file or directory (i.e., total
1507 # number).
1508 # Other callbacks classes are used to retrieve per-owner counts, etc.
1509
1510 sub new
1511 {
1512 # dirSummary: SummaryInfo object
1513 my ($class, $path, $summary) = @_;
1514
1515 my $self = [$path, $summary];
1516
1517 bless $self, $class;
1518 return $self;
1519 }
1520
1521 # page_link is HTML reference to file table page next level down -
1522 # for top-level page: link to directory-level page
1523 # for directory-level page: link to source file details
1524 sub page_link
1525 {
1526 my $self = shift;
1527 my $data = $self->summary();
1528 my $page_link = '';
1529 $page_link =
1530 ($main::flat && '.' ne $data->relativeDir()) ?
1531 File::Spec->catfile($data->relativeDir(), $self->name()) :
1532 $self->name();
1533 if ($data->type() eq 'file') {
1534 if ($main::no_sourceview) {
1535 return "";
1536 }
1537 $page_link .= ".gcov";
1538 $page_link .= ".frameset"
1539 if ($main::frames);
1540 } else {
1541 $page_link =~ s/^$lcovutil::dirseparator//;
1542 $page_link .= $lcovutil::dirseparator . "index";
1543 }
1544 $page_link .= '.' . $main::html_ext;
1545 return $lcovutil::case_insensitive ? lc($page_link) : $page_link;
1546 }
1547
1548 sub data
1549 {
1550 my $self = shift;
1551 # ($found, $hit, $fn_found, $fn_hit, $br_found, $br_hit, $page_link,
1552 # $fileSummary, $fileDetails)
1553
1554 my $summary = $self->summary();
1555 my @rtn;
1556 foreach my $type (SummaryInfo::LINE_DATA, SummaryInfo::FUNCTION_DATA,
1557 SummaryInfo::BRANCH_DATA, SummaryInfo::MCDC_DATA
1558 ) {
1559 my $hash = $summary->[$type]->[SummaryInfo::DATA];
1560 push(@rtn, $hash->{found}, $hash->{hit});
1561 }
1562 my $link = $self->page_link();
1563 my $sourceFile = $summary->fileDetails()
1564 if 'file' eq $summary->type();
1565 push(@rtn, $link, $summary, $sourceFile);
1566 return @rtn;
1567 }
1568
1569 sub secondaryElementFileData
1570 {
1571 my ($self, $name) = @_;
1572 my $summary = $self->summary();
1573 my $sourceFile = $summary->fileDetails()
1574 if 'file' eq $summary->type();
1575 return [$summary->name(), $summary, $sourceFile, $self->page_link()];
1576 }
1577
1578 sub name
1579 {
1580 my $self = shift;
1581 return $self->[0];
1582 }
1583
1584 sub summary
1585 {
1586 # return undef or SummaryInfo object
1587 my $self = shift;
1588 return $self->[1];
1589 }
1590
1591 sub findOwnerList
1592 {
1593 my $self = shift;
1594 # return [ [owner, lineCovData, branchCovData]] for each owner
1595 # where lineCovData = [missedCount, totalCount, callback]
1596 # branchCovData = [missed, total, callback] or undef if not enabled
1597 # - sorted in descending order number of missed lines
1598 return $self->summary()->findOwnerList(@_);
1599 }
1600
1601 sub dateDetailCallback
1602 {
1603 # callback to compute count in particular date bin
1604 my ($self, $ageval, $covtype) = @_;
1605 $covtype == SummaryInfo::LINE_DATA ||
1606 $covtype == SummaryInfo::BRANCH_DATA ||
1607 $covtype == SummaryInfo::MCDC_DATA ||
1608 $covtype == SummaryInfo::FUNCTION_DATA or
1609 die("'$covtype' type not supported");
1610
1611 return DateDetailCallback->new($self->summary(), $ageval, $covtype);
1612 }
1613
1614 sub ownerDetailCallback
1615 {
1616 # callback to compute count in particular owner bin
1617 my ($self, $owner, $covtype) = @_;
1618 $covtype == SummaryInfo::LINE_DATA ||
1619 $covtype == SummaryInfo::BRANCH_DATA or
1620 $covtype == SummaryInfo::MCDC_DATA or
1621 die("'$covtype' type not supported");
1622
1623 return OwnerDetailCallback->new($self->summary(), $owner, $covtype);
1624 }
1625
1626 sub totalCallback
1627 {
1628 my ($self, $covtype) = @_;
1629 # callback to compute total elements of 'covtype' in each TLA
1630 if (SummaryInfo::LINE_DATA == $covtype) {
1631 return $self->summary();
1632 } else {
1633 return CovTypeSummaryCallback->new($self->summary(), $covtype);
1634 }
1635 }
1636
1637 package FileOrDirectoryOwnerCallback;
1638 # callback class used by 'write_file_table' to retrieve owner-
1639 # specific coverage numbers (for all entries in the directory)
1640
1641 sub new
1642 {
1643 my ($class, $owner, $dirSummary) = @_;
1644
1645 my $self = [$owner, $dirSummary];
1646 bless $self, $class;
1647 return $self;
1648 }
1649
1650 sub name
1651 {
1652 my $self = shift;
1653 return $self->[0];
1654 }
1655
1656 sub summary
1657 {
1658 my $self = shift;
1659 return $self->[1];
1660 }
1661
1662 sub data
1663 {
1664 my $self = shift;
1665
1666 my $lineCb = OwnerDetailCallback->new($self->[1], $self->[0],
1667 SummaryInfo::LINE_DATA);
1668 my $found = $lineCb->get('found');
1669 my $hit = $lineCb->get('hit');
1670 my $branchCb =
1671 OwnerDetailCallback->new($self->[1], $self->[0],
1672 SummaryInfo::BRANCH_DATA);
1673 my $mcdcCb =
1674 OwnerDetailCallback->new($self->[1], $self->[0],
1675 SummaryInfo::MCDC_DATA);
1676 my $fn_found = 0;
1677 # ($found, $hit, $fn_found, $fn_hit, $br_found, $br_hit, $page_link,
1678 # $fileSummary, $fileDetails)
1679 # this is the 'totals' callback for this owner - so there is no
1680 # associated file or summary info. Pass undef.
1681 return ($lineCb->get('found'), $lineCb->get('hit'),
1682 0, 0, # fn_found, fn_hit
1683 $branchCb->get('found'), $branchCb->get('hit'),
1684 $mcdcCb->get('found'), $mcdcCb->get('hit'));
1685 }
1686
1687 sub totalCallback
1688 {
1689 # callback to compute total 'covtype' elements in each TLA
1690 my ($self, $covtype) = @_;
1691 die("$covtype not supported by OwnerDetail callback")
1692 unless ($covtype == SummaryInfo::LINE_DATA ||
1693 $covtype == SummaryInfo::BRANCH_DATA ||
1694 $covtype == SummaryInfo::MCDC_DATA);
1695
1696 return OwnerDetailCallback->new($self->[1], $self->name(), $covtype);
1697 }
1698
1699 sub findFileList
1700 {
1701 my ($self, $all) = @_;
1702
1703 # return [ [filename, lineCovData, branchCovData]] for each file
1704 # such that this owner has at least 1 line.
1705 # where lineCovData = [missedCount, totalCount, OwnerDetailCallback]
1706 # branchCovData = [missed, total, dateDetailCallback]
1707 # or undef if not enabled
1708 # - sorted in descending order number of missed lines
1709 my $dirSummary = $self->[1];
1710 my $owner = $self->[0];
1711 my @files;
1712 my $skipped = 0;
1713 foreach my $file ($dirSummary->sources()) {
1714 my $source = $dirSummary->get_source($file);
1715 next unless $source->contains_owner($owner);
1716
1717 my $lineCb =
1718 OwnerDetailCallback->new($source, $owner, SummaryInfo::LINE_DATA);
1719 my $brCb =
1720 OwnerDetailCallback->new($source, $owner, SummaryInfo::BRANCH_DATA);
1721 my $mcdcCb =
1722 OwnerDetailCallback->new($source, $owner, SummaryInfo::MCDC_DATA);
1723 my $funcCb =
1724 OwnerDetailCallback->new($source, $owner,
1725 SummaryInfo::FUNCTION_DATA);
1726 my $total = $lineCb->get('found');
1727 my $br_total = $lcovutil::br_coverage ? $brCb->get('found') : 0;
1728 my $fn_total = $lcovutil::func_coverage ? $funcCb->get('found') : 0;
1729 my $mcdc_total = $lcovutil::mcdc_coverage ? $mcdcCb->get('found') : 0;
1730 next
1731 if (0 == $total &&
1732 0 == $br_total &&
1733 0 == $mcdc_total &&
1734 0 == $fn_total);
1735 my $missed = $lineCb->get('missed');
1736 my $br_missed = $lcovutil::br_coverage ? $brCb->get('missed') : 0;
1737 my $mcdc_missed = $lcovutil::mcdc_coverage ? $mcdcCb->get('missed') : 0;
1738 my $fn_missed = $lcovutil::func_coverage ? $funcCb->get('missed') : 0;
1739
1740 if ($all ||
1741 0 != $missed ||
1742 0 != $br_missed ||
1743 0 != $fn_missed ||
1744 0 != $mcdc_missed) {
1745
1746 push(@files,
1747 [$file,
1748 [$missed, $total, $lineCb],
1749 [$br_missed, $br_total, $brCb],
1750 [$mcdc_missed, $mcdc_total, $mcdcCb],
1751 [$fn_missed, $fn_total, $funcCb]
1752 ]);
1753 } else {
1754 ++$skipped;
1755 }
1756 }
1757 return [$skipped, @files];
1758 }
1759
1760 sub secondaryElementFileData
1761 {
1762 my ($self, $name) = @_;
1763 my $dirSummary = $self->[1];
1764 my $file = File::Basename::basename($name);
1765 my $sourceSummary = $dirSummary->get_source($name);
1766
1767 my $page_link;
1768 if ($sourceSummary->is_directory()) {
1769 $page_link =
1770 File::Spec->catfile($name, "index-bin_owner." . $main::html_ext);
1771 } elsif ($main::no_sourceview) {
1772 $page_link = "";
1773 } else {
1774 $name = $file;
1775 $page_link = $name . ".gcov.";
1776 $page_link .= "frameset."
1777 if $main::frames;
1778 $page_link .= $main::html_ext;
1779 }
1780 $page_link = lc($page_link) if $lcovutil::case_insensitive;
1781 # pass owner in callback data
1782 my $sourceFile = $sourceSummary->fileDetails()
1783 if 'file' eq $sourceSummary->type();
1784 return [$name, $sourceSummary, $sourceFile, $page_link, $self->[0]];
1785 }
1786
1787 package FileOrDirectoryDateCallback;
1788 # callback class used by 'write_file_table' to retrieve date-
1789 # specific coverage numbers (for all entries in the directory)
1790
1791 sub new
1792 {
1793 my ($class, $bin, $dirSummary) = @_;
1794
1795 my $self = [$bin, $dirSummary->age_sample($bin), $dirSummary];
1796 bless $self, $class;
1797 return $self;
1798 }
1799
1800 sub name
1801 {
1802 my $self = shift;
1803 return $SummaryInfo::ageGroupHeader[$self->[0]];
1804 }
1805
1806 sub summary
1807 {
1808 my $self = shift;
1809 return $self->[2];
1810 }
1811
1812 sub data
1813 {
1814 my $self = shift;
1815
1816 my @rtn;
1817 foreach my $covType (SummaryInfo::LINE_DATA, SummaryInfo::FUNCTION_DATA,
1818 SummaryInfo::BRANCH_DATA, SummaryInfo::MCDC_DATA
1819 ) {
1820 my $cb = DateDetailCallback->new($self->[2], $self->[1], $covType);
1821 push(@rtn, $cb->get('found'), $cb->get('hit'));
1822 }
1823 # ($found, $hit, $fn_found, $fn_hit, $br_found, $br_hit, $page_link,
1824 # $fileSummary, $fileDetails)
1825 # this is the top-level 'total' callback - so no associated file or
1826 # summary info
1827 return @rtn;
1828 }
1829
1830 sub totalCallback
1831 {
1832 # callback to compute total elements of 'covtype' in each TLA
1833 my ($self, $covtype) = @_;
1834 return DateDetailCallback->new($self->[2], $self->[1], $covtype);
1835 }
1836
1837 sub findFileList
1838 {
1839 my ($self, $all) = @_;
1840
1841 # return [ [filename, lineCovData, branchCovData]] for each file
1842 # such that this owner has at least 1 line.
1843 # where lineCovData = [missedCount, totalCount, OwnerDetailCallback]
1844 # branchCovData = [missed, total, dateDetailCallback]
1845 # or undef if not enabled
1846 # - sorted in descending order number of missed lines
1847 my $dirSummary = $self->[2];
1848 my $ageval = $self->[1];
1849 my @files;
1850 my $skipped = 0;
1851 foreach my $file ($dirSummary->sources()) {
1852 my $source = $dirSummary->get_source($file);
1853
1854 my $lineCb =
1855 DateDetailCallback->new($source, $ageval, SummaryInfo::LINE_DATA);
1856 my $brCb =
1857 DateDetailCallback->new($source, $ageval, SummaryInfo::BRANCH_DATA);
1858 my $mcdcCb =
1859 DateDetailCallback->new($source, $ageval, SummaryInfo::MCDC_DATA);
1860 my $funcCb =
1861 DateDetailCallback->new($source, $ageval,
1862 SummaryInfo::FUNCTION_DATA);
1863 my $total = $lineCb->get('found');
1864 my $br_total = $lcovutil::br_coverage ? $brCb->get('found') : 0;
1865 my $mcdc_total = $lcovutil::mcdc_coverage ? $mcdcCb->get('found') : 0;
1866 my $fn_total = $lcovutil::func_coverage ? $funcCb->get('found') : 0;
1867 next
1868 if (0 == $total &&
1869 0 == $br_total &&
1870 0 == $mcdc_total &&
1871 0 == $fn_total);
1872
1873 my $missed = $lineCb->get('missed');
1874 my $br_missed = $lcovutil::br_coverage ? $brCb->get('missed') : 0;
1875 my $mcdc_missed = $lcovutil::mcdc_coverage ? $mcdcCb->get('missed') : 0;
1876 my $fn_missed = $lcovutil::func_coverage ? $funcCb->get('missed') : 0;
1877 if ($all ||
1878 0 != $missed ||
1879 0 != $br_missed ||
1880 0 != $mcdc_missed ||
1881 0 != $fn_missed) {
1882 push(@files,
1883 [$file,
1884 [$missed, $total, $lineCb],
1885 [$br_missed, $br_total, $brCb],
1886 [$mcdc_missed, $mcdc_total, $mcdcCb],
1887 [$fn_missed, $fn_total, $funcCb]
1888 ]);
1889 } else {
1890 ++$skipped;
1891 }
1892 }
1893 return [$skipped, @files];
1894 }
1895
1896 sub secondaryElementFileData
1897 {
1898 my ($self, $name) = @_;
1899 my $dirSummary = $self->[2];
1900 my $file = File::Basename::basename($name);
1901 my $sourceSummary = $dirSummary->get_source($name);
1902
1903 my $page_link;
1904 if ($sourceSummary->is_directory()) {
1905 $page_link =
1906 File::Spec->catfile($name, "index-bin_date." . $main::html_ext);
1907 } elsif ($main::no_sourceview) {
1908 $page_link = "";
1909 } else {
1910 $name = $file;
1911 $page_link = $name . ".gcov.";
1912 $page_link .= "frameset."
1913 if $main::frames;
1914 $page_link .= $main::html_ext;
1915 }
1916 $page_link = lc($page_link) if $lcovutil::case_insensitive;
1917 # pass bin index in callback data
1918 my $sourceFile = $sourceSummary->fileDetails()
1919 if 'file' eq $sourceSummary->type();
1920 return [$name, $sourceSummary, $sourceFile, $page_link, $self->[0]];
1921 }
1922
1923 package CovTypeSummaryCallback;
1924 # callback class to return total branches in each TLA category
1925 sub new
1926 {
1927 my ($class, $summary, $covType) = @_;
1928 defined($summary) or
1929 die("no summary");
1930 die("$covType not supported yet")
1931 unless ($covType eq SummaryInfo::LINE_DATA ||
1932 $covType eq SummaryInfo::BRANCH_DATA ||
1933 $covType eq SummaryInfo::MCDC_DATA ||
1934 $covType eq SummaryInfo::FUNCTION_DATA);
1935 my $self = [$summary, $covType];
1936 bless $self, $class;
1937 return $self;
1938 }
1939
1940 sub get
1941 {
1942 my ($self, $key) = @_;
1943
1944 return $self->[0]->get($key, $self->[1]);
1945 }
1946
1947 sub owner
1948 {
1949 my $self = shift;
1950 die("CovTypeSummaryCallback::owner not supported for " . $self->[1])
1951 unless ($self->[1] == SummaryInfo::BRANCH_DATA ||
1952 $self->[1] == SummaryInfo::MCDC_DATA);
1953 return $self->[0]->owner();
1954 }
1955
1956 sub age
1957 {
1958 my $self = shift;
1959 return $self->[0]->age();
1960 }
1961
1962 sub bin
1963 {
1964 my $self = shift;
1965 return $self->[0]->bin();
1966 }
1967
1968 sub covType
1969 {
1970 my $self = shift;
1971 return $self->[1];
1972 }
1973
1974 package PrintCallback;
1975 # maintain some callback data from one line to the next
1976
1977 use constant {
1978 FILE_INFO => 0, # SourceFile struct
1979 LINE_DATA => 1, # FileCoverageInfo struct
1980 TLA => 2,
1981 OWNER => 3,
1982 AGE => 4,
1983 NEXT_OWNER => 5,
1984 NEXT_AGE => 6,
1985 LINENO => 7,
1986 };
1987
1988 sub new
1989 {
1990 my ($class, $sourceFileStruct, $lineCovInfo) = @_;
1991 my $self = [$sourceFileStruct,
1992 $lineCovInfo,
1993 "", # current TLA
1994 "", # owner
1995 "", # age
1996 {}, # next header line for corresponding owner
1997 {}, # next header line for corresponding date bin
1998 undef # line number
1999 ];
2000 bless $self, $class;
2001 return $self;
2002 }
2003
2004 sub sourceDetail
2005 {
2006 my $self = shift;
2007 return $self->[FILE_INFO];
2008 }
2009
2010 sub lineData
2011 {
2012 my $self = shift;
2013 return $self->[LINE_DATA];
2014 }
2015
2016 sub lineNo
2017 {
2018 my ($self, $lineNo) = @_;
2019 $self->[LINENO] = $lineNo
2020 if defined($lineNo);
2021 return $self->[LINENO];
2022 }
2023
2024 sub tla
2025 {
2026 my ($self, $newTLA, $lineNo) = @_;
2027 # NOTE: 'undef' TLA means that this line is not code (it is a comment,
2028 # blank line, opening brace or something).
2029 # We return 'same' as previous line' in that case so the category
2030 # block can be larger (e.g., 1 CBC line, a 2 line comment, then 3 more
2031 # lines) can get just one label (first line).
2032 # This reduces visual clutter.
2033 # Note that the 'block finding' code has to do the same thing (else the
2034 # HTML links won't be generated correctly)
2035 if (defined($newTLA) &&
2036 $newTLA ne $self->[TLA]) {
2037 $self->[TLA] = $newTLA;
2038 return $newTLA;
2039 }
2040 return " " x $main::tla_field_width; # same TLA as previous line.
2041 }
2042
2043 sub age
2044 {
2045 my ($self, $newval, $lineNo) = @_;
2046 if (defined($newval) && $newval ne $self->[AGE]) {
2047 $self->[AGE] = $newval;
2048 return $newval;
2049 }
2050 return " " x $main::age_field_width; # same age as previous line.
2051 }
2052
2053 sub owner
2054 {
2055 my ($self, $newval, $lineNo) = @_;
2056 if (defined($newval) && $newval ne $self->[OWNER]) {
2057 $self->[OWNER] = $newval;
2058 return $newval;
2059 }
2060 return " " x $main::owner_field_width; # same age as previous line.
2061 }
2062
2063 sub current
2064 {
2065 my ($self, $key) = @_;
2066
2067 if ($key eq 'tla') {
2068 return $self->[TLA];
2069 } elsif ($key eq 'owner') {
2070 return $self->[OWNER];
2071 } elsif ($key eq 'age') {
2072 return $self->[AGE];
2073 } else {
2074 ($key eq 'dateBucket') or
2075 die("unexpected key $key");
2076 return SummaryInfo::findAgeBin($self->[AGE]);
2077 }
2078 }
2079
2080 sub nextOwner
2081 {
2082 my ($self, $owner, $tla, $value) = @_;
2083 my $map = $self->[NEXT_OWNER];
2084
2085 my $key = $tla . ' ' . $owner;
2086 if (defined($value)) {
2087 $map->{$key} = $value;
2088 return $value;
2089 }
2090 return exists($map->{$key}) ? $map->{$key} : undef;
2091 }
2092
2093 sub nextDate
2094 {
2095 my ($self, $date, $tla, $value) = @_;
2096 my $map = $self->[NEXT_AGE];
2097 my $key = $tla . ' ' . $date;
2098 if (defined($value)) {
2099 $map->{$key} = $value;
2100 return $value;
2101 }
2102 return $map->{$key};
2103 }
2104
2105 package ReadBaselineSource;
2106
2107 use base 'ReadCurrentSource';
2108
2109 sub new
2110 {
2111 my ($class, $diffData) = @_;
2112
2113 my $self = $class->SUPER::new();
2114 push(@$self, $diffData);
2115
2116 return $self;
2117 }
2118
2119 sub open
2120 {
2121 my ($self, $filename) = @_;
2122 my $diffmap = $self->[1];
2123 if (defined($diffmap) && $diffmap->containsFile($filename)) {
2124 # if there are any diffs, then need to load the current source, then
2125 # walk the diff to insert and remove changed lines
2126
2127 my $currentSrc = $self->_load($filename, 'baseline');
2128 my $src = $diffmap->recreateBaseline($filename, $currentSrc);
2129 return $self->parseLines($filename, $src);
2130 }
2131 # else no diff data here - just read the file
2132 return ReadCurrentSource::open($self, $filename, 'baseline');
2133 }
2134
2135 package LineData;
2136
2137 use constant {
2138 TYPE => 0,
2139 LINENO_BASE => 1,
2140 LINENO_CURRENT => 2, # location of this line in current data
2141 LINE_DATA => 3,
2142 BRANCH_DATA => 4,
2143 MCDC_DATA => 5,
2144 FUNCTION_DATA => 6,
2145
2146 # data elements in line data
2147 TLA => 0,
2148 LINE_BASELINE => 1,
2149 LINE_CURRENT => 2,
2150
2151 # data elements for branch/function data
2152 DATA_BASELINE => 0,
2153 DATA_CURRENT => 1,
2154 DATA_DIFFERENTIAL => 2,
2155 };
2156
2157 sub new
2158 {
2159 my ($class, $type) = @_;
2160 # [ type, lineNo_base, lineNo_current,
2161 # bucket, base_count, curr_count <- line coverage count data
2162 # base_branch, curr_branch, differential_branch ] <- branch coverage count data
2163 # $type in ('insert', 'equal', 'delete')
2164 my $self = [$type, undef, undef,
2165 ['UNK', undef, undef], # line coverage data
2166 [], # branch coverage data
2167 [], # MCDC coverage data
2168 []
2169 ]; # function coverage
2170 bless $self, $class;
2171 return $self;
2172 }
2173
2174 sub to_list
2175 {
2176 # used by script-level 'select' callback
2177 my $self = shift;
2178
2179 my @rtn = ($self->[TYPE],
2180 [$self->tla(),
2181 $self->in_curr() ? $self->curr_count() : undef,
2182 $self->in_base() ? $self->base_count() : undef
2183 ]);
2184 # @todo perhaps visit MC/DC here too
2185 my $branch = $self->differential_branch();
2186 if (defined($branch)) {
2187 my @data;
2188 push(@rtn, \@data);
2189 foreach my $block ($branch->blocks()) {
2190 my $br = $branch->getBlock($block);
2191 my @b;
2192 push(@data, \@b);
2193 foreach my $b (@$br) {
2194 my ($br, $tla, $d) = @$b;
2195 my ($base_count, $curr_count) = @$d;
2196 push(@b, [$tla, $curr_count, $base_count]);
2197 }
2198 }
2199 } else {
2200 $branch = $self->current_branch();
2201 if (defined($branch)) {
2202 my @data;
2203 push(@rtn, \@data);
2204 foreach my $block ($branch->blocks()) {
2205 my $br = $branch->getBlock($block);
2206 push(@data, $br->count());
2207 }
2208 } else {
2209 push(@rtn, undef);
2210 }
2211 }
2212 return \@rtn;
2213 }
2214
2215 sub tla
2216 {
2217 my ($self, $tla) = @_;
2218 my $linecov = $self->[LINE_DATA];
2219 $linecov->[TLA] = $tla
2220 if defined($tla);
2221 return $linecov->[TLA];
2222 }
2223
2224 sub type
2225 {
2226 my $self = shift;
2227 return $self->[TYPE];
2228 }
2229
2230 sub lineNo
2231 {
2232 my ($self, $which, $lineNo) = @_;
2233 my $loc;
2234 if ($which eq "current") {
2235 $loc = LINENO_CURRENT;
2236 } else {
2237 die("unknown key $which - should be 'base' or 'current'")
2238 unless $which eq "base";
2239 $loc = LINENO_BASE;
2240 }
2241 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2242 "inconsistent $which line location $loc: " .
2243 $self->[$loc] . " -> $lineNo")
2244 if (defined($lineNo) &&
2245 defined($self->[$loc]) &&
2246 $self->[$loc] != $lineNo);
2247
2248 $self->[$loc] = $lineNo
2249 if defined($lineNo);
2250 return $self->[$loc];
2251 }
2252
2253 sub in_base
2254 {
2255 # @return true or false: is this object present in the baseline?
2256 my $self = shift;
2257 # coverpoint is in baseline data if line coverage number is defined
2258 return defined($self->[LINE_DATA]->[LINE_BASELINE]);
2259 }
2260
2261 sub in_curr
2262 {
2263 # @return true or false: is this object present in the current version?
2264 # storing negative number for 'current' location of deleted line -
2265 # first location above or below the deleted region
2266 my $self = shift;
2267 # coverpoint is in current data if line coverage number is defined
2268 # otherwise, the line may be present without coverage data associated
2269 # with it (say, excluded now - or possibly filtered out)
2270 return defined($self->[LINE_DATA]->[LINE_CURRENT]);
2271 }
2272
2273 sub base_count
2274 {
2275 # return line hit count in baseline
2276 my ($self, $inc) = @_;
2277 die("non-zero count but not in base")
2278 if (defined($inc) && !defined($self->[LINENO_BASE]));
2279 my $linecov = $self->[LINE_DATA];
2280 if (defined($inc)) {
2281 if (defined($linecov->[LINE_BASELINE])) {
2282 $linecov->[LINE_BASELINE] += $inc;
2283 } else {
2284 $linecov->[LINE_BASELINE] = $inc;
2285 }
2286 }
2287
2288 return $linecov->[LINE_BASELINE];
2289 }
2290
2291 sub curr_count
2292 {
2293 # return line hit count in current
2294 my ($self, $inc) = @_;
2295 die("non-zero count but not in current")
2296 if (defined($inc) &&
2297 (!defined($self->[LINENO_CURRENT]) || $self->[LINENO_CURRENT] < 0));
2298 my $linecov = $self->[LINE_DATA];
2299 if (defined($inc)) {
2300 if (defined($linecov->[LINE_CURRENT])) {
2301 $linecov->[LINE_CURRENT] += $inc;
2302 } else {
2303 $linecov->[LINE_CURRENT] += $inc;
2304 }
2305 }
2306 return $linecov->[LINE_CURRENT];
2307 }
2308
2309 sub _mergeBranchData
2310 {
2311 my ($self, $loc, $branchData, $filename) = @_;
2312 my $branch = $self->[BRANCH_DATA];
2313 if (defined($branch->[$loc])) {
2314
2315 my $current = $branch->[$loc];
2316 foreach my $branchId ($current->blocks()) {
2317 # LCOV_EXCL_START
2318 if (!$branchData->hasBlock($branchId)) {
2319 # don't know how to get here...but someone on the internet
2320 # managed to do it - so we need to handle the error
2321 my $which = $loc == DATA_BASELINE ? 'baseline' : 'current';
2322 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
2323 $filename . ':' . $current->line() .
2324 ": '$which' line " .
2325 $self->lineNo($which) .
2326 " merge block (line " .
2327 $branchData->line() .
2328 ") does not contain branch $branchId."
2329 );
2330 next;
2331 }
2332 # LCOV_EXCL_STOP
2333
2334 my $c = $current->getBlock($branchId);
2335 my $d = $branchData->getBlock($branchId);
2336 # handle case of inconsistent branch data
2337 my $nc = scalar(@$c);
2338 my $nd = scalar(@$d);
2339 # LCOV_EXCL_START
2340 if ($nc != $nd) {
2341 # similarly: this should not happen - but it might
2342 my $which = $loc == DATA_BASELINE ? 'baseline' : 'current';
2343 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
2344 $filename . ':' . $current->line() .
2345 ": '$which' line " . $self->lineNo($which) .
2346 " branch $branchId contains $nc elements but merge data contains $nd."
2347 );
2348 }
2349 # LCOV_EXCL_STOP
2350 for (my $i = ($nc > $nd ? $nd : $nc) - 1; $i >= 0; --$i) {
2351 my $br = $d->[$i];
2352 $c->[$i]->merge($br);
2353 }
2354 # now append any new values from 'branchData':
2355 # (go here only if |D| > |C| and we ignore the mismatch error
2356 for (my $i = $nc; $i < $nd; ++$i) {
2357 push(@$c, Storable::dclone($d->[$i]));
2358 }
2359 }
2360 } else {
2361 $branch->[$loc] = Storable::dclone($branchData);
2362 }
2363 }
2364
2365 sub baseline_branch
2366 {
2367 my ($self, $branchData, $filename) = @_;
2368 die("has baseline branch data but not in baseline")
2369 if (defined($branchData) && !defined($self->[LINENO_BASE]));
2370 if (defined($branchData)) {
2371 $self->_mergeBranchData(DATA_BASELINE, $branchData, $filename);
2372 }
2373 my $branch = $self->[BRANCH_DATA];
2374 return $branch->[DATA_BASELINE];
2375 }
2376
2377 sub current_branch
2378 {
2379 my ($self, $branchData, $filename) = @_;
2380 die("has current branch data but not in current")
2381 if (defined($branchData) &&
2382 (!defined($self->[LINENO_CURRENT]) || $self->[LINENO_CURRENT] < 0));
2383 if (defined($branchData)) {
2384 $self->_mergeBranchData(DATA_CURRENT, $branchData, $filename);
2385 }
2386 my $branch = $self->[BRANCH_DATA];
2387 return $branch->[DATA_CURRENT];
2388 }
2389
2390 sub differential_branch
2391 {
2392 my ($self, $differential) = @_;
2393 my $branch = $self->[BRANCH_DATA];
2394 if (defined($differential)) {
2395 $branch->[DATA_DIFFERENTIAL] = $differential;
2396 }
2397 return $branch->[DATA_DIFFERENTIAL];
2398 }
2399
2400 sub _mergeMcdcData
2401 {
2402 # this is nearly identical to 'function' implementation...maybe share
2403 my ($self, $loc, $mcdcData, $filename) = @_;
2404 my $mcdc = $self->[MCDC_DATA];
2405 if (defined($mcdc->[$loc])) {
2406
2407 my $current = $mcdc->[$loc];
2408 $current->merge($mcdcData);
2409 } else {
2410 $mcdc->[$loc] = Storable::dclone($mcdcData);
2411 }
2412 }
2413
2414 sub baseline_mcdc
2415 {
2416 my ($self, $mcdcData, $filename) = @_;
2417 die("has baseline MC/DC data but not in baseline")
2418 if (defined($mcdcData) && !defined($self->[LINENO_BASE]));
2419 if (defined($mcdcData)) {
2420 $self->_mergeMcdcData(DATA_BASELINE, $mcdcData, $filename);
2421 }
2422 my $mcdc = $self->[MCDC_DATA];
2423 return $mcdc->[DATA_BASELINE];
2424 }
2425
2426 sub current_mcdc
2427 {
2428 my ($self, $mcdcData, $filename) = @_;
2429 die("has current MC/DC data but not in current")
2430 if (defined($mcdcData) &&
2431 (!defined($self->[LINENO_CURRENT]) || $self->[LINENO_CURRENT] < 0));
2432 if (defined($mcdcData)) {
2433 $self->_mergeMcdcData(DATA_CURRENT, $mcdcData, $filename);
2434 }
2435 my $mcdc = $self->[MCDC_DATA];
2436 return $mcdc->[DATA_CURRENT];
2437 }
2438
2439 sub differential_mcdc
2440 {
2441 my ($self, $differential) = @_;
2442 my $mcdc = $self->[MCDC_DATA];
2443 if (defined($differential)) {
2444 $mcdc->[DATA_DIFFERENTIAL] = $differential;
2445 }
2446 return $mcdc->[DATA_DIFFERENTIAL];
2447 }
2448
2449 sub _mergeFunctionData
2450 {
2451 my ($self, $loc, $functionData) = @_;
2452 die('expected FunctionEntry found ' . ref($functionData))
2453 unless 'FunctionEntry' eq ref($functionData);
2454 my $function = $self->[FUNCTION_DATA];
2455 if (defined($function->[$loc])) {
2456 my $current = $function->[$loc];
2457 $current->merge($functionData);
2458 } else {
2459 # also clone hit count data
2460 $function->[$loc] = $functionData->cloneWithEndLine(1, 1);
2461 }
2462 }
2463
2464 sub baseline_function
2465 {
2466 my ($self, $functionData) = @_;
2467 die("has baseline function data but not in baseline")
2468 if (defined($functionData) && !defined($self->[LINENO_BASE]));
2469 if (defined($functionData)) {
2470 $self->_mergeFunctionData(DATA_BASELINE, $functionData);
2471 }
2472 my $function = $self->[FUNCTION_DATA];
2473 return $function->[DATA_BASELINE];
2474 }
2475
2476 sub current_function
2477 {
2478 my ($self, $functionData) = @_;
2479 die("has current function data but not in current")
2480 if (defined($functionData) &&
2481 (!defined($self->[LINENO_CURRENT]) || $self->[LINENO_CURRENT] < 0));
2482 if (defined($functionData)) {
2483 $self->_mergeFunctionData(DATA_CURRENT, $functionData);
2484 }
2485 my $function = $self->[FUNCTION_DATA];
2486 return $function->[DATA_CURRENT];
2487 }
2488
2489 sub differential_function
2490 {
2491 my ($self, $differential) = @_;
2492 my $function = $self->[FUNCTION_DATA];
2493 if (defined($differential)) {
2494 $function->[DATA_DIFFERENTIAL] = $differential;
2495 }
2496 return $function->[DATA_DIFFERENTIAL];
2497 }
2498
2499 # structure holding coverage data for a particular file:
2500 # - associated with a line line number:
2501 # - line coverage
2502 # - branch coverage
2503 # - function coverage (not directly associated with line number
2504 package FileCoverageInfo;
2505
2506 use constant {
2507 VERSION => 0,
2508 LINEMAP => 1,
2509 DELETED_LINE_LEADER => 2,
2510 FUNCTIONMAP => 3,
2511 };
2512
2513 sub new
2514 {
2515 my ($class, $filename, $base_data, $current_data, $diffMap, $verbose) = @_;
2516
2517 # [hash of lineNumber -> LineData struct, optional FunctionMap]
2518 my $self = [
2519 [defined($base_data) ? $base_data->version() : undef,
2520 $current_data->version()
2521 ],
2522 {}, # the line data map
2523 {} # currentLineNo -> [deleted lines for which this is the leader]
2524 ];
2525 bless $self, $class;
2526
2527 $diffMap->show_map($filename)
2528 if ((defined($verbose) && $verbose) ||
2529 (defined($lcovutil::verbose) && $lcovutil::verbose > 1));
2530
2531 # line coverage categorization includes date- and owner- bins in
2532 # the vanilla case when there is no baseline.
2533 $self->_categorizeLineCov($filename, $base_data, $current_data,
2534 $diffMap, $verbose);
2535 $self->_categorizeBranchCov($filename, $base_data, $current_data,
2536 $diffMap, $verbose)
2537 if ($lcovutil::br_coverage);
2538 $self->_categorizeMcdcCov($filename, $base_data, $current_data,
2539 $diffMap, $verbose)
2540 if ($lcovutil::mcdc_coverage);
2541 $self->_categorizeFunctionCov($filename, $base_data, $current_data,
2542 $diffMap, $verbose)
2543 if ($lcovutil::func_coverage);
2544
2545 while (my ($lineNo, $deleted) = each(%{$self->[DELETED_LINE_LEADER]})) {
2546 @$deleted =
2547 sort({ $a->lineNo('base') <=> $b->lineNo('base') } @$deleted);
2548 }
2549 return $self;
2550 }
2551
2552 sub version
2553 {
2554 my ($self, $which) = @_;
2555 return $which eq 'current' ? $self->[VERSION]->[1] : $self->[VERSION]->[0];
2556 }
2557
2558 sub lineMap
2559 {
2560 my $self = shift;
2561 return $self->[LINEMAP];
2562 }
2563
2564 sub functionMap
2565 {
2566 # simply a map of function leader name -> differential FunctionEntry
2567 my $self = shift;
2568 return (scalar(@$self) >= FUNCTIONMAP) ? $self->[FUNCTIONMAP] : undef;
2569 }
2570
2571 sub line
2572 {
2573 my ($self, $lineNo) = @_;
2574 my $lineMap = $self->lineMap();
2575 return exists($lineMap->{$lineNo}) ? $lineMap->{$lineNo} : undef;
2576 }
2577
2578 sub deletedLineData
2579 {
2580 my ($self, $currentLineNumber) = @_;
2581
2582 my $map = $self->[DELETED_LINE_LEADER];
2583 return
2584 exists($map->{$currentLineNumber}) ? $map->{$currentLineNumber} : undef;
2585 }
2586
2587 sub recategorizeTlaAsBaseline
2588 {
2589 # intended use: this file appears to have been added to the "coverage"
2590 # suite - but the file itself is old/has been around for a long time.
2591 # - by default, we will see this as "Included Code"
2592 # - which means that 'un-exercised' code will be "UIC"
2593 # - but: non-zero UIC will fail our Jenkins coverage ratchet.
2594 # As a workaround: treat this file as if the baseline data was the same
2595 # as 'current' - so code will be categorized as "CBC/UBC" - which will not
2596 # trigger the coverage criteria.
2597 my $self = shift;
2598 my $lineMap = $self->lineMap();
2599 my %remap = ('UIC' => 'UBC',
2600 'GIC' => 'CBC');
2601
2602 while (my ($line, $data) = each(%$lineMap)) {
2603 die("unexpected $line 'in_base'") if $data->in_base();
2604
2605 my $lineTla = $data->tla();
2606 if (exists($remap{$lineTla})) {
2607 # don't remap GNC, UNC, etc
2608 $data->tla($remap{$lineTla});
2609 }
2610
2611 # branch coverage...
2612 if ($lcovutil::br_coverage && defined($data->differential_branch())) {
2613 my $br = $data->differential_branch();
2614
2615 foreach my $branchId ($br->blocks()) {
2616 my $diff = $br->getBlock($branchId);
2617 foreach my $b (@$diff) {
2618 my $tla = $b->[1];
2619 if (exists($remap{$tla})) {
2620 $b->[1] = $remap{$tla};
2621 }
2622 }
2623 }
2624 } # if branch data
2625
2626 # MC/DC coverage...
2627 if ($lcovutil::mcdc_coverage && defined($data->differential_mcdc())) {
2628 my $mcdc = $data->differential_mcdc();
2629
2630 while (my ($groupSize, $group) = each(%{$mcdc->groups()})) {
2631 foreach my $cond (@$group) {
2632 # remap both the true and false sense..
2633 foreach my $sense (0, 1) {
2634 my $c = $cond->count($sense);
2635 my $tla = $c->[0];
2636 if (exists($remap{$tla})) {
2637 $c->[0] = $remap{$tla};
2638 }
2639 }
2640 }
2641 }
2642 } # if MCDC data
2643
2644 # function coverage..
2645 if ($lcovutil::func_coverage && defined($data->differential_function()))
2646 {
2647 my $func = $data->differential_function();
2648 my $hit = $func->hit();
2649 my $tla = $hit->[1];
2650 if (exists($remap{$tla})) {
2651 $hit->[1] = $remap{$tla};
2652 }
2653
2654 while (my ($alias, $data) = each(%{$func->aliases()})) {
2655 my $tla = $data->[1];
2656 if (exists($remap{$tla})) {
2657 $data->[1] = $remap{$tla};
2658 }
2659 }
2660 }
2661 } # if function data
2662 }
2663
2664 sub _categorize
2665 {
2666 my ($baseCount, $currCount) = @_;
2667 my $tla;
2668 if (0 == $baseCount) {
2669 $tla = (0 == $currCount) ? "UBC" : "GBC";
2670 } elsif (0 == $currCount) {
2671 $tla = "LBC";
2672 } else {
2673 $tla = "CBC";
2674 }
2675 return $tla;
2676 }
2677
2678 sub _findLineData
2679 {
2680 my ($self, $diffMap, $filename, $base_lineNo) = @_;
2681 my $current_lineNo =
2682 $diffMap->lookup($filename, $diffMap->OLD, $base_lineNo);
2683 my $type = $diffMap->type($filename, $diffMap->OLD, $base_lineNo);
2684
2685 my $lineDataMap = $self->lineMap();
2686 my $linedata;
2687
2688 if ($type ne "delete") {
2689 if (!defined($lineDataMap->{$current_lineNo})) {
2690 $linedata = LineData->new($type);
2691 $lineDataMap->{$current_lineNo} = $linedata;
2692 $linedata->lineNo('current', $current_lineNo);
2693 } else {
2694 $linedata = $lineDataMap->{$current_lineNo};
2695 }
2696 $linedata->lineNo('base', $base_lineNo);
2697 } else {
2698 # nothing walks the keylist so a prefix is sufficient to distinguish
2699 # records that should be summarized but not displayed
2700 my $dline = "<<<" . $base_lineNo;
2701 if (!exists($lineDataMap->{$dline})) {
2702 $linedata = LineData->new($type);
2703 $linedata->lineNo('base', $base_lineNo);
2704 $lineDataMap->{$dline} = $linedata;
2705 # look up and/or down to find the first baseline line
2706 # which is not deleted - and store that as the corresponding
2707 # 'current' line.
2708 # this way, we can know the extents of the deleted region
2709 my $c;
2710 for (my $i = $base_lineNo - 1; $i > 0; --$i) {
2711 if ('delete' ne $diffMap->type($filename, $diffMap->OLD, $i)) {
2712 $c = $diffMap->lookup($filename, $diffMap->OLD, $i);
2713 last;
2714 }
2715 }
2716 if (!defined($c)) {
2717 # there were no 'current' lines above me - so I must be
2718 # at the first line in the file. It must not be deleted
2719 $c = 1;
2720 die("$filename:1: incorrectly marked 'delete'")
2721 if (
2722 'delete' eq $diffMap->type($filename, $diffMap->OLD, $c));
2723 }
2724 die("$filename: no current block for deleted line $base_lineNo")
2725 unless defined($c);
2726 $linedata->lineNo('current', -$c);
2727 # keep track of where deleted lines were - so we can
2728 # mark them in the source view
2729 if (exists($self->[DELETED_LINE_LEADER]->{$c})) {
2730 push(@{$self->[DELETED_LINE_LEADER]->{$c}}, $linedata);
2731 } else {
2732 $self->[DELETED_LINE_LEADER]->{$c} = [$linedata];
2733 }
2734 } else {
2735 $linedata = $lineDataMap->{$dline};
2736 }
2737 }
2738 return $linedata;
2739 }
2740
2741 # categorize line coverage numbers
2742 sub _categorizeLineCov
2743 {
2744 my ($self, $filename, $base_data, $current_data, $diffMap, $verbose) = @_;
2745 my $lineDataMap = $self->lineMap();
2746
2747 if ($verbose) {
2748 print("categorize lines $filename\n");
2749 }
2750 # $lineCovBase, $lineCovCurrent are CountData objects
2751 my $lineCovBase = $base_data->sum() if defined($base_data);
2752 my $lineCovCurrent = $current_data->sum();
2753
2754 # walk the branch coverpoints to check for data consistency:
2755 # - we expect a line coverpoint in every location which has branches
2756 # - if not found, the generate message and/or create a fake coverpoint
2757 # LLVM seems to like to generate inconsistent data.
2758 my $branchCurrent = $current_data->sumbr();
2759 foreach my $line ($branchCurrent->keylist()) {
2760 # just ignore bogus data - we already warned when we read the data
2761 next if ($line <= 0);
2762
2763 my $type = $diffMap->type($filename, $diffMap->NEW, $line);
2764 # LCOV_EXCL_START
2765 if ($type eq 'delete') {
2766 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
2767 "'current' line $filename:$line should not be marked 'delete'");
2768 delete($branchCurrent->{$line});
2769 next;
2770 }
2771 # LCOV_EXCL_STOP
2772 }
2773
2774 # it is sufficient to just walk the 'global' (merged) line
2775 # coverage dataset because we only care/we only show total
2776 # coverage - not changed coverage per testcase.
2777 # (This observation is also true for branch and function
2778 # coverages.)
2779 foreach my $line ($lineCovCurrent->keylist()) {
2780 # just ignore bogus data - we already warned when we read the data
2781 next if ($line <= 0);
2782 my $type = $diffMap->type($filename, $diffMap->NEW, $line);
2783 if ($type eq 'delete') {
2784 # can happen in some inconsistent case, when there are certain
2785 # out-of-range references in a file which contained diffs - and we
2786 # ignored the error check
2787 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2788 "'current' line $filename:$line should not be marked 'delete'");
2789 $lineCovCurrent->remove($line);
2790 next;
2791 }
2792 my $linedata;
2793 if (!exists($lineDataMap->{$line})) {
2794 $linedata = LineData->new($type);
2795 $lineDataMap->{$line} = $linedata;
2796 } else {
2797 $linedata = $lineDataMap->{$line};
2798 }
2799 my $val = $lineCovCurrent->value($line);
2800 $linedata->lineNo("current", $line);
2801 $linedata->curr_count($val);
2802 $linedata->tla($val == 0 ? 'UNC' : 'GNC')
2803 if (!defined($lineCovBase));
2804 }
2805 return unless (defined($lineCovBase));
2806
2807 foreach my $bline ($lineCovBase->keylist()) {
2808 # just ignore bogus data - we already warned when we read the data
2809 next if ($bline <= 0);
2810 my $linedata = $self->_findLineData($diffMap, $filename, $bline);
2811 my $val = $lineCovBase->value($bline);
2812 $linedata->base_count($val);
2813 }
2814 if ($verbose) {
2815 print(" line data map:\n");
2816 foreach my $line (sort keys %$lineDataMap) {
2817 my $data = $lineDataMap->{$line};
2818 print(" $line: ",
2819 $data->type(),
2820 ' curr:',
2821 $data->in_curr() ? $data->lineNo('current') : '-',
2822 ' base:',
2823 $data->in_base() ? $data->lineNo('base') : '-',
2824 "\n");
2825 }
2826 }
2827 foreach my $line (sort keys %$lineDataMap) {
2828 my $linedata = $lineDataMap->{$line};
2829 my $tla;
2830 if ($linedata->type() eq "insert") {
2831 if (!$linedata->in_curr()) {
2832 # can get here if the 'diff' file is wrong with respect to
2833 # baseline vs. current coverage data - e.g., showing that
2834 # an unchanged line has a difference
2835 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2836 "$filename:$line: 'diff' data claims this line is inserted but it is not in 'current' coverage data"
2837 );
2838 next;
2839 }
2840 $tla = ($linedata->curr_count() > 0) ? "GNC" : "UNC";
2841 print(" insert $line $tla\n") if ($verbose);
2842 } elsif ($linedata->type() eq "delete") {
2843 if (!$linedata->in_base()) {
2844 # similarly: can get here if the diff vs baseline/current data
2845 # is inconsistent.
2846 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2847 "$filename:$line: 'diff' data claims this line is deleted but it is not in 'baseline' coverage data"
2848 );
2849 next;
2850 }
2851 $tla = ($linedata->base_count() > 0) ? "DCB" : "DUB";
2852 print(" delete $line $tla\n") if ($verbose);
2853 } else {
2854 die("FileCoverageInfo:: deleted segment line=$line file=$filename")
2855 unless $linedata->type() eq "equal";
2856
2857 if ($linedata->in_base() && $linedata->in_curr()) {
2858 $tla =
2859 _categorize($linedata->base_count(), $linedata->curr_count);
2860 } elsif ($linedata->in_base()) {
2861 $tla = ($linedata->base_count() > 0) ? "ECB" : "EUB";
2862 $linedata->tla($tla);
2863 } else {
2864 die("FileCoverageInfo:: non-executed line line=$line file=$filename"
2865 ) unless $linedata->in_curr();
2866
2867 $tla = ($linedata->curr_count() > 0) ? "GIC" : "UIC";
2868 }
2869 print(" equal $line $tla in:" .
2870 ($linedata->in_base() ? ' base' : '') .
2871 ($linedata->in_curr() ? ' curr' : '') . "\n")
2872 if ($verbose);
2873 }
2874 $linedata->tla($tla);
2875 }
2876 }
2877
2878 sub _cloneBranchEntry
2879 {
2880 my ($cloneInto, $cloneFrom, $missTla, $hitTla) = @_;
2881 foreach my $branchId ($cloneFrom->blocks()) {
2882 my $block = $cloneInto->addBlock($branchId);
2883 foreach my $br (@{$cloneFrom->getBlock($branchId)}) {
2884 my $count = $br->count();
2885 my $tla = (0 == $count) ? $missTla : $hitTla;
2886 push(@$block, [$br, $tla, [undef, $count]]);
2887 }
2888 }
2889 }
2890
2891 # categorize branch coverage numbers
2892 sub _categorizeBranchCov
2893 {
2894 my ($self, $filename, $base_data, $current_data, $diffMap, $verbose) = @_;
2895 my $lineDataMap = $self->lineMap();
2896
2897 my $branchBaseline = $base_data->sumbr() if defined($base_data);
2898 my $branchCurrent = $current_data->sumbr();
2899
2900 my %branchCovLines;
2901 # look through the 'current' data, to find all the branch data
2902 # keep track of hit count in baseline, current - in element 2 of the
2903 # retained branch data. These counts are useful - for example, to report
2904 # the hit count in the baseline for LBC branches:
2905 # - e.g., in random testing: is this branch lost because it was a
2906 # low probablilty event (..baselinecount is a small number)>
2907 # Or because we did something bad and no longer reach what had been
2908 # a high probability event?
2909 foreach my $line ($branchCurrent->keylist()) {
2910 next if ($line <= 0); # ignore bogus
2911 unless (exists($lineDataMap->{$line})) {
2912 # unless ignored, should have been caught or fixed during
2913 # TraceInfo::_checkConsistency
2914 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2915 "\"$filename\":$line line has branchcov but no linecov data (skipping)."
2916 );
2917 next;
2918 }
2919 my $data = $lineDataMap->{$line};
2920
2921 $branchCovLines{$line} = 1;
2922 # we expect that the line number matches...
2923 $data->lineNo("current", $line);
2924 # append this branch data for the line
2925 my $currBranchData = $branchCurrent->value($line);
2926 $data->current_branch($currBranchData, $filename);
2927 if (!defined($branchBaseline)) {
2928 my $categorized = BranchEntry->new($line);
2929 $data->differential_branch($categorized);
2930 _cloneBranchEntry($categorized, $currBranchData, 'UNC', 'GNC');
2931 }
2932 } # foreach line in 'current' branch data
2933
2934 return unless defined($branchBaseline);
2935
2936 # now look through the baseline to find matching data
2937
2938 foreach my $base_line ($branchBaseline->keylist()) {
2939 my $data = $self->_findLineData($diffMap, $filename, $base_line);
2940 my $curr_line = $data->lineNo('current');
2941 my $type = $data->type();
2942 if ($type ne 'delete') {
2943 $branchCovLines{$curr_line} = 1;
2944 } else {
2945 # the line has been deleted...just record the data
2946 my $deleteKey = "<<<" . $base_line;
2947 }
2948 my $baseBranchData = $branchBaseline->value($base_line);
2949 $data->baseline_branch($baseBranchData, $filename);
2950 } # foreach line in baseline data
2951
2952 # go through all the branch data for each line, and categorize everything
2953 foreach my $line (keys(%branchCovLines)) {
2954 next if ($line <= 0); # ignore bogus
2955 my $data = $self->lineMap()->{$line};
2956 my $type = $data->type();
2957 my $curr = $data->current_branch();
2958 my $base = $data->baseline_branch();
2959 my $categorized = BranchEntry->new($line);
2960 $data->differential_branch($categorized);
2961 # handle case that baseline and/or current do not contain branch data
2962 my @currBlocks = defined($curr) ? $curr->blocks() : ();
2963 my @baseBlocks = defined($base) ? $base->blocks() : ();
2964
2965 if ($type eq 'insert') {
2966 # can get here if diff data vs baseline/current is not consistent
2967 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2968 "baseline branch data should not be defined for inserted line $filename:$line"
2969 ) if defined($base);
2970
2971 _cloneBranchEntry($categorized, $curr, 'UNC', 'GNC');
2972 } elsif ($type eq 'delete') {
2973 # similarly: get here if diff data vs baseline/current is not consistent
2974 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
2975 "current branch data should not be defined for deleted line $filename:$line"
2976 ) if defined($curr);
2977
2978 _cloneBranchEntry($categorized, $base, 'DUB', 'DCB');
2979 } else {
2980 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
2981 "unexpected branch coverage type $type at $filename:$line")
2982 if $type ne 'equal';
2983
2984 # branch might or might not be in both baseline and current
2985 foreach my $branchId (@baseBlocks) {
2986 my $b = $base->getBlock($branchId);
2987 my $branchData = $categorized->addBlock($branchId);
2988 if (defined($curr) &&
2989 $curr->hasBlock($branchId)) {
2990 my $c = $curr->getBlock($branchId);
2991
2992 my $num_base = scalar(@$b);
2993 my $num_curr = scalar(@$c);
2994 my $max = $num_base > $num_curr ? $num_base : $num_curr;
2995 my $tla;
2996 for (my $i = 0; $i < $max; ++$i) {
2997 if ($i < $num_base &&
2998 $i < $num_curr) {
2999 my $base_br = $b->[$i];
3000 my $curr_br = $c->[$i];
3001 $tla =
3002 _categorize($base_br->count(),
3003 $curr_br->count());
3004 push(@$branchData,
3005 [$curr_br, $tla,
3006 [$base_br->count(), $curr_br->count()]
3007 ]);
3008 } elsif ($i < $num_base) {
3009 my $base_br = $b->[$i];
3010 $tla = (0 == $base_br->count()) ? 'EUB' : 'ECB';
3011 push(@$branchData,
3012 [$base_br, $tla, [$base_br->count(), undef]]);
3013 } else {
3014 my $curr_br = $c->[$i];
3015 $tla = (0 == $curr_br->count()) ? 'UIC' : 'GIC';
3016 push(@$branchData,
3017 [$curr_br, $tla, [undef, $curr_br->count()]]);
3018 }
3019 }
3020 } else {
3021 # branch not found in current...
3022 foreach my $base_br (@$b) {
3023 my $tla = (0 == $base_br->count()) ? 'EUB' : 'ECB';
3024 push(@$branchData,
3025 [$base_br, $tla, [$base_br->count(), undef]]);
3026 }
3027 }
3028 }
3029 # now check for branches that are in current but not in baseline...
3030 foreach my $branchId (@currBlocks) {
3031 next
3032 if defined($base) &&
3033 $base->hasBlock($branchId); # already processed
3034 my $c = $curr->getBlock($branchId);
3035 my $branchData = $categorized->addBlock($branchId);
3036 foreach my $curr_br (@$c) {
3037 my $tla = (0 == $curr_br->count()) ? 'UIC' : 'GIC';
3038 push(@$branchData,
3039 [$curr_br, $tla, [undef, $curr_br->count()]]);
3040 }
3041 } # foreach branchId in current that isn't in base
3042 }
3043 }
3044 }
3045
3046 sub _cloneMcdcEntry
3047 {
3048 my ($cloneInto, $cloneFrom, $missTla, $hitTla) = @_;
3049 while (my ($groupSize, $group) = each(%{$cloneFrom->groups()})) {
3050 foreach my $expr (@$group) {
3051 foreach my $sense (0, 1) {
3052 my $count = $expr->count($sense);
3053 my $tla = (0 == $count) ? $missTla : $hitTla;
3054 $count = [$tla, undef, $count]
3055 ; # [TLA, baseline value, current value]
3056 $cloneInto->insertExpr('unknownFile', $groupSize,
3057 $sense, $count,
3058 $expr->index(), $expr->expression());
3059 }
3060 }
3061 }
3062 }
3063
3064 sub _categorizeMcdcCov
3065 {
3066 my ($self, $filename, $base_data, $current_data, $diffMap, $verbose) = @_;
3067 my $lineDataMap = $self->lineMap();
3068
3069 my $mcdcBaseline = $base_data->mcdc() if defined($base_data);
3070 my $mcdcCurrent = $current_data->mcdc();
3071
3072 my %mcdcCovLines;
3073 # look through the 'current' data, to find all the MC/DC data
3074 # keep track of hit count in baseline, current - in element 2 of the
3075 # retained MC/DC data. These counts are useful - for example, to report
3076 # the hit count in the baseline for LBC elements:
3077 # - e.g., in random testing: is this branch lost because it was a
3078 # low probablilty event (..baseline count is a small number)>
3079 # Or because we did something bad and no longer reach what had been
3080 # a high probability event?
3081 foreach my $line ($mcdcCurrent->keylist()) {
3082 next if ($line <= 0); # ignore bogus
3083 unless (exists($lineDataMap->{$line})) {
3084 # unless ignored, should have been caught or fixed during
3085 # TraceInfo::_checkConsistency
3086 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3087 "\"$filename\":$line line has MC/DC but no linecov data (skipping)."
3088 );
3089 next;
3090 }
3091 my $data = $lineDataMap->{$line};
3092
3093 $mcdcCovLines{$line} = 1;
3094 # we expect that the line number matches...
3095 $data->lineNo("current", $line);
3096 # append this MC/DC data for the line (this is an MCDC_Block)
3097 my $currMcdcData = $mcdcCurrent->value($line);
3098 $data->current_mcdc($currMcdcData, $filename);
3099 if (!defined($mcdcBaseline)) {
3100 my $categorized = MCDC_Block->new($line);
3101 $data->differential_mcdc($categorized);
3102 _cloneMcdcEntry($categorized, $currMcdcData, 'UNC', 'GNC');
3103 }
3104 } # foreach line in 'current' branch data
3105
3106 return unless defined($mcdcBaseline);
3107
3108 # now look through the baseline to find matching data
3109
3110 foreach my $base_line ($mcdcBaseline->keylist()) {
3111 next if ($base_line <= 0); # ignore bogus
3112 my $data = $self->_findLineData($diffMap, $filename, $base_line);
3113 my $curr_line = $data->lineNo('current');
3114 my $type = $data->type();
3115 if ($type ne 'delete') {
3116 $mcdcCovLines{$curr_line} = 1;
3117 } else {
3118 # the line has been deleted...just record the data
3119 my $deleteKey = "<<<" . $base_line;
3120 }
3121 my $baseMcdcData = $mcdcBaseline->value($base_line);
3122 $data->baseline_mcdc($baseMcdcData, $filename);
3123 } # foreach line in baseline data
3124
3125 # go through all the MC/DC data for each line, and categorize everything
3126 foreach my $line (keys(%mcdcCovLines)) {
3127 my $data = $self->lineMap()->{$line};
3128 my $type = $data->type();
3129 my $curr = $data->current_mcdc();
3130 my $base = $data->baseline_mcdc();
3131 my $categorized = MCDC_Block->new($line);
3132 $data->differential_mcdc($categorized);
3133 # handle case that baseline and/or current do not conta MC/DC data
3134 my $currGroups = defined($curr) ? $curr->groups() : ();
3135 my $baseGroups = defined($base) ? $base->groups() : ();
3136
3137 if ($type eq 'insert') {
3138 # can get here if diff data vs baseline/current is not consistent
3139 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3140 "baseline MC/DC data should not be defined for inserted line $filename:$line"
3141 ) if defined($base);
3142
3143 _cloneMcdcEntry($categorized, $curr, 'UNC', 'GNC');
3144 } elsif ($type eq 'delete') {
3145 # similarly: get here if diff data vs baseline/current is not consistent
3146 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3147 "current MC/DC data should not be defined for deleted line $filename:$line"
3148 ) if defined($curr);
3149
3150 _cloneMcdcEntry($categorized, $base, 'DUB', 'DCB');
3151 } else {
3152 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
3153 "unexpected MC/DC coverage type $type at $filename:$line")
3154 if $type ne 'equal';
3155 # group might or might not be in both baseline and current
3156 while (my ($groupSize, $bgroup) = each(%$baseGroups)) {
3157
3158 if (defined($currGroups) && exists($currGroups->{$groupSize})) {
3159 my $cgroup = $currGroups->{$groupSize};
3160
3161 for (my $i = 0; $i < $groupSize; ++$i) {
3162 my $b = $bgroup->[$i];
3163 my $c = $cgroup->[$i];
3164 die("mismatched expressions")
3165 unless $b->expression() eq $c->expression();
3166
3167 foreach my $sense (0, 1) {
3168 my $b_count = $b->count($sense);
3169 my $c_count = $c->count($sense);
3170 my $tla = _categorize($b_count, $c_count);
3171 $categorized->insertExpr('unknownFile', $groupSize,
3172 $sense, [$tla, $b_count, $c_count],
3173 $i, $c->expression());
3174 }
3175 }
3176 } else {
3177 # not found in current
3178 foreach my $b (@$bgroup) {
3179 foreach my $sense (0, 1) {
3180 my $b_count = $b->count($sense);
3181 my $tla = $b_count ? 'ECB' : 'EUB';
3182 $categorized->insertExpr('unknownFile', $groupSize,
3183 $sense, [$tla, $b_count, undef],
3184 $b->index(), $b->expression());
3185 }
3186 }
3187 }
3188 } #foreach group in base
3189 } # endif deleted line
3190 } # foreach line
3191 }
3192
3193 sub _cloneFunctionEntry
3194 {
3195 my ($cloneInto, $cloneFrom, $missTla, $hitTla) = @_;
3196
3197 my $hit = $cloneFrom->hit();
3198 my $tla = (0 == $hit) ? $missTla : $hitTla;
3199 $cloneInto->setCountDifferential([$hit, $tla]);
3200 my $aliases = $cloneFrom->aliases();
3201 foreach my $alias (keys %$aliases) {
3202 $hit = $aliases->{$alias};
3203 $tla = (0 == $hit) ? $missTla : $hitTla;
3204 $cloneInto->addAliasDifferential($alias, [$hit, $tla]);
3205 }
3206 }
3207
3208 sub _categorizeFunctionCov
3209 {
3210 my ($self, $filename, $base_data, $current_data, $diffMap, $verbose) = @_;
3211 die("map should not be defined yet") unless !defined($self->functionMap());
3212 my $differentialMap = {};
3213 push(@$self, $differentialMap);
3214 my $lineDataMap = $self->lineMap();
3215
3216 my $funcBase = $base_data->func() if defined($base_data);
3217 my $funcCurrent = $current_data->func();
3218 # use merged line coverage to categorize function by checking for
3219 # edits in function range
3220 # $lineCovBase and $lineCovCurrent are 'CountData' objects
3221 # - of lineNo->hit count
3222 my $lineCovBase = $base_data->sum() if defined($base_data);
3223 my $lineCovCurrent = $current_data->sum();
3224
3225 my %funcCovLines;
3226 foreach my $key ($funcCurrent->keylist()) {
3227 my $func = $funcCurrent->findKey($key);
3228 my $line = $func->line();
3229 next if ($line <= 0); # ignore bogus
3230 my $type = $diffMap->type($filename, $diffMap->NEW, $line);
3231 $funcCovLines{$line} = 1;
3232 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
3233 "'current' line $filename:$line should not be marked 'delete'")
3234 if $type eq 'delete';
3235 my $data;
3236 if (!exists($lineDataMap->{$line})) {
3237 $data = LineData->new($type);
3238 $lineDataMap->{$line} = $data;
3239 } else {
3240 $data = $lineDataMap->{$line};
3241 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
3242 "type mismatch " . $data->type() .
3243 " -> $type for $filename:$line")
3244 unless $data->type() eq $type;
3245 }
3246 # we expect that the line number matches...
3247 $data->lineNo("current", $line);
3248 # function data for the line
3249 $data->current_function($func);
3250 if (!defined($funcBase)) {
3251 my $name = $func->name();
3252 my $categorized =
3253 FunctionEntry->new($name, $funcCurrent,
3254 $line, $func->end_line());
3255 $differentialMap->{$name} = $categorized;
3256 $data->differential_function($categorized);
3257
3258 _cloneFunctionEntry($categorized, $func, 'UNC', 'GNC');
3259 }
3260 } # foreach function in current data
3261
3262 return unless (defined($funcBase));
3263
3264 # look through the baseline to find matching data
3265 foreach my $key ($funcBase->keylist()) {
3266 my $func = $funcBase->findKey($key);
3267 my $line = $func->line();
3268 next if ($line <= 0); # ignore bogus
3269 my $data = $self->_findLineData($diffMap, $filename, $line);
3270
3271 my $type = $data->type();
3272 my $curr_line = $data->lineNo('current');
3273 if ($type ne 'delete') {
3274 $funcCovLines{$curr_line} = 1;
3275 } else {
3276 # the line has been deleted...just record the data
3277 my $deleteKey = "<<<" . $line;
3278 $funcCovLines{$deleteKey} = 1;
3279 }
3280 $data->baseline_function($func);
3281 } # foreach function in baseline data
3282
3283 # go through function data for each line and categorize...
3284 foreach my $line (keys %funcCovLines) {
3285 my $data = $lineDataMap->{$line};
3286 my $type = $data->type();
3287 my $curr = $data->current_function();
3288 my $base = $data->baseline_function();
3289 my $categorized;
3290 if (defined($curr)) {
3291 # also copy the end line
3292 $categorized = $curr->cloneWithEndLine(1);
3293 } else {
3294 # not in current - don't copy end line
3295 # @todo if needed, could compute where the end line of the deleted
3296 # function is now
3297 $categorized = $base->cloneWithEndLine(0);
3298 }
3299 my $name = $categorized->name();
3300 $differentialMap->{$name} = $categorized;
3301 $data->differential_function($categorized);
3302
3303 if (!defined($base)) {
3304 # either this line was inserted or the line hasn't changed but
3305 # wasn't recognized as a function before (e.g., unused template)
3306 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3307 "$filename:$line: unexpected undef baseline function data for deleted $name"
3308 ) if $type eq 'delete';
3309 _cloneFunctionEntry($categorized, $curr,
3310 $type eq 'insert' ? 'UNC' : 'UIC',
3311 $type eq 'insert' ? 'GNC' : 'GIC');
3312 } elsif (!defined($curr)) {
3313 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3314 "$filename:$line: unexpected undef current function data for inserted $name"
3315 ) if $type eq 'insert';
3316 _cloneFunctionEntry($categorized, $base,
3317 $type eq 'delete' ? 'DUB' : 'EUB',
3318 $type eq 'delete' ? 'DCB' : 'ECB');
3319 } else {
3320 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
3321 "unexpected function coverage type $type at $filename:$line")
3322 if $type ne 'equal';
3323 # if we know end lines for this function, then check if there
3324 # have been any changes in the function body. If any changes,
3325 # then mark GNC or UNC
3326 my $changed;
3327 my $end_line = $curr->end_line();
3328
3329 if (defined($end_line)) {
3330 # we keep list of functions and branch coverpoints contained
3331 # in the function - and can report per-function coverage
3332 # in the function detail view. Maybe user will prioritize
3333 # functions which are hit but whose coverage is low
3334 $changed = 0;
3335 for (my $line = $curr->line(); $line <= $end_line; ++$line) {
3336 # data for this line
3337 my $type = $diffMap->type($filename, $diffMap->NEW, $line);
3338
3339 # claim a change if:
3340 # - line is new and is source code, OR
3341 # - line is unchanged and was code before and isn't code
3342 # now, or line wasn't code before and is now
3343 if ($type eq 'insert' &&
3344 defined($lineCovCurrent->value($line))) # line is code
3345 {
3346 $changed = 1;
3347 last;
3348 } else {
3349 # line is same
3350 my $bline =
3351 $diffMap->lookup($filename, $diffMap->NEW, $line);
3352 if (defined($lineCovBase->value($bline)) ^
3353 defined($lineCovCurrent->value($line))) {
3354 $changed = 1;
3355 last;
3356 }
3357 }
3358 } # end for each current line in current function
3359 $end_line = $base->end_line();
3360 if (defined($end_line) && !$changed) {
3361 # check for baseline lines which were deleted
3362 for (my $bline = $base->line();
3363 $bline <= $end_line;
3364 ++$bline) {
3365 # data for this line
3366 my $type =
3367 $diffMap->type($filename, $diffMap->OLD, $bline);
3368 # claim a change if line is deleted and was code
3369 # before.
3370 # note that we already checked unchanged lines, above
3371 if ($type ne 'equal' && # line is in old but not in new
3372 defined($lineCovBase->value($bline))
3373 ) # line is code
3374 {
3375 $changed = 1;
3376 last;
3377 }
3378 } # end for each current line in current function
3379 }
3380 lcovutil::info(1, "$name body at $filename:$line is changed\n")
3381 if ($changed);
3382 }
3383 my $tla = _categorize($base->hit(), $curr->hit());
3384 if (defined($changed) &&
3385 $changed) {
3386 if ($tla eq 'UBC') {
3387 $tla = 'UNC';
3388 } elsif ($tla eq 'GBC' ||
3389 $tla eq 'CBC') {
3390 $tla = 'GNC';
3391 } # else is LBC - leave it that way
3392 lcovutil::info(2,
3393 "$name recategorized to $tla at $filename:$line\n");
3394 }
3395
3396 $categorized->setCountDifferential([$curr->hit(), $tla]);
3397 # particular alias may be in both versions
3398 my $base_aliases = $base->aliases();
3399 my $curr_aliases = $curr->aliases();
3400 foreach my $alias (keys %$base_aliases) {
3401 my $hit = $base_aliases->{$alias};
3402
3403 my $tla;
3404 if (exists($curr_aliases->{$alias})) {
3405 my $hitCurr = $curr_aliases->{$alias};
3406 $tla = _categorize($hit, $hitCurr);
3407 $hit = $hitCurr;
3408 # adjust TLA if function range known..
3409 if (defined($changed) &&
3410 $changed) {
3411 if ($tla eq 'UBC') {
3412 $tla = 'UNC';
3413 } elsif ($tla eq 'GBC' ||
3414 $tla eq 'CBC') {
3415 $tla = 'GNC';
3416 } # else is LBC - leave it that way
3417 lcovutil::info(2,
3418 "$name alias $alias recategorized to $tla at $filename:$line\n"
3419 );
3420 }
3421 } else {
3422 $tla = (0 == $hit) ? 'EUB' : 'ECB';
3423 }
3424 $categorized->addAliasDifferential($alias, [$hit, $tla]);
3425 }
3426 # now look for aliases that are in current but not in baseline
3427 foreach my $alias (keys %$curr_aliases) {
3428 next if exists($base_aliases->{$alias});
3429
3430 my $hit = $curr_aliases->{$alias};
3431 my $tla = (0 == $hit) ? "UIC" : "GIC";
3432 $categorized->addAliasDifferential($alias, [$hit, $tla]);
3433 }
3434 }
3435
3436 if ('UNK' eq $data->tla()) {
3437 # there is a function here - but no line - manufacture some data
3438 my $d = $categorized->hit();
3439 my ($hit, $funcTla) = @$d;
3440 $data->tla($funcTla);
3441 if (defined($base) &&
3442 $data->in_base()) {
3443 $data->base_count($base->hit());
3444 }
3445 if (defined($curr) &&
3446 $data->in_curr()) {
3447 $data->curr_count($hit);
3448 }
3449 }
3450 }
3451 }
3452
3453 package DiffMap;
3454
3455 # @todo Could convert this use use a callback API - similar to annotate, etc.
3456 # that would be more consistent and might execute faster.
3457
3458 use constant {
3459 LINEMAP => 0,
3460 FILEMAP => 1,
3461 BASELINE => 2,
3462 # keep track of line number where file entry is found in diff file
3463 # - use line number in error messages.
3464 DIFF_FILENAME => 3,
3465 LOCATION => 4,
3466 UNCHANGED => 5,
3467 ALIASES => 6,
3468 DIFF_ROOT => 7,
3469
3470 OLD => 0,
3471 NEW => 1,
3472 TYPE => 2,
3473
3474 _START => 0,
3475 _END => 1
3476 };
3477
3478 sub new
3479 {
3480 my $class = shift;
3481 my $self = [{}, # linemap
3482 {}, # filemap: new_filename->old_filename
3483 {}, # baseline: filename -> baseline lineno -> text
3484 undef, # diff filename
3485 [{}, {}], # def location
3486 # element 0: old filename -> line number where this
3487 # entry starts
3488 # element 1: new filename -> line numbern
3489 {} # unchanged
3490 ];
3491 bless $self, $class;
3492 return $self;
3493 }
3494
3495 sub load
3496 {
3497 my ($self, $path, $info, $buildDirs) = @_;
3498 $self->_read_udiff($path);
3499
3500 # find list of soft links in [buildDirs] which may point to files in $info
3501 # we need to keep all the aliases as there may be files in baseline
3502 # which are not in current
3503 if (@$buildDirs) {
3504 my @stack = @$buildDirs;
3505 while (@stack) {
3506 my $dir = pop(@stack);
3507 die("unexpected non-directory '$dir'") unless -d $dir;
3508 $dir = File::Spec->catdir($main::cwd, $dir)
3509 unless File::Spec->file_name_is_absolute($dir);
3510
3511 opendir(my $dh, $dir) or die("can't open directory $dir: $!");
3512 while (my $entry = readdir($dh)) {
3513 next if $entry eq '.' || $entry eq '..';
3514 my $path = File::Spec->catfile($dir, $entry);
3515 if (-d $path) {
3516 push(@stack, $path);
3517 } elsif (-l $path) {
3518 my $l = Cwd::realpath($path);
3519 next if (!-e $l || TraceFile::skipCurrentFile($l));
3520 # may need to turn $l into relative path??
3521 $self->[ALIASES]->{$path} = $l if (-f $l);
3522 #lcovutil::info("add alias '$path' -> '$l'\n");
3523 # really, this should be a file...
3524 die("unexpected soft link $path to directory")
3525 unless -f $l;
3526 }
3527 # else just ignore file entry
3528 }
3529 closedir($dh);
3530 }
3531 }
3532 return $self;
3533 }
3534
3535 sub empty
3536 {
3537 my $self = shift;
3538 return !scalar(%{$self->[LINEMAP]});
3539 }
3540
3541 sub findName
3542 {
3543 my ($self, $file) = @_;
3544 my $f = $lcovutil::case_insensitive ? lc($file) : $file;
3545 $f = $self->[ALIASES]->{$f} if exists($self->[ALIASES]->{$f});
3546
3547 if (File::Spec->file_name_is_absolute($f) &&
3548 !exists($self->[LINEMAP]->{$f})) {
3549 my $p =
3550 $lcovutil::case_insensitive ?
3551 lc($self->[DIFF_ROOT]) :
3552 $self->[DIFF_ROOT];
3553 $p .= $lcovutil::dirseparator;
3554 my $l = length($p);
3555 if (length($f) > $l &&
3556 $p eq substr($f, 0, $l)) {
3557 my $s = substr($f, $l);
3558 if (exists($self->[LINEMAP]->{$s})) {
3559 $f = $s;
3560 } elsif (exists($self->[ALIASES]->{$s})) {
3561 $f = $self->[ALIASES]->{$s};
3562 }
3563 }
3564 }
3565 return $f;
3566 }
3567
3568 sub containsFile
3569 {
3570 my ($self, $file) = @_;
3571 $file = $self->findName($file);
3572 return exists($self->[LINEMAP]->{$file});
3573 }
3574
3575 sub recreateBaseline
3576 {
3577 my ($self, $filename, $currentSrcLines) = @_;
3578
3579 my $diffs = $self->[LINEMAP]->{$self->findName($filename)};
3580 die("no diff data for $filename") unless defined $diffs;
3581
3582 my $deleted = $self->[BASELINE]->{$self->findName($filename)};
3583 my @lines;
3584 foreach my $chunk (@$diffs) {
3585 if ($chunk->[TYPE] eq 'equal') {
3586 my ($from, $to) = @{$chunk->[NEW]};
3587 push(@lines, @{$currentSrcLines}[($from - 1) .. ($to - 1)]);
3588 } elsif ($chunk->[TYPE] eq 'delete') {
3589 my $r = $chunk->[OLD];
3590 for (my $i = $r->[_START]; $i <= $r->[_END]; ++$i) {
3591 die("missing baseline line $i")
3592 unless defined($deleted) && exists($deleted->{$i});
3593 push(@lines, $deleted->{$i});
3594 }
3595 }
3596 # else 'insert': nothing to do/those lines are not in baseline
3597 }
3598 return \@lines;
3599 }
3600
3601 sub lookup
3602 {
3603 my ($self, $file, $vers, $line) = @_;
3604
3605 $file = $self->findName($file);
3606
3607 if (!exists($self->[LINEMAP]->{$file})) {
3608 #mapping is identity when no diff was read
3609 return $line;
3610 }
3611
3612 my @candidates =
3613 grep { $_->[$vers]->[_START] < $line } @{$self->[LINEMAP]->{$file}};
3614 # candidates is empty if $line==1 - which is unusual, as there is typically
3615 # a comment, copyright notice, #include, or whatever on the first line
3616 return $line unless @candidates;
3617
3618 my $chunk = pop @candidates;
3619
3620 my $alt = ($vers == OLD) ? NEW : OLD;
3621
3622 if ($line > $chunk->[$vers]->[_END]) {
3623 return ($chunk->[$alt]->[_END] + ($line - $chunk->[$vers]->[_END]));
3624 }
3625 return ($chunk->[$alt]->[_START] + ($line - $chunk->[$vers]->[_START]));
3626 }
3627
3628 sub type
3629 {
3630 my ($self, $file, $vers, $line) = @_;
3631
3632 $file = $self->findName($file);
3633
3634 if (!defined($self->[LINEMAP]->{$file})) {
3635 #mapping is identity when no diff was read
3636 if (defined($main::show_tla) &&
3637 (@main::base_filenames ||
3638 $main::diff_filename)
3639 ) {
3640 return "equal"; # categories will be "GIC", "UIC"
3641 } else {
3642 return "insert"; # categories will be "GNC", "UNC"
3643 }
3644 }
3645
3646 if (!defined($self->[FILEMAP]->{$file})) {
3647 #mapping with no filemap when baseline file was deleted
3648 return "delete";
3649 }
3650
3651 # ->{start} equal $line only if beginning of range or omitted in ->{type}
3652 my @candidates =
3653 grep { $_->[$vers]->[_START] <= $line } @{$self->[LINEMAP]->{$file}};
3654 my $chunk = pop @candidates;
3655 my $prev = pop @candidates;
3656 while (defined($prev) &&
3657 $line >= $prev->[$vers]->[_START] &&
3658 $line <= $prev->[$vers]->[_END]) {
3659 $chunk = $prev;
3660 $prev = pop @candidates;
3661 }
3662 if (!defined($chunk)) {
3663 warn "DiffMap::type(): got undef chunk at $file, $vers, $line\n";
3664 return "undef chunk";
3665 }
3666 if (!defined($chunk->[TYPE])) {
3667 warn "DiffMap::type(): got undef type at $file, $vers, $line\n";
3668 return "undef type";
3669 }
3670 return $chunk->[TYPE];
3671 }
3672
3673 sub baseline_file_name
3674 {
3675 # file may have been moved between baseline and current...
3676 my ($self, $current_name) = @_;
3677
3678 my $key = $self->findName($current_name);
3679 if (exists($self->[FILEMAP]->{$key})) {
3680 return $self->[FILEMAP]->{$key};
3681 }
3682 return $current_name;
3683 }
3684
3685 sub files
3686 {
3687 my $self = shift;
3688 return keys(%{$self->[FILEMAP]});
3689 }
3690
3691 sub dump_map
3692 {
3693 my $self = shift;
3694
3695 foreach my $file (keys %{$self->[FILEMAP]}) {
3696 my $currfile =
3697 defined($self->[FILEMAP]->{$file}) ? $self->[FILEMAP]->{$file} :
3698 "[deleted]";
3699 printf("In $file (was: $currfile):\n");
3700 foreach my $chunk (@{$self->[LINEMAP]->{$file}}) {
3701 _printChunk($chunk);
3702 }
3703 }
3704 return $self;
3705 }
3706
3707 sub check_version_match
3708 {
3709 my ($self, $baseline, $current) = @_;
3710 return unless $lcovutil::versionCallback;
3711
3712 # skip files which were dropped (no longer in project) or were
3713 # just added to the project (was not in the baseline - so we aren't
3714 # looking for differences.
3715 foreach my $curr ($current->files()) {
3716 next unless $baseline->file_exists($curr);
3717 my $currData = $current->data($curr);
3718 my $curr_version = $currData->version();
3719 my $baseData = $baseline->data($curr);
3720 my $base_version = $baseData->version();
3721
3722 # silently compare version...
3723 my $versionMatch =
3724 lcovutil::checkVersionMatch($curr, $base_version, $curr_version,
3725 "diff entry compare", 1);
3726 if ($self->containsFile($curr)) {
3727 # file is in 'diff' data: we expect the version to be different
3728 # between baseline/current
3729 if ($versionMatch) {
3730 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3731 "File \"$curr\" appears in 'diff' data file '" .
3732 $self->[DIFF_FILENAME] .
3733 "' but 'baseline' and 'current' versions '" .
3734 ($curr_version ? $curr_version : '<undef>') .
3735 "' match");
3736 }
3737 } else {
3738 # not in 'diff': we expect the versions to be identical
3739 if (!$versionMatch) {
3740 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
3741 "File \"$curr\" version changed from '" .
3742 ($base_version ? $base_version : '<undef') .
3743 "' to '" .
3744 ($curr_version ? $curr_version : '<undef>') .
3745 "' but file not found in 'diff' data file '" .
3746 $self->[DIFF_FILENAME] . "'.");
3747 }
3748 }
3749 }
3750 }
3751
3752 sub check_path_consistency
3753 {
3754 # check that paths which appear in diff also appear in baseline or current
3755 # .info files - if not, then there is likely a path consistency issue
3756 # $baseline and $current are both TraceFile structs -
3757 # return 0 if inconsistency found
3758
3759 my ($self, $baseline, $current) = @_;
3760 (ref($baseline) eq 'TraceFile' && ref($current) eq 'TraceFile') or
3761 die("wrong arg types");
3762
3763 # check that files which are in both baseline and current and are NOT
3764 # in the 'diff' data have the same version.
3765 # That is: files whose version differs should appear in the diff data
3766 $self->check_version_match($baseline, $current);
3767
3768 my %diffMap; # current_filename -> where_used
3769 my %diffBaseMap; # current_directory -> []
3770 # for every 'current' filename in the udiff file
3771 foreach my $f ($self->files()) {
3772 $diffMap{$f} = 0; # this file not used in baseline or current (yet)
3773 my $b = File::Basename::basename($f);
3774 $diffBaseMap{$b} = [[], {}]
3775 unless exists($diffBaseMap{$b});
3776 push(@{$diffBaseMap{$b}->[0]}, $f);
3777 }
3778 # foreach unchanged file in udiff data
3779 foreach my $f (keys %{$self->[UNCHANGED]}) {
3780 # unchanged in baseline and current
3781 $diffMap{$f} = 3;
3782 }
3783 my %missed;
3784 # for each file in 'current' info:
3785 foreach my $curr ($current->files()) {
3786 my $b = File::Basename::basename($curr);
3787 if ($self->containsFile($curr)) {
3788 my $alias =
3789 exists($self->[ALIASES]->{$curr}) ? $self->[ALIASES]->{$curr} :
3790 $curr;
3791 $diffMap{$alias} |= 1; # used in current
3792 $diffBaseMap{$b}->[1]->{$alias} = 0
3793 unless exists($diffBaseMap{$b}->[1]->{$alias});
3794 ++$diffBaseMap{$b}->[1]->{$alias};
3795 } elsif (!exists($self->[UNCHANGED]->{$self->findName($curr)})) {
3796 $missed{$curr} = 1; # in current but not in diff
3797 }
3798 }
3799 # for each file in 'baseline' info:
3800 foreach my $base ($baseline->files()) {
3801 my $b = File::Basename::basename($base);
3802 if ($self->containsFile($base)) {
3803 my $alias =
3804 exists($self->[ALIASES]->{$base}) ? $self->[ALIASES]->{$base} :
3805 $base;
3806 $diffMap{$alias} |= 2; # used in baseline
3807 $diffBaseMap{$b}->[1]->{$alias} = 0
3808 unless exists($diffBaseMap{$b}->[1]->{$alias});
3809 ++$diffBaseMap{$b}->[1]->{$alias};
3810 } elsif (!exists($self->[UNCHANGED]->{$self->findName($base)})) {
3811 # in baseline but not in diff
3812 if (exists($missed{$base})) {
3813 $missed{$base} |= 2;
3814 } else {
3815 $missed{$base} = 2;
3816 }
3817 }
3818 }
3819 my $ok = 1;
3820 foreach my $f (sort keys(%missed)) {
3821 my $b = File::Basename::basename($f);
3822 next unless exists($diffBaseMap{$b});
3823
3824 # this basename is in the diff file and didn't match any other
3825 # trace filename entry (i.e., same filename in more than one
3826 # source code directory) - then warn about possible pathname issue
3827 my ($diffFiles, $sourceFiles) = @{$diffBaseMap{$b}};
3828 # find the files which appear in the 'diff' list which have the
3829 # same basename and were not matched - those might be candidates
3830 my @unused;
3831 for my $d (@$diffFiles) {
3832 # my $location = $self->[DIFF_FILENAME] . ':' . $self->[LOCATION]->[NEW]->{$d};
3833 push(@unused, $d)
3834 unless exists($sourceFiles->{$d});
3835 }
3836 next unless @unused;
3837
3838 # my $baseData = $baseline->data($f);
3839 # my $baseLocation = join(":", ${$baseData->location()});
3840 # my $currData = $current->data($f);
3841 # my $currLocation = join(":", ${$currData->location()});
3842
3843 my $type;
3844 if (2 == $missed{$f}) {
3845 $type = "baseline";
3846 } elsif (1 == $missed{$f}) {
3847 $type = "current";
3848 } else {
3849 $type = "both baseline and current";
3850 }
3851 my $single = 1 == scalar(@unused);
3852 # @todo could print line numbers in baseline, current .info files and
3853 # in diff file ..
3854 if (lcovutil::warn_once($lcovutil::ERROR_MISMATCH, $f)) {
3855 my $suffix =
3856 $main::elide_path_mismatch ? ' (elided)' :
3857 lcovutil::explain_once(
3858 'elide-path-mismatch',
3859 ' Perhaps see "--elide-path-mismatch", "--substitute" and "--build-directory" options in \'man '
3860 . $lcovutil::tool_name . '\'');
3861 lcovutil::ignorable_warning(
3862 $lcovutil::ERROR_MISMATCH,
3863 "source file '$f' (in $type .info file" .
3864 ($missed{$f} == 3 ? "s" : "") .
3865 ") has same basename as 'diff' "
3866 .
3867 ($single ? 'entry ' : "entries:\n\t"
3868 ) .
3869 "'" .
3870 join("'\n\t", @unused) .
3871 "' - but a different path." .
3872 ($single ? " " : "\n\t") .
3873 'Possible pathname mismatch?' .
3874 $suffix);
3875 }
3876 if ($main::elide_path_mismatch &&
3877 $missed{$f} == 3 &&
3878 $single) {
3879 $self->[FILEMAP]->{$f} = $f;
3880 $self->[LINEMAP]->{$f} = $self->[LINEMAP]->{$unused[0]};
3881 } else {
3882 $ok = 0;
3883 }
3884 }
3885 return $ok;
3886 }
3887
3888 sub _printChunk
3889 {
3890 my $chunk = shift;
3891 printf(" %6s\t[%d:%d]\t[%d:%d]\n",
3892 $chunk->[TYPE], $chunk->[OLD]->[_START],
3893 $chunk->[OLD]->[_END], $chunk->[NEW]->[_START],
3894 $chunk->[NEW]->[_END]);
3895 }
3896
3897 sub _newChunk
3898 {
3899 my ($type, $baseline_start, $current_start) = @_;
3900 # new chunk starts and ends on the same line - until we see more lines and
3901 # extend either the old or new range
3902 return [[$baseline_start, $baseline_start],
3903 [$current_start, $current_start],
3904 $type
3905 ];
3906 }
3907
3908 sub show_map
3909 {
3910 my ($self, $file) = @_;
3911
3912 $file = $self->findName($file);
3913 return $self unless exists($self->[FILEMAP]->{$file});
3914 my $currfile =
3915 defined($self->[FILEMAP]->{$file}) ? $self->[FILEMAP]->{$file} :
3916 "[deleted]";
3917 print("In $file" . ($currfile ne $file ? " (was: $currfile)" : '') . ":\n");
3918 foreach my $chunk (@{$self->[LINEMAP]->{$file}}) {
3919 _printChunk($chunk);
3920 }
3921 return $self;
3922 }
3923
3924 sub _read_udiff
3925 {
3926 my $self = shift;
3927 my $diff_file = shift; # Name of diff file
3928 my $line; # Contents of current line
3929 my $file_old; # Name of old file in diff section
3930 my $file_new; # Name of new file in diff section
3931 my $filename; # Name of common filename of diff section
3932
3933 # Check if file exists and is readable
3934 stat($diff_file);
3935 if (!(-r _)) {
3936 die("cannot read udiff file $diff_file!\n");
3937 }
3938
3939 $self->[DIFF_FILENAME] = $diff_file;
3940
3941 my $diffFile = InOutFile->in($diff_file);
3942 my $diffHdl = $diffFile->hdl();
3943
3944 my $chunk;
3945 my $old_block = 0;
3946 my $new_block = 0;
3947 # would like to use Regexp::Common::time - but module not installed
3948 #my $time = $RE{time}{iso};
3949 my $time =
3950 '[1-9]{1}[0-9]{3}\-[0-9]{2}\-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}(\.[0-9]*)?( .[0-9]+)?';
3951 # Parse diff file line by line
3952 my $verbose = 0;
3953 while (<$diffHdl>) {
3954 chomp($_);
3955 s/\r//g;
3956 $line = $_;
3957
3958 # the 'diff' new/old file name line may be followed by a timestamp
3959 # If so, remove it so our regexp matches more easily.
3960 # p4 and git diff outputs do not have the timestamp
3961 if ($line =~ /^[-+=]{3} \S.*(\s+$time)$/) {
3962 $line =~ s/\Q$1\E$//;
3963 }
3964 foreach ($line) {
3965 /^Git Root: (.+)$/ && do {
3966 $self->[DIFF_ROOT] = $1;
3967 last;
3968 };
3969
3970 # Filename of unchanged file:
3971 # === <filename>
3972 /^=== (.+)$/ && do # note: filename may contain whitespace
3973 {
3974 if ($filename) {
3975 die("not case insensitive")
3976 unless !$lcovutil::case_insensitive ||
3977 ($filename eq lc($filename));
3978 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
3979 undef $filename;
3980 }
3981 my $file = $1;
3982 $file = lcovutil::strip_directories($file, $main::strip);
3983 my $key = ReadCurrentSource::resolve_path($file, 1);
3984 $key = lc($key) if $lcovutil::case_insensitive;
3985 if (exists($self->[UNCHANGED]->{$key})) {
3986 # unchanged entry flag value should be 1
3987 die("$diff_file:$.: $key already in linemap - marked unchanged"
3988 . ($file eq $key ? '' : " (substituted '$file')"))
3989 unless $self->[UNCHANGED]->{$key};
3990 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
3991 "$diff_file:$.: duplicate 'unchanged' entry for $key\n"
3992 );
3993 last;
3994 }
3995 $verbose = (defined($main::verboseScopeRegexp) &&
3996 $key =~ m/$main::verboseScopeRegexp/);
3997 print(" $key: unchanged\n") if $verbose;
3998 # LCOV_EXCL_START
3999 if (exists($self->[LINEMAP]->{$key})) {
4000 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
4001 "$diff_file:$.: $key 'unchanged' entry found but diff records exist"
4002 . ($file eq $key ? '' : " (substituted '$file')"));
4003 # message ignored - delete the diff records
4004 delete($self->[LINEMAP]->{$key});
4005 }
4006 # LCOV_EXCL_STOP
4007 $self->[UNCHANGED]->{$key} = 1;
4008 last;
4009 };
4010
4011 # Filename of old file:
4012 # --- <filename>
4013 /^--- (.+)$/ && do {
4014 if ($filename) {
4015 die("not case insensitive")
4016 unless !$lcovutil::case_insensitive ||
4017 ($filename eq lc($filename));
4018 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4019 undef $filename;
4020 }
4021 $file_old = $1;
4022 $file_old =
4023 lcovutil::strip_directories($file_old, $main::strip);
4024 $file_old = ReadCurrentSource::resolve_path($file_old, 1);
4025 $file_old = lc($file_old) if $lcovutil::case_insensitive;
4026 $self->[LOCATION]->[OLD]->{$file_old} = $.;
4027 last;
4028 };
4029 # Filename of new file:
4030 # +++ <filename>
4031 /^\+\+\+ (.+)$/ && do {
4032 # Add last file to resulting hash
4033 $file_new = $1;
4034 $file_new =
4035 lcovutil::strip_directories($file_new, $main::strip);
4036 my $key = ReadCurrentSource::resolve_path($file_new, 1);
4037 $key = lc($key)
4038 if $lcovutil::case_insensitive;
4039 my $notNull = $file_new ne $lcovutil::devnull;
4040 $filename = $notNull ? $key : undef;
4041
4042 if ($filename) {
4043 # LCOV_EXCL_START
4044 if (exists($self->[UNCHANGED]->{$key})) {
4045 lcovutil::ignorable_error(
4046 $lcovutil::ERROR_INTERNAL,
4047 "$diff_file:$.: $filename marked unchanged but diff record found"
4048 .
4049 ($file_new eq $key ? '' :
4050 " (substituted '$file_new')"));
4051 # OK - error ignored...remove the 'unchanged' marker
4052 delete($self->[UNCHANGED]->{$key});
4053 }
4054 # LCOV_EXCL_STOP
4055 $self->[LINEMAP]->{$key} = [];
4056 }
4057 $verbose = (defined($main::verboseScopeRegexp) &&
4058 $key =~ m/$main::verboseScopeRegexp/);
4059 print("file $key\n") if $verbose;
4060 if ($notNull) {
4061 $self->[FILEMAP]->{$key} = $file_old;
4062 # keep track of location where this file was found
4063 $self->[LOCATION]->[NEW]->{$key} =
4064 $.; # record original name too.. $file_new
4065 }
4066 # new file - chunk starts here
4067 $chunk = _newChunk('equal', 1, 1);
4068 last;
4069 };
4070 # Start of diff block:
4071 # @@ -old_start,old_num, +new_start,new_num @@
4072 /^\@\@\s+-(\d+),(\d+)\s+\+(\d+),(\d+)\s+\@\@.*$/ && do {
4073 if ($1 > ($chunk->[OLD]->[_END])) {
4074 # old start skips "equal" lines
4075 if ($chunk->[TYPE] ne "equal") {
4076 if ($filename) {
4077 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4078 _printChunk($chunk) if ($verbose);
4079 }
4080 $chunk =
4081 _newChunk('equal',
4082 $chunk->[OLD]->[_END] + 1,
4083 $chunk->[NEW]->[_END] + 1);
4084 }
4085 }
4086 # "END" will be incremented on content lines
4087 $chunk->[OLD]->[_END] = $1 - 1;
4088 $chunk->[NEW]->[_END] = $3 - 1;
4089 $old_block = $2;
4090 $new_block = $4;
4091 #printf "equal [%d:%d] [%d:%d]\n", $l[0], $l[1], $l[2], $l[3];
4092 last;
4093 };
4094 # Unchanged line
4095 # <line starts with blank>
4096 /^ / && do {
4097 if ($old_block == 0 && $new_block == 0) {
4098 last;
4099 }
4100 if ($chunk->[TYPE] ne "equal") {
4101 if ($filename) {
4102 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4103 _printChunk($chunk) if ($verbose);
4104 }
4105 # next chunk starts right after current one
4106 $chunk = _newChunk('equal',
4107 $chunk->[OLD]->[_END] + 1,
4108 $chunk->[NEW]->[_END] + 1);
4109 } else {
4110 $chunk->[NEW]->[_END] += 1;
4111 $chunk->[OLD]->[_END] += 1;
4112 }
4113 last;
4114 };
4115 # Line as seen in old file
4116 # <line starts with '-'>
4117 /^-(.*)$/ && do {
4118 if ($old_block == 0 && $new_block == 0) {
4119 last;
4120 }
4121 my $baseline_lineno = $chunk->[OLD]->[_END] + 1;
4122 # really only need to keep track of baseline content if user
4123 # is planning on doing any filtering
4124 my $lines;
4125 if (exists($self->[BASELINE]->{$file_old})) {
4126 $lines = $self->[BASELINE]->{$file_old};
4127 } else {
4128 $lines = {};
4129 $self->[BASELINE]->{$file_old} = $lines;
4130 }
4131 $lines->{$baseline_lineno} = $1;
4132
4133 if ($chunk->[TYPE] ne "delete") {
4134 if ($filename) {
4135 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4136 _printChunk($chunk) if ($verbose);
4137 }
4138 $chunk = _newChunk('delete', $baseline_lineno,
4139 $chunk->[NEW]->[_END]);
4140 } else {
4141 $chunk->[OLD]->[_END] = $baseline_lineno;
4142 }
4143 last;
4144 };
4145 # Line as seen in new file
4146 # <line starts with '+'>
4147 /^\+/ && do {
4148 if ($old_block == 0 && $new_block == 0) {
4149 last;
4150 }
4151 if ($chunk->[TYPE] ne "insert") {
4152 if ($filename) {
4153 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4154 _printChunk($chunk) if ($verbose);
4155 }
4156 $chunk = _newChunk('insert',
4157 $chunk->[OLD]->[_END],
4158 $chunk->[NEW]->[_END] + 1);
4159 } else {
4160 $chunk->[NEW]->[_END] += 1;
4161 }
4162 last;
4163 };
4164 # Empty line
4165 /^$/ && do {
4166 if ($old_block == 0 && $new_block == 0) {
4167 last;
4168 }
4169 if ($chunk->[TYPE] ne "equal") {
4170 if ($filename) {
4171 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4172 _printChunk($chunk) if ($verbose);
4173 }
4174 $chunk = _newChunk('equal',
4175 $chunk->[OLD]->[_END] + 1,
4176 $chunk->[NEW]->[_END] + 1);
4177 } else {
4178 $chunk->[NEW]->[_END] += 1;
4179 $chunk->[OLD]->[_END] += 1;
4180 }
4181 last;
4182 };
4183 }
4184 }
4185
4186 # Add final diff file section to resulting hash
4187 if ($filename) {
4188 push(@{$self->[LINEMAP]->{$filename}}, $chunk);
4189 _printChunk($chunk) if ($verbose);
4190 }
4191
4192 # default root
4193 $self->[DIFF_ROOT] = $main::cwd unless defined($self->[DIFF_ROOT]);
4194
4195 if ($self->empty()) {
4196 # this is probably OK - there are no differences between 'baseline' and current.
4197 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
4198 "'diff' data file $diff_file contains no differences (this may be OK, if there are no difference between 'baseline' and 'current').\n"
4199 . "Make sure to use 'diff -u' when generating the diff file.");
4200 }
4201 return $self;
4202 }
4203
4204 package InInterestingRegion;
4205
4206 use constant {
4207 NEXT => 0,
4208 PREV => 1,
4209 STACK => 2,
4210 ANNOTATE_OBJ => 3,
4211 LINECOV_HASH => 4,
4212 # non-code line in a contiguous region before or after the
4213 # 'interesting' code lie - should also be included -
4214 # keep track of the length of that region, above and below
4215 LINES_BEFORE => 5,
4216 LINES_AFTER => 6,
4217
4218 };
4219
4220 our $num_context_lines = 5;
4221
4222 sub new
4223 {
4224 my ($class, $srcFileStruct, $lineCovHash) = @_;
4225
4226 my $self = [undef, undef,
4227 Storable::dclone($srcFileStruct->interesting_lines()),
4228 $srcFileStruct, $lineCovHash
4229 ];
4230 # we will call the $annotateObj->line(int) to collect annotate data
4231 # for certain lines - to find out of a non-code line is in a
4232 # contiguous region by the same author, in the same SHA or etc.
4233 $self->[NEXT] = shift(@{$self->[STACK]});
4234 if (defined($self->[NEXT]) && $self->[NEXT] != 1) {
4235 _computeContextBefore($self, 0);
4236 }
4237 return bless $self, $class;
4238 }
4239
4240 sub _computeContextBefore
4241 {
4242 my ($self, $prev) = @_;
4243
4244 my $count = 0;
4245 my $data = $self->[LINECOV_HASH];
4246 my $annotate = $self->[ANNOTATE_OBJ];
4247 # find contiguous source region which matches the select criteria.
4248 # That might include non-code lined (e.g., comments)
4249 for (my $l = $self->[NEXT] - 1; $l > $prev; --$l) {
4250 my $lineData = $data->{$l} if exists($data->{$l});
4251 my $annotateData = $annotate->line($l);
4252 last
4253 unless SummaryInfo::selected($lineData, $annotateData,
4254 $self->[ANNOTATE_OBJ]->path(), $l);
4255 ++$count;
4256 }
4257 # region of interest is the (possibly empty) contiguous region we found
4258 # plus the number of context lines
4259 $self->[LINES_BEFORE] = $num_context_lines + $count;
4260 }
4261
4262 sub interesting
4263 {
4264 my ($self, $lineNum) = @_;
4265 die("unexpected lineNum '$lineNum'") if $lineNum < 1;
4266 if (defined($self->[NEXT])) {
4267 if ($lineNum == $self->[NEXT]) {
4268 $self->[PREV] = $self->[NEXT];
4269 $self->[NEXT] = shift(@{$self->[STACK]});
4270 # compute following context lines - starting from here
4271 # and going to either end of file or next interesting line
4272 my $max = defined($self->[NEXT]) ? $self->[NEXT] :
4273 $self->[ANNOTATE_OBJ]->num_lines();
4274 my $count = 0;
4275 my $data = $self->[LINECOV_HASH];
4276 my $annotate = $self->[ANNOTATE_OBJ];
4277 for (my $l = $self->[PREV] + 1; $l < $max; ++$l) {
4278 my $lineData = $data->{$l} if exists($data->{$l});
4279 my $annotateData = $annotate->line($l);
4280 last
4281 if !SummaryInfo::selected($lineData, $annotateData,
4282 $self->[ANNOTATE_OBJ]->path(), $l);
4283 ++$count;
4284 }
4285 $self->[LINES_AFTER] = $num_context_lines + $count;
4286
4287 # and how many lines before the next interesting one?
4288 if (defined($self->[NEXT])) {
4289 $self->_computeContextBefore($self->[PREV]);
4290 } else {
4291 $self->[LINES_BEFORE] = 0;
4292 }
4293 return 1;
4294 } elsif ($lineNum >= $self->[NEXT] - $self->[LINES_BEFORE]) {
4295 return 1;
4296 }
4297 }
4298 if (defined($self->[PREV])) {
4299 if ($lineNum <= $self->[PREV] + $self->[LINES_AFTER]) {
4300 return 1;
4301 }
4302 $self->[PREV] = undef;
4303 }
4304 return 0;
4305 }
4306
4307 package SourceLine;
4308
4309 use constant {
4310 LINE => 0,
4311 TEXT => 1,
4312 OWNER => 2,
4313 FULL_NAME => 3,
4314 DATE => 4,
4315 AGE => 5,
4316 COMMIT => 6,
4317 LINE_TLA => 7,
4318 BRANCH_TLA => 8,
4319 MCDC_TLA => 9,
4320 FUNCTION_TLA => 10,
4321 };
4322
4323 sub new
4324 {
4325 my $class = shift;
4326 # [lineNo, text, abbrev_name, full_name, date, age, commitID, lineTLA, branchTLA,
4327 # MCDC_TLA, functionTLA]
4328 my @data = @_;
4329 my $self = \@data;
4330 bless $self, $class;
4331 return $self;
4332 }
4333
4334 sub to_list
4335 {
4336 # used by 'select' callback - if not a package
4337 my $self = shift;
4338 if ($#$self >= OWNER) {
4339 my @rtn = @{$self}[OWNER, FUNCTION_TLA];
4340 return \@rtn;
4341 }
4342 return undef;
4343 }
4344
4345 sub owner
4346 {
4347 my $self = shift;
4348 return $#$self >= OWNER ? $self->[OWNER] : undef;
4349 }
4350
4351 sub full_name
4352 {
4353 my $self = shift;
4354 return $#$self >= FULL_NAME ? $self->[FULL_NAME] : undef;
4355 }
4356
4357 # line coverage TLA
4358 sub tla
4359 {
4360 my ($self, $tla) = @_;
4361 $self->[LINE_TLA] = $tla
4362 if (defined($tla));
4363 return $#$self >= LINE_TLA ? $self->[LINE_TLA] : undef;
4364 }
4365
4366 sub branchElem
4367 {
4368 my ($self, $branchElem) = @_;
4369 $self->[BRANCH_TLA] = $branchElem
4370 if defined($branchElem);
4371 return $#$self >= BRANCH_TLA ? $self->[BRANCH_TLA] : undef;
4372 }
4373
4374 sub mcdcElem
4375 {
4376 my ($self, $mcdcElem) = @_;
4377 $self->[MCDC_TLA] = $mcdcElem
4378 if defined($mcdcElem);
4379 return $#$self >= MCDC_TLA ? $self->[MCDC_TLA] : undef;
4380 }
4381
4382 sub functionElem
4383 {
4384 my ($self, $funcElem) = @_;
4385 $self->[FUNCTION_TLA] = $funcElem
4386 if defined($funcElem);
4387 return $#$self >= FUNCTION_TLA ? $self->[FUNCTION_TLA] : undef;
4388 }
4389
4390 sub commit
4391 {
4392 my $self = shift;
4393 return $#$self >= COMMIT ? $self->[COMMIT] : undef;
4394 }
4395
4396 sub date
4397 {
4398 my $self = shift;
4399 return $#$self >= DATE ? $self->[DATE] : undef;
4400 }
4401
4402 sub age
4403 {
4404 my $self = shift;
4405 return $#$self >= AGE ? $self->[AGE] : undef;
4406 }
4407
4408 sub line
4409 {
4410 my $self = shift;
4411 return $self->[LINE];
4412 }
4413
4414 sub text
4415 {
4416 my $self = shift;
4417 return $self->[TEXT];
4418 }
4419
4420 package SourceFile;
4421 our @annotateScript;
4422 our $annotateCallback;
4423 our $annotateTooltip = 'Line %l: commit %C on %d by %F';
4424 our $annotatedFiles = 0;
4425 our $totalFiles = 0;
4426
4427 use constant {
4428 PATH => 0,
4429 LINES => 1,
4430 INTERESTING_LINES => 2,
4431 LINE_OWNERS => 3,
4432 LINE_CATEGORIES => 4,
4433 BRANCH_OWNERS => 5,
4434 BRANCH_CATEGORIES => 6,
4435 MCDC_OWNERS => 5,
4436 MCDC_CATEGORIES => 6,
4437 };
4438
4439 sub new
4440 {
4441 my ($class, $filepath, $fileSummary, $fileCovInfo, $hasNoBaselineData) = @_;
4442
4443 (ref($fileSummary) eq 'SummaryInfo' &&
4444 ref($fileCovInfo) eq "FileCoverageInfo") or
4445 die("unexpected input args");
4446
4447 my $self = [$filepath,
4448 [], # lines
4449 undef, # list of interesting lines
4450 {}, # owner -> hash of TLS->list of lines
4451 {}, # TLA -> list of lines
4452 {} # owner -> hash of TLA->list of lines
4453 ];
4454 bless $self, $class;
4455
4456 $fileSummary->fileDetails($self);
4457
4458 # use the line coverage count to synthesize a fake file, if we can't
4459 # find an actual file
4460 $self->_load($fileCovInfo);
4461
4462 if ($hasNoBaselineData) {
4463 my $fileAge = $self->age();
4464 if (defined($fileAge) &&
4465 (!defined($main::age_basefile) ||
4466 $fileAge > $main::age_basefile)
4467 ) {
4468 # go through the fileCov data and change UIC->UBC, GIC->CBC
4469 # - pretend that we already saw this file data - this is the first
4470 # coverage report which contains this data.
4471 $fileCovInfo->recategorizeTlaAsBaseline();
4472 }
4473 }
4474
4475 # sort lines in ascending numerical order - we want the 'owner'
4476 # and 'tla' line lists to be sorted - and it is probably faster to
4477 # sort the file list once than to sort each of the sub-lists
4478 # individually afterward.
4479 # DCB, DUB category keys have leading "<<<" characters - which we strip
4480 # in order to compare
4481 my $currentTla;
4482 my $regionStartLine;
4483 my $lineCovData = $fileCovInfo->lineMap();
4484
4485 my @lineArray; # interesting line numbers
4486 my $inRegion;
4487 if (defined($selectCallback)) {
4488 # This implementation looks for all the 'line' coverpoints - then
4489 # expands the selected region around those points - e.g., by
4490 # adding noncode lines which are in the selected changelist and
4491 # surrounding the selected region with 'num_context_lines' of
4492 # context.
4493 # A side effect of this criteria is that disjoint noncode regions -
4494 # e.g., comments or unused #ifdef code - will not be selected.
4495 # A different implementation would go through the annotated source
4496 # and mark all selected lines, then go through again to add
4497 # context.
4498 # It isn't clear which approach is best - but the current approach
4499 # seems to match user expectations - so I'm going with it, at
4500 # least for now.
4501 # Not too hard to do - but significant overkill - to make the
4502 # approach configurable. Let's see if there is user demand.
4503 while (my ($line, $lne) = each(%$lineCovData)) {
4504 # ignore deleted lines as they don't appear in source listing
4505 my $tla = $lne->tla();
4506 # no annotations for deleted line
4507 my $annotateData = $self->line($line)
4508 unless grep(/$tla/, ('DUB', 'DCB'));
4509 # callback arguments are (LineData, SourceLine)
4510 if (SummaryInfo::selected($lne, $annotateData,
4511 $self->path(), $line)) {
4512 push(@lineArray, $line);
4513 }
4514 }
4515 @lineArray = sort({ $a <=> $b } @lineArray);
4516 $self->[INTERESTING_LINES] = \@lineArray;
4517 $inRegion = InInterestingRegion->new($self, $lineCovData);
4518 }
4519 foreach my $line (sort({
4520 my $ka =
4521 ("<" ne substr($a, 0, 1)) ? $a :
4522 substr($a, 3);
4523 my $kb =
4524 ("<" ne substr($b, 0, 1)) ? $b :
4525 substr($b, 3);
4526 $ka <=> $kb
4527 } keys(%{$lineCovData}))
4528 ) {
4529 # is this line within N of an interesting one?
4530 my $lne = $lineCovData->{$line};
4531 my $tla = $lne->tla();
4532 # deleted line associated with first 'current' line above -
4533 # or line below, if there is no current line above
4534 my $lineNum =
4535 grep(/$tla/, ('DUB', 'DCB')) ? -$lne->lineNo('current') : $line;
4536
4537 if (defined($inRegion) &&
4538 !$inRegion->interesting($lineNum)) {
4539 lcovutil::info(1,
4540 " drop $line" .
4541 ($line eq $lineNum ? '' : " ($lineNum)") . "\n");
4542 $fileSummary->removeLine($lne);
4543 delete($lineCovData->{$line});
4544 next;
4545 }
4546 $self->_countLineTlaData($line, $lne, $fileSummary);
4547
4548 $self->_countBranchTlaData($line, $lne, $fileSummary)
4549 if ($lcovutil::br_coverage && defined($lne->differential_branch()));
4550
4551 $self->_countMcdcTlaData($line, $lne, $fileSummary)
4552 if ($lcovutil::mcdc_coverage && defined($lne->differential_mcdc()));
4553
4554 $self->_countFunctionTlaData($line, $lne, $fileSummary)
4555 if ($lcovutil::func_coverage &&
4556 defined($lne->differential_function()));
4557 }
4558 if (defined($main::show_dateBins) &&
4559 %$lineCovData && # haven't filtered out everything
4560 !$self->isProjectFile()
4561 ) {
4562 lcovutil::info("no owner/date info for '$filepath'\n");
4563 }
4564 return $self;
4565 }
4566
4567 sub simplify
4568 {
4569 my $self = shift;
4570 # retain only the information required to populate the hyperlinks in
4571 # the parent 'directory details' table
4572 # This struct can be huge, for a large, complicated file
4573 $self->[INTERESTING_LINES] = undef;
4574
4575 my %keep;
4576 # keep the first line in each date bin..
4577 for (my $bin = 0; $bin <= $#ageGroupHeader; ++$bin) {
4578 foreach my $tla (keys %{$self->[LINE_CATEGORIES]}) {
4579 # at least for the moment, skip deleted lines
4580 next if grep(/$tla/, ('DUB', 'DCB'));
4581 my $line = $self->nextInDateBin($bin, $tla);
4582 $keep{$line} = 1 if defined($line);
4583 }
4584 if ($lcovutil::br_coverage) {
4585 foreach my $tla (keys %{$self->[BRANCH_CATEGORIES]}) {
4586 next if grep(/$tla/, ('DUB', 'DCB'));
4587 my $line = $self->nextBranchInDateBin($bin, $tla);
4588 $keep{$line} = 1 if defined($line);
4589 }
4590 }
4591 if ($lcovutil::mcdc_coverage) {
4592 foreach my $tla (keys %{$self->[MCDC_CATEGORIES]}) {
4593 next if grep(/$tla/, ('DUB', 'DCB'));
4594 my $line = $self->nextMcdcInDateBin($bin, $tla);
4595 $keep{$line} = 1 if defined($line);
4596 }
4597 }
4598 }
4599
4600 # retain first location of each TLA (globally) and each TLA for each owner
4601 foreach my $bin (LINE_OWNERS, LINE_CATEGORIES,
4602 BRANCH_OWNERS, BRANCH_CATEGORIES,
4603 MCDC_OWNERS, MCDC_CATEGORIES
4604 ) {
4605 while (my ($key, $list) = each(%{$self->[$bin]})) {
4606 if ('ARRAY' eq ref($list)) {
4607 next if grep(/$key/, ('DUB', 'DCB'));
4608 # retain the first entry and any interesting entries
4609 $keep{$list->[0]} = 1;
4610 @$list = grep(exists($keep{$_}), @$list);
4611 } else {
4612 die("unexpected type") unless 'HASH' eq ref($list);
4613 while (my ($tla, $l) = each(%$list)) {
4614 next if grep(/$tla/, ('DUB', 'DCB'));
4615 # retain the first entry
4616 $keep{$l->[0]} = 1;
4617 @$l = grep(exists($keep{$_}), @$l);
4618 }
4619 }
4620 }
4621 }
4622 # throw away everything we aren't interested in
4623 for (my $l = $self->num_lines(); $l > 0; --$l) {
4624 if (!exists($keep{$l})) {
4625 $self->[LINES]->[$l - 1] = undef;
4626 }
4627 }
4628 }
4629
4630 sub _countBranchTlaData
4631 {
4632 my ($self, $line, $lineData, $fileSummary) = @_;
4633 my $differentialData = $lineData->differential_branch();
4634
4635 my %foundBranchTlas;
4636 my ($src_age, $developer, $srcLine);
4637 my $lineTla = $lineData->tla();
4638 $srcLine = $self->line($line);
4639 if (!defined($srcLine)) {
4640 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
4641 "no data for 'branch' line:$line, file:" . $self->path())
4642 if (!$lcovutil::warn_once_per_file ||
4643 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE, $self->path()));
4644 } else {
4645 $srcLine->branchElem($differentialData);
4646 if (@SourceFile::annotateScript &&
4647 !grep(/^$lineTla$/, ('DUB', 'DCB'))) {
4648 # deleted lines don't have owner data...
4649 # if this line is not in the project (e.g., from some 3rd party
4650 # library - then we might not have file history for it.
4651 $src_age = $srcLine->age();
4652 $developer = $srcLine->owner();
4653
4654 if (defined($developer)) {
4655 my $shash = $self->[BRANCH_OWNERS];
4656 if (!exists($shash->{$developer})) {
4657 $shash->{$developer} = {};
4658 $shash->{$developer}->{lines} = [];
4659 }
4660 push(@{$shash->{$developer}->{lines}}, $line);
4661 }
4662 }
4663 }
4664
4665 my %recorded;
4666 foreach my $branchId ($differentialData->blocks()) {
4667 my $diff = $differentialData->getBlock($branchId);
4668 foreach my $b (@$diff) {
4669 my $tla = $b->[1];
4670 # LCOV_EXCL_START
4671 unless (defined($tla)) {
4672 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
4673 "undef TLA for branch $branchId of " . $self->path() .
4674 ":$line - lineTLA:$lineTla taken:" . $b->[0]);
4675 next;
4676 }
4677 # LCOV_EXCL_STOP
4678 $fileSummary->[SummaryInfo::BRANCH_DATA]->[SummaryInfo::DATA]
4679 ->{$tla} += 1;
4680 # keep track of all the branch TLAs found on this line...
4681 if (!exists($foundBranchTlas{$tla})) {
4682 $foundBranchTlas{$tla} = 1;
4683 $self->[BRANCH_CATEGORIES]->{$tla} = []
4684 unless exists($self->[BRANCH_CATEGORIES]->{$tla});
4685 }
4686 push(@{$self->[BRANCH_CATEGORIES]->{$tla}}, $line);
4687
4688 next
4689 if (0 == ($SummaryInfo::tlaLocation{$tla} & 0x1));
4690 # skip "DUB' and 'DCB' categories - which are not in current
4691 # and thus have no line associated
4692
4693 # and the age...
4694 #lcovutil::info("$l: $tla" . $lineData->in_curr() . "\n");
4695
4696 unless (defined($srcLine) && defined($src_age)) {
4697 # just count totals
4698 $fileSummary->branchCovCount($tla, 'noGroup', undef, 1);
4699 next;
4700 }
4701
4702 # increment count of branches of this age we found for this TLA
4703 $fileSummary->branchCovCount($tla, "age", $src_age, 1);
4704
4705 # HGC: could clean this up...no need to keep track
4706 # of 'hit' as we can just compute from CBC + GNC + ...
4707 # found another line...
4708 my $hit = grep(/$tla/, ('GBC', 'GIC', 'GNC', 'CBC'));
4709 $fileSummary->branchCovCount("found", "age", $src_age, 1);
4710 $fileSummary->branchCovCount("hit", "age", $src_age, 1)
4711 if $hit;
4712
4713 next
4714 unless defined($developer);
4715
4716 # add this line to those that belong to this owner..
4717
4718 # first: increment line count in 'file summary'
4719 my $ohash =
4720 $fileSummary->[SummaryInfo::BRANCH_DATA]->[SummaryInfo::OWNERS];
4721 if (!exists($ohash->{$developer})) {
4722 my %data = ('hit' => $hit ? 1 : 0,
4723 'found' => 1,
4724 $tla => 1);
4725 $ohash->{$developer} = \%data;
4726 } else {
4727 my $d = $ohash->{$developer};
4728 $d->{$tla} = 0
4729 unless exists($d->{$tla});
4730 $d->{$tla} += 1;
4731 $d->{found} += 1;
4732 $d->{hit} += 1
4733 if $hit;
4734 }
4735
4736 # now append this branchTLA to the owner...
4737 my $ownerKey = $developer . $tla;
4738 if (!exists($recorded{$ownerKey})) {
4739 $recorded{$ownerKey} = 1;
4740 my $dhash = $self->[BRANCH_OWNERS]->{$developer};
4741 $dhash->{$tla} = []
4742 unless exists($dhash->{$tla});
4743 push(@{$dhash->{$tla}}, $line);
4744 }
4745 }
4746 }
4747 }
4748
4749 sub _countMcdcTlaData
4750 {
4751 my ($self, $line, $lineData, $fileSummary) = @_;
4752 my $differentialData = $lineData->differential_mcdc();
4753
4754 my %foundMcdcTlas;
4755 my ($src_age, $developer, $srcLine);
4756 my $lineTla = $lineData->tla();
4757 $srcLine = $self->line($line);
4758 if (!defined($srcLine)) {
4759 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
4760 "no data for 'MC/DC' line:$line, file:" . $self->path())
4761 if (!$lcovutil::warn_once_per_file ||
4762 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE, $self->path()));
4763 } else {
4764 $srcLine->mcdcElem($differentialData);
4765 if (@SourceFile::annotateScript &&
4766 !grep(/^$lineTla$/, ('DUB', 'DCB'))) {
4767 # deleted lines don't have owner data...
4768 # if this line is not in the project (e.g., from some 3rd party
4769 # library - then we might not have file history for it.
4770 $src_age = $srcLine->age();
4771 $developer = $srcLine->owner();
4772
4773 if (defined($developer)) {
4774 my $shash = $self->[BRANCH_OWNERS];
4775 if (!exists($shash->{$developer})) {
4776 $shash->{$developer} = {};
4777 $shash->{$developer}->{lines} = [];
4778 }
4779 push(@{$shash->{$developer}->{lines}}, $line);
4780 }
4781 }
4782 }
4783
4784 my %recorded;
4785 while (my ($groupSize, $group) = each(%{$differentialData->groups()})) {
4786 foreach my $expr (@$group) {
4787 foreach my $sense (0, 1) {
4788 my $count = $expr->count($sense);
4789 my $tla = $count->[0];
4790 # LCOV_EXCL_START
4791 unless (defined($tla)) {
4792 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
4793 "undef TLA for sense $sense of MC/DC " .
4794 $expr->index() .
4795 ' of ' . $self->path() .
4796 ":$line - lineTLA:$lineTla taken:" .
4797 $count->[1]);
4798 next;
4799 }
4800 # LCOV_EXCL_STOP
4801 $fileSummary->[SummaryInfo::MCDC_DATA]->[SummaryInfo::DATA]
4802 ->{$tla} += 1;
4803 # keep track of all the branch TLAs found on this line...
4804 if (!exists($foundMcdcTlas{$tla})) {
4805 $foundMcdcTlas{$tla} = 1;
4806 $self->[MCDC_CATEGORIES]->{$tla} = []
4807 unless exists($self->[MCDC_CATEGORIES]->{$tla});
4808 }
4809 push(@{$self->[MCDC_CATEGORIES]->{$tla}}, $line);
4810
4811 next
4812 if (0 == ($SummaryInfo::tlaLocation{$tla} & 0x1));
4813 # skip "DUB' and 'DCB' categories - which are not in current
4814 # and thus have no line associated
4815
4816 # and the age...
4817 #lcovutil::info("$l: $tla" . $lineData->in_curr() . "\n");
4818
4819 unless (defined($srcLine) && defined($src_age)) {
4820 # just count totals
4821 $fileSummary->mcdcCovCount($tla, 'noGroup', undef, 1);
4822 next;
4823 }
4824
4825 # increment count of branches of this age we found for this TLA
4826 $fileSummary->mcdcCovCount($tla, "age", $src_age, 1);
4827
4828 my $hit = grep(/$tla/, ('GBC', 'GIC', 'GNC', 'CBC'));
4829 $fileSummary->mcdcCovCount("found", "age", $src_age, 1);
4830 $fileSummary->mcdcCovCount("hit", "age", $src_age, 1)
4831 if $hit;
4832
4833 next
4834 unless defined($developer);
4835
4836 # add this line to those that belong to this owner..
4837
4838 # first: increment line count in 'file summary'
4839 my $ohash =
4840 $fileSummary->[SummaryInfo::MCDC_DATA]
4841 ->[SummaryInfo::OWNERS];
4842 if (!exists($ohash->{$developer})) {
4843 my %data = ('hit' => $hit ? 1 : 0,
4844 'found' => 1,
4845 $tla => 1);
4846 $ohash->{$developer} = \%data;
4847 } else {
4848 my $d = $ohash->{$developer};
4849 $d->{$tla} = 0
4850 unless exists($d->{$tla});
4851 $d->{$tla} += 1;
4852 $d->{found} += 1;
4853 $d->{hit} += 1
4854 if $hit;
4855 }
4856
4857 # now append this branchTLA to the owner...
4858 my $ownerKey = $developer . $tla;
4859 if (!exists($recorded{$ownerKey})) {
4860 $recorded{$ownerKey} = 1;
4861 my $dhash = $self->[MCDC_OWNERS]->{$developer};
4862 $dhash->{$tla} = []
4863 unless exists($dhash->{$tla});
4864 push(@{$dhash->{$tla}}, $line);
4865 }
4866 }
4867 }
4868 }
4869 }
4870
4871 sub _countLineTlaData
4872 {
4873 my ($self, $line, $lineData, $fileSummary) = @_;
4874 # there is differential line coverage data...
4875 my $tla = $lineData->tla();
4876
4877 if (!exists($SummaryInfo::tlaLocation{$tla})) {
4878 # this case can happen if the line number annotations are
4879 # wrong in the .info file - so the first line of some function
4880 # or some branch coverage line number turns out not to be an
4881 # executable source code line
4882 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
4883 "unexpected category $tla for line " . $self->path() . ":$line");
4884 return;
4885 }
4886 # one more line in this bucket...
4887 $fileSummary->[SummaryInfo::LINE_DATA]->[SummaryInfo::DATA]->{$tla} += 1;
4888 # create the category list, if necessary
4889 $self->[LINE_CATEGORIES]->{$tla} = []
4890 unless exists($self->[LINE_CATEGORIES]->{$tla});
4891
4892 push(@{$self->[LINE_CATEGORIES]->{$tla}}, $line);
4893
4894 # and the age data...
4895
4896 if ($SummaryInfo::tlaLocation{$tla} & 0x1) {
4897 # skip "DUB' and 'DCB' categories - which are not in current
4898 # and thus have no line associated
4899
4900 #lcovutil::info("$l: $tla" . $lineData->in_curr() . "\n");
4901
4902 my $l = $self->line($line);
4903
4904 if (!defined($l)) {
4905 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
4906 "no data for line:$line, TLA:$tla, file:" . $self->path())
4907 if (!$lcovutil::warn_once_per_file ||
4908 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
4909 $self->path()));
4910 return;
4911 }
4912 # set the TLA of this line...
4913 $l->tla($tla);
4914
4915 my $src_age = $l->age();
4916 # if this line is not in the project (e.g., from some 3rd party
4917 # library - then we might not have file history for it.
4918 return
4919 unless defined($src_age);
4920
4921 # increment count of lines of this age we found for this TLA
4922 $fileSummary->lineCovCount($tla, "age", $src_age, 1);
4923
4924 if ($lineData->in_curr()) {
4925 # HGC: could clean this up...no need to keep track
4926 # of 'hit' as we can just compute from CBC + GNC + ...
4927 # found another line...
4928 $fileSummary->lineCovCount("found", "age", $src_age, 1);
4929 if ($lineData->curr_count() > 0) {
4930 $fileSummary->lineCovCount("hit", "age", $src_age, 1);
4931 }
4932 }
4933
4934 if (defined($l->owner())) {
4935 # add this line to those that belong to this owner..
4936 my $developer = $l->owner();
4937
4938 # first: increment line count in 'file summary'
4939 my $ohash =
4940 $fileSummary->[SummaryInfo::LINE_DATA]->[SummaryInfo::OWNERS];
4941 $ohash->{$developer} = {}
4942 unless exists($ohash->{$developer});
4943 my $d = $ohash->{$developer};
4944 $d->{$tla} = 0
4945 unless exists($d->{$tla});
4946 $d->{$tla} += 1;
4947
4948 # now push this line onto the list of in this file, belonging
4949 # to this owner
4950 $self->[LINE_OWNERS]->{$developer} = {}
4951 unless exists($self->[LINE_OWNERS]->{$developer});
4952 my $dhash = $self->[LINE_OWNERS]->{$developer};
4953 $dhash->{lines} = []
4954 unless exists($dhash->{lines});
4955 push(@{$dhash->{lines}}, $line);
4956 $dhash->{$tla} = []
4957 unless exists($dhash->{$tla});
4958 # and the list of lines with this TLA, belonging to this user
4959 push(@{$dhash->{$tla}}, $line);
4960 }
4961 }
4962 }
4963
4964 sub _accountFunction
4965 {
4966 my ($fileSummary, $tla, $src_age) = @_;
4967
4968 # LCOV_EXCL_START
4969 unless (defined($tla)) {
4970 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
4971 "undef function TLA for age '$src_age' of " .
4972 $fileSummary->name());
4973 return 1; # error
4974 }
4975 # LCOV_EXCL_STOP
4976
4977 $fileSummary->[SummaryInfo::FUNCTION_DATA]->[SummaryInfo::DATA]->{$tla} +=
4978 1;
4979
4980 if (defined($src_age)) {
4981 $fileSummary->functionCovCount($tla, 'age', $src_age, 1);
4982
4983 my $hit = grep(/$tla/, ('GBC', 'GIC', 'GNC', 'CBC'));
4984 $fileSummary->functionCovCount("found", "age", $src_age, 1);
4985 $fileSummary->functionCovCount("hit", "age", $src_age, 1)
4986 if $hit;
4987 }
4988 return 0;
4989 }
4990
4991 sub _countFunctionTlaData
4992 {
4993 my ($self, $line, $lineData, $fileSummary) = @_;
4994 my $func = $lineData->differential_function();
4995
4996 my %foundFunctionTlas;
4997 my ($src_age, $developer, $srcLine);
4998
4999 my $h = $func->hit();
5000 my $mergedTla = $h->[1];
5001 # LCOV_EXCL_START
5002 if (!defined($mergedTla)) {
5003 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
5004 "undef TLA for function '" . $func->name() .
5005 "' hit " . $h->[0] . " at line " .
5006 $line . " (" . $lineData->tla() .
5007 ' ' . $lineData->curr_count() . ")");
5008 #die("this should not happen");
5009 # This is new code - somehow miscategorized.
5010 $mergedTla = $h->[0] == 0 ? 'UNC' : 'GNC';
5011 $h->[1] = $mergedTla;
5012 #return;
5013 }
5014 # LCOV_EXCL_STOP
5015
5016 if (!grep(/^$mergedTla$/, ('DUB', 'DCB'))) {
5017 # deleted lines don't have owner data...
5018 $srcLine = $self->line($line);
5019 # info might not be available, if no annotations
5020 if (defined($srcLine)) {
5021 # should probably look at the source code to find the open/close
5022 # parens - then claim the age is the youngest line
5023 $src_age = $srcLine->age();
5024 $srcLine->functionElem($func);
5025 }
5026 }
5027
5028 if ($main::merge_function_aliases) {
5029 _accountFunction($fileSummary, $mergedTla, $src_age);
5030 } else {
5031 my $aliases = $func->aliases();
5032 foreach my $alias (keys %$aliases) {
5033 my $data = $aliases->{$alias};
5034 my $tla = $data->[1];
5035 # LCOV_EXCL_START
5036 if (!defined($tla)) {
5037 lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
5038 "undef TLA for alias:'$alias' hit:" .
5039 $data->[0] . " of function '" . $func->name() .
5040 "' hit " . $h->[0] . " at line " . $line . " (" .
5041 $lineData->tla() . ' ' . $lineData->curr_count() . ")");
5042 # die("this should not happen either");
5043 $tla = $data->[0] == 0 ? 'UNC' : 'GNC';
5044 $data->[1] = $tla;
5045 }
5046 # LCOV_EXCL_STOP
5047 _accountFunction($fileSummary, $tla, $src_age);
5048 }
5049 }
5050 }
5051
5052 sub path
5053 {
5054 my $self = shift;
5055 return $self->[PATH];
5056 }
5057
5058 sub isProjectFile
5059 {
5060 # return 'true' if no owner/date information for this file.
5061 my $self = shift;
5062 return scalar(%{$self->[LINE_OWNERS]});
5063 }
5064
5065 sub line
5066 {
5067 my $self = shift;
5068 my $i = shift;
5069 die("bad line index '$i'")
5070 unless ($i =~ /^[0-9]+$/);
5071 return $self->[LINES]->[$i - 1];
5072 }
5073
5074 # how old is the oldest (or youngest) line in this file?
5075 sub age
5076 {
5077 my ($self, $youngest) = @_;
5078 return undef unless $self->isProjectFile();
5079
5080 my $age = $self->line(1)->age();
5081 foreach my $line (@{$self->lines()}) {
5082 my $a = $line->age();
5083 if (defined($youngest)) {
5084 $age = $a
5085 if ($a < $age);
5086 } else {
5087 $age = $a
5088 if ($a > $age);
5089 }
5090 }
5091 return $age;
5092 }
5093
5094 sub lines
5095 {
5096 my $self = shift;
5097 return $self->[LINES];
5098 }
5099
5100 sub num_lines
5101 {
5102 my $self = shift;
5103 return scalar(@{$self->[LINES]});
5104 }
5105
5106 sub is_empty
5107 {
5108 my $self = shift;
5109 # anything interesting here?
5110 return defined($self->interesting_lines()) &&
5111 0 == @{$self->interesting_lines()};
5112 }
5113
5114 sub interesting_lines
5115 {
5116 my $self = shift;
5117 # return list of lines containing coverpoints, which are marked by
5118 # the $selectionCallback - see the --select-script parameter
5119 return $self->[INTERESTING_LINES];
5120 }
5121
5122 sub binarySearchLine
5123 {
5124 my ($list, $after) = @_;
5125
5126 defined($list) && 0 != scalar(@$list) or
5127 die("invalid location list");
5128
5129 my $max = $#$list;
5130 my $min = 0;
5131 my $mid;
5132 while (1) {
5133 $mid = int(($max + $min) / 2);
5134 my $v = $list->[$mid];
5135 if ($v > $after) {
5136 $max = $mid;
5137 } elsif ($v < $after) {
5138 $min = $mid;
5139 } else {
5140 return $mid;
5141 }
5142 my $diff = $max - $min;
5143 if ($diff <= 1) {
5144 $mid = $min;
5145 $mid = $max
5146 if $list->[$min] < $after;
5147 last;
5148 }
5149 }
5150 return $list->[$mid] >= $after ? $mid : undef;
5151 }
5152
5153 sub nextTlaGroup
5154 {
5155 # return number of first line of next group of specified linecov TLA -
5156 # for example, if line [5:8] and [13:17] are 'CNC', then:
5157 # 5 = nextTlaGroup('CBC') : "after == undef"
5158 # 13 = nextTlaGroup('CBC', 5) : skip contiguous group of CBC lines
5159 # undef = nexTlaGroup('CBC', 13) : no following group
5160 my ($self, $tla, $after) = @_;
5161 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5162 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5163 "unknown linecov TLA '$tla'");
5164 return undef;
5165 }
5166
5167 # note the the "$self->line(...)" argument is 1-based (not zero-base)
5168 my $line;
5169 if (defined($after) &&
5170 defined($self->line($after)->tla())) {
5171 die("$after is not in $tla group")
5172 unless ($self->line($after)->tla() eq $tla);
5173 # skip to the end of the current section...
5174 # if the TLA of this group is unset (non-code line: comment,
5175 # blank, etc) - then look for next code line. If that line's
5176 # TLA matches, then treat as a contiguous group.
5177 # This way, we avoid visual clutter from having a lot of single-line
5178 # TLA segments.
5179 my $lastline = scalar(@{$self->[LINES]});
5180 for ($line = $after + 1; $line <= $lastline; ++$line) {
5181 my $t = $self->line($line)->tla();
5182 last
5183 if (defined($t) &&
5184 $t ne $tla);
5185 }
5186 } else {
5187 $line = 1;
5188 }
5189 my $locations = $self->[LINE_CATEGORIES]->{$tla};
5190 my $idx = binarySearchLine($locations, $line);
5191 return defined($idx) ? $locations->[$idx] : undef;
5192 }
5193
5194 sub nextCategoryTlaGroup
5195 {
5196 # return number of first line of next group of specified branchcov TLA -
5197 # note that all branch lines are independent - so we will
5198 # report and go the next branch, even if it is on the adjacent line
5199 my ($type, $category, $self, $tla, $after) = @_;
5200 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5201 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5202 "unknown $type TLA '$tla'");
5203 return undef;
5204 }
5205 die("no $type data for TLA '$tla'")
5206 unless exists($self->[$category]->{$tla});
5207
5208 my $locations = $self->[$category]->{$tla};
5209
5210 $after = defined($after) ? $after + 1 : 1;
5211 my $idx = binarySearchLine($locations, $after);
5212 return defined($idx) ? $locations->[$idx] : undef;
5213 }
5214
5215 sub nextBranchTlaGroup
5216 {
5217 # ($self, $tla, $after_line)
5218 return nextCategoryTlaGroup('branch', BRANCH_CATEGORIES, @_);
5219 }
5220
5221 sub nextMcdcTlaGroup
5222 {
5223 return nextCategoryTlaGroup('MC/DC', MCDC_CATEGORIES, @_);
5224 }
5225
5226 sub nextInDateBin
5227 {
5228 my ($self, $dateBin, $tla, $after) = @_;
5229
5230 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5231 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5232 "unknown linecov TLA '$tla'");
5233 return undef;
5234 }
5235 $dateBin <= $#SummaryInfo::ageGroupHeader or
5236 die("unexpected age group $dateBin");
5237
5238 # note the the "$self->line(...)" argument is 1-based (not zero-base)
5239 my $line;
5240 if (defined($after)) {
5241
5242 ($self->line($after)->tla() eq $tla) or
5243 die("$after is not in $tla group");
5244
5245 my $lastline = scalar(@{$self->[LINES]});
5246 # skip to the end of the current section...
5247 for ($line = $after + 1; $line <= $lastline; ++$line) {
5248 my $t = $self->line($line)->tla();
5249 my $a = $self->line($line)->age();
5250 if (!defined($a)) {
5251 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5252 "no age data for line:$line, file:" . $self->path())
5253 if (!$lcovutil::warn_once_per_file ||
5254 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5255 $self->path()));
5256 return undef;
5257 }
5258 last
5259 if (defined($t) &&
5260 ($t ne $tla ||
5261 $dateBin != SummaryInfo::findAgeBin($a)));
5262 }
5263 } else {
5264 $line = 1;
5265 }
5266 # the data isn't stored by date bin (at least for now) - so the
5267 # only way to find it currently is by searching forward.
5268 my $tlaLocations = $self->[LINE_CATEGORIES]->{$tla};
5269 my $idx = binarySearchLine($tlaLocations, $line);
5270 return undef unless defined($idx);
5271 my $max = scalar(@$tlaLocations);
5272 for (; $idx < $max; ++$idx) {
5273 $line = $tlaLocations->[$idx];
5274 my $l = $self->line($line);
5275 if (!defined($l)) {
5276 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5277 "no data for line:$line, file:" . $self->path())
5278 if (!$lcovutil::warn_once_per_file ||
5279 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5280 $self->path()));
5281 return undef;
5282 }
5283 my $a = $l->age();
5284 if (!defined($a)) {
5285 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5286 "no age data for line:$line, file:" . $self->path())
5287 if (!$lcovutil::warn_once_per_file ||
5288 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5289 $self->path()));
5290 return undef;
5291 }
5292 my $bin = SummaryInfo::findAgeBin($a);
5293
5294 if ($bin == $dateBin) {
5295 my $t = $l->tla();
5296 return $line
5297 if (defined($t) &&
5298 $t eq $tla);
5299 }
5300 }
5301 return undef;
5302 }
5303
5304 sub nextInOwnerBin
5305 {
5306 my ($self, $owner, $tla, $after) = @_;
5307
5308 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5309 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5310 "unknown linecov TLA '$tla'");
5311 return undef;
5312 }
5313 exists($self->[LINE_OWNERS]->{$owner}) &&
5314 exists($self->[LINE_OWNERS]->{$owner}->{$tla}) or
5315 die("$owner not responsible for any $tla lines in" . $self->path());
5316
5317 # note the the "$self->line(...)" argument is 1-based (not zero-base)
5318 my $line;
5319 if (defined($after)) {
5320
5321 ($self->line($after)->tla() eq $tla) or
5322 die("$after is not in $tla group");
5323
5324 my $lastline = scalar(@{$self->[LINES]});
5325 # skip to the end of the current section...
5326 for ($line = $after + 1; $line <= $lastline; ++$line) {
5327 my $l = $self->line($line);
5328 if (!defined($l)) {
5329 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5330 "no data for line:$line, file:" . $self->path())
5331 if (!$lcovutil::warn_once_per_file ||
5332 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5333 $self->path()));
5334 return undef;
5335 }
5336 my $t = $l->tla();
5337 my $o = $l->owner();
5338 if (!defined($o)) {
5339 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5340 "no owber data for line:$line, file:" . $self->path())
5341 if (!$lcovutil::warn_once_per_file ||
5342 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5343 $self->path()));
5344 return undef;
5345 }
5346 last
5347 if (defined($t) &&
5348 ($t ne $tla ||
5349 $o ne $owner));
5350 }
5351 } else {
5352 $line = 1;
5353 }
5354
5355 my $locations = $self->[LINE_OWNERS]->{$owner}->{$tla};
5356 my $idx = binarySearchLine($locations, $line);
5357 return defined($idx) ? $locations->[$idx] : undef;
5358 }
5359
5360 sub nextCategoryInDateBin
5361 {
5362 my ($type, $category, $self, $dateBin, $tla, $after) = @_;
5363
5364 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5365 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5366 "unknown $type TLA '$tla'");
5367 return undef;
5368 }
5369 $dateBin <= $#SummaryInfo::ageGroupHeader or
5370 die("unexpected age group $dateBin");
5371
5372 # note the the "$self->line(...)" argument is 1-based (not zero-base)
5373 $after = defined($after) ? $after + 1 : 1;
5374
5375 exists($self->[$category]->{$tla}) or
5376 die("no $tla ${type}es in " . $self->path());
5377
5378 my $lines = $self->[$category]->{$tla};
5379 my $idx = binarySearchLine($lines, $after);
5380
5381 return undef unless defined($idx);
5382 my $max = scalar(@$lines);
5383 for (; $idx < $max; ++$idx) {
5384 my $line = $lines->[$idx];
5385 my $l = $self->line($line);
5386 if (!defined($l)) {
5387 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5388 "no data for line:$line, file:" . $self->path())
5389 if (!$lcovutil::warn_once_per_file ||
5390 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5391 $self->path()));
5392 next;
5393 }
5394 my $a = $l->age();
5395 if (!defined($a)) {
5396 lcovutil::ignorable_error($lcovutil::ERROR_UNMAPPED_LINE,
5397 "no age data for line:$line, file:" . $self->path())
5398 if (!$lcovutil::warn_once_per_file ||
5399 lcovutil::warn_once($lcovutil::ERROR_UNMAPPED_LINE,
5400 $self->path()));
5401 return undef;
5402 }
5403 my $bin = SummaryInfo::findAgeBin($a);
5404 if ($bin == $dateBin) {
5405 return $line;
5406 }
5407 }
5408 return undef;
5409 }
5410
5411 sub nextBranchInDateBin
5412 {
5413 # ($self, $dateBin, $tla, $after) = @_;
5414 return nextCategoryInDateBin('branch', BRANCH_CATEGORIES, @_);
5415 }
5416
5417 sub nextMcdcInDateBin
5418 {
5419 return nextCategoryInDateBin('MC/DC', MCDC_CATEGORIES, @_);
5420 }
5421
5422 sub nextCategoryInOwnerBin
5423 {
5424 my ($type, $category, $self, $owner, $tla, $after) = @_;
5425
5426 if (!exists($SummaryInfo::tlaLocation{$tla})) {
5427 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
5428 "unknown $type TLA '$tla'");
5429 return undef;
5430 }
5431
5432 # note the the "$self->line(...)" argument is 1-based (not zero-base)
5433 $after = defined($after) ? $after + 1 : 1;
5434
5435 if (exists($self->[$category]->{$owner})) {
5436 my $od = $self->[$category]->{$owner};
5437 if (exists($od->{$tla})) {
5438 my $l = $od->{$tla};
5439 my $idx = binarySearchLine($l, $after);
5440 return defined($idx) ? $l->[$idx] : undef;
5441 }
5442 }
5443 return undef;
5444 }
5445
5446 sub nextBranchInOwnerBin
5447 {
5448 # ($self, $owner, $tla, $after) = @_;
5449 return nextCategoryInOwnerBin('branch', BRANCH_OWNERS, @_);
5450 }
5451
5452 sub nextMcdcInOwnerBin
5453 {
5454 # ($self, $owner, $tla, $after) = @_;
5455 return nextCategoryInOwnerBin('MC/DC', MCDC_OWNERS, @_);
5456 }
5457
5458 sub _computeAge
5459 {
5460 my ($when, $path) = @_;
5461
5462 # if SOURCE_DATE_EPOCH is set, then use that as 'now': age of this
5463 # file is as of the epoch date.
5464 # if this file is newer than that ($when is in the future of epoch) - then
5465 # warn and put this file into the 'zero age' bin.
5466 my $now =
5467 exists($ENV{SOURCE_DATE_EPOCH}) ?
5468 DateTime->from_epoch(epoch => $ENV{SOURCE_DATE_EPOCH}) :
5469 DateTime->now();
5470 my $then = lcovutil::parse_w3cdtf($when);
5471 if ($then > $now) {
5472 if (lcovutil::warn_once($lcovutil::ERROR_INCONSISTENT_DATA, $path)) {
5473 # issue annotation warning at most once per file
5474 # also attempt to clarify where the date comes from
5475 my $data =
5476 exists($ENV{SOURCE_DATE_EPOCH}) ?
5477 (
5478 lcovutil::warn_once($lcovutil::ERROR_INCONSISTENT_DATA,
5479 'SOURCE_DATE_EPOCH') ?
5480 "computed from your 'SOURCE_DATE_EPOCH=$ENV{SOURCE_DATE_EPOCH}' environment variable - see 'man genhtml'"
5481 :
5482 "'SOURCE_DATE_EPOCH=$ENV{SOURCE_DATE_EPOCH}'") :
5483 "'now'";
5484
5485 lcovutil::ignorable_error($lcovutil::ERROR_INCONSISTENT_DATA,
5486 "File \"$path\": '$now' ($data) is older than annotate time '$when'"
5487 );
5488 }
5489 return 0;
5490 }
5491 return $then->delta_days($now)->in_units('days');
5492 }
5493
5494 sub _load
5495 {
5496 my ($self, $fileCovInfo) = @_;
5497
5498 my $start = Time::HiRes::gettimeofday();
5499 ++$totalFiles;
5500
5501 my $path = ReadCurrentSource::resolve_path($self->path());
5502 # try to simplify path - 'realpath' will fail if the file does
5503 # not exist - but that might be fine if it exists in the repo
5504 my $repo_path = Cwd::realpath($path);
5505 if (!defined($repo_path)) {
5506 if (!defined($annotateCallback) &&
5507 !$main::synthesizeMissingFile) {
5508 my $suffix =
5509 lcovutil::explain_once('synthesize',
5510 ' (see --synthesize-missing option to work around)');
5511 lcovutil::ignorable_error($lcovutil::ERROR_SOURCE,
5512 "\"" . $self->path() . "\" does not exist: $!" . $suffix);
5513 }
5514 $repo_path = $self->path();
5515 }
5516
5517 # check for version mismatch...
5518 if (@lcovutil::extractVersionScript) {
5519 my $currentVersion = $fileCovInfo->version('current');
5520 my $version = lcovutil::extractFileVersion($repo_path);
5521 if (defined($version) &&
5522 '' ne $version) {
5523 if (defined($currentVersion)) {
5524 lcovutil::checkVersionMatch($repo_path, $version,
5525 $currentVersion, 'load');
5526 } else {
5527 my $suffix = lcovutil::explain_once('missingVersionMsg',
5528 "\n\tSee the 'compute_file_version' section in man lcovrc(5)."
5529 );
5530 lcovutil::ignorable_error($lcovutil::ERROR_VERSION,
5531 "'$repo_path': computed '$version' but version not defined in 'current' data file "
5532 . $main::info_filenames[0]
5533 . $suffix);
5534 }
5535 } elsif (defined($currentVersion)) {
5536 lcovutil::ignorable_error($lcovutil::ERROR_VERSION,
5537 "'$repo_path': version mismatch: your '--version-script' returned empty but 'current' data in "
5538 . $main::info_filenames[0]
5539 . " defines '$currentVersion'");
5540 }
5541 my $end = Time::HiRes::gettimeofday();
5542 $lcovutil::profileData{check_version}{$self->path()} = $end - $start;
5543 }
5544
5545 if (defined($annotateCallback) &&
5546 # also skip if we already emitted 'missing file' error
5547 (defined($lcovutil::versionCallback) ||
5548 !lcovutil::fileExistenceBeforeCallbackError($repo_path))
5549 ) {
5550 my $begin = Time::HiRes::gettimeofday();
5551 my $lineNum = 0;
5552
5553 my ($status, $lines);
5554 eval { ($status, $lines) = $annotateCallback->annotate($repo_path); };
5555 if ($@) {
5556 my $context = MessageContext::context();
5557 lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
5558 'annotate(' . $self->path() . ") failed$context: $@");
5559 $status = 1;
5560 # set $lines so exit status error below prints something
5561 $lines = [[$@]];
5562 }
5563 if (!$status && defined($lines)) {
5564 my $found; # check that either all lines are annotated or none are
5565 foreach my $line (@$lines) {
5566
5567 my ($text, $abbrev, $full, $when, $commit) = @$line;
5568 ++$lineNum;
5569
5570 my $age = _computeAge($when, $path);
5571 if ($commit ne 'NONE') {
5572 die("inconsistent 'annotate' data for '$repo_path': both 'commit' and 'no commit' lines"
5573 ) if (defined($found) && !$found);
5574 $found = 1;
5575
5576 defined($abbrev) or
5577 die("owner is undef for $repo_path:$lineNum");
5578 } else {
5579 die("inconsistent 'annotate' data for '$repo_path': both 'no commit' and 'commit' lines"
5580 ) if (defined($found) && $found);
5581 $found = 0;
5582 $abbrev = "no.body";
5583 }
5584 $full = $abbrev unless defined($full);
5585 push @{$self->[LINES]},
5586 SourceLine->new($lineNum, $text, $abbrev, $full,
5587 $when, $age, $commit);
5588 }
5589
5590 my $end = Time::HiRes::gettimeofday();
5591
5592 $lcovutil::profileData{annotate}{$self->path()} = $end - $begin;
5593
5594 ++$annotatedFiles if $found;
5595 $self->_synthesize($fileCovInfo, 1); # fake annotations too
5596 return $self;
5597 } else {
5598
5599 # non-zero exit status: something bad happened in annotation
5600 # if we ignore the error - then fall through and just try to load the file
5601 my $text = '';
5602 $text = ': ' . $lines->[0]->[0] . '...'
5603 if $lines && @$lines;
5604 # might be useful to provide more than one line of context - if there is more than one line?
5605
5606 lcovutil::report_exit_status($lcovutil::ERROR_ANNOTATE_SCRIPT,
5607 "annotate command failed",
5608 $status, '', $text);
5609 } # end if error
5610 } # end if annotate script exists
5611
5612 # Check if file exists and is readable
5613 my $begin = Time::HiRes::gettimeofday();
5614 if (!-r $path) {
5615 # perhaps this error should be ignorable: if the source is not
5616 # found and the 'source' error is ignored, then synthesize
5617 # Note that we can't extract version data from synthesized code.
5618 if ($main::synthesizeMissingFile ||
5619 # don't complain if we weren't going to do anything with the file -
5620 # not generating source view and not checking versions or annotating
5621 ($main::no_sourceview &&
5622 0 == scalar(@lcovutil::extractVersionScript) &&
5623 !lcovutil::is_filter_enabled())
5624 ) {
5625 $self->_synthesize($fileCovInfo,
5626 defined($SourceFile::annotateCallback));
5627 my $end = Time::HiRes::gettimeofday();
5628 $lcovutil::profileData{synth}{$self->path()} = $end - $begin;
5629 return $self;
5630 }
5631 die($self->path() .
5632 " is not readable or doesn't exist. See the '--substitute', '--filter missing' and '--synthesize-missing' $lcovutil::tool_name options for methods to fix the path or ignore the problem."
5633 );
5634 }
5635 $self->_bare_load($path);
5636 $self->_synthesize($fileCovInfo, defined($SourceFile::annotateCallback));
5637 my $end = Time::HiRes::gettimeofday();
5638 $lcovutil::profileData{load}{$self->path()} = $end - $begin;
5639 return $self;
5640 }
5641
5642 sub _synthesize
5643 {
5644 my ($self, $fileCovInfo, $annotate) = @_;
5645
5646 my $lineData = $fileCovInfo->lineMap();
5647 my $currentLast = scalar(@{$self->[LINES]});
5648 my $last_line = 0;
5649 while (my ($l, $d) = each(%$lineData)) {
5650 $last_line = $l if ('<' ne substr($l, 0, 1) && $l > $last_line);
5651 }
5652 my %functionDecls;
5653 if ($lcovutil::func_coverage) {
5654 while (my ($fnName, $funcEntry) = each(%{$fileCovInfo->functionMap()}))
5655 {
5656 my $tla = $funcEntry->hit()->[1];
5657 # deleted function doesn't count
5658 next if grep(/^$tla$/, ('DUB', 'DCB'));
5659 my $line = $funcEntry->line();
5660 my $end = $funcEntry->end_line();
5661 $last_line = $line if $line > $last_line;
5662 $functionDecls{$line} = "/* BEGIN: function \"$fnName\" */"
5663 if ($line >= $currentLast);
5664 if (defined($end)) {
5665 $functionDecls{$end} = "/* END: function \"$fnName\" */"
5666 if ($end >= $currentLast);
5667 if ($end > $last_line) {
5668 # function end is not an executable line,
5669 # but is after last executable line
5670 $last_line = $end;
5671 }
5672 }
5673 }
5674 }
5675 return $self if ($last_line < 1 ||
5676 $currentLast >= $last_line);
5677 my $why;
5678 if (0 == $currentLast) {
5679 # Synthesize source data from coverage trace to replace unreadable file
5680 my $suffix =
5681 $lcovutil::ignore[$lcovutil::ERROR_SOURCE] ?
5682 ' - synthesizing fake content.' :
5683 '.';
5684 lcovutil::ignorable_error($lcovutil::ERROR_SOURCE,
5685 "cannot read '" . $self->path() .
5686 "' - file is empty or unreadable$suffix")
5687 unless $main::no_sourceview;
5688 $why = 'empty or unreadable';
5689 } else {
5690 my $suffix = '';
5691 if ($lcovutil::ignore[$lcovutil::ERROR_RANGE]) {
5692 my $num = $last_line - $currentLast;
5693 my $plural = $num == 1 ? 'line' : "$num lines";
5694 $suffix = ' ... synthesizing fake content for last ' . $plural;
5695 }
5696 lcovutil::ignorable_error($lcovutil::ERROR_RANGE,
5697 $self->path() . ' contains only ' . $currentLast .
5698 ' lines but coverage data refers to line ' .
5699 $last_line . $suffix);
5700 $why = 'not long enough';
5701 }
5702 # Simulate gcov behavior
5703 my $notFound = "/* " . $self->path() . " $why */";
5704 my $synth = "/* (content generated from coverage data) */";
5705 my $idx = 1;
5706 my @fakeline = (undef, # line number
5707 undef); # source text
5708 if ($annotate) {
5709 my $now =
5710 exists($ENV{SOURCE_DATE_EPOCH}) ?
5711 DateTime->from_epoch(epoch => $ENV{SOURCE_DATE_EPOCH}) :
5712 DateTime->now();
5713 push(@fakeline, 's.n.thetic', # owner
5714 'faked synthetic user', # full name
5715 $now, # when
5716 _computeAge($now, $self->path()), # age
5717 'synthesized'); # commit ID
5718 }
5719 for (my $line = $currentLast + 1; $line <= $last_line; $line++) {
5720 my $mod = $idx++ % 20;
5721 my $text;
5722 # if there is function decl here...mark it.
5723 if (exists($functionDecls{$line})) {
5724 $text = $functionDecls{$line};
5725 } else {
5726 $text = (($mod == 1) ? $notFound :
5727 ($mod == 2) ? $synth :
5728 "/* ... */");
5729 }
5730 splice(@fakeline, 0, 2, $line, $text);
5731 push(@{$self->[LINES]}, SourceLine->new(@fakeline));
5732 }
5733 return $self;
5734 }
5735
5736 sub _bare_load
5737 {
5738 my ($self, $path) = @_;
5739
5740 my $lineno = 0;
5741 local *HANDLE; # File handle for reading the diff file
5742
5743 open(HANDLE, "<", $path) or
5744 die("unable to open '" . $self->path() . "': $!\n");
5745 while (my $line = <HANDLE>) {
5746 chomp $line;
5747 $line =~ s/\r//g; # Also remove CR from line-end
5748
5749 $lineno++;
5750 push @{$self->[LINES]}, SourceLine->new($lineno, $line);
5751 }
5752 close(HANDLE) or die("unable to close $path: $!\n");
5753 return $self;
5754 }
5755
5756 # a class to hold either line or branch counts for each testcase -
5757 # used by the "--show-details" feature.
5758 package TestcaseTlaCount;
5759
5760 sub new
5761 {
5762 # $testcaseCounts: either 'CountData' or 'BranchData' structure
5763 # - the data for this testcase
5764 # $fileDetails: SourceFile structure - data for the filename
5765 # $covtype: 'line' or 'branch'
5766 my ($class, $testcaseCounts, $fileDetails, $covtype) = @_;
5767
5768 my %tlaData;
5769 if ($covtype != SummaryInfo::FUNCTION_DATA) {
5770 $tlaData{found} = $testcaseCounts->found();
5771 $tlaData{hit} = $testcaseCounts->hit();
5772 } else {
5773 $tlaData{found} =
5774 $testcaseCounts->numFunc($main::merge_function_aliases);
5775 $tlaData{hit} = $testcaseCounts->numHit($main::merge_function_aliases);
5776 }
5777 if ($main::show_tla &&
5778 defined($fileDetails)) {
5779 for my $tla (("CBC", "GBC", "GIC", "GNC")) {
5780 $tlaData{$tla} = 0;
5781 }
5782 if (SummaryInfo::LINE_DATA == $covtype) {
5783 foreach my $line ($testcaseCounts->keylist()) {
5784 # skip uncovered lines...
5785 next if $testcaseCounts->value($line) == 0;
5786 my $lineData =
5787 $fileDetails->line($line); # "SourceLine" structure
5788 my $tla = $lineData->tla();
5789 die("unexpected TLA '$tla' in CounntData for line $line")
5790 unless exists($tlaData{$tla});
5791 $tlaData{$tla} += 1;
5792 }
5793 } elsif (SummaryInfo::BRANCH_DATA == $covtype) {
5794 foreach my $line ($testcaseCounts->keylist()) {
5795 my $lineData =
5796 $fileDetails->line($line); # "SourceLine" structure
5797 my $branchEntry = $lineData->branchElem();
5798 foreach my $id ($branchEntry->blocks()) {
5799 my $block = $branchEntry->getBlock($id);
5800 foreach my $data (@$block) {
5801 my ($br, $tla) = @$data;
5802 my $count = $br->count();
5803 die("unexpected branch TLA $tla for count $count at " .
5804 $fileDetails->path() . ":$line")
5805 unless (($count != 0) == exists($tlaData{$tla}));
5806 next if (0 == $count);
5807 $tlaData{$tla} += 1;
5808 }
5809 }
5810 }
5811 } elsif (SummaryInfo::MCDC_DATA == $covtype) {
5812 foreach my $line ($testcaseCounts->keylist()) {
5813 my $lineData =
5814 $fileDetails->line($line); # "SourceLine" structure
5815 my $mcdcEntry = $lineData->mcdcElem();
5816 while (my ($groupSize, $group) = each(%{$mcdcEntry->groups()}))
5817 {
5818 foreach my $expr (@$group) {
5819 foreach my $sense (0, 1) {
5820 # use 'current' count...
5821 my ($tla, $b_count, $c_count) =
5822 @{$expr->count($sense)};
5823 die("unexpected branch TLA $tla for count $c_count at "
5824 . $fileDetails->path()
5825 . ":$line")
5826 unless (
5827 ($c_count != 0) == exists($tlaData{$tla}));
5828 next if (0 == $c_count);
5829 $tlaData{$tla} += 1;
5830 }
5831 }
5832 }
5833 }
5834 } else {
5835 die("$covtype not supported yet")
5836 unless $covtype == SummaryInfo::FUNCTION_DATA;
5837 foreach my $key ($testcaseCounts->keylist()) {
5838 my $func = $testcaseCounts->findKey($key);
5839 my $line = $func->line();
5840 # differential FunctionEntry
5841 my $lineData = $fileDetails->line($line);
5842 my $differential = $lineData->functionElem();
5843 my @data;
5844 if ($main::merge_function_aliases) {
5845 push(@data, $differential->hit());
5846 } else {
5847 my $aliases = $differential->aliases();
5848 foreach my $alias (keys %$aliases) {
5849 push(@data, $aliases->{$alias});
5850 }
5851 }
5852 foreach my $d (@data) {
5853 my ($count, $tla) = @$d;
5854 die("unexpected branch TLA $tla for count $count")
5855 unless (($count != 0) == exists($tlaData{$tla}));
5856 #next if (0 == $count);
5857 $tlaData{$tla} += 1;
5858 }
5859 }
5860 }
5861 }
5862 my $self = [$testcaseCounts, $fileDetails, \%tlaData, $covtype];
5863 bless $self, $class;
5864 return $self;
5865 }
5866
5867 sub covtype
5868 {
5869 my $self = shift;
5870 return $self->[3];
5871 }
5872
5873 sub count
5874 {
5875 my ($self, $tla) = @_;
5876
5877 my $tlaCounts = $self->[2];
5878 return exists($tlaCounts->{$tla}) ? $tlaCounts->{$tla} : 0;
5879 }
5880
5881 package GenHtml;
5882
5883 use constant {
5884 TOP => 0,
5885 WORKLIST => 1,
5886 PENDING => 2,
5887 JOBS => 3,
5888 CHILD_DATA => 4,
5889 RETRY_COUNT => 5,
5890 TMPDIR => 6,
5891 DELAY_TIMER => 7,
5892 CURRENT_PARALLEL => 8,
5893 };
5894
5895 sub new
5896 {
5897 my ($class, $current_data) = @_;
5898 my $self = [
5899 SummaryInfo->new("top", ''), # top has empty name
5900 [], # worklist: dependencies are complete - this can run immediately
5901 {}, # %pending; # map of name->list of as-yet incomplete dependencies
5902 # This task can be scheduled as soon as its last dependency
5903 # is complete.
5904 [], # jobs which are to be scheduled for execution
5905 {}, # childData - for callback
5906 {}, # jobID -> fail count for this job
5907 File::Temp->newdir("genhtml_XXXX",
5908 DIR => $lcovutil::tmp_dir,
5909 CLEANUP => 1),
5910 0, # delay timer
5911 0 # current count of parallel jobs
5912 ];
5913 bless $self, $class;
5914
5915 lcovutil::info(1, "Writing temporary data to " . $self->[TMPDIR] . "\n");
5916 my $pending = $self->[PENDING];
5917 my $worklist = $self->[WORKLIST];
5918 my $top_level_summary = $self->[0];
5919 # no parent data for top-level
5920 my $toplevelPerTestData =
5921 ($main::hierarchical || $main::flat) ? [{}, {}, {}, {}] : undef;
5922 $pending->{""} = [
5923 ['top',
5924 [$top_level_summary, $toplevelPerTestData,
5925 $top_level_summary->name()
5926 ],
5927 ['root'],
5928 ['root'],
5929 [undef, undef]
5930 ],
5931 {}
5932 ];
5933
5934 # sort the worklist so segment will tend to contain files from the same directory
5935 foreach my $f (sort $current_data->files()) {
5936 my $traceInfo = $current_data->data($f);
5937 my $filename = ReadCurrentSource::resolve_path($traceInfo->filename());
5938 my ($vol, $parentDir, $file) = File::Spec->splitpath($filename);
5939 if (!File::Spec->file_name_is_absolute($filename)) {
5940 if ($parentDir) {
5941 $parentDir = File::Spec->catfile($main::cwd, $parentDir);
5942 } else {
5943 $parentDir = $main::cwd;
5944 }
5945 $filename = File::Spec->catfile($parentDir, $file);
5946 }
5947 my $short_name =
5948 $main::no_prefix ? $filename :
5949 main::apply_prefix($filename, @main::dir_prefix);
5950 my $is_absolute = File::Spec->file_name_is_absolute($short_name);
5951 $short_name =~ s|^$lcovutil::dirseparator||;
5952 my @short_path = File::Spec->splitdir($short_name);
5953 my @path = File::Spec->splitdir($parentDir);
5954
5955 my @rel_dir_stack =
5956 @short_path; # @rel_dir_stack: relative path to parent dir of $f
5957 pop(@rel_dir_stack); # remove filename from the end
5958 my $pendingParent;
5959 if ($main::hierarchical) {
5960 # excludes trailing '/'
5961 my $base = substr($filename, 0, -(length($short_name) + 1));
5962 my $relative_path = "";
5963 my $path = $base;
5964 $pendingParent =
5965 $pending->{""}; # this is the top-level object dependency
5966 my @sp;
5967 my @p = split($lcovutil::dirseparator, substr($base, 0, -1))
5968 ; # remove trailing '/'
5969 while (scalar(@rel_dir_stack)) {
5970 my $element = shift(@rel_dir_stack);
5971 $relative_path .= $element;
5972 $path .= $lcovutil::dirseparator . $element;
5973 push(@p, $element);
5974 push(@sp, $element);
5975 if (exists($pending->{$path})) {
5976 $pendingParent = $pending->{$path};
5977 } else {
5978 my $perTestData = [{}, {}, {}, {}];
5979
5980 my @dirData = (SummaryInfo->new("directory", $relative_path,
5981 $is_absolute),
5982 $perTestData,
5983 $path);
5984 add_dependency($pendingParent, $path);
5985 my @spc = @sp;
5986 my @pc = @p;
5987 $pendingParent = [
5988 ['dir', \@dirData,
5989 \@spc, \@pc,
5990 $pendingParent
5991 ],
5992 {}
5993 ];
5994 die("unexpected pending entry")
5995 if exists($pending->{$dirData[2]});
5996 $pending->{$dirData[2]} = $pendingParent;
5997 }
5998 $relative_path .= $lcovutil::dirseparator;
5999 }
6000 } elsif (!$main::flat) {
6001 # not hierarchical
6002 my $relative_path = File::Spec->catdir(@rel_dir_stack);
6003 if (!exists($pending->{$parentDir})) {
6004 my $perTestData = [{}, {}, {}, {}];
6005 my @dirData = (SummaryInfo->new(
6006 "directory", $relative_path, $is_absolute
6007 ),
6008 $perTestData,
6009 $parentDir);
6010 $pending->{$parentDir} = [
6011 ['dir', \@dirData, \@rel_dir_stack, \@path,
6012 $pending->{$top_level_summary->name()}
6013 ],
6014 {}
6015 ];
6016 }
6017 $pendingParent = $pending->{$parentDir};
6018
6019 # my directory is dependency for the top-level
6020 add_dependency($pending->{$top_level_summary->name()}, $parentDir);
6021 }
6022
6023 # current file is a dependency of the top-level for a flat (2-level)
6024 # report - or of the parent directory otherwise
6025 my $mergeInto = $main::flat ? $pending->{$top_level_summary->name()} :
6026 $pendingParent;
6027 add_dependency($mergeInto, $f);
6028 # this file is ready to be processed
6029 my @fileData = (SummaryInfo->new("file", $filename), [{}, {}, {}], $f);
6030 push(@$worklist,
6031 ['file', \@fileData, \@short_path, \@path, $mergeInto]);
6032 }
6033
6034 $self->compute();
6035 # remove empty directories produced when no data in the directory
6036 # was selected. We want to clean both the directory and its parents.
6037 foreach my $dir (@cleanDirectoryList) {
6038 while ($dir) {
6039 my $d = File::Spec->catfile($main::output_directory, $dir);
6040 if (-d $d) {
6041 print("removing empty $d\n");
6042 if (!rmdir($d)) {
6043 # directory not empty - stop
6044 last;
6045 }
6046 }
6047 $d = File::Basename::dirname($dir); # look up
6048 last if $d eq $dir;
6049 $dir = $d;
6050 }
6051 }
6052 $lcovutil::profileData{mergeDelayTimer} = $self->[DELAY_TIMER];
6053 printf("overall delay: %0.3fs\n", $self->[DELAY_TIMER])
6054 if $main::debugScheduler;
6055 return $self;
6056 }
6057
6058 sub top()
6059 {
6060 my $self = shift;
6061 return $self->[0];
6062 }
6063
6064 sub add_dependency
6065 {
6066 my ($parent, $name) = @_;
6067 lcovutil::debug(1,
6068 "add depend $name' in -> " . $parent->[0]->[1]->[2] . "\n")
6069 unless exists($parent->[1]->{$name});
6070 print("add depend $name -> " . $parent->[0]->[1]->[2] . "\n")
6071 if $main::debugScheduler > 1;
6072 $parent->[1]->{$name} = 1;
6073 }
6074
6075 sub completed_dependency
6076 {
6077 # return 0 when last dependency is removed
6078 my ($self, $parent, $name) = @_;
6079
6080 my $pending = $self->[PENDING];
6081 die("missing pending '$parent'")
6082 unless exists($pending->{$parent});
6083 my $pendingParent = $pending->{$parent};
6084 die("missing pending entry for $name (in $parent")
6085 unless exists($pendingParent->[1]->{$name});
6086 delete($pendingParent->[1]->{$name});
6087 print("completed $name -> $parent " . scalar(%{$pendingParent->[1]}) . "\n")
6088 if $main::debugScheduler > 1;
6089 # LCOV_EXCL_START
6090 if ($main::debugScheduler > 1) {
6091 # print parent dependencies
6092 while (my ($k, $d) = each(%{$pendingParent->[1]})) {
6093 die("unexpected parent dependency $k ARRAY: " . $d->[0] . ' ' .
6094 join('/', @{$d->[2]}))
6095 if ('ARRAY' eq ref($d) || 1 != $d);
6096 print(" $k\n");
6097 }
6098 }
6099 # LCOV_EXCL_STOP
6100 if (!%{$pendingParent->[1]}) {
6101 # no more dependencies - schedule this one
6102 my $p = $pendingParent->[0];
6103 print("completed dependencies - schedule " . $p->[0] . ' ' .
6104 join('/', @{$p->[2]}) . "\n")
6105 if $main::debugScheduler > 1;
6106 push(@{$self->[WORKLIST]}, $p);
6107 delete($pending->{$parent});
6108 }
6109 }
6110
6111 sub merge_one
6112 {
6113 my ($self, $parentPerTestData, $fullname, $perTest, $summary,
6114 $parentSummary, $parentPath, $parallel)
6115 = @_;
6116 my $type = $summary->type();
6117 if ('file' eq $type) {
6118 my $base_name = File::Basename::basename($fullname);
6119 for (my $i = 0; $i < scalar(@$perTest); $i++) {
6120 $parentPerTestData->[$i]->{$base_name} = $perTest->[$i];
6121 }
6122 } elsif ('directory' eq $type) {
6123 for (my $i = 0; $i < scalar(@$perTest); $i++) {
6124 while (my ($basename, $data) = each(%{$perTest->[$i]})) {
6125 $parentPerTestData->[$i]->{$basename} = $data;
6126 }
6127 }
6128 } else {
6129 die("unexpected type $type")
6130 unless $type eq 'top';
6131 # set the top-level to this (restored) value...
6132 $self->[0] = $summary if $parallel;
6133 }
6134 if ($type ne 'top') {
6135 my $mergeInto = $main::flat ? $self->top() : $parentSummary;
6136 $mergeInto->append($summary);
6137
6138 my $parentName = $main::flat ? '' : $parentPath;
6139 $self->completed_dependency($parentName, $fullname);
6140 }
6141 }
6142
6143 sub compute_one
6144 {
6145 my ($type, $name, $summary, $parentSummary, $perTestData,
6146 $rel_dir, $base_dir, $trunc_dir)
6147 = @_;
6148
6149 my $start = Time::HiRes::gettimeofday();
6150
6151 if ('file' eq $type) {
6152 my ($testdata, $testfncdata, $testbrdata, $testcase_mcdc) =
6153 main::process_file($summary, $parentSummary,
6154 $trunc_dir, $rel_dir, $name);
6155 $perTestData = [$testdata, $testfncdata, $testbrdata, $testcase_mcdc];
6156 } elsif ('dir' eq $type) {
6157 # process the directory...
6158 main::write_summary_pages($name, 1, # this is a directory,
6159 $summary, $main::show_details,
6160 $rel_dir, $base_dir, $trunc_dir,
6161 $perTestData);
6162 } else {
6163 die("unexpected task")
6164 unless 'top' eq $type;
6165 # Create sorted pages
6166 main::write_summary_pages($name, 0, # 0 == list directories
6167 $summary,
6168 # generate top-level 'details' in flat or hierarchical modes
6169 $main::show_details &&
6170 ($main::flat || $main::hierarchical),
6171 ".", "", undef, $perTestData);
6172 }
6173 $summary->checkCoverageCriteria();
6174 if ('file' eq $type &&
6175 1 < $lcovutil::maxParallelism &&
6176 !($main::buildSerializableDatabase || $main::show_details)) {
6177
6178 if ($main::no_sourceview ||
6179 $main::frames ||
6180 !$main::show_tla) {
6181 $summary->[SummaryInfo::FILE_DETAILS] = undef;
6182 } elsif ($main::show_tla) {
6183 # just store the location of the first coverpoint in each display
6184 # group - rather than returning the whole detail structure?
6185 $summary->[SummaryInfo::FILE_DETAILS]->simplify();
6186 }
6187 }
6188 my $end = Time::HiRes::gettimeofday();
6189 $lcovutil::profileData{file}{$name} = $end - $start;
6190
6191 return $perTestData;
6192 }
6193
6194 sub _waitChild
6195 {
6196 my ($self, $waitForPending, $noHang) = @_;
6197
6198 my $currentSize = 0;
6199 my $consumption = 0;
6200 if (0 != $lcovutil::maxMemory) {
6201 $currentSize = lcovutil::current_process_size();
6202 $consumption = ($self->[CURRENT_PARALLEL] + 1) * $currentSize;
6203 }
6204
6205 my $reaped = 0;
6206 if ($waitForPending ||
6207 $self->[CURRENT_PARALLEL] >= $lcovutil::maxParallelism ||
6208 ($self->[CURRENT_PARALLEL] > 1 && $consumption > $lcovutil::maxMemory)
6209 ) {
6210
6211 my $children = $self->[CHILD_DATA];
6212
6213 # wait here for child:
6214 # - while we are oversubscribed
6215 # - too many parallel jobs or
6216 # - consuming too much memory), OR
6217 # - if the worklist is empty but there are pending jobs
6218 # - the pending jobs will be put onto the worklist when
6219 # their dependency finishes
6220 my $worklist = $self->[WORKLIST];
6221 my $pending = $self->[PENDING];
6222 lcovutil::info(1,
6223 "memory constraint ($consumption > $lcovutil::maxMemory violated: waiting."
6224 . (scalar(@$worklist) + scalar(keys(%$pending)))
6225 . " remaining\n")
6226 if ($consumption > $lcovutil::maxMemory);
6227 my $start = Time::HiRes::gettimeofday();
6228 my $child = wait();
6229 my $end = Time::HiRes::gettimeofday();
6230 $self->[DELAY_TIMER] += $end - $start;
6231 return 0 unless $child > 0;
6232 my $childstatus = $?;
6233
6234 unless (exists($children->{$child})) {
6235 lcovutil::report_unknown_child($child);
6236 return $reaped;
6237 }
6238 $self->merge_child($child, $childstatus);
6239
6240 $reaped += 1;
6241 }
6242 if ($noHang) {
6243 while (1) {
6244 my $start = Time::HiRes::gettimeofday();
6245 my $child = waitpid(-1, POSIX::WNOHANG);
6246 if (0 < $child) {
6247 my $end = Time::HiRes::gettimeofday();
6248 $self->[DELAY_TIMER] += $end - $start;
6249 my $childstatus = $?;
6250 my $children = $self->[CHILD_DATA];
6251 unless (exists($children->{$child})) {
6252 lcovutil::report_unknown_child($child);
6253 next;
6254 }
6255 $self->merge_child($child, $childstatus);
6256 $reaped += 1;
6257 } else {
6258 last;
6259 }
6260 }
6261 }
6262 print("reaped $reaped current:", $self->[CURRENT_PARALLEL],
6263 " jobs:", scalar(@{$self->[JOBS]}),
6264 " work:", scalar(@{$self->[WORKLIST]}),
6265 " pending:", scalar(%{$self->[PENDING]}),
6266 "\n") if ($main::debugScheduler && $reaped);
6267
6268 return $reaped;
6269 }
6270
6271 sub _reschedule
6272 {
6273 my ($self, $jobID, $jobs) = @_;
6274 # clean up
6275 foreach my $task (@$jobs) {
6276 my $selfSummary = $task->[1];
6277 $selfSummary->unsetDirs(); # reset state
6278 }
6279 push(@{$self->[JOBS]}, [$jobs, $jobID]); # put job back
6280 print(" reschedule $jobID current:",
6281 $self->[CURRENT_PARALLEL],
6282 " jobs: ", scalar(@{$self->[JOBS]}), "\n")
6283 if $main::debugScheduler;
6284 }
6285
6286 sub _report_fail_and_reschedule
6287 {
6288 my ($self, $jobId, $jobs, $childPid, $reason) = @_;
6289 my $counts = $self->[RETRY_COUNT];
6290 if (exists($counts->{$jobId})) {
6291 $counts->{$jobId} += 1;
6292 } else {
6293 $counts->{$jobId} = 1;
6294 }
6295 lcovutil::report_fork_failure("compute job $jobId (child $childPid)",
6296 $reason, 0, $counts->{$jobId});
6297 $self->_reschedule($jobId, $jobs);
6298 }
6299
6300 sub _process_child
6301 {
6302 my ($self, $jobs, $jobId, $startTime) = @_;
6303
6304 # clear the profile data - we want just my contribution
6305 my $childStart = Time::HiRes::gettimeofday();
6306 my $tmp = '' . $self->[TMPDIR];
6307 my $stdout_file = File::Spec->catfile($tmp, "genhtml_$$.log");
6308 my $stderr_file = File::Spec->catfile($tmp, "genhtml_$$.err");
6309 my $currentState = lcovutil::initial_state();
6310 # clear counters so we store count only what we saw in the child
6311 $SourceFile::annotatedFiles = 0;
6312 $SourceFile::totalFiles = 0;
6313
6314 my $status = 0;
6315 my @rtnData;
6316 my ($stdout, $stderr, $code) = Capture::Tiny::capture {
6317
6318 foreach my $t (@$jobs) {
6319 my ($task, $sSummary, $rel_dir, $full_dir_path, $base_dir,
6320 $trunc_dir)
6321 = @$t;
6322 my @taskData;
6323 push(@rtnData, \@taskData);
6324
6325 my ($type, $data, $short_path, $path, $parentData) = @$task;
6326 my ($selfSummary, $perTestData, $name) = @$data;
6327 die("inconsistent")
6328 unless $selfSummary == $sSummary;
6329 my ($parentSummary, $parentPerTestData, $parentPath);
6330 ($parentSummary, $parentPerTestData, $parentPath) =
6331 @{$parentData->[0]->[1]}
6332 unless 'top' eq $type;
6333
6334 eval {
6335 my $thisTestData =
6336 compute_one($type, $name, $selfSummary, $parentSummary,
6337 $perTestData, $rel_dir, $base_dir, $trunc_dir);
6338
6339 # clear the parent pointer that we hacked into place. Don't want that
6340 # extra data returned by dumper.
6341 $selfSummary->[SummaryInfo::PARENT] = undef;
6342 $selfSummary->[SummaryInfo::SOURCES] = {}
6343 if $selfSummary->type() ne 'file';
6344 my $objname =
6345 $selfSummary->type() eq 'top' ? "" : $selfSummary->name();
6346 my $criteria = $CoverageCriteria::coverageCriteria{$objname}
6347 if exists($CoverageCriteria::coverageCriteria{$objname});
6348
6349 push(@taskData,
6350 $thisTestData, $parentPerTestData,
6351 $selfSummary, $criteria);
6352 }; # eval
6353 if ($@) {
6354 $status = 1;
6355 print(STDERR $@);
6356 # @todo maybe this should be an ignorable error
6357 next;
6358 }
6359
6360 } # foreach
6361 }; # end capture
6362 # print stdout and stderr ...
6363 foreach my $d ([$stdout_file, $stdout], [$stderr_file, $stderr]) {
6364 next
6365 unless ($d->[1]); # only print if there is something to print
6366 my $f = InOutFile->out($d->[0]);
6367 my $h = $f->hdl();
6368 print($h $d->[1]);
6369 }
6370
6371 my $file = File::Spec->catfile($tmp, "dumper_$$");
6372 my $childEnd = Time::HiRes::gettimeofday();
6373 $lcovutil::profileData{child}{$jobId} = $childEnd - $childStart;
6374 my $data;
6375 eval {
6376 $data = Storable::store([\@rtnData,
6377 [$SourceFile::annotatedFiles,
6378 $SourceFile::totalFiles
6379 ],
6380 lcovutil::compute_update($currentState),
6381 [$childStart, $childEnd]
6382 ],
6383 $file);
6384 my $done = Time::HiRes::gettimeofday();
6385 printf(" %d: dump %d %d jobs %0.3fs %0.3fMb %s\n",
6386 $jobId, $$, scalar(@$jobs),
6387 $done - $childEnd,
6388 (-f $file ? (-s $file) : 0) / (1024 * 1024),
6389 DateTime->now())
6390 if ($main::debugScheduler);
6391 };
6392 if ($@ || !defined($data)) {
6393 lcovutil::ignorable_error($lcovutil::ERROR_PARALLEL,
6394 "Job $jobId: child $$ serialize failed" . ($@ ? ": $@" : ''));
6395 $status = 1;
6396 }
6397 return $status;
6398 }
6399
6400 sub _segment_worklist
6401 {
6402 my ($self, $segmentID) = @_;
6403 my $worklist = $self->[WORKLIST];
6404
6405 my $nTasks = scalar(@$worklist);
6406 # how many cores are available?
6407 my $nCores = $lcovutil::maxParallelism - $self->[CURRENT_PARALLEL];
6408 # let's distribute them evenly
6409 # could be more sophisticated and look at the compute time used
6410 # by each of those tasks previously - then balance the expected load
6411 my $tasksPerCore =
6412 $lcovutil::maxParallelism > 1 ? ($nTasks + $nCores - 1) / $nCores :
6413 1;
6414 $tasksPerCore = $lcovutil::max_tasks_per_core
6415 if ($tasksPerCore > $lcovutil::max_tasks_per_core);
6416 while (@$worklist &&
6417 scalar(@{$self->[JOBS]}) <= $nCores) {
6418 my @jobs;
6419 push(@{$self->[JOBS]}, [\@jobs, $segmentID++]);
6420 foreach my $task (splice(@$worklist, 0, $tasksPerCore)) {
6421
6422 my ($type, $data, $short_path, $path, $parentData) = @$task;
6423 my ($selfSummary, $perTestData, $name) = @$data;
6424 #main::info("$type: $name\n");
6425 # break initialization into 2 statements - see
6426 # https://stackoverflow.com/questions/26676488/why-is-the-variable-not-available
6427 my ($parentSummary, $parentPerTestData, $parentPath);
6428 ($parentSummary, $parentPerTestData, $parentPath) =
6429 @{$parentData->[0]->[1]}
6430 unless 'top' eq $type;
6431
6432 my $rel_dir;
6433 my $full_dir_path;
6434 if ($type eq 'file') {
6435 $rel_dir =
6436 File::Spec->catdir(@{$short_path}[0 .. $#$short_path - 1]);
6437 die("file error for " . File::Spec->catdir(@$short_path))
6438 if '' eq $rel_dir;
6439 $full_dir_path = File::Spec->catdir(@{$path}[0 .. $#$path - 1]);
6440 } elsif ($type eq 'dir') {
6441 $rel_dir = File::Spec->catdir(@$short_path);
6442 $full_dir_path = File::Spec->catdir(@$path);
6443 } else {
6444 $rel_dir = '.';
6445 $full_dir_path = '.';
6446 }
6447 $rel_dir = lc($rel_dir) if ($lcovutil::case_insensitive);
6448 my $p = File::Spec->catdir($main::output_directory, $rel_dir);
6449 File::Path::make_path($p) unless -d $p || $main::no_html;
6450 my $base_dir = main::get_relative_base_path($rel_dir);
6451 my $trunc_dir = ($rel_dir eq '') ? 'root' : $rel_dir;
6452
6453 push(@jobs,
6454 [$task, $selfSummary, $rel_dir,
6455 $full_dir_path, $base_dir, $trunc_dir
6456 ]);
6457 } # foreach task assigned to this core
6458 }
6459 return $segmentID;
6460 }
6461
6462 sub compute
6463 {
6464 my $self = shift;
6465
6466 my $worklist = $self->[WORKLIST];
6467 my $pending = $self->[PENDING];
6468 my $joblist = $self->[JOBS];
6469 my $children = $self->[CHILD_DATA];
6470 my $failedAttempts = 0;
6471 my $segmentID = 0;
6472
6473 WORK:
6474 while ($self->[CURRENT_PARALLEL] ||
6475 @$joblist ||
6476 @$worklist ||
6477 %$pending) {
6478
6479 if (1 < $lcovutil::maxParallelism) {
6480 # wait here for child:
6481 # - while we are oversubscribed
6482 # - too many parallel jobs or
6483 # - consuming too much memory), OR
6484 # - if the worklist is empty and there are no jobs ready to
6485 # go (these are jobs which failed and were reschedule - e.g.,
6486 # due to out-of-memory).
6487 # There are two possibilities:
6488 # - there are pending jobs:
6489 # they will be put on the worklist when their dependency
6490 # finishes (at least one of those dependencies must be
6491 # running now - we could go check that...)
6492 # - there are no pending jobs: so there must be just
6493 # one remaining top-level job currently running -
6494 # when it finishes, we are done.
6495 # Also do a nonblocking wait here to collect any children that
6496 # have finished - so we have a better chance to parallelize
6497 # more/have more tasks that we can dispatch
6498 print(" currentParallel:",
6499 $self->[CURRENT_PARALLEL],
6500 " pending:", scalar(%$pending), "\n")
6501 if ($main::debugScheduler > 1 ||
6502 ($main::debugScheduler &&
6503 0 == scalar(@$worklist) &&
6504 0 == scalar(@$joblist)));
6505 if ($self->_waitChild(
6506 0 == scalar(@$worklist) && 0 == scalar(@$joblist), 1
6507 )) {
6508 # reaped at least one child process
6509 next WORK;
6510 }
6511 }
6512 #LCOV_EXCL_START
6513 unless (@$worklist || @$joblist) {
6514 foreach my $e (keys %$pending) {
6515 # something went wrong - print some debug data
6516 lcovutil::info("me: $e: depends\n");
6517 my $p = $pending->{$e};
6518 while (my ($k, $d) = each(%{$p->[1]})) {
6519 lcovutil::info(" $k\n");
6520 die("unexpected data for depend $k: $d") unless $d == 1;
6521 }
6522 lcovutil::info(" parent: " . $p->[0]->[0] . ' ' .
6523 join('/', @{$p->[0]->[2]}) . "\n");
6524 }
6525 # can get here if child process hit a 'die' (as opposed to an error)
6526 # and "--keep-going" was specified.
6527 die("unexpected empty worklist??");
6528 }
6529 #LCOV_EXCL_STOP
6530
6531 # schedule a few items from the worklist if we can..
6532 $segmentID = $self->_segment_worklist($segmentID);
6533
6534 while (@$joblist) {
6535 if (1 < $lcovutil::maxParallelism) {
6536 # need to wait here if insufficient resources
6537 # (only wait until resource available - pending and
6538 # worklist are managed above)
6539 my $reaped = $self->_waitChild(0);
6540 die("unexpected reap count $reaped") if $reaped > 1;
6541 }
6542 my $d = pop(@$joblist);
6543 my ($jobs, $jobId) = @$d;
6544
6545 my $start = Time::HiRes::gettimeofday();
6546 foreach my $task (@$jobs) {
6547 # keep track of where this data is stored - need it later for
6548 # top-level 'flat' view
6549 my $selfSummary = $task->[1];
6550 my $relDir = $task->[2];
6551 my $fullDir = $task->[3];
6552 $selfSummary->relativeDir($relDir);
6553 $selfSummary->fullDir($fullDir);
6554 }
6555
6556 # distribute this job to parallel execution unless there is
6557 # nothing else running. In that case, we won't continue
6558 # until this job is finished - so might as well do it
6559 # locally and not incur parallelism overhead.
6560 if (1 < $lcovutil::maxParallelism &&
6561 ($self->[CURRENT_PARALLEL] > 0 ||
6562 0 != scalar(@$joblist) ||
6563 scalar(@$jobs) > 1)
6564 ) {
6565 $lcovutil::profileData{nJobs}{$jobId} = scalar(@$jobs);
6566
6567 $lcovutil::deferWarnings = 1;
6568 my $pid = fork();
6569 if (!defined($pid)) {
6570 # fork failed
6571 ++$failedAttempts;
6572 # report_fork_failure sleeps a bit if it doesn't error out
6573 lcovutil::report_fork_failure("process segment $jobId",
6574 $!, $failedAttempts);
6575 # put job back into schedule
6576 $self->_reschedule($jobId, $jobs);
6577 next;
6578 }
6579 # fork succeeded - so reset 'consecutive fails' counter
6580 $failedAttempts = 0;
6581 if (0 == $pid) {
6582 # I'm the child
6583 my $status = $self->_process_child($jobs, $jobId, $start);
6584 exit($status);
6585 } else {
6586 $children->{$pid} = [$jobs, $jobId, $start];
6587 ++$self->[CURRENT_PARALLEL];
6588 print("forked $jobId current: ",
6589 $self->[CURRENT_PARALLEL],
6590 " jobs:", scalar(@$joblist), "\n")
6591 if $main::debugScheduler;
6592 }
6593 } else {
6594 #not parallel
6595 lcovutil::info(1, "serial execution of task $jobId\n")
6596 if ($lcovutil::maxParallelism > 1);
6597 die("unexpected distribution") unless 1 == scalar(@$jobs);
6598 my ($task, $sSummary, $rel_dir, $full_dir_path,
6599 $base_dir, $trunc_dir)
6600 = @{$jobs->[0]};
6601
6602 my ($type, $data, $short_path, $path, $parentData) = @$task;
6603 my ($selfSummary, $perTestData, $name) = @$data;
6604 die("inconsistent") unless $selfSummary == $sSummary;
6605 my ($parentSummary, $parentPerTestData, $parentPath);
6606 ($parentSummary, $parentPerTestData, $parentPath) =
6607 @{$parentData->[0]->[1]}
6608 unless 'top' eq $type;
6609
6610 my $thisTestData =
6611 compute_one($type, $name, $selfSummary, $parentSummary,
6612 $perTestData, $rel_dir, $base_dir, $trunc_dir);
6613
6614 $self->merge_one($parentPerTestData, $name,
6615 $thisTestData, $selfSummary,
6616 $parentSummary, $parentPath);
6617 my $end = Time::HiRes::gettimeofday();
6618 $lcovutil::profileData{$type}{$name} = $end - $start;
6619 }
6620 } # while (job list not empty)
6621 } # while (work remains)
6622 }
6623
6624 sub merge_child($$$)
6625 {
6626 my $mergeStart = Time::HiRes::gettimeofday();
6627 my ($self, $childPid, $childstatus) = @_;
6628 my $children = $self->[CHILD_DATA];
6629
6630 --$self->[CURRENT_PARALLEL];
6631 my ($jobs, $jobId, $start) = @{$children->{$childPid}};
6632 delete($children->{$childPid});
6633
6634 my $tmp = '' . $self->[TMPDIR];
6635 my $dumpfile = File::Spec->catfile($tmp, "dumper_$childPid");
6636 my $childLog = File::Spec->catfile($tmp, "genhtml_$childPid.log");
6637 my $childErr = File::Spec->catfile($tmp, "genhtml_$childPid.err");
6638 foreach my $f ($childLog, $childErr) {
6639 if (!-f $f) {
6640 $f = ''; # there was no output
6641 next;
6642 }
6643 if (open(RESTORE, "<", $f)) {
6644 # slurp into a string and eval..
6645 my $str = do { local $/; <RESTORE> }; # slurp whole thing
6646 close(RESTORE) or die("unable to close $f: $!\n");
6647 unlink $f;
6648 $f = $str;
6649 } else {
6650 $f = "unable to open $f: $!";
6651 if (0 == $childstatus) {
6652 lcovutil::report_parallel_error('genhtml',
6653 $lcovutil::ERROR_PARALLEL, $childPid, 0, $f,
6654 keys(%$children));
6655 }
6656 }
6657 }
6658 my $signal = $childstatus & 0xFF;
6659 # non-parallel execution prints stuff to stdout - so we should too
6660 print(STDOUT $childLog)
6661 if ((0 != $childstatus &&
6662 $signal != POSIX::SIGKILL &&
6663 $lcovutil::max_fork_fails != 0) ||
6664 $lcovutil::verbose >= 0);
6665 print(STDERR $childErr);
6666
6667 # now undump the data ...
6668 my $dStart = Time::HiRes::gettimeofday();
6669 my $dumped = Storable::retrieve($dumpfile)
6670 if (-f $dumpfile && 0 == $childstatus);
6671 my $dEnd = Time::HiRes::gettimeofday();
6672 printf(" %d restore %d: %0.3fs %s (parallel %d)\n",
6673 $jobId, $childPid, $dEnd - $dStart,
6674 DateTime->now(), $self->[CURRENT_PARALLEL])
6675 if $main::debugScheduler;
6676
6677 if (defined($dumped)) {
6678 eval {
6679 my ($jobData, $countData, $update, $otherData) = @$dumped;
6680
6681 die("error processing child")
6682 if (scalar(@$jobData) != scalar(@$jobs));
6683
6684 $SourceFile::annotatedFiles += $countData->[0];
6685 $SourceFile::totalFiles += $countData->[1];
6686 lcovutil::update_state(@$update);
6687
6688 $lcovutil::profileData{startDelay}{$jobId} =
6689 $otherData->[0] - $start;
6690 $lcovutil::profileData{mergeDelay}{$jobId} =
6691 $mergeStart - $otherData->[1];
6692
6693 foreach my $t (@$jobs) {
6694 my $task = $t->[0];
6695 my ($type, $data, $short_path, $fullname, $parentData) = @$task;
6696 my ($childSummary, $perTestData, $name) = @$data;
6697 my ($parentSummary, $parentPerTestData, $parentPath);
6698 ($parentSummary, $parentPerTestData, $parentPath) =
6699 @{$parentData->[0]->[1]}
6700 unless 'top' eq $type;
6701
6702 my $taskData = shift(@$jobData);
6703 # there was an error while processing the child
6704 die("error processing child " . scalar(@$taskData))
6705 if (scalar(@$taskData) != 4);
6706
6707 my ($thisTestData, $pPerTestData, $summary, $criteria) =
6708 @$taskData;
6709 $childSummary->copyGuts($summary);
6710 $self->merge_one($parentPerTestData, $name, $thisTestData,
6711 $childSummary, $parentSummary, $parentPath, 1);
6712
6713 # and save the deserialized criteria data
6714 if (defined($criteria)) {
6715 my $name =
6716 $childSummary->type() eq 'top' ? "" :
6717 $childSummary->name();
6718 $CoverageCriteria::coverageCriteria{$name} = $criteria;
6719 $criteria->[1] = 0 if $criteria->[1] eq '';
6720 my $v = $criteria->[1];
6721 die('unexpected criteria data \'' .
6722 join(' ', @$criteria) . '\'')
6723 unless (Scalar::Util::looks_like_number($v));
6724 $CoverageCriteria::coverageCriteriaStatus =
6725 ($v != 0 || 0 != scalar(@{$criteria->[2]})) ? $v : 0;
6726 }
6727 } # foreach job
6728 };
6729 if ($@) {
6730 $childstatus = 1 << 8 unless $childstatus;
6731 print(STDERR $@);
6732 lcovutil::report_parallel_error('genhtml',
6733 $lcovutil::ERROR_PARALLEL, $childPid, $childstatus,
6734 "unable to deserialize $dumpfile: $@",
6735 keys(%$children));
6736 }
6737 }
6738 if (!-f $dumpfile) {
6739 $self->_report_fail_and_reschedule($jobId, $jobs, $childPid,
6740 "serialized data $dumpfile not found");
6741 } elsif (!defined($dumped) || $childstatus != 0) {
6742 my $signal = $childstatus & 0xFF;
6743 if (POSIX::SIGKILL == $signal) {
6744 $self->_report_fail_and_reschedule($jobId, $jobs, $childPid,
6745 "killed by OS - possibly due to out-of-memory");
6746 } else {
6747 #print("stdout: $childLog\nstderr: $childErr\n");
6748 my $msg = "compute job $jobId";
6749 $msg .= ": unable to deserialize $dumpfile"
6750 unless defined($dumped);
6751 lcovutil::report_parallel_error('genhtml', $lcovutil::ERROR_CHILD,
6752 $childPid, $childstatus, $msg, keys(%$children));
6753 }
6754 }
6755 my $end = Time::HiRes::gettimeofday();
6756 $lcovutil::profileData{segment}{$jobId} = $end - $start;
6757 $lcovutil::profileData{merge_segment}{$jobId} = $end - $mergeStart;
6758
6759 unlink $dumpfile
6760 if -f $dumpfile;
6761 }
6762
6763 package main;
6764
6765 # Global variables & initialization
6766
6767 lcovutil::save_cmd_line(\@ARGV, "$FindBin::RealBin");
6768
6769 # TraceFile Instance containing all data from the 'current' .info file
6770 # - constructed at start of GenHtml
6771 our $current_data;
6772 # TraceFile Instance containing all data from the baseline .info file (if any)
6773 # - constructed in GenHtml (if needed)
6774 our $base_data;
6775 # Instance containing all data from diff file
6776 our $diff_data = DiffMap->new();
6777 our @opt_dir_prefix; # Array of prefixes to remove from all sub directories
6778 our @dir_prefix;
6779 our %test_description; # Hash containing test descriptions if available
6780 our $current_date = get_date_string(undef);
6781
6782 our @info_filenames; # List of .info files to use as data source
6783 our $header_title; # Title at top of HTML report page (above table)
6784 our $footer; # String at bottom of HTML report page
6785 our $test_title; # Title for output as written to each page header
6786 our $output_directory; # Name of directory in which to store output
6787 our @base_filenames; # Optional: names of files containing baseline data
6788 our $age_basefile; # how old is the baseline data file?
6789 our $baseline_title; # Optional name of baseline - written to page headers
6790 our $baseline_date; # Optional date that baseline was created
6791 our $diff_filename; # Optional name of file containing baseline data
6792 our $strip; # If set, strip leading directories when applying diff
6793 our $desc_filename; # Name of file containing test descriptions
6794 our $css_filename; # Optional name of external stylesheet file to use
6795 our $show_details; # If set, generate detailed directory view
6796 our $no_prefix; # If set, do not remove filename prefix
6797 our $show_tla; # categorize coverage data (or not)
6798 our $show_functionProportions = 0
6799 ; # show proportion of lines/branches contained in the function which are hit
6800 our $show_hitTotalCol; # include the 'hit' or 'missed' total count in tables
6801 # - this is part of the 'legacy' view
6802 # - also enabled when full differential categories are used
6803 # (i.e., but not when there is no baseline data - so no
6804 # categories apart from 'GNC' and 'UNC'
6805 our $use_legacyLabels;
6806 our $show_dateBins; # show last modified and last author info
6807 our $show_ownerBins; # show list of people who have edited code
6808 # (in this file/this directory/etc)
6809 our $show_nonCodeOwners; # show last modified and last author info for
6810 # non-code lines (e.g., comments)
6811 our $show_zeroTlaColumns; # unless set, improve readability by removing
6812 # summary table columns which contain
6813 # only zero (blank) entries
6814 our $show_simplifiedColors;
6815 our $treatNewFileAsBaseline;
6816 our $elide_path_mismatch =
6817 0; # handle case that file in 'baseline' and 'current' .info
6818 # data matches some name in the 'diff' file such that
6819 # the basename is the same but the pathname is different
6820 # - then pretend that the names DID match
6821 our $synthesizeMissingFile =
6822 0; # create file content if not found for annotation
6823 our $hierarchical = 0; # if true: show directory hierarchy
6824 # default: legacy two-level report
6825 our $flat = 0; # if true: single table of all files in top level
6826
6827 our $sort_tables = 1; # If set, provide directory listings with sorted entries
6828 our $no_sort; # Disable sort
6829 our $frames; # If set, use frames for source code view
6830 our $keep_descriptions; # If set, do not remove unused test case descriptions
6831 our $suppress_function_aliases; # if set, don't show list of collapsed
6832 # function aliases
6833 our $merge_function_aliases;
6834 our $no_sourceview; # If set, do not create a source code view for each file
6835 our $no_html; # don't generate HTML if set
6836 our $legend; # If set, include legend in output
6837 our $tab_size = 8; # Number of spaces to use in place of tab
6838 our $html_prolog_file; # Custom HTML prolog file (up to and including <body>)
6839 our $html_epilog_file; # Custom HTML epilog file (from </body> onwards)
6840 our $html_prolog; # Actual HTML prolog
6841 our $html_epilog; # Actual HTML epilog
6842 our $html_ext = "html"; # Extension for generated HTML files
6843 our $html_gzip = 0; # Compress with gzip
6844 our $opt_missed; # List/sort lines by missed counts
6845 our $dark_mode; # Use dark mode palette or normal
6846 our $charset = "UTF-8"; # Default charset for HTML pages
6847 our @fileview_sortlist;
6848 our @fileview_sortname = ("", "-sort-l", "-sort-f", "-sort-b", '-sort-m');
6849 our @fileview_prefixes = ("");
6850 our @funcview_sortlist;
6851 our @rate_name = ("Lo", "Med", "Hi");
6852 our @rate_png = ("ruby.png", "amber.png", "emerald.png");
6853 our $rc_desc_html = 0; # lcovrc: genhtml_desc_html
6854 our $deprecated_highlight; # ignored former option
6855
6856 our $cwd = cwd(); # Current working directory
6857
6858 # for debugging
6859 our $verboseScopeRegexp; # dump categorization processing if match
6860
6861 #
6862 # Code entry point
6863 #
6864
6865 $SIG{__WARN__} = \&lcovutil::warn_handler;
6866 $SIG{__DIE__} = \&lcovutil::die_handler;
6867
6868 STDERR->autoflush;
6869 STDOUT->autoflush;
6870
6871 my @datebins;
6872 my (@rc_date_bins, @rc_annotate_script, @rc_select_script, @rc_date_labels);
6873
6874 my %genhtml_rc_opts = (
6875 "genhtml_css_file" => \$css_filename,
6876 "genhtml_header" => \$header_title,
6877 "genhtml_footer" => \$footer,
6878 "genhtml_line_field_width" => \$line_field_width,
6879 "genhtml_overview_width" => \$overview_width,
6880 "genhtml_nav_resolution" => \$nav_resolution,
6881 "genhtml_nav_offset" => \$nav_offset,
6882 "genhtml_keep_descriptions" => \$keep_descriptions,
6883 "genhtml_no_prefix" => \$no_prefix,
6884 "genhtml_no_source" => \$no_sourceview,
6885 "genhtml_num_spaces" => \$tab_size,
6886 "genhtml_frames" => \$frames,
6887 "genhtml_legend" => \$legend,
6888 "genhtml_html_prolog" => \$html_prolog_file,
6889 "genhtml_html_epilog" => \$html_epilog_file,
6890 "genhtml_html_extension" => \$html_ext,
6891 "genhtml_html_gzip" => \$html_gzip,
6892 "genhtml_precision" => \$lcovutil::default_precision,
6893 "genhtml_function_coverage" => \$lcovutil::func_coverage,
6894 "genhtml_branch_coverage" => \$lcovutil::br_coverage,
6895 "genhtml_hi_limit" => \$hi_limit,
6896 "genhtml_med_limit" => \$med_limit,
6897 "genhtml_line_hi_limit" => \$ln_hi_limit,
6898 "genhtml_line_med_limit" => \$ln_med_limit,
6899 "genhtml_function_hi_limit" => \$fn_hi_limit,
6900 "genhtml_function_med_limit" => \$fn_med_limit,
6901 "genhtml_branch_hi_limit" => \$br_hi_limit,
6902 "genhtml_branch_med_limit" => \$br_med_limit,
6903 "genhtml_mcdc_hi_limit" => \$mcdc_hi_limit,
6904 "genhtml_mcdc_med_limit" => \$mcdc_med_limit,
6905 "genhtml_branch_field_width" => \$br_field_width,
6906 "genhtml_mcdc_field_width" => \$mcdc_field_width,
6907 "genhtml_owner_field_width" => \$owner_field_width,
6908 "genhtml_age_field_width" => \$age_field_width,
6909 "genhtml_sort" => \$sort_tables,
6910 "genhtml_charset" => \$charset,
6911 "genhtml_desc_html" => \$rc_desc_html,
6912 'merge_function_aliases' => \$merge_function_aliases,
6913 'suppress_function_aliases' => \$suppress_function_aliases,
6914 "genhtml_missed" => \$opt_missed,
6915 "genhtml_dark_mode" => \$dark_mode,
6916 "genhtml_hierarchical" => \$hierarchical,
6917 "genhtml_flat_view" => \$flat,
6918 "genhtml_show_havigation" => \$show_tla,
6919 "genhtml_show_noncode_owners" => \$show_nonCodeOwners,
6920 "genhtml_show_function_proportion" => \$show_functionProportions,
6921 'genhtml_show_owner_table' => \$show_ownerBins,
6922 "genhtml_demangle_cpp" => \@lcovutil::cpp_demangle,
6923 "genhtml_demangle_cpp_tool" => \$lcovutil::cpp_demangle_tool,
6924 "genhtml_demangle_cpp_params" => \$lcovutil::cpp_demangle_params,
6925 'genhtml_annotate_script' => \@rc_annotate_script,
6926 'genhtml_annotate_tooltip' => \$SourceFile::annotateTooltip,
6927 "select_script" => \@rc_select_script,
6928 'num_context_lines' => \$InInterestingRegion::num_context_lines,
6929 'genhtml_date_bins' => \@rc_date_bins,
6930 'genhtml_date_labels' => \@rc_date_labels,
6931 'truncate_owner_table' => \@truncateOwnerTableLevels,
6932 'owner_table_entries' => \$ownerTableElements,
6933 'compact_summary_tables' => \$compactSummaryTables,
6934 'genhtml_synthesize_missing' => \$synthesizeMissingFile,
6935 'scope_regexp' => \$verboseScopeRegexp,);
6936
6937 my $save;
6938 my $serialize;
6939 my $validateHTML = exists($ENV{LCOV_VALIDATE});
6940
6941 my %genhtml_options = ("output-directory|o=s" => \$output_directory,
6942 "header-title=s" => \$header_title,
6943 "footer=s" => \$footer,
6944 "title|t=s" => \$test_title,
6945 "description-file|d=s" => \$desc_filename,
6946 "keep-descriptions|k" => \$keep_descriptions,
6947 "css-file|c=s" => \$css_filename,
6948 "baseline-file|b=s" => \@base_filenames,
6949 "baseline-title=s" => \$baseline_title,
6950 "baseline-date=s" => \$baseline_date,
6951 "current-date=s" => \$current_date,
6952 "diff-file=s" => \$diff_filename,
6953 "annotate-script=s" => \@SourceFile::annotateScript,
6954 "select-script=s" => \@selectCallbackScript,
6955 "new-file-as-baseline" => \$treatNewFileAsBaseline,
6956 'elide-path-mismatch' => \$elide_path_mismatch,
6957 'synthesize-missing' => \$synthesizeMissingFile,
6958 # if 'show-owners' is set: generate the owner table
6959 # if it is passed a value: show all the owners,
6960 # regardless of whether they have uncovered code or not
6961 'show-owners:s' => \$show_ownerBins,
6962 'show-noncode' => \$show_nonCodeOwners,
6963 'show-zero-columns' => \$show_zeroTlaColumns,
6964 'simplified-colors' => \$show_simplifiedColors,
6965 "date-bins=s" => \@datebins,
6966 'date-labels=s' => \@SummaryInfo::ageGroupHeader,
6967 "prefix|p=s" => \@opt_dir_prefix,
6968 "num-spaces=i" => \$tab_size,
6969 "no-prefix" => \$no_prefix,
6970 "no-sourceview" => \$no_sourceview,
6971 'no-html' => \$no_html,
6972 "show-details|s" => \$show_details,
6973 "frames|f" => \$frames,
6974 "highlight" => \$deprecated_highlight,
6975 "legend" => \$legend,
6976 'save' => \$save,
6977 'serialize=s' => \$serialize,
6978 'scheduler+' => \$debugScheduler,
6979 "html-prolog=s" => \$html_prolog_file,
6980 "html-epilog=s" => \$html_epilog_file,
6981 "html-extension=s" => \$html_ext,
6982 "html-gzip" => \$html_gzip,
6983 "hierarchical" => \$hierarchical,
6984 "flat" => \$flat,
6985 "sort-tables" => \$sort_tables,
6986 "no-sort" => \$no_sort,
6987 "precision=i" => \$lcovutil::default_precision,
6988 "missed" => \$opt_missed,
6989 "dark-mode" => \$dark_mode,
6990 "show-navigation" => \$show_tla,
6991 "show-proportion" => \$show_functionProportions,
6992 "merge-aliases" => \$merge_function_aliases,
6993 "suppress-aliases" => \$suppress_function_aliases,
6994 'validate' => \$validateHTML,);
6995
6996 # remove ambiguous entry from common table -
6997 # (genhtml has '--sort-inputs' and '--sort-tables')
6998 # handle the (no obsolete) '--sort' option
6999 Getopt::Long::Configure("pass_through", "no_auto_abbrev");
7000 my $obsoleteSort;
7001 Getopt::Long::GetOptions('sort' => \$obsoleteSort);
7002 Getopt::Long::Configure('default');
7003
7004 # Parse command line options
7005 if (
7006 !lcovutil::parseOptions(\%genhtml_rc_opts, \%genhtml_options,
7007 \$output_directory)
7008 ) {
7009 print(STDERR "Use $tool_name --help to get usage information\n");
7010 exit(1);
7011 }
7012
7013 if (defined($obsoleteSort)) {
7014 $sort_tables = $obsoleteSort;
7015 lcovutil::ignorable_warning($lcovutil::ERROR_DEPRECATED,
7016 "option '--sort' is deprecated and will be removed in a future release; please use '--sort-tables' instead."
7017 );
7018 }
7019
7020 $merge_function_aliases = 1
7021 if ($suppress_function_aliases ||
7022 defined($lcovutil::cov_filter[$lcovutil::FILTER_FUNCTION_ALIAS]));
7023
7024 lcovutil::ignorable_error($lcovutil::ERROR_DEPRECATED,
7025 "option '--highlight' has been removed.")
7026 if ($deprecated_highlight);
7027 $buildSerializableDatabase = 1 if $serialize;
7028 $no_sourceview = 1 if $no_html;
7029
7030 # Copy related values if not specified
7031 $ln_hi_limit = $hi_limit if (!defined($ln_hi_limit));
7032 $ln_med_limit = $med_limit if (!defined($ln_med_limit));
7033 $fn_hi_limit = $hi_limit if (!defined($fn_hi_limit));
7034 $fn_med_limit = $med_limit if (!defined($fn_med_limit));
7035 $br_hi_limit = $hi_limit if (!defined($br_hi_limit));
7036 $br_med_limit = $med_limit if (!defined($br_med_limit));
7037 $mcdc_hi_limit = $hi_limit if (!defined($mcdc_hi_limit));
7038 $mcdc_med_limit = $med_limit if (!defined($mcdc_med_limit));
7039 $frames = undef unless (defined($frames) && $frames);
7040
7041 foreach my $rc ([\@datebins, \@rc_date_bins],
7042 [\@SummaryInfo::ageGroupHeader, \@rc_date_labels],
7043 [\@SourceFile::annotateScript, \@rc_annotate_script],
7044 [\@selectCallbackScript, \@rc_select_script]
7045
7046 ) {
7047 @{$rc->[0]} = @{$rc->[1]} unless (@{$rc->[0]});
7048 }
7049
7050 foreach my $cb ([\$SourceFile::annotateCallback, \@SourceFile::annotateScript],
7051 [\$selectCallback, \@selectCallbackScript]) {
7052 lcovutil::configure_callback($cb->[0], @{$cb->[1]})
7053 if scalar(@{$cb->[1]});
7054 }
7055
7056 if (defined($lcovutil::stop_on_error) &&
7057 !$lcovutil::stop_on_error) {
7058 # in the spirit of "don't stop" - don't worry about missing files.
7059 $synthesizeMissingFile = 1;
7060 }
7061
7062 # Merge sort options
7063 $sort_tables = 0
7064 if ($no_sort);
7065 die(
7066 "unsupported use of mutually exclusive '--flat' and '--hierachical' options")
7067 if ($flat && $hierarchical);
7068
7069 $show_tla = 1
7070 if (@base_filenames) || defined($diff_filename);
7071 if ($show_tla &&
7072 (0 == scalar(@base_filenames) &&
7073 !defined($diff_filename))
7074 ) {
7075 # no baseline - so not a differential report.
7076 # modify some settings to generate corresponding RTL code.
7077 $use_legacyLabels = 1;
7078 SummaryInfo::noBaseline();
7079 } else {
7080 $show_hitTotalCol = 1;
7081 }
7082
7083 if (@SourceFile::annotateScript) {
7084 $show_dateBins = 1;
7085 if (0 == scalar(@datebins)) {
7086 # default: 7, 30, 180 days
7087 @datebins = @SummaryInfo::defaultCutpoints;
7088 } else {
7089 my %uniqify =
7090 map { $_, 1 }
7091 split($lcovutil::split_char,
7092 join($lcovutil::split_char, @datebins));
7093 @datebins = sort(keys %uniqify);
7094 }
7095 SummaryInfo::setAgeGroups(@datebins);
7096
7097 if (defined($show_ownerBins)) {
7098 @truncateOwnerTableLevels =
7099 split($lcovutil::split_char,
7100 join($lcovutil::split_char, @truncateOwnerTableLevels));
7101 foreach my $l (@truncateOwnerTableLevels) {
7102 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
7103 "Unknown 'truncate_owner_table' level '$l': should be 'top', 'directory', or 'file'."
7104 ) unless grep(/^$l$/, ('top', 'directory', 'file'));
7105 }
7106
7107 lcovutil::ignorable_error($lcovutil::ERROR_USAGE,
7108 "Unsupported value 'owner_table_entries = $ownerTableElements': expected positive integer."
7109 )
7110 unless (!defined($ownerTableElements) ||
7111 (Scalar::Util::looks_like_number($ownerTableElements) &&
7112 0 < $ownerTableElements));
7113 }
7114 } else {
7115 $treatNewFileAsBaseline = undef;
7116 die("\"--show-owners\" option requires \"--annotate-script\" for revision control integration"
7117 ) if defined($show_ownerBins);
7118 die("\"--date-bins\" option requires \"--annotate-script\" for revision control integraion"
7119 ) if (0 != scalar(@datebins));
7120 }
7121 if (0 != (defined($diff_filename) ^ (0 != scalar(@base_filenames)))) {
7122 if (@base_filenames) {
7123 lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
7124 "Specified --baseline-file without --diff-file: assuming no source differences. Hope that is OK.\n"
7125 );
7126 } else {
7127 lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
7128 "Specified --diff-file without --baseline-file: assuming baseline code coverage was empty (nothing covered). Hope that is OK\n"
7129 );
7130 # OK..just assume that the baseline is empty...
7131 }
7132 $show_tla = 1;
7133 }
7134
7135 if (defined($header_title)) {
7136 $title = $header_title;
7137 } else {
7138 # use the default title bar.
7139 $title =~ s/ differential// # not a differential report, if no baseline...
7140 unless defined($diff_filename) || 0 != scalar(@base_filenames);
7141 }
7142 push(@fileview_prefixes, "-date")
7143 if ($show_dateBins);
7144 push(@fileview_prefixes, "-owner")
7145 if (defined($show_ownerBins));
7146
7147 # use LCOV original colors if no baseline file
7148 # (so no differential coverage)
7149 if ($use_legacyLabels ||
7150 !$show_tla ||
7151 (defined($show_simplifiedColors) &&
7152 $show_simplifiedColors)
7153 ) {
7154 lcovutil::use_vanilla_color();
7155 }
7156
7157 if ($dark_mode) {
7158 # if 'dark_mode' is set, then update the color maps
7159 # For the moment - just reverse the foreground and background
7160 my %reverse;
7161 while (my ($key, $value) = each(%lcovutil::normal_palette)) {
7162 $reverse{lc($value)} = $key;
7163 }
7164
7165 foreach my $tla (@SummaryInfo::tlaPriorityOrder) {
7166 # swap
7167 my $bg = $lcovutil::tlaColor{$tla};
7168
7169 my $key = substr($bg, 1);
7170 # if this color is in normal_palette, then swap to dark_palette
7171 # version. Otherwise, just swap the 'tlaColor' and 'tlaTextColor'
7172 # (foreground and background)
7173 if (exists($reverse{lc($key)})) {
7174 my $k = $reverse{lc($key)};
7175 $lcovutil::tlaColor{$tla} = '#' . uc($lcovutil::dark_palette{$k});
7176 } else {
7177 $lcovutil::tlaColor{$tla} = $lcovutil::tlaTextColor{$tla};
7178 }
7179 $lcovutil::tlaTextColor{$tla} = $bg;
7180 }
7181 }
7182
7183 @info_filenames = AggregateTraces::find_from_glob(@ARGV);
7184
7185 # Split the list of prefixes if needed
7186 parse_dir_prefix(@opt_dir_prefix);
7187
7188 # Check for info filename
7189 if (!@info_filenames) {
7190 die("No filename specified\n" .
7191 "Use $tool_name --help to get usage information\n");
7192 }
7193
7194 # Generate a title if none is specified
7195 $test_title = compute_title(\@ARGV, \@info_filenames)
7196 unless $test_title;
7197
7198 if (@base_filenames) {
7199 my @base_patterns = @base_filenames unless $baseline_title;
7200 @base_filenames = AggregateTraces::find_from_glob(@base_filenames);
7201
7202 $baseline_title = compute_title(\@base_patterns, \@base_filenames)
7203 unless $baseline_title;
7204 my $baseline_create;
7205
7206 if ($baseline_date) {
7207 eval {
7208 my $epoch = Date::Parse::str2time($baseline_date);
7209 $baseline_create = DateTime->from_epoch(epoch => $epoch);
7210 };
7211 if ($@) {
7212 #did not parse
7213 lcovutil::info(
7214 "failed to parse date '$baseline_date' - falling back to file creation time\n"
7215 );
7216 }
7217 }
7218 if (!defined($baseline_create)) {
7219 # if not specified, use 'last modified' of first baseline trace file
7220 my $create = (stat($base_filenames[0]))[9];
7221 $baseline_create = DateTime->from_epoch(epoch => $create);
7222 $baseline_date = get_date_string($create)
7223 unless defined($baseline_date);
7224 }
7225 $age_basefile =
7226 $baseline_create->delta_days(DateTime->now())->in_units('days');
7227 }
7228
7229 # Make sure css_filename is an absolute path (in case we're changing
7230 # directories)
7231 if ($css_filename) {
7232 if (!File::Spec->file_name_is_absolute($css_filename)) {
7233 $css_filename = File::Spec->catfile($cwd, $css_filename);
7234 }
7235 }
7236
7237 # Make sure tab_size is within valid range
7238 if ($tab_size < 1) {
7239 print(STDERR "ERROR: invalid number of spaces specified: $tab_size!\n");
7240 exit(1);
7241 }
7242
7243 # Get HTML prolog and epilog
7244 $html_prolog = get_html_prolog($html_prolog_file);
7245 $html_epilog = get_html_epilog($html_epilog_file);
7246
7247 # Issue a warning if --no-sourceview is enabled together with --frames
7248 if (defined($frames)) {
7249 if ($no_sourceview) {
7250 lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
7251 "option --frames disabled because --no-sourceview was specified.");
7252 $frames = undef;
7253 } elsif ($show_tla) {
7254 lcovutil::info(
7255 "Note: file table to source location navigation hyperlinks are disabled when --frames is enabled\n"
7256 );
7257 }
7258 }
7259
7260 # Issue a warning if --no-prefix is enabled together with --prefix
7261 if ($no_prefix && @dir_prefix) {
7262 lcovutil::ignorable_warning($lcovutil::ERROR_USAGE,
7263 "option --prefix disabled because --no-prefix was ignored");
7264 @dir_prefix = ();
7265 }
7266
7267 @fileview_sortlist = ($SORT_FILE);
7268 @funcview_sortlist = ($SORT_FILE);
7269
7270 if ($sort_tables) {
7271 push(@fileview_sortlist, $SORT_LINE);
7272 push(@fileview_sortlist, $SORT_FUNC) if ($lcovutil::func_coverage);
7273 push(@fileview_sortlist, $SORT_BRANCH) if ($lcovutil::br_coverage);
7274 push(@fileview_sortlist, $SORT_MCDC) if ($lcovutil::mcdc_coverage);
7275 push(@funcview_sortlist, $SORT_LINE);
7276 if ($show_functionProportions) {
7277 push(@funcview_sortlist, $SORT_MISSING_LINE);
7278 push(@funcview_sortlist, $SORT_MISSING_BRANCH)
7279 if ($lcovutil::br_coverage);
7280 push(@funcview_sortlist, $SORT_MISSING_MCDC)
7281 if ($lcovutil::mcdc_coverage);
7282 }
7283 }
7284
7285 if ($frames) {
7286 # Include genpng code needed for overview image generation
7287 do(File::Spec->catfile($tool_dir, 'genpng'));
7288 }
7289
7290 # Make sure precision is within valid range
7291 check_precision();
7292
7293 # Make sure output_directory exists, create it if necessary
7294 $output_directory = '.'
7295 if !defined($output_directory);
7296 if ($output_directory && !-d $output_directory) {
7297 info(1, "make_path $output_directory\n");
7298 File::Path::make_path($output_directory);
7299 }
7300
7301 if ($save && $output_directory)
7302 { # save copy of .info and diff files: useful for debugging user cases later
7303 foreach my $d (['baseline_', @base_filenames],
7304 ['', $diff_filename],
7305 ['current_', @info_filenames]
7306 ) {
7307 my $prefix = shift @$d;
7308 $prefix = '' unless @base_filenames;
7309 foreach my $from (@$d) {
7310 next unless defined($from);
7311 my $to = File::Spec->catfile($output_directory,
7312 $prefix . File::Basename::basename($from));
7313 File::Copy::copy($from, $to) unless -f $to;
7314 }
7315 }
7316 }
7317
7318 # save command line in output directory - useful for later debugging:
7319 my $f = File::Spec->catfile($output_directory, 'cmd_line');
7320 open(CMD, '>', $f) or die("unable to open $f: $!");
7321 print(CMD $lcovutil::profileData{config}{cmdLine} . "\n");
7322 close(CMD) or die("unable to close $f: $!\n");
7323
7324 my $exit_status = 0;
7325 # Do something
7326 my $now = Time::HiRes::gettimeofday();
7327 my $top;
7328 eval { $top = gen_html(); };
7329 if ($@) {
7330 $exit_status = 1;
7331 print(STDERR $@);
7332 }
7333
7334 my $then = Time::HiRes::gettimeofday();
7335 $lcovutil::profileData{overall} = $then - $now;
7336
7337 if (0 == $exit_status) {
7338 # warn about unused include/exclude directives
7339 lcovutil::warn_file_patterns();
7340 ReadCurrentSource::warn_sourcedir_patterns();
7341 }
7342
7343 # now check the coverage criteria (if any)
7344 if (0 == $exit_status &&
7345 ($CoverageCriteria::coverageCriteriaStatus ||
7346 @CoverageCriteria::coverageCriteriaScript)
7347 ) {
7348 CoverageCriteria::summarize();
7349 # fail for signal or status
7350 $exit_status = (($CoverageCriteria::coverageCriteriaStatus & 0xFF) |
7351 ($CoverageCriteria::coverageCriteriaStatus >> 8));
7352 }
7353
7354 if ($serialize) {
7355 #my $f = File::Spec->catfile($output_directory, 'coverage.dat');
7356 my $data;
7357 eval { $data = Storable::store($top, $serialize); };
7358 if ($@ || !defined($data)) {
7359 print("unable to serialize coverage data", $@ ? ": $@" : '');
7360 $exit_status = 1;
7361 }
7362 }
7363
7364 lcovutil::cleanup_callbacks();
7365 lcovutil::save_profile(File::Spec->catfile($output_directory, 'genhtml'),
7366 File::Spec->catfile($output_directory, 'profile.html'));
7367
7368 if (0 == $exit_status && $validateHTML) {
7369 ValidateHTML->new($output_directory, '.' . $html_ext);
7370 }
7371
7372 # exit with non-zero status if --keep-going and some errors detected
7373 $exit_status = 1
7374 if (0 == $exit_status && lcovutil::saw_error());
7375
7376 exit($exit_status);
7377
7378 #
7379 # print_usage(handle)
7380 #
7381 # Print usage information.
7382 #
7383
7384 sub print_usage(*)
7385 {
7386 local *HANDLE = $_[0];
7387
7388 print(HANDLE <<END_OF_USAGE);
7389 Usage: $tool_name [OPTIONS] TRACEFILE_PATTERN(S)
7390
7391 Create HTML output for coverage data found in TRACEFILE. Note that TRACEFILE
7392 may also be a list of filenames.
7393
7394 COMMON OPTIONS
7395 -h, --help Print this help, then exit
7396 --version Print version number, then exit
7397 -v, --verbose Increase verbosity level
7398 -q, --quiet Decrease verbosity level (e.g. to turn off
7399 progress messages)
7400 --debug Increase debug verbosity level
7401 --config-file FILENAME Specify configuration file location
7402 --rc SETTING=VALUE Override configuration file setting
7403 --ignore-errors ERRORS Continue after ERRORS (see man page for
7404 full list of errors and their meaning)
7405 --keep-going Do not stop if an error occurs
7406 --tempdir DIRNAME Write temporary and intermediate data here
7407 --preserve Keep intermediate files for debugging
7408
7409 OPERATION
7410 -o, --output-directory OUTDIR Write HTML output to OUTDIR
7411 -d, --description-file DESCFILE Read test case descriptions from DESCFILE
7412 -k, --keep-descriptions Do not remove unused test descriptions
7413 -b, --baseline-file BASEFILE Use BASEFILE as baseline file glob match pattern
7414 --annotate-script SCRIPT Use SCRIPT to get revision control data
7415 --criteria-script SCRIPT Use SCRIPT to check for acceptance criteria
7416 --version-script SCRIPT Use SCRIPT to check for compatibility of
7417 source code and coverage data
7418 --resolve-script SCRIPT Call script to find source file frpm path
7419 --(no-)checksum Compare (ignore) source line checksum
7420 --diff-file UDIFF Unified diff file UDIFF describes source
7421 code changes between baseline and current
7422 --new-file-as-baseline Classify new files as baseline data
7423 --elide-path-mismatch Identify matching files if their basename
7424 matches even though dirname does not
7425 --date-bins day[,day,...] Use DAY number of days as upper age limit
7426 for the corresponding date bin
7427 -p, --prefix PREFIX Remove PREFIX from all directory names
7428 --no-prefix Do not remove prefix from directory names
7429 --(no-)function-coverage Enable (disable) function coverage display
7430 --(no-)branch-coverage Enable (disable) branch coverage display
7431 --filter FILTERS Apply FILTERS to input data (see man page
7432 for full list of filters and their effects)
7433 --include PATTERN Only show output for files matching PATTERN
7434 --exclude PATTERN Skip output for files matching PATTERN
7435 --source-directory DIR Search DIR for source files
7436 --substitute REGEXP Change source file names according to REGEXP
7437 --erase-functions REGEXP Exclude data for functions matching REGEXP
7438 --omit-lines REGEXP Ignore data in lines matching REGEXP
7439 --forget-test-names Merge data for all tests names
7440 --synthesize-missing Generate fake source for missing files
7441 -j, --parallel [N] Use parallel processing with at most N jobs
7442 --memory MB Use at most MB memory in parallel processing
7443 --profile [FILENAME] Write performance statistics to FILENAME
7444 (default: OUTDIR/genhtml.json)
7445 --save Write copy of input files to OUTDIR
7446
7447 HTML OUTPUT
7448 -f, --frames Use HTML frames for source code view
7449 -t, --title TITLE Use TITLE as label for current data
7450 --baseline-title TITLE Use TITLE as label for baseline data
7451 --current-date DATE Use DATE as date label for current data
7452 --baseline-date DATE Use DATE as date label for baseline data
7453 -c, --css-file CSSFILE Use external style sheet file CSSFILE
7454 --header-title BANNER Banner at top of each HTML page
7455 --footer FOOTER Footer at bottom of each HTML page
7456 --no-sourceview Do not create source code view
7457 --num-spaces NUM Replace tabs with NUM spaces in source view
7458 --legend Include color legend in HTML output
7459 --html-prolog FILE Use FILE as HTML prolog for generated pages
7460 --html-epilog FILE Use FILE as HTML epilog for generated pages
7461 --html-extension EXT Use EXT as filename extension for pages
7462 --html-gzip Use gzip to compress HTML
7463 --(no-)sort Enable (disable) sorted coverage views
7464 --demangle-cpp [OPT] Demangle C++ function names
7465 --precision NUM Set precision of coverage rate
7466 --missed Show miss counts as negative numbers
7467 --dark-mode Use the dark-mode CSS
7468 --simplified-colors Use reduced color scheme for categories
7469 --hierarchical Generate multilevel HTML report,
7470 matching source code directory structure
7471 --flat Generate flat HTML report, with all files
7472 listed on top-level page
7473 -s, --show-details Generate detailed directory view
7474 --show-owners [all] Show owner summary table. If optional
7475 value provided, show all the owners,
7476 regardless of whether they have uncovered
7477 code or not
7478 --show-noncode Show author in summary table even if none
7479 of their lines are recognized as code
7480 --show-zero-columns Keep summary columns for categories with
7481 no entries (default: remove)
7482 --show-navigation Include 'goto first hit/not hit' and
7483 'goto next hit/not hit' hyperlinks in
7484 non-differential source code detail page
7485 --show-proportion Show function coverage rates
7486 --suppress-aliases Merge data for function aliases
7487
7488 For more information see the genhtml man page.
7489 END_OF_USAGE
7490
7491 }
7492
7493 #
7494 # print_overall_rate(trace, ln_do, fn_do, br_do, mcdc_do, summary)
7495 #
7496 # Print overall coverage rates for the specified coverage types.
7497 #
7498
7499 sub print_overall_rate($$$$$$)
7500 {
7501 my ($currentTrace, $ln_do, $fn_do, $br_do, $mcdc_do, $summary) = @_;
7502
7503 # use verbosity level -1: so print unless user says "-q -q"...really quiet
7504 info(-1, "Overall coverage rate:\n");
7505 my @types;
7506 push(@types, SummaryInfo::LINE_DATA) if $ln_do;
7507 push(@types, SummaryInfo::FUNCTION_DATA) if $fn_do;
7508 push(@types, SummaryInfo::BRANCH_DATA) if $br_do;
7509 push(@types, SummaryInfo::MCDC_DATA) if $mcdc_do;
7510
7511 # use source file count from current - we don;t care about files
7512 # that were deleted and are in baseline
7513 info(-1, " source files: %d\n", scalar($currentTrace->files()));
7514 my $width = length("source files");
7515 my $indent = ' ';
7516 for my $type (@types) {
7517 my $name = SummaryInfo::type2str($type);
7518 my $plural = "ch" eq substr($name, -2, 2) ? "es" : "s";
7519 my $label = "$name$plural";
7520 my $fill = '.' x ($width - length($label));
7521 info(-1,
7522 " $name$plural$fill: %s\n",
7523 get_overall_line($summary->get("found", $type),
7524 $summary->get("hit", $type),
7525 $name));
7526 if ($main::show_tla) {
7527 for my $tla (@SummaryInfo::tlaPriorityOrder) {
7528 my $v = $summary->get($tla, $type);
7529 next if $v == 0;
7530 my $label =
7531 $main::use_legacyLabels ?
7532 $SummaryInfo::tlaToLegacySrcLabel{$tla} :
7533 $tla;
7534 my $f = '.' x ($width - (length($indent) + length($label)));
7535 info(-1, " $indent$label$f: $v\n");
7536 }
7537 }
7538 }
7539 summarize_cov_filters();
7540 summarize_messages();
7541 }
7542
7543 #
7544 # gen_html()
7545 #
7546 # Generate a set of HTML pages from contents of .info file INFO_FILENAME.
7547 # Files will be written to the current directory. If provided, test case
7548 # descriptions will be read from .tests file TEST_FILENAME and included
7549 # in output.
7550 #
7551 # Die on error.
7552 #
7553
7554 sub gen_html()
7555 {
7556 # "Read
7557
7558 # Read in all specified .info files
7559 my $now = Time::HiRes::gettimeofday();
7560 my $readSourceFile = ReadCurrentSource->new();
7561 ($current_data) = AggregateTraces::merge($readSourceFile, @info_filenames);
7562 my $then = Time::HiRes::gettimeofday();
7563 $lcovutil::profileData{parse_current} = $then - $now;
7564
7565 info("Found %d entries.\n", scalar($current_data->files()));
7566
7567 # Read and apply diff data if specified - need this before we
7568 # try to read and process the baseline..
7569 if ($diff_filename) {
7570 $now = Time::HiRes::gettimeofday();
7571 info("Reading diff file $diff_filename\n");
7572 $diff_data->load($diff_filename, $current_data,
7573 \@lcovutil::build_directory);
7574 $then = Time::HiRes::gettimeofday();
7575 $lcovutil::profileData{parse_diff} = $then - $now;
7576 }
7577
7578 # Read and apply baseline data if specified
7579 if (@base_filenames) {
7580 $now = Time::HiRes::gettimeofday();
7581 my $readBaseSource = ReadBaselineSource->new($diff_data);
7582 $then = Time::HiRes::gettimeofday();
7583 $lcovutil::profileData{parse_source} = $then - $now;
7584 # Read baseline file
7585
7586 $now = Time::HiRes::gettimeofday();
7587 ($base_data) = AggregateTraces::merge($readBaseSource, @base_filenames);
7588 info("Found %d baseline entries.\n", scalar($base_data->files()));
7589 $then = Time::HiRes::gettimeofday();
7590 $lcovutil::profileData{parse_baseline} = $then - $now;
7591 } elsif (defined($diff_filename)) {
7592 # no data..
7593 $base_data = TraceFile->new();
7594 }
7595
7596 if ($diff_filename) {
7597 # check for files which appear in the udiff but which dont appear
7598 # in either the current or baseline trace data. Those may be
7599 # mapping issues - different pathname in .info file vs udiff
7600 if (!$diff_data->check_path_consistency($base_data, $current_data)) {
7601 lcovutil::ignorable_error($lcovutil::ERROR_PATH,
7602 "possible path inconsistency in baseline/current/udiff data");
7603 }
7604 }
7605
7606 if ($no_prefix) {
7607 # User requested that we leave filenames alone
7608 info("User asked not to remove filename prefix\n");
7609 } elsif (!@dir_prefix) {
7610 # Get prefix common to most directories in list
7611 my $prefix = get_prefix(1, $current_data->files());
7612
7613 if ($prefix) {
7614 info("Found common filename prefix \"$prefix\"\n");
7615 $dir_prefix[0] = $prefix;
7616 } else {
7617 info("No common filename prefix found!\n");
7618 $no_prefix = 1;
7619 }
7620 } else {
7621 my $msg = "Using user-specified filename prefix ";
7622 my $dirs = $current_data->directories();
7623 my $i = 0;
7624 # somewhat of a hack: the layout code doesn't react well when
7625 # the 'prefix' directory contains source files (as opposed to
7626 # containing a directory which contains source files).
7627 # Rather than trying to handle that special case, just munge the
7628 # prefix to be something we like better.
7629 while ($i <= $#dir_prefix) {
7630 my $p = $dir_prefix[$i];
7631 # remove redundant /'s
7632 $p =~ s/$lcovutil::dirseparator+$//;
7633 $p = substr($p, 0, -1)
7634 if $lcovutil::dirseparator eq substr($p, -1);
7635 while (exists($dirs->{$p}) && $p) {
7636 $p = File::Basename::dirname($p);
7637 }
7638 unless ($p) {
7639 lcovutil::info("skipping prefix $dir_prefix[$i]\n");
7640 splice(@dir_prefix, $i, 1);
7641 next;
7642 }
7643 lcovutil::info(
7644 "using prefix '$p' (rather than '$dir_prefix[$i]')\n")
7645 if ($p ne $dir_prefix[$i]);
7646 $dir_prefix[$i] = $p;
7647 $msg .= ", " unless 0 == $i;
7648 $msg .= "\"" . $p . "\"";
7649 ++$i;
7650 }
7651 info($msg . "\n");
7652 }
7653
7654 # Read in test description file if specified
7655 if ($desc_filename) {
7656 info("Reading test description file $desc_filename\n");
7657 %test_description = %{read_testfile($desc_filename)};
7658
7659 # Remove test descriptions which are not referenced
7660 # from %current_data if user didn't tell us otherwise
7661 if (!$keep_descriptions) {
7662 remove_unused_descriptions();
7663 }
7664 }
7665
7666 # add quotes to args - so string concat works if there are embedded spaces, etc
7667 foreach my $s (\@SourceFile::annotateScript,
7668 \@CoverageCriteria::coverageCriteriaScript,
7669 \@lcovutil::extractVersionScript) {
7670 my $count = scalar(@$s);
7671 next unless $count > 1;
7672 foreach my $e (@$s) {
7673 $e = "'$e'" if ($e =~ /\s/);
7674 }
7675 }
7676
7677 unless ($no_html) {
7678 info(1, "Writing .css and .png files.\n");
7679 write_css_file();
7680 write_png_files();
7681 }
7682 if ($html_gzip) {
7683 info(1, "Writing .htaccess file.\n");
7684 write_htaccess_file();
7685 }
7686
7687 info("Generating output.\n");
7688
7689 my $genhtml = GenHtml->new($current_data);
7690
7691 if (@SourceFile::annotateScript &&
7692 0 == $SourceFile::annotatedFiles) {
7693 lcovutil::ignorable_error($lcovutil::ERROR_ANNOTATE_SCRIPT,
7694 "\"--annotate-script '" .
7695 join(' ', @SourceFile::annotateScript) .
7696 "'\" did not find any revision-controlled files in your sandbox"
7697 );
7698 }
7699
7700 # Check if there are any test case descriptions to write out
7701 if (%test_description) {
7702 info("Writing test case description file.\n");
7703 write_description_file(\%test_description, $genhtml->top());
7704 }
7705
7706 print_overall_rate($current_data, 1, $lcovutil::func_coverage,
7707 $lcovutil::br_coverage, $lcovutil::mcdc_coverage,
7708 $genhtml->top());
7709
7710 return $genhtml->top();
7711 }
7712
7713 #
7714 # html_create(handle, filename)
7715 #
7716
7717 sub html_create($$)
7718 {
7719 my $handle = $_[0];
7720 my $filename = File::Spec->catfile($output_directory, $_[1]);
7721 $filename = lc($filename) if $lcovutil::case_insensitive;
7722
7723 if ($html_gzip) {
7724 open($handle, "|-", "gzip -c > $filename'") or
7725 die("cannot open $filename for writing (gzip): $!\n");
7726 } else {
7727 open($handle, ">", $filename) or
7728 die("cannot open $filename for writing: $!\n");
7729 }
7730 }
7731
7732 # $ctrls = [$view_type, $sort_type, $bin_prefix]
7733 # $perTestcaseResult = [\%line, \%func, \%branch]
7734 #sub write_dir_page($$$$$$$;$)
7735 sub write_dir_page
7736 {
7737 my ($callback_type, $ctrls, $page_suffix,
7738 $title, $rel_dir, $base_dir,
7739 $trunc_dir, $summary, $perTestcaseResult) = @_;
7740
7741 my $bin_prefix = $ctrls->[3];
7742 # Generate directory overview page including details
7743 html_create(*HTML_HANDLE,
7744 File::Spec->catfile(
7745 $rel_dir, "index$bin_prefix$page_suffix.$html_ext"
7746 ));
7747 if (!defined($trunc_dir)) {
7748 $trunc_dir = "";
7749 }
7750 $title .= " - " if ($trunc_dir ne "");
7751 write_html_prolog(*HTML_HANDLE, $base_dir, "LCOV - $title$trunc_dir");
7752 my $activeTlaColsForType =
7753 write_header(*HTML_HANDLE, $callback_type, $ctrls, $trunc_dir,
7754 $rel_dir, $summary, undef, undef);
7755 if (0 != $summary->sources()) {
7756 write_file_table(*HTML_HANDLE, $callback_type, $base_dir,
7757 $perTestcaseResult,
7758 $summary, $ctrls, $activeTlaColsForType);
7759 } else {
7760 my $msg =
7761 "Coverage data table is empty - no coverpoints exist in the selected subset.";
7762 write_html(*HTML_HANDLE, <<END_OF_HTML);
7763 <br>
7764 <table width="100%" border=0 cellspacing=0 cellpadding=0>
7765 <tr><td class="subTableHeader">$msg</td></tr>
7766 </table>
7767 <br>
7768 END_OF_HTML
7769 }
7770 write_html_epilog(*HTML_HANDLE, $base_dir);
7771 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
7772 }
7773
7774 sub write_summary_pages($$$$$$$$)
7775 {
7776 my ($name, $summaryType, $summary, $show_details,
7777 $rel_dir, $base_dir, $trunc_dir, $testhashes) = @_;
7778
7779 my $callback_type = $summaryType == 1 ? 'directory' : 'top';
7780 foreach my $c ($summary->sources()) {
7781 my $child = $summary->get_source($c);
7782 # filter this one out if no data
7783 if ($child->is_empty()) {
7784 $summary->remove_source($c);
7785 }
7786 }
7787 return if $main::no_html;
7788 if (0 == $summary->sources() && $summaryType == 1) {
7789 # remove empty directory
7790 push(@cleanDirectoryList, $rel_dir);
7791 return;
7792 }
7793
7794 if ($main::show_tla) {
7795 info('Processing '
7796 .
7797 ($summaryType == 1 ? ('directory: ' . $summary->name()) :
7798 'top level:') .
7799 "\n");
7800 my $sep = $summaryType == 1 ? $summary->name() : '';
7801 foreach my $t ('line',
7802 $lcovutil::br_coverage ? 'branch' : undef,
7803 $lcovutil::mcdc_coverage ? 'mcdc' : undef,
7804 $lcovutil::func_coverage ? 'function' : undef
7805 ) {
7806 my $s = $summary->tlaSummary($t) if defined($t);
7807 next unless $s;
7808 info(" $t: $s\n");
7809 }
7810 }
7811
7812 my $start = Time::HiRes::gettimeofday();
7813 my @summaryBins;
7814 if (defined($main::show_ownerBins)) {
7815 if (0 != scalar($summary->owners(
7816 $main::show_ownerBins, SummaryInfo::LINE_DATA
7817 ))
7818 ||
7819 ( $lcovutil::br_coverage &&
7820 0 != scalar($summary->owners(
7821 $main::show_ownerBins, SummaryInfo::BRANCH_DATA
7822 )))
7823 ||
7824 ( $lcovutil::mcdc_coverage &&
7825 0 != scalar($summary->owners(
7826 $main::show_ownerBins, SummaryInfo::MCDC_DATA
7827 )))
7828 ) {
7829 # at least one owner will appear - so table will be referenced
7830 push(@summaryBins, 'owner');
7831 } else {
7832 lcovutil::info(1,
7833 $summary->name() . " has no visible owners..eliding page\n");
7834 }
7835 }
7836 push(@summaryBins, 'date') if defined($main::show_dateBins);
7837
7838 my $singleSource = 1 == scalar($summary->sources());
7839 my @dirPageCalls;
7840 foreach my $sort_type (@main::fileview_sortlist) {
7841 my @ctrls = ($summaryType, # 1 == 'list files'
7842 "name", # primary key
7843 $sort_type, "", $singleSource);
7844 my $sort_str = $main::fileview_sortname[$sort_type];
7845 # 'fileview prefixes' is ('', '-date', '-owner)
7846 foreach my $bin_prefix (@main::fileview_prefixes) {
7847 # Generate directory overview page (without details)
7848 # no per-testcase data in this page...
7849 $ctrls[3] = $bin_prefix;
7850 # need copy because we are calling multiple child processes
7851 my @copy = @ctrls;
7852 push(@dirPageCalls,
7853 [\@copy, $sort_str, $test_title, $rel_dir,
7854 $base_dir, $trunc_dir, $summary
7855 ]);
7856
7857 if ($show_details) {
7858 # Generate directory overview page including details
7859 push(@dirPageCalls,
7860 [\@copy, "-detail" . $sort_str,
7861 $test_title, $rel_dir,
7862 $base_dir, $trunc_dir,
7863 $summary, $testhashes
7864 ]);
7865 }
7866 }
7867 $ctrls[3] = ""; # no bin...
7868 foreach my $primary_key (@summaryBins) {
7869 # we don't associate function owner - so we elide 'function' columns in the
7870 # 'owner detail' pages - and thus won't create a sort-by-function link.
7871 # Don't generate the unreferenced page
7872 next if $sort_type == $SORT_FUNC && $primary_key eq 'owner';
7873 # we elide the 'line' sort links for date/owner page if there
7874 # is only one file
7875 next
7876 if $sort_type == $SORT_LINE &&
7877 $primary_key ne 'name' &&
7878 scalar($summary->sources()) < 2;
7879 $ctrls[1] = $primary_key;
7880 my @copy = @ctrls;
7881 push(@dirPageCalls,
7882 [\@copy, '-bin_' . $primary_key . $sort_str,
7883 $test_title, $rel_dir, $base_dir, $trunc_dir, $summary
7884 ]);
7885 }
7886 last if $singleSource;
7887 }
7888
7889 foreach my $params (@dirPageCalls) {
7890 write_dir_page($callback_type, @$params);
7891 last # only write 'index.html' - not the sorted versions
7892 if ($summary->is_empty());
7893 }
7894 my $end = Time::HiRes::gettimeofday();
7895 $lcovutil::profileData{html}{$name} = $end - $start;
7896 }
7897
7898 sub write_function_page($$$$$$$$$$$$$$$)
7899 {
7900 # Generate function table for this file
7901 my ($fileCovInfo, $base_dir, $rel_dir, $trunc_dir,
7902 $base_name, $title, $sumcount, $funcdata,
7903 $testfncdata, $sumbrcount, $testbrdata, $mcdc,
7904 $testcase_mcdc, $sort_type, $summary) = @_;
7905 # $fileCovInfo is array [function hash, line hash, branch hash]
7906 my $filename;
7907 if ($sort_type == $main::SORT_FILE) {
7908 $filename = File::Spec->catfile($rel_dir, "$base_name.func.$html_ext");
7909 } elsif ($sort_type == $main::SORT_LINE) {
7910 # by declaration line number
7911 $filename =
7912 File::Spec->catfile($rel_dir, "$base_name.func-c.$html_ext");
7913 } elsif ($sort_type == $main::SORT_MISSING_LINE) {
7914 # by number of un-exercised lines
7915 $filename =
7916 File::Spec->catfile($rel_dir, "$base_name.func-l.$html_ext");
7917 } elsif ($sort_type == $main::SORT_MISSING_MCDC) {
7918 # by number of un-exercised MC/DC expressions
7919 return unless %{$fileCovInfo->[3]};
7920 $filename =
7921 File::Spec->catfile($rel_dir, "$base_name.func-m.$html_ext");
7922 } else {
7923 die("Unexpected sort $sort_type")
7924 unless ($sort_type == $main::SORT_MISSING_BRANCH);
7925 # don't emit page if there are no branches in the file
7926 return unless %{$fileCovInfo->[2]};
7927 # by declaration line number
7928 $filename =
7929 File::Spec->catfile($rel_dir, "$base_name.func-b.$html_ext");
7930 }
7931 html_create(*HTML_HANDLE, $filename);
7932 my $pagetitle = "LCOV - $title - " .
7933 File::Spec->catfile($trunc_dir, $base_name) . " - functions";
7934 write_html_prolog(*HTML_HANDLE, $base_dir, $pagetitle);
7935 write_header(*HTML_HANDLE,
7936 'file', # function table always written from 'file' level
7937 [4, 'name', $sort_type,],
7938 File::Spec->catfile($trunc_dir, $base_name),
7939 File::Spec->catfile($rel_dir, $base_name),
7940 $summary, undef, $funcdata->[0]);
7941 write_function_table(*HTML_HANDLE, $fileCovInfo,
7942 "$base_name.gcov.$html_ext", $sumcount,
7943 $funcdata, $testfncdata,
7944 $sumbrcount, $testbrdata,
7945 $mcdc, $testcase_mcdc,
7946 $base_name, $base_dir,
7947 $sort_type);
7948 write_html_epilog(*HTML_HANDLE, $base_dir, 1);
7949 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
7950 }
7951
7952 #
7953 # process_file(parent_dir_summary, trunc_dir, rel_dir, filename)
7954 #
7955
7956 sub process_file($$$$$)
7957 {
7958 my ($fileSummary, $parent_dir_summary, $trunc_dir, $rel_dir, $filename) =
7959 @_;
7960 my $trunc_name = apply_prefix($filename, @dir_prefix);
7961 info("Processing file $trunc_name"
7962 .
7963 (($main::diff_filename && $diff_data->containsFile($filename)) ?
7964 ' (source code changed)' :
7965 '') .
7966 "\n");
7967
7968 my $base_name = basename($filename);
7969 my $base_dir = get_relative_base_path($rel_dir);
7970 my @source;
7971 my $pagetitle;
7972 local *HTML_HANDLE;
7973
7974 my $fileData = $current_data->data($filename); # TraceInfo struct
7975 my ($testdata, $sumcount, $funcdata,
7976 $checkdata, $testfncdata, $testbrdata,
7977 $sumbrcount, $mcdc_summary, $testcase_mcdc) = $fileData->get_info();
7978
7979 my ($lines_found, $lines_hit, $br_found, $br_hit,
7980 $mcdc_found, $mcdc_hit, $fn_found, $fn_hit)
7981 = ($fileData->found(), $fileData->hit(),
7982 $fileData->branch_found(), $fileData->branch_hit(),
7983 $fileData->mcdc_found(), $fileData->mcdc_hit(),
7984 $fileData->function_found(), $fileData->function_hit());
7985
7986 $fileSummary->lines_found($lines_found);
7987 $fileSummary->lines_hit($lines_hit);
7988 $fileSummary->function_found($fn_found);
7989 $fileSummary->function_hit($fn_hit);
7990 $fileSummary->branch_found($br_found);
7991 $fileSummary->branch_hit($br_hit);
7992 $fileSummary->mcdc_found($mcdc_found);
7993 $fileSummary->mcdc_hit($mcdc_hit);
7994
7995 # handle case that file was moved between baseline and current
7996 my $baseline_filename = $diff_data->baseline_file_name($filename);
7997 # when looking up the baseline file, handle the case that the
7998 # pathname does not match exactly - see comment in TraceFile::data
7999 my $fileBase = $base_data->data($baseline_filename, 1)
8000 if defined($base_data);
8001 my $fileCurrent = $current_data->data($filename);
8002 # build coverage differential categories
8003 my $now = Time::HiRes::gettimeofday();
8004 my $fileCovInfo =
8005 FileCoverageInfo->new($filename,
8006 $fileBase,
8007 $fileCurrent,
8008 $diff_data,
8009 defined($main::verboseScopeRegexp) &&
8010 $filename =~ m/$main::verboseScopeRegexp/);
8011 my $then = Time::HiRes::gettimeofday();
8012 $lcovutil::profileData{categorize}{$filename} = $then - $now;
8013
8014 my $r = " lines=$lines_found hit=$lines_hit";
8015 $r .= " functions=$fn_found hit=$fn_hit"
8016 if $lcovutil::func_coverage && $fn_found != 0;
8017 $r .= " branches=$br_found hit=$br_hit"
8018 if $lcovutil::br_coverage && $br_found != 0;
8019 $r .= " MC/DC=$mcdc_found hit=$mcdc_hit"
8020 if $lcovutil::mcdc_coverage && $mcdc_found != 0;
8021 info($r . "\n");
8022
8023 my $fileHasNoBaselineInfo = $main::treatNewFileAsBaseline &&
8024 (!defined($fileBase) ||
8025 ($fileBase->is_empty() && @main::base_filenames));
8026 # if this file is older than the baseline and there is no associated
8027 # baseline data - then it appears to have been added to the build
8028 # recently
8029 # We want to treat the code as "CBC" or "UBC" (not "GIC" and "UIC")
8030 # because we only just turned section "on" - and we don't want the
8031 # coverage ratchet to fail the build if UIC is nonzero
8032
8033 # NOTE: SourceFile constructor modifies some input data:
8034 # - $fileSummary struct is also modified: update total counts in
8035 # each bucket, counts in each date range
8036 # - $fileCovInfo: change GIC->CBC, UIC->UBC if $fineNotInBaseline and
8037 # source code is older than baseline file
8038 my $srcfile = SourceFile->new($filename, $fileSummary, $fileCovInfo,
8039 $fileHasNoBaselineInfo);
8040 my $endSrc = Time::HiRes::gettimeofday();
8041 $lcovutil::profileData{source}{$filename} = $endSrc - $then;
8042
8043 if (@main::base_filenames) {
8044 # summarize the bin data if we had baseline data for comparison
8045 foreach my $t (['line', $lines_found],
8046 ['branch', $lcovutil::br_coverage ? $br_found : 0],
8047 ['mcdc', $lcovutil::mcdc_coverage ? $mcdc_found : 0],
8048 ['function', $lcovutil::func_coverage ? $fn_found : 0]
8049 ) {
8050 next if 0 == $t->[1];
8051 info(' ' .
8052 $t->[0] . ': ' . $fileSummary->tlaSummary($t->[0]) . "\n");
8053 }
8054 }
8055
8056 if ($srcfile->is_empty()) {
8057 return;
8058 }
8059 # somewhat of a hack: we are ultimately going to merge $fileSummary
8060 # (the data for this particular file) into $parent_dir (the data
8061 # for the parent directory) - but we need to do that in the caller
8062 # (because we are building $fileSummary in a child process that we are
8063 # going to pass back. But we also use the parent and its name
8064 # in HTML generation...
8065 # we clear this setting before we return the generated summary
8066 $fileSummary->setParent($parent_dir_summary);
8067
8068 my $from = Time::HiRes::gettimeofday();
8069 # Return after this point in case user asked us not to generate
8070 # source code view
8071 if (!$no_sourceview) {
8072 # Generate source code view for this file
8073 my $differentialFunctionMap;
8074 if ($lcovutil::func_coverage) {
8075 $differentialFunctionMap = $fileCovInfo->functionMap();
8076 if ($SummaryInfo::selectCallback) {
8077 # prune hash to remove functions which are outside the
8078 # selected region
8079 my $lineCovMap = $fileCovInfo->lineMap();
8080 my %tempMap;
8081 while (my ($f, $fn) = each(%$differentialFunctionMap)) {
8082 my $line = $fn->line();
8083 $tempMap{$f} = $fn if exists($lineCovMap->{$line});
8084 }
8085 $differentialFunctionMap = \%tempMap;
8086 }
8087 }
8088 html_create(*HTML_HANDLE,
8089 File::Spec->catfile($rel_dir, "$base_name.gcov.$html_ext"));
8090 $pagetitle = "LCOV - $test_title - " .
8091 File::Spec->catfile($trunc_dir, $base_name);
8092 write_html_prolog(*HTML_HANDLE, $base_dir, $pagetitle);
8093 write_header(*HTML_HANDLE,
8094 'file',
8095 [2, 'name', 0],
8096 File::Spec->catfile($trunc_dir, $base_name),
8097 File::Spec->catfile($rel_dir, $base_name),
8098 $fileSummary,
8099 $srcfile,
8100 $differentialFunctionMap);
8101
8102 @source = write_source(*HTML_HANDLE, $srcfile, $sumcount,
8103 $checkdata, $fileCovInfo, $funcdata,
8104 $sumbrcount, $mcdc_summary);
8105
8106 write_html_epilog(*HTML_HANDLE, $base_dir, 1);
8107 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
8108
8109 if ($lcovutil::func_coverage) {
8110 # Create function tables
8111 my $lineCovMap = $fileCovInfo->lineMap();
8112 # simply map between function leader name and differential data
8113 # compute number of hit/missed coverpoints in each function
8114 my %lineCov;
8115 my %branchCov;
8116 my %mcdcCov;
8117 if ($main::show_functionProportions) {
8118 while (my ($name, $funcEntry) = each(%$differentialFunctionMap))
8119 {
8120 my $lineData = $funcEntry->findMyLines($sumcount);
8121 if (defined($lineData)) {
8122 my $found = 0;
8123 my $hit = 0;
8124 foreach my $d (@$lineData) {
8125 ++$found;
8126 ++$hit if (0 != $d->[1]);
8127 }
8128 $lineCov{$name} = [$found, $hit];
8129 }
8130 if ($lcovutil::br_coverage) {
8131 my $branchData =
8132 $funcEntry->findMyBranches($sumbrcount);
8133 if (defined($branchData) &&
8134 0 != scalar(@$branchData)) {
8135 # there are branches here..
8136 my $found = 0;
8137 my $hit = 0;
8138 foreach my $branch (@$branchData) {
8139 my ($f, $h) = $branch->totals();
8140 $found += $f;
8141 $hit += $h;
8142 }
8143 $branchCov{$name} = [$found, $hit];
8144 }
8145 }
8146 if ($lcovutil::mcdc_coverage) {
8147 my $mcdcData = $funcEntry->findMyMcdc($mcdc_summary);
8148 if (defined($mcdcData) &&
8149 0 != scalar(@$mcdcData)) {
8150 # there are MC/DC expressions here..
8151 my $found = 0;
8152 my $hit = 0;
8153 foreach my $mcdc (@$mcdcData) {
8154 my ($f, $h) = $mcdc->totals();
8155 $found += $f;
8156 $hit += $h;
8157 }
8158 $mcdcCov{$name} = [$found, $hit];
8159 }
8160 }
8161 }
8162 }
8163 if (%$differentialFunctionMap) {
8164 foreach my $sort_type (@funcview_sortlist) {
8165 write_function_page([$differentialFunctionMap,
8166 \%lineCov, \%branchCov, \%mcdcCov,
8167 ],
8168 $base_dir,
8169 $rel_dir,
8170 $trunc_dir,
8171 $base_name,
8172 $test_title,
8173 $sumcount,
8174 $funcdata,
8175 $testfncdata,
8176 $sumbrcount,
8177 $testbrdata,
8178 $mcdc_summary,
8179 $testcase_mcdc,
8180 $sort_type,
8181 $fileSummary);
8182 }
8183 }
8184 }
8185
8186 # Additional files are needed in case of frame output
8187 if ($frames) {
8188 # Create overview png file
8189 my $simplified = defined($main::show_simplifiedColors) &&
8190 $main::show_simplifiedColors;
8191 my $png = File::Spec->catfile($rel_dir, "$base_name.gcov.png");
8192 $png = lc($png) if $lcovutil::case_insensitive;
8193 gen_png(File::Spec->catfile($output_directory, $png),
8194 $main::show_tla && !$simplified,
8195 $main::dark_mode,
8196 $overview_width,
8197 $tab_size,
8198 @source);
8199
8200 # Create frameset page
8201 html_create(*HTML_HANDLE,
8202 File::Spec->catfile(
8203 $rel_dir, "$base_name.gcov.frameset.$html_ext"
8204 ));
8205 write_frameset(*HTML_HANDLE, $base_dir, $base_name, $pagetitle);
8206 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
8207
8208 # Write overview frame
8209 html_create(*HTML_HANDLE,
8210 File::Spec->catfile(
8211 $rel_dir, "$base_name.gcov.overview.$html_ext"
8212 ));
8213 write_overview(*HTML_HANDLE, $base_dir, $base_name,
8214 $pagetitle, scalar(@source));
8215 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
8216 }
8217 }
8218 my $to = Time::HiRes::gettimeofday();
8219 $lcovutil::profileData{html}{$filename} = $to - $from;
8220 return ($testdata, $testfncdata, $testbrdata, $testcase_mcdc);
8221 }
8222
8223 sub compute_title($$)
8224 {
8225 my ($patterns, $info_files) = @_;
8226
8227 my $title;
8228 if (1 == scalar(@$info_files)) {
8229 # just one coverage DB file
8230 $title = basename($info_files->[0]);
8231 } elsif (1 == scalar(@$patterns)) {
8232 # just one pattern...
8233 $title = $patterns->[0];
8234 $title = substr($title, length($main::cwd) + 1)
8235 if (File::Spec->file_name_is_absolute($title) &&
8236 length($main::cwd) < length($title) &&
8237 $main::cwd eq substr($title, 0, length($main::cwd)));
8238 } else {
8239 $title = scalar(@$info_files) . ' coverage DB files';
8240 }
8241 return $title;
8242 }
8243
8244 #
8245 # get_prefix(min_dir, filename_list)
8246 #
8247 # Search FILENAME_LIST for a directory prefix which is common to as many
8248 # list entries as possible, so that removing this prefix will minimize the
8249 # sum of the lengths of all resulting shortened filenames while observing
8250 # that no filename has less than MIN_DIR parent directories.
8251 #
8252
8253 sub get_prefix($@)
8254 {
8255 my ($min_dir, @filename_list) = @_;
8256 my %prefix; # mapping: prefix -> sum of lengths
8257 my $current; # Temporary iteration variable
8258
8259 # Find list of prefixes
8260 my @munged;
8261 foreach (@filename_list) {
8262 # Need explicit assignment to get a copy of $_ so that
8263 # shortening the contained prefix does not affect the list
8264 my $current = ReadCurrentSource::resolve_path($_);
8265 my ($vol, $parentDir, $file) = File::Spec->splitpath($current);
8266 if (!File::Spec->file_name_is_absolute($current)) {
8267 if ($parentDir) {
8268 $parentDir = File::Spec->catfile($main::cwd, $parentDir);
8269 } else {
8270 $parentDir = $main::cwd;
8271 }
8272 $current = File::Spec->catfile($parentDir, $file);
8273 }
8274 push(@munged, $current);
8275 while ($current = shorten_prefix($current)) {
8276 # Skip rest if the remaining prefix has already been
8277 # added to hash
8278 if (exists($prefix{$current})) { last; }
8279
8280 # Initialize with 0
8281 $prefix{$current} = "0";
8282 }
8283
8284 }
8285
8286 # Remove all prefixes that would cause filenames to have less than
8287 # the minimum number of parent directories
8288 foreach my $filename (@munged) {
8289 my $dir = dirname($filename);
8290
8291 for (my $i = 0; $i < $min_dir; $i++) {
8292 delete($prefix{$dir});
8293 $dir = shorten_prefix($dir);
8294 }
8295 }
8296
8297 # Check if any prefix remains
8298 return undef if (!%prefix);
8299
8300 # Calculate sum of lengths for all prefixes
8301 foreach $current (keys(%prefix)) {
8302 foreach (@munged) {
8303 # Add original length
8304 $prefix{$current} += length($_);
8305
8306 # Check whether prefix matches
8307 if (substr($_, 0, length($current)) eq $current) {
8308 # Subtract prefix length for this filename
8309 $prefix{$current} -= length($current);
8310 }
8311 }
8312 }
8313
8314 # Find and return prefix with minimal sum
8315 $current = (keys(%prefix))[0];
8316
8317 foreach (keys(%prefix)) {
8318 if ($prefix{$_} < $prefix{$current}) {
8319 $current = $_;
8320 }
8321 }
8322 return ($current);
8323 }
8324
8325 #
8326 # shorten_prefix(prefix)
8327 #
8328 # Return PREFIX shortened by last directory component.
8329 #
8330
8331 sub shorten_prefix($)
8332 {
8333 my ($vol, $dir, $name) = File::Spec->splitpath($_[0]);
8334
8335 return File::Spec->catdir($vol, $dir);
8336 }
8337
8338 #
8339 # get_relative_base_path(subdirectory)
8340 #
8341 # Return a relative path string which references the base path when applied
8342 # in SUBDIRECTORY.
8343 #
8344 # Example: get_relative_base_path("fs/mm") -> "../../"
8345 #
8346
8347 sub get_relative_base_path($)
8348 {
8349 # Make an empty directory path a special case
8350 if (!$_[0]) { return (""); }
8351
8352 # Count number of /s in path
8353 my $index = ($_[0] =~ s/$lcovutil::dirseparator/$lcovutil::dirseparator/g);
8354
8355 # Add a ../ to $result for each / in the directory path + 1
8356 my $result = "";
8357 for (; $index >= 0; $index--) {
8358 $result .= "..$lcovutil::dirseparator";
8359 }
8360 return $result;
8361 }
8362
8363 #
8364 # read_testfile(test_filename)
8365 #
8366 # Read in file TEST_FILENAME which contains test descriptions in the format:
8367 #
8368 # TN:<whitespace><test name>
8369 # TD:<whitespace><test description>
8370 #
8371 # for each test case. Return a reference to a hash containing a mapping
8372 #
8373 # test name -> test description.
8374 #
8375 # Die on error.
8376 #
8377
8378 sub read_testfile($)
8379 {
8380 my $file = shift;
8381 my %result;
8382 my $test_name;
8383 my $changed_testname;
8384 local *TEST_HANDLE;
8385
8386 open(TEST_HANDLE, "<", $file) or
8387 die("cannot open $file]: $!\n");
8388
8389 while (<TEST_HANDLE>) {
8390 chomp($_);
8391 s/\r//g;
8392 # Match lines beginning with TN:<whitespace(s)>
8393 next if /^#/; # skip comment
8394 if (/^TN:\s*(.*?)\s*$/) {
8395 # Store name for later use
8396 $test_name = $1;
8397 if ($test_name =~ s/\W/_/g) {
8398 $changed_testname = 1;
8399 }
8400 }
8401
8402 # Match lines beginning with TD:<whitespace(s)>
8403 if (/^TD:\s*(.*?)\s*$/) {
8404 if (!defined($test_name)) {
8405 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
8406 "\"$file\":$.: Found test description without prior test name."
8407 );
8408 next;
8409 }
8410 # Check for empty line
8411 if ($1) {
8412 # Add description to hash
8413 $result{$test_name} .= " $1";
8414 } else {
8415 # Add empty line
8416 $result{$test_name} .= "\n\n";
8417 }
8418 }
8419 }
8420
8421 close(TEST_HANDLE) or die("unable to close HTML file: $!\n");
8422 if (!%result) {
8423 lcovutil::ignorable_error($lcovutil::ERROR_EMPTY,
8424 "no test descriptions found in '$file'.");
8425 }
8426
8427 if ($changed_testname) {
8428 lcovutil::ignorable_error($lcovutil::ERROR_FORMAT,
8429 "invalid characters removed from testname in descriptions file '$file'."
8430 );
8431 }
8432
8433 return \%result;
8434 }
8435
8436 #
8437 # escape_html(STRING)
8438 #
8439 # Return a copy of STRING in which all occurrences of HTML special characters
8440 # are escaped.
8441 #
8442
8443 sub escape_html($)
8444 {
8445 my $string = $_[0];
8446
8447 if (!$string) { return ""; }
8448
8449 $string =~ s/&/&amp;/g; # & -> &amp;
8450 $string =~ s/</&lt;/g; # < -> &lt;
8451 $string =~ s/>/&gt;/g; # > -> &gt;
8452 $string =~ s/\"/&quot;/g; # " -> &quot;
8453
8454 while ($string =~ /^([^\t]*)(\t)/) {
8455 my $replacement = " " x ($tab_size - (length($1) % $tab_size));
8456 $string =~ s/^([^\t]*)(\t)/$1$replacement/;
8457 }
8458
8459 $string =~ s/\n/<br>/g; # \n -> <br>
8460
8461 return $string;
8462 }
8463
8464 #
8465 # get_date_string()
8466 #
8467 # Return the current date in the form: yyyy-mm-dd
8468 #
8469
8470 sub get_date_string($)
8471 {
8472 my $time = $_[0];
8473 my @timeresult;
8474
8475 if (!$time) {
8476 if (defined $ENV{'SOURCE_DATE_EPOCH'}) {
8477 @timeresult = gmtime($ENV{'SOURCE_DATE_EPOCH'});
8478 } else {
8479 @timeresult = localtime();
8480 }
8481 } else {
8482 @timeresult = localtime($time);
8483 }
8484 my ($year, $month, $day, $hour, $min, $sec) = @timeresult[5, 4, 3, 2, 1, 0];
8485
8486 return
8487 sprintf("%d-%02d-%02d %02d:%02d:%02d",
8488 $year + 1900,
8489 $month + 1, $day, $hour, $min, $sec);
8490 }
8491
8492 #
8493 # write_description_file(descriptions, overall_found, overall_hit,
8494 # total_fn_found, total_fn_hit, total_br_found,
8495 # total_br_hit)
8496 #
8497 # Write HTML file containing all test case descriptions. DESCRIPTIONS is a
8498 # reference to a hash containing a mapping
8499 #
8500 # test case name -> test case description
8501 #
8502 # Die on error.
8503 #
8504
8505 sub write_description_file($$)
8506 {
8507 my %description = %{$_[0]};
8508 my $summary = $_[1];
8509 my $test_name;
8510 local *HTML_HANDLE;
8511
8512 html_create(*HTML_HANDLE, "descriptions.$html_ext");
8513
8514 write_html_prolog(*HTML_HANDLE, "", "LCOV - test case descriptions");
8515 write_header(*HTML_HANDLE, 'top', [3, 'name', 0],
8516 "", "", $summary, undef, undef);
8517
8518 write_test_table_prolog(*HTML_HANDLE,
8519 "Test case descriptions - alphabetical list");
8520
8521 foreach $test_name (sort(keys(%description))) {
8522 my $desc = $description{$test_name};
8523
8524 $desc = escape_html($desc) if (!$rc_desc_html);
8525 write_test_table_entry(*HTML_HANDLE, $test_name, $desc);
8526 }
8527
8528 write_test_table_epilog(*HTML_HANDLE);
8529 write_html_epilog(*HTML_HANDLE, "");
8530
8531 close(*HTML_HANDLE) or die("unable to close HTML handle: $!\n");
8532 }
8533
8534 #
8535 # write_png_files()
8536 #
8537 # Create all necessary .png files for the HTML-output in the current
8538 # directory. .png-files are used as bar graphs.
8539 #
8540 # Die on error.
8541 #
8542
8543 sub write_png_files()
8544 {
8545 my %data;
8546 local *PNG_HANDLE;
8547
8548 $data{"ruby.png"} =
8549 $dark_mode ?
8550 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8551 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8552 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8553 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54,
8554 0x45, 0x80, 0x1b, 0x18, 0x00, 0x00, 0x00, 0x39, 0x4a, 0x74,
8555 0xf4, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08,
8556 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
8557 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
8558 0x44, 0xae, 0x42, 0x60, 0x82
8559 ] :
8560 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8561 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8562 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8563 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d,
8564 0x45, 0x07, 0xd2, 0x07, 0x11, 0x0f, 0x18, 0x10, 0x5d, 0x57,
8565 0x34, 0x6e, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73,
8566 0x00, 0x00, 0x0b, 0x12, 0x00, 0x00, 0x0b, 0x12, 0x01, 0xd2,
8567 0xdd, 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d,
8568 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00,
8569 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54, 0x45, 0xff, 0x35, 0x2f,
8570 0x00, 0x00, 0x00, 0xd0, 0x33, 0x9a, 0x9d, 0x00, 0x00, 0x00,
8571 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x60, 0x00,
8572 0x00, 0x00, 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00,
8573 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
8574 0x82
8575 ];
8576
8577 $data{"amber.png"} =
8578 $dark_mode ?
8579 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8580 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8581 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8582 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54,
8583 0x45, 0x99, 0x86, 0x30, 0x00, 0x00, 0x00, 0x51, 0x83, 0x43,
8584 0xd7, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08,
8585 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
8586 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
8587 0x44, 0xae, 0x42, 0x60, 0x82
8588 ] :
8589 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8590 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8591 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8592 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d,
8593 0x45, 0x07, 0xd2, 0x07, 0x11, 0x0f, 0x28, 0x04, 0x98, 0xcb,
8594 0xd6, 0xe0, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73,
8595 0x00, 0x00, 0x0b, 0x12, 0x00, 0x00, 0x0b, 0x12, 0x01, 0xd2,
8596 0xdd, 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d,
8597 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00,
8598 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54, 0x45, 0xff, 0xe0, 0x50,
8599 0x00, 0x00, 0x00, 0xa2, 0x7a, 0xda, 0x7e, 0x00, 0x00, 0x00,
8600 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x60, 0x00,
8601 0x00, 0x00, 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00,
8602 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
8603 0x82
8604 ];
8605 $data{"emerald.png"} =
8606 $dark_mode ?
8607 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8608 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8609 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8610 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54,
8611 0x45, 0x00, 0x66, 0x00, 0x0a, 0x0a, 0x0a, 0xa4, 0xb8, 0xbf,
8612 0x60, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08,
8613 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
8614 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
8615 0x44, 0xae, 0x42, 0x60, 0x82
8616 ] :
8617 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8618 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8619 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8620 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d,
8621 0x45, 0x07, 0xd2, 0x07, 0x11, 0x0f, 0x22, 0x2b, 0xc9, 0xf5,
8622 0x03, 0x33, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73,
8623 0x00, 0x00, 0x0b, 0x12, 0x00, 0x00, 0x0b, 0x12, 0x01, 0xd2,
8624 0xdd, 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d,
8625 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00,
8626 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54, 0x45, 0x1b, 0xea, 0x59,
8627 0x0a, 0x0a, 0x0a, 0x0f, 0xba, 0x50, 0x83, 0x00, 0x00, 0x00,
8628 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x60, 0x00,
8629 0x00, 0x00, 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00,
8630 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
8631 0x82
8632 ];
8633 $data{"snow.png"} =
8634 $dark_mode ?
8635 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8636 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8637 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8638 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54,
8639 0x45, 0xdd, 0xdd, 0xdd, 0x00, 0x00, 0x00, 0xae, 0x9c, 0x6c,
8640 0x92, 0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x08,
8641 0xd7, 0x63, 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0xe2,
8642 0x21, 0xbc, 0x33, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e,
8643 0x44, 0xae, 0x42, 0x60, 0x82
8644 ] :
8645 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8646 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01,
8647 0x00, 0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25,
8648 0xdb, 0x56, 0xca, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d,
8649 0x45, 0x07, 0xd2, 0x07, 0x11, 0x0f, 0x1e, 0x1d, 0x75, 0xbc,
8650 0xef, 0x55, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73,
8651 0x00, 0x00, 0x0b, 0x12, 0x00, 0x00, 0x0b, 0x12, 0x01, 0xd2,
8652 0xdd, 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d,
8653 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61, 0x05, 0x00,
8654 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54, 0x45, 0xff, 0xff, 0xff,
8655 0x00, 0x00, 0x00, 0x55, 0xc2, 0xd3, 0x7e, 0x00, 0x00, 0x00,
8656 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x60, 0x00,
8657 0x00, 0x00, 0x02, 0x00, 0x01, 0xe5, 0x27, 0xde, 0xfc, 0x00,
8658 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60,
8659 0x82
8660 ];
8661
8662 $data{"glass.png"} = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
8663 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
8664 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01,
8665 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56,
8666 0xca, 0x00, 0x00, 0x00, 0x04, 0x67, 0x41, 0x4d,
8667 0x41, 0x00, 0x00, 0xb1, 0x8f, 0x0b, 0xfc, 0x61,
8668 0x05, 0x00, 0x00, 0x00, 0x06, 0x50, 0x4c, 0x54,
8669 0x45, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x55,
8670 0xc2, 0xd3, 0x7e, 0x00, 0x00, 0x00, 0x01, 0x74,
8671 0x52, 0x4e, 0x53, 0x00, 0x40, 0xe6, 0xd8, 0x66,
8672 0x00, 0x00, 0x00, 0x01, 0x62, 0x4b, 0x47, 0x44,
8673 0x00, 0x88, 0x05, 0x1d, 0x48, 0x00, 0x00, 0x00,
8674 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b,
8675 0x12, 0x00, 0x00, 0x0b, 0x12, 0x01, 0xd2, 0xdd,
8676 0x7e, 0xfc, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49,
8677 0x4d, 0x45, 0x07, 0xd2, 0x07, 0x13, 0x0f, 0x08,
8678 0x19, 0xc4, 0x40, 0x56, 0x10, 0x00, 0x00, 0x00,
8679 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63,
8680 0x60, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x48,
8681 0xaf, 0xa4, 0x71, 0x00, 0x00, 0x00, 0x00, 0x49,
8682 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
8683 ];
8684
8685 if ($sort_tables) {
8686 $data{"updown.png"} =
8687 $dark_mode ?
8688 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8689 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0a,
8690 0x00, 0x00, 0x00, 0x0e, 0x08, 0x06, 0x00, 0x00, 0x00, 0x16,
8691 0xa3, 0x8d, 0xab, 0x00, 0x00, 0x00, 0x43, 0x49, 0x44, 0x41,
8692 0x54, 0x28, 0xcf, 0x63, 0x60, 0x40, 0x03, 0x77, 0xef, 0xde,
8693 0xfd, 0x7f, 0xf7, 0xee, 0xdd, 0xff, 0xe8, 0xe2, 0x8c, 0xe8,
8694 0x8a, 0x90, 0xf9, 0xca, 0xca, 0xca, 0x8c, 0x18, 0x0a, 0xb1,
8695 0x99, 0x82, 0xac, 0x98, 0x11, 0x9f, 0x22, 0x64, 0xc5, 0x8c,
8696 0x84, 0x14, 0xc1, 0x00, 0x13, 0xc3, 0x80, 0x01, 0xea, 0xbb,
8697 0x91, 0xf8, 0xe0, 0x21, 0x29, 0xc0, 0x89, 0x89, 0x42, 0x06,
8698 0x62, 0x13, 0x05, 0x00, 0xe1, 0xd3, 0x2d, 0x91, 0x93, 0x15,
8699 0xa4, 0xb2, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44,
8700 0xae, 0x42, 0x60, 0x82
8701 ] :
8702 [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00,
8703 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0a,
8704 0x00, 0x00, 0x00, 0x0e, 0x08, 0x06, 0x00, 0x00, 0x00, 0x16,
8705 0xa3, 0x8d, 0xab, 0x00, 0x00, 0x00, 0x3c, 0x49, 0x44, 0x41,
8706 0x54, 0x28, 0xcf, 0x63, 0x60, 0x40, 0x03, 0xff, 0xa1, 0x00,
8707 0x5d, 0x9c, 0x11, 0x5d, 0x11, 0x8a, 0x24, 0x23, 0x23, 0x23,
8708 0x86, 0x42, 0x6c, 0xa6, 0x20, 0x2b, 0x66, 0xc4, 0xa7, 0x08,
8709 0x59, 0x31, 0x23, 0x21, 0x45, 0x30, 0xc0, 0xc4, 0x30, 0x60,
8710 0x80, 0xfa, 0x6e, 0x24, 0x3e, 0x78, 0x48, 0x0a, 0x70, 0x62,
8711 0xa2, 0x90, 0x81, 0xd8, 0x44, 0x01, 0x00, 0xe9, 0x5c, 0x2f,
8712 0xf5, 0xe2, 0x9d, 0x0f, 0xf9, 0x00, 0x00, 0x00, 0x00, 0x49,
8713 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
8714 ];
8715 }
8716
8717 foreach (keys(%data)) {
8718 my $f = File::Spec->catfile($main::output_directory, $_);
8719 open(PNG_HANDLE, ">", $f) or
8720 die("cannot create $f: $!\n");
8721 binmode(PNG_HANDLE);
8722 print(PNG_HANDLE map(chr, @{$data{$_}}));
8723 close(PNG_HANDLE) or die("unable to close PNG handle: $!\n");
8724 }
8725 }
8726
8727 #
8728 # write_htaccess_file()
8729 #
8730
8731 sub write_htaccess_file()
8732 {
8733 local *HTACCESS_HANDLE;
8734 my $htaccess_data;
8735
8736 my $f = File::Spec->catdir($main::output_directory, '.htaccess');
8737 open(*HTACCESS_HANDLE, ">", $f) or
8738 die("cannot open $f for writing: $!\n");
8739
8740 $htaccess_data = (<<"END_OF_HTACCESS")
8741 AddEncoding x-gzip .html
8742 END_OF_HTACCESS
8743 ;
8744
8745 print(HTACCESS_HANDLE $htaccess_data);
8746 close(*HTACCESS_HANDLE) or die("unable to close .htaccess: $!\n");
8747 }
8748
8749 #
8750 # write_css_file()
8751 #
8752 # Write the cascading style sheet file gcov.css to the current directory.
8753 # This file defines basic layout attributes of all generated HTML pages.
8754 #
8755
8756 sub write_css_file()
8757 {
8758 local *CSS_HANDLE;
8759
8760 my $f = File::Spec->catdir($main::output_directory, 'gcov.css');
8761 # Check for a specified external style sheet file
8762 if ($css_filename) {
8763 # Simply copy that file
8764 system("cp", $css_filename, $f) and
8765 die("cannot copy file $css_filename: $!\n");
8766 return;
8767 }
8768
8769 open(CSS_HANDLE, ">", $f) or
8770 die("cannot open $f for writing: $!\n");
8771
8772 # *************************************************************
8773
8774 # *************************************************************
8775 my $ownerBackground = "#COLOR_17"; # very light pale grey/blue
8776 my $ownerCovHi = "#COLOR_18"; # light green
8777 my $ownerCovMed = "#COLOR_19"; # light yellow
8778 my $ownerCovLo = "#COLOR_20"; # lighter red
8779 # use same background color as file entry unless in hierarchical report
8780 my $directoryBackground = $main::hierarchical ? '#COLOR_18' : '#COLOR_06';
8781 my $css_data = ($_ = <<"END_OF_CSS")
8782 /* All views: initial background and text color */
8783 body
8784 {
8785 color: #COLOR_00;
8786 background-color: #COLOR_14;
8787 }
8788
8789 /* All views: standard link format*/
8790 a:link
8791 {
8792 color: #COLOR_15;
8793 text-decoration: underline;
8794 }
8795
8796 /* All views: standard link - visited format */
8797 a:visited
8798 {
8799 color: #COLOR_01;
8800 text-decoration: underline;
8801 }
8802
8803 /* All views: standard link - activated format */
8804 a:active
8805 {
8806 color: #COLOR_11;
8807 text-decoration: underline;
8808 }
8809
8810 /* All views: main title format */
8811 td.title
8812 {
8813 text-align: center;
8814 padding-bottom: 10px;
8815 font-family: sans-serif;
8816 font-size: 20pt;
8817 font-style: italic;
8818 font-weight: bold;
8819 }
8820 /* table footnote */
8821 td.footnote
8822 {
8823 text-align: left;
8824 padding-left: 100px;
8825 padding-right: 10px;
8826 background-color: #COLOR_08; /* light blue table background color */
8827 /* dark blue table header color
8828 background-color: #COLOR_03; */
8829 white-space: nowrap;
8830 font-family: sans-serif;
8831 font-style: italic;
8832 font-size:70%;
8833 }
8834 /* "Line coverage date bins" leader */
8835 td.subTableHeader
8836 {
8837 text-align: center;
8838 padding-bottom: 6px;
8839 font-family: sans-serif;
8840 font-weight: bold;
8841 vertical-align: center;
8842 }
8843
8844 /* All views: header item format */
8845 td.headerItem
8846 {
8847 text-align: right;
8848 padding-right: 6px;
8849 font-family: sans-serif;
8850 font-weight: bold;
8851 vertical-align: top;
8852 white-space: nowrap;
8853 }
8854
8855 /* All views: header item value format */
8856 td.headerValue
8857 {
8858 text-align: left;
8859 color: #COLOR_15;
8860 font-family: sans-serif;
8861 font-weight: bold;
8862 white-space: nowrap;
8863 }
8864
8865 /* All views: header item coverage table heading */
8866 td.headerCovTableHead
8867 {
8868 text-align: center;
8869 padding-right: 6px;
8870 padding-left: 6px;
8871 padding-bottom: 0px;
8872 font-family: sans-serif;
8873 white-space: nowrap;
8874 }
8875
8876 /* All views: header item coverage table entry */
8877 td.headerCovTableEntry
8878 {
8879 text-align: right;
8880 color: #COLOR_15;
8881 font-family: sans-serif;
8882 font-weight: bold;
8883 white-space: nowrap;
8884 padding-left: 12px;
8885 padding-right: 4px;
8886 background-color: #COLOR_08;
8887 }
8888
8889 /* All views: header item coverage table entry for high coverage rate */
8890 td.headerCovTableEntryHi
8891 {
8892 text-align: right;
8893 color: #COLOR_00;
8894 font-family: sans-serif;
8895 font-weight: bold;
8896 white-space: nowrap;
8897 padding-left: 12px;
8898 padding-right: 4px;
8899 background-color: #COLOR_04;
8900 }
8901
8902 /* All views: header item coverage table entry for medium coverage rate */
8903 td.headerCovTableEntryMed
8904 {
8905 text-align: right;
8906 color: #COLOR_00;
8907 font-family: sans-serif;
8908 font-weight: bold;
8909 white-space: nowrap;
8910 padding-left: 12px;
8911 padding-right: 4px;
8912 background-color: #COLOR_13;
8913 }
8914
8915 /* All views: header item coverage table entry for ow coverage rate */
8916 td.headerCovTableEntryLo
8917 {
8918 text-align: right;
8919 color: #COLOR_00;
8920 font-family: sans-serif;
8921 font-weight: bold;
8922 white-space: nowrap;
8923 padding-left: 12px;
8924 padding-right: 4px;
8925 background-color: #COLOR_10;
8926 }
8927
8928 /* All views: header legend value for legend entry */
8929 td.headerValueLeg
8930 {
8931 text-align: left;
8932 color: #COLOR_00;
8933 font-family: sans-serif;
8934 font-size: 80%;
8935 white-space: nowrap;
8936 padding-top: 4px;
8937 }
8938
8939 /* All views: color of horizontal ruler */
8940 td.ruler
8941 {
8942 background-color: #COLOR_03;
8943 }
8944
8945 /* All views: version string format */
8946 td.versionInfo
8947 {
8948 text-align: center;
8949 padding-top: 2px;
8950 font-family: sans-serif;
8951 font-style: italic;
8952 }
8953
8954 /* Directory view/File view (all)/Test case descriptions:
8955 table headline format */
8956 td.tableHead
8957 {
8958 text-align: center;
8959 color: #COLOR_14;
8960 background-color: #COLOR_03;
8961 font-family: sans-serif;
8962 font-size: 120%;
8963 font-weight: bold;
8964 white-space: nowrap;
8965 padding-left: 4px;
8966 padding-right: 4px;
8967 }
8968
8969 span.tableHeadSort
8970 {
8971 padding-right: 4px;
8972 }
8973
8974 /* Directory view/File view (all): filename entry format */
8975 td.coverFile
8976 {
8977 text-align: left;
8978 padding-left: 10px;
8979 padding-right: 20px;
8980 color: #COLOR_15;
8981 background-color: #COLOR_08;
8982 font-family: monospace;
8983 }
8984
8985 /* Directory view/File view (all): directory name entry format */
8986 td.coverDirectory
8987 {
8988 text-align: left;
8989 padding-left: 10px;
8990 padding-right: 20px;
8991 color: #COLOR_15;
8992 background-color: $directoryBackground;
8993 font-family: monospace;
8994 }
8995
8996 /* Directory view/File view (all): filename entry format */
8997 td.overallOwner
8998 {
8999 text-align: center;
9000 font-weight: bold;
9001 font-family: sans-serif;
9002 background-color: #COLOR_08;
9003 padding-right: 10px;
9004 padding-left: 10px;
9005 }
9006
9007 /* Directory view/File view (all): filename entry format */
9008 td.ownerName
9009 {
9010 text-align: right;
9011 font-style: italic;
9012 font-family: sans-serif;
9013 background-color: $ownerBackground;
9014 padding-right: 10px;
9015 padding-left: 20px;
9016 }
9017
9018 /* Directory view/File view (all): bar-graph entry format*/
9019 td.coverBar
9020 {
9021 padding-left: 10px;
9022 padding-right: 10px;
9023 background-color: #COLOR_08;
9024 }
9025
9026 /* Directory view/File view (all): bar-graph entry format*/
9027 td.owner_coverBar
9028 {
9029 padding-left: 10px;
9030 padding-right: 10px;
9031 background-color: $ownerBackground;
9032 }
9033
9034 /* Directory view/File view (all): bar-graph outline color */
9035 td.coverBarOutline
9036 {
9037 background-color: #COLOR_00;
9038 }
9039
9040 /* Directory view/File view (all): percentage entry for files with
9041 high coverage rate */
9042 td.coverPerHi
9043 {
9044 text-align: right;
9045 padding-left: 10px;
9046 padding-right: 10px;
9047 background-color: #COLOR_04;
9048 font-weight: bold;
9049 font-family: sans-serif;
9050 }
9051
9052 /* 'owner' entry: slightly lighter color than 'coverPerHi' */
9053 td.owner_coverPerHi
9054 {
9055 text-align: right;
9056 padding-left: 10px;
9057 padding-right: 10px;
9058 background-color: $ownerCovHi;
9059 font-weight: bold;
9060 font-family: sans-serif;
9061 }
9062
9063 /* Directory view/File view (all): line count entry */
9064 td.coverNumDflt
9065 {
9066 text-align: right;
9067 padding-left: 10px;
9068 padding-right: 10px;
9069 background-color: #COLOR_08;
9070 white-space: nowrap;
9071 font-family: sans-serif;
9072 }
9073
9074 /* td background color and font for the 'owner' section of the table */
9075 td.ownerTla
9076 {
9077 text-align: right;
9078 padding-left: 10px;
9079 padding-right: 10px;
9080 background-color: $ownerBackground;
9081 white-space: nowrap;
9082 font-family: sans-serif;
9083 font-style: italic;
9084 }
9085
9086 /* Directory view/File view (all): line count entry for files with
9087 high coverage rate */
9088 td.coverNumHi
9089 {
9090 text-align: right;
9091 padding-left: 10px;
9092 padding-right: 10px;
9093 background-color: #COLOR_04;
9094 white-space: nowrap;
9095 font-family: sans-serif;
9096 }
9097
9098 td.owner_coverNumHi
9099 {
9100 text-align: right;
9101 padding-left: 10px;
9102 padding-right: 10px;
9103 background-color: $ownerCovHi;
9104 white-space: nowrap;
9105 font-family: sans-serif;
9106 }
9107
9108 /* Directory view/File view (all): percentage entry for files with
9109 medium coverage rate */
9110 td.coverPerMed
9111 {
9112 text-align: right;
9113 padding-left: 10px;
9114 padding-right: 10px;
9115 background-color: #COLOR_13;
9116 font-weight: bold;
9117 font-family: sans-serif;
9118 }
9119
9120 td.owner_coverPerMed
9121 {
9122 text-align: right;
9123 padding-left: 10px;
9124 padding-right: 10px;
9125 background-color: $ownerCovMed;
9126 font-weight: bold;
9127 font-family: sans-serif;
9128 }
9129
9130 /* Directory view/File view (all): line count entry for files with
9131 medium coverage rate */
9132 td.coverNumMed
9133 {
9134 text-align: right;
9135 padding-left: 10px;
9136 padding-right: 10px;
9137 background-color: #COLOR_13;
9138 white-space: nowrap;
9139 font-family: sans-serif;
9140 }
9141
9142 td.owner_coverNumMed
9143 {
9144 text-align: right;
9145 padding-left: 10px;
9146 padding-right: 10px;
9147 background-color: $ownerCovMed;
9148 white-space: nowrap;
9149 font-family: sans-serif;
9150 }
9151
9152 /* Directory view/File view (all): percentage entry for files with
9153 low coverage rate */
9154 td.coverPerLo
9155 {
9156 text-align: right;
9157 padding-left: 10px;
9158 padding-right: 10px;
9159 background-color: #COLOR_10;
9160 font-weight: bold;
9161 font-family: sans-serif;
9162 }
9163
9164 td.owner_coverPerLo
9165 {
9166 text-align: right;
9167 padding-left: 10px;
9168 padding-right: 10px;
9169 background-color: $ownerCovLo;
9170 font-weight: bold;
9171 font-family: sans-serif;
9172 }
9173
9174 /* Directory view/File view (all): line count entry for files with
9175 low coverage rate */
9176 td.coverNumLo
9177 {
9178 text-align: right;
9179 padding-left: 10px;
9180 padding-right: 10px;
9181 background-color: #COLOR_10;
9182 white-space: nowrap;
9183 font-family: sans-serif;
9184 }
9185
9186 td.owner_coverNumLo
9187 {
9188 text-align: right;
9189 padding-left: 10px;
9190 padding-right: 10px;
9191 background-color: $ownerCovLo;
9192 white-space: nowrap;
9193 font-family: sans-serif;
9194 }
9195
9196 /* File view (all): "show/hide details" link format */
9197 a.detail:link
9198 {
9199 color: #COLOR_06;
9200 font-size:80%;
9201 }
9202
9203 /* File view (all): "show/hide details" link - visited format */
9204 a.detail:visited
9205 {
9206 color: #COLOR_06;
9207 font-size:80%;
9208 }
9209
9210 /* File view (all): "show/hide details" link - activated format */
9211 a.detail:active
9212 {
9213 color: #COLOR_14;
9214 font-size:80%;
9215 }
9216
9217 /* File view (detail): test name entry */
9218 td.testName
9219 {
9220 text-align: right;
9221 padding-right: 10px;
9222 background-color: #COLOR_08;
9223 font-family: sans-serif;
9224 }
9225
9226 /* File view (detail): test percentage entry */
9227 td.testPer
9228 {
9229 text-align: right;
9230 padding-left: 10px;
9231 padding-right: 10px;
9232 background-color: #COLOR_08;
9233 font-family: sans-serif;
9234 }
9235
9236 /* File view (detail): test lines count entry */
9237 td.testNum
9238 {
9239 text-align: right;
9240 padding-left: 10px;
9241 padding-right: 10px;
9242 background-color: #COLOR_08;
9243 font-family: sans-serif;
9244 }
9245
9246 /* Test case descriptions: test name format*/
9247 dt
9248 {
9249 font-family: sans-serif;
9250 font-weight: bold;
9251 }
9252
9253 /* Test case descriptions: description table body */
9254 td.testDescription
9255 {
9256 padding-top: 10px;
9257 padding-left: 30px;
9258 padding-bottom: 10px;
9259 padding-right: 30px;
9260 background-color: #COLOR_08;
9261 }
9262
9263 /* Source code view: function entry */
9264 td.coverFn
9265 {
9266 text-align: left;
9267 padding-left: 10px;
9268 padding-right: 20px;
9269 color: #COLOR_15;
9270 background-color: #COLOR_08;
9271 font-family: monospace;
9272 }
9273
9274 /* Source code view: function entry zero count*/
9275 td.coverFnLo
9276 {
9277 text-align: right;
9278 padding-left: 10px;
9279 padding-right: 10px;
9280 background-color: #COLOR_10;
9281 font-weight: bold;
9282 font-family: sans-serif;
9283 }
9284
9285 /* Source code view: function entry nonzero count*/
9286 td.coverFnHi
9287 {
9288 text-align: right;
9289 padding-left: 10px;
9290 padding-right: 10px;
9291 background-color: #COLOR_08;
9292 font-weight: bold;
9293 font-family: sans-serif;
9294 }
9295
9296 td.coverFnAlias
9297 {
9298 text-align: right;
9299 padding-left: 10px;
9300 padding-right: 20px;
9301 color: #COLOR_15;
9302 /* make this a slightly different color than the leader - otherwise,
9303 otherwise the alias is hard to distinguish in the table */
9304 background-color: #COLOR_17; /* very light pale grey/blue */
9305 font-family: monospace;
9306 }
9307
9308 /* Source code view: function entry zero count*/
9309 td.coverFnAliasLo
9310 {
9311 text-align: right;
9312 padding-left: 10px;
9313 padding-right: 10px;
9314 background-color: $ownerCovLo; /* lighter red */
9315 font-family: sans-serif;
9316 }
9317
9318 /* Source code view: function entry nonzero count*/
9319 td.coverFnAliasHi
9320 {
9321 text-align: right;
9322 padding-left: 10px;
9323 padding-right: 10px;
9324 background-color: #COLOR_08;
9325 font-weight: bold;
9326 font-family: sans-serif;
9327 }
9328
9329 /* Source code view: source code format */
9330 pre.source
9331 {
9332 font-family: monospace;
9333 white-space: pre;
9334 margin-top: 2px;
9335 }
9336
9337 /* elided/removed code */
9338 span.elidedSource
9339 {
9340 font-family: sans-serif;
9341 /*font-size: 8pt; */
9342 font-style: italic;
9343 background-color: lightgrey;
9344 }
9345
9346 /* Source code view: line number format */
9347 span.lineNum
9348 {
9349 background-color: #COLOR_09;
9350 }
9351
9352 /* Source code view: line number format when there are deleted
9353 lines in the corresponding location */
9354 span.lineNumWithDelete
9355 {
9356 foreground-color: #COLOR_09;
9357 background-color: lightgrey;
9358 }
9359
9360 /* Source code view: format for Cov legend */
9361 span.coverLegendCov
9362 {
9363 padding-left: 10px;
9364 padding-right: 10px;
9365 padding-bottom: 2px;
9366 background-color: #COLOR_07;
9367 }
9368
9369 /* Source code view: format for NoCov legend */
9370 span.coverLegendNoCov
9371 {
9372 padding-left: 10px;
9373 padding-right: 10px;
9374 padding-bottom: 2px;
9375 background-color: #COLOR_12;
9376 }
9377
9378 /* Source code view: format for the source code heading line */
9379 pre.sourceHeading
9380 {
9381 white-space: pre;
9382 font-family: monospace;
9383 font-weight: bold;
9384 margin: 0px;
9385 }
9386
9387 /* All views: header legend value for low rate */
9388 td.headerValueLegL
9389 {
9390 font-family: sans-serif;
9391 text-align: center;
9392 white-space: nowrap;
9393 padding-left: 4px;
9394 padding-right: 2px;
9395 background-color: #COLOR_10;
9396 font-size: 80%;
9397 }
9398
9399 /* All views: header legend value for med rate */
9400 td.headerValueLegM
9401 {
9402 font-family: sans-serif;
9403 text-align: center;
9404 white-space: nowrap;
9405 padding-left: 2px;
9406 padding-right: 2px;
9407 background-color: #COLOR_13;
9408 font-size: 80%;
9409 }
9410
9411 /* All views: header legend value for hi rate */
9412 td.headerValueLegH
9413 {
9414 font-family: sans-serif;
9415 text-align: center;
9416 white-space: nowrap;
9417 padding-left: 2px;
9418 padding-right: 4px;
9419 background-color: #COLOR_04;
9420 font-size: 80%;
9421 }
9422
9423 /* All views except source code view: legend format for low coverage */
9424 span.coverLegendCovLo
9425 {
9426 padding-left: 10px;
9427 padding-right: 10px;
9428 padding-top: 2px;
9429 background-color: #COLOR_10;
9430 }
9431
9432 /* All views except source code view: legend format for med coverage */
9433 span.coverLegendCovMed
9434 {
9435 padding-left: 10px;
9436 padding-right: 10px;
9437 padding-top: 2px;
9438 background-color: #COLOR_13;
9439 }
9440
9441 /* All views except source code view: legend format for hi coverage */
9442 span.coverLegendCovHi
9443 {
9444 padding-left: 10px;
9445 padding-right: 10px;
9446 padding-top: 2px;
9447 background-color: #COLOR_04;
9448 }
9449
9450 a.branchTla:link
9451 {
9452 color: #COLOR_00;
9453 }
9454
9455 a.branchTla:visited
9456 {
9457 color: #COLOR_00;
9458 }
9459
9460 a.mcdcTla:link
9461 {
9462 color: #COLOR_00;
9463 }
9464
9465 a.mcdcTla:visited
9466 {
9467 color: #COLOR_00;
9468 }
9469 END_OF_CSS
9470 ;
9471
9472 foreach my $tla (@SummaryInfo::tlaPriorityOrder) {
9473 my $title = $SummaryInfo::tlaToTitle{$tla};
9474 my $color = $lcovutil::tlaColor{$tla};
9475 foreach my $elem ("td", "span") {
9476 my $align = $elem eq 'td' ? "right" : "left";
9477 $css_data .= ($_ = <<"END_OF_SPAN")
9478
9479 /* Source code view/table entry background: format for lines classified as "$title" */
9480 $elem.tla$tla
9481 {
9482 text-align: $align;
9483 background-color: $color;
9484 }
9485 $elem.tlaBg$tla {
9486 background-color: $color;
9487 }
9488 END_OF_SPAN
9489 ;
9490 }
9491 # the href anchor tag background
9492 $css_data .= ($_ = <<"END_OF_SPAN");
9493 a.tlaBg$tla {
9494 background-color: $color;
9495 color: #COLOR_00;
9496 }
9497
9498 td.headerCovTableHead$tla {
9499 text-align: center;
9500 padding-right: 6px;
9501 padding-left: 6px;
9502 padding-bottom: 0px;
9503 font-family: sans-serif;
9504 white-space: nowrap;
9505 background-color: $color;
9506 }
9507 END_OF_SPAN
9508 }
9509
9510 # 'span' tags for date bins...
9511 # probably should have one for each bin...
9512 $css_data .= ($_ = <<"END_OF_DATE_SPAN")
9513
9514 /* Source code view: format for date/owner bin that is not hit */
9515 span.missBins
9516 {
9517 background-color: #COLOR_10 /* red */
9518 }
9519 END_OF_DATE_SPAN
9520 ;
9521
9522 # *************************************************************
9523
9524 # Remove leading tab from all lines
9525 $css_data =~ s/^\t//gm;
9526 $css_data =~ s/^ //gm; # and 8 spaces...
9527
9528 # Apply palette
9529 my $palette =
9530 $dark_mode ? \%lcovutil::dark_palette : \%lcovutil::normal_palette;
9531
9532 while (my ($key, $color) = each(%$palette)) {
9533 $css_data =~ s/$key/$color/gm;
9534 }
9535
9536 print(CSS_HANDLE $css_data);
9537
9538 close(CSS_HANDLE) or die("unable to close CSS handle: $!\n");
9539 }
9540
9541 #
9542 # get_bar_graph_code(base_dir, cover_found, cover_hit)
9543 #
9544 # Return a string containing HTML code which implements a bar graph display
9545 # for a coverage rate of cover_hit * 100 / cover_found.
9546 #
9547
9548 sub get_bar_graph_code($$$)
9549 {
9550 my ($base_dir, $found, $hit) = @_;
9551 my $graph_code;
9552
9553 # Check number of instrumented lines
9554 if ($found == 0) { return ""; }
9555
9556 my $alt = rate($hit, $found, "%");
9557 my $width = rate($hit, $found, undef, 0);
9558 my $remainder = 100 - $width;
9559
9560 # Decide which .png file to use
9561 my $png_name =
9562 $rate_png[classify_rate($found, $hit, $ln_med_limit, $ln_hi_limit)];
9563
9564 if ($width == 0) {
9565 # Zero coverage
9566 $graph_code = (<<END_OF_HTML);
9567 <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="${base_dir}snow.png" width=100 height=10 alt="$alt"></td></tr></table>
9568 END_OF_HTML
9569 } elsif ($width == 100) {
9570 # Full coverage
9571 $graph_code = (<<END_OF_HTML);
9572 <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="${base_dir}$png_name" width=100 height=10 alt="$alt"></td></tr></table>
9573 END_OF_HTML
9574 } else {
9575 # Positive coverage
9576 $graph_code = (<<END_OF_HTML);
9577 <table border=0 cellspacing=0 cellpadding=1><tr><td class="coverBarOutline"><img src="${base_dir}$png_name" width=$width height=10 alt="$alt"><img src="${base_dir}snow.png" width=$remainder height=10 alt="$alt"></td></tr></table>
9578 END_OF_HTML
9579 }
9580
9581 # Remove leading tabs from all lines
9582 $graph_code =~ s/^\t+//gm;
9583 chomp($graph_code);
9584
9585 return ($graph_code);
9586 }
9587
9588 #
9589 # sub classify_rate(found, hit, med_limit, high_limit)
9590 #
9591 # Return 0 for low rate, 1 for medium rate and 2 for hi rate.
9592 #
9593
9594 sub classify_rate($$$$)
9595 {
9596 my ($found, $hit, $med, $hi) = @_;
9597
9598 if ($found == 0) {
9599 return 2;
9600 }
9601 my $rate = rate($hit, $found);
9602 if ($rate < $med) {
9603 return 0;
9604 } elsif ($rate < $hi) {
9605 return 1;
9606 }
9607 return 2;
9608 }
9609
9610 #
9611 # write_html(filehandle, html_code)
9612 #
9613 # Write out HTML_CODE to FILEHANDLE while removing a leading tabulator mark
9614 # in each line of HTML_CODE.
9615 #
9616
9617 sub write_html(*$)
9618 {
9619 local *HTML_HANDLE = $_[0];
9620 my $html_code = $_[1];
9621
9622 # Remove leading tab from all lines
9623 $html_code =~ s/^\t//gm;
9624
9625 print(HTML_HANDLE $html_code) or
9626 die("cannot write HTML data ($!)\n");
9627 }
9628
9629 #
9630 # write_html_prolog(filehandle, base_dir, pagetitle)
9631 #
9632 # Write an HTML prolog common to all HTML files to FILEHANDLE. PAGETITLE will
9633 # be used as HTML page title. BASE_DIR contains a relative path which points
9634 # to the base directory.
9635 #
9636
9637 sub write_html_prolog(*$$)
9638 {
9639 my $basedir = $_[1];
9640 my $pagetitle = $_[2];
9641 my $prolog;
9642
9643 $prolog = $html_prolog;
9644 $prolog =~ s/\@pagetitle\@/$pagetitle/g;
9645 $prolog =~ s/\@basedir\@/$basedir/g;
9646
9647 write_html($_[0], $prolog);
9648 }
9649
9650 #
9651 # write_header_prolog(filehandle, base_dir)
9652 #
9653 # Write beginning of page header HTML code.
9654 #
9655
9656 sub write_header_prolog(*$)
9657 {
9658 # *************************************************************
9659
9660 write_html($_[0], <<END_OF_HTML);
9661 <table width="100%" border=0 cellspacing=0 cellpadding=0>
9662 <tr><td class="title">$title</td></tr>
9663 <tr><td class="ruler"><img src="$_[1]glass.png" width=3 height=3 alt=""></td></tr>
9664
9665 <tr>
9666 <td width="100%">
9667 <table cellpadding=1 border=0 width="100%">
9668 END_OF_HTML
9669
9670 # *************************************************************
9671 }
9672
9673 #
9674 # write_header_line(handle, content)
9675 #
9676 # Write a header line with the specified table contents.
9677 #
9678
9679 sub write_header_line(*@)
9680 {
9681 my ($handle, @content) = @_;
9682
9683 write_html($handle, " <tr>\n");
9684 # label order has to match data that is passed
9685 my @labels = qw/width class colspan title/;
9686 foreach my $entry (@content) {
9687 my @d = @$entry;
9688 my $text = splice(@d, 2, 1) if (scalar(@d) > 1);
9689 # entry may not contain some data - e.g., does not have colspan or title
9690 die("unexpected entry format") unless scalar(@labels) >= scalar(@d);
9691 my $str = " <td";
9692 for (my $i = 0; $i <= $#d; ++$i) {
9693 my $e = $d[$i];
9694 $str .= ' ' . $labels[$i] . "=\"$e\""
9695 if defined($e);
9696 }
9697 $str .= '>';
9698 $str .= $text
9699 if defined($text);
9700 $str .= "</td>\n";
9701 # so 'str' looked like '<td width="value" colspan="value">whatever</td>'
9702 write_html($handle, $str);
9703 }
9704 write_html($handle, " </tr>\n"); # then end the row
9705 }
9706
9707 #
9708 # write_header_epilog(filehandle, base_dir)
9709 #
9710 # Write end of page header HTML code.
9711 #
9712
9713 sub write_header_epilog(*$)
9714 {
9715 # *************************************************************
9716
9717 write_html($_[0], <<END_OF_HTML);
9718 <tr><td><img src="$_[1]glass.png" width=3 height=3 alt=""></td></tr>
9719 </table>
9720 </td>
9721 </tr>
9722
9723 <tr><td class="ruler"><img src="$_[1]glass.png" width=3 height=3 alt=""></td></tr>
9724 </table>
9725
9726 END_OF_HTML
9727 # *************************************************************
9728 }
9729
9730 #
9731 # write_file_table_prolog(handle, file_heading, binHeading, primary_key, ([heading, num_cols], ...))
9732 #
9733 # Write heading for file table.
9734 #
9735
9736 sub write_file_table_prolog(*$$$@)
9737 {
9738 my ($handle, $file_heading, $bin_heading, $primary_key, @columns) = @_;
9739 my $num_columns = 0;
9740 my $file_width = 40;
9741 my $col;
9742 my $width;
9743
9744 foreach $col (@columns) {
9745 my ($heading, $cols, $titles) = @{$col};
9746
9747 $num_columns += $cols;
9748 }
9749 $num_columns++ if (defined($bin_heading));
9750 $width = int((100 - $file_width) / $num_columns);
9751
9752 # Table definition
9753 write_html($handle, <<END_OF_HTML);
9754 <center>
9755 <table width="80%" cellpadding=1 cellspacing=1 border=0>
9756
9757 <tr>
9758 <td width="$file_width%"><br></td>
9759 END_OF_HTML
9760 if (defined($bin_heading)) {
9761 # owner or date column
9762 write_html($handle, <<END_OF_HTML);
9763 <td width="$width%"></td>
9764 END_OF_HTML
9765 }
9766 # Empty first row
9767 foreach $col (@columns) {
9768 my ($heading, $cols) = @{$col};
9769
9770 while ($cols-- > 0) {
9771 write_html($handle, <<END_OF_HTML);
9772 <td width="$width%"></td>
9773 END_OF_HTML
9774 }
9775 }
9776 # Next row
9777 if ($primary_key eq "name") {
9778 my $spanType = defined($bin_heading) ? "colspan" : "rowspan";
9779 ++$num_columns;
9780 write_html($handle, <<END_OF_HTML);
9781 </tr>
9782
9783 <tr>
9784 <td class="tableHead" $spanType=2>$file_heading</td>
9785 END_OF_HTML
9786 } else {
9787 my $t = ucfirst($primary_key);
9788 # a bit of a hack...just substitute the primary key and related
9789 # strings into the 'file heading' link - so we display the
9790 # 'sort' widget
9791 if ($primary_key eq 'owner' &&
9792 $file_heading =~ /^([^ ]+) <span/) {
9793 my $viewType = $1;
9794 $file_heading =~ s/$viewType/$t/;
9795 $file_heading =~ s/file name/$primary_key/g;
9796 $t = $file_heading;
9797 $file_heading = $viewType;
9798 }
9799 $num_columns += 2;
9800 write_html($handle, <<END_OF_HTML);
9801 </tr>
9802
9803 <tr>
9804 <td class="tableHead" rowspan=2>$t</td>
9805 <td class="tableHead" rowspan=2>$file_heading</td>
9806 END_OF_HTML
9807 }
9808 # Heading row
9809 foreach $col (@columns) {
9810 my ($heading, $cols, $titles) = @{$col};
9811 my $colspan = "";
9812 my $rowspan = "";
9813 $colspan = " colspan=$cols" if ($cols > 1);
9814 $rowspan = " rowspan=2" if (!defined($titles));
9815 write_html($handle, <<END_OF_HTML);
9816 <td class="tableHead"$colspan$rowspan>$heading</td>
9817 END_OF_HTML
9818 }
9819 write_html($handle, <<END_OF_HTML);
9820 </tr>
9821 <tr>
9822 END_OF_HTML
9823
9824 # title row
9825 if (defined($bin_heading)) {
9826 # Next row
9827 my $str = ucfirst($bin_heading);
9828 write_html($handle, <<END_OF_HTML);
9829 <td class="tableHead">Name</td>
9830 <td class="tableHead">$str</td>
9831 END_OF_HTML
9832 }
9833
9834 foreach $col (@columns) {
9835 my ($heading, $cols, $titles) = @{$col};
9836 my $colspan = "";
9837 my $rowspan = "";
9838
9839 if (defined($titles)) {
9840 foreach my $t (@$titles) {
9841 my $span = "";
9842 my $popup = '';
9843 if ("ARRAY" eq ref($t)) {
9844 my ($tla, $num, $help) = @$t;
9845 $span = " colspan=" . $num if $num > 1;
9846 $popup = " title=\"$help\""
9847 if (defined $help);
9848 $t = $tla;
9849 }
9850 write_html($handle, <<END_OF_HTML);
9851 <td class="tableHead"$span$popup> $t</td>
9852 END_OF_HTML
9853 }
9854 }
9855 }
9856 write_html($handle, <<END_OF_HTML);
9857 </tr>
9858 END_OF_HTML
9859 return $num_columns;
9860 }
9861
9862 sub escape_id($)
9863 {
9864 my ($name) = @_;
9865
9866 # Name/ID attribute requirements according to HTML 4.01 Transitional
9867 $name =~ s/[^A-Za-z0-9-_:.]/_/g;
9868
9869 return $name;
9870 }
9871
9872 # write_file_table_entry(handle, base_dir,
9873 # [ name, [filename, fileDetails, fileHref, cbdata],
9874 # activeTlaCols,
9875 # rowspan, primary_key, is_secondary, fileview,
9876 # page_type, page_link, dirSummary, showDetailCol,
9877 # asterisk ],
9878 # ([ found, hit, med_limit, hi_limit, graph ], ..)
9879 #
9880 # Write an entry of the file table.
9881 # $fileview: 0 == 'table is listing directories', 1 == 'list files'
9882 #
9883
9884 sub write_file_table_entry(*$$@)
9885 {
9886 my ($handle, $base_dir, $data, @entries) = @_;
9887 my ($name, $callbackData, $activeTlaCols,
9888 $rowspan, $primary_key, $is_secondary,
9889 $fileview, $page_type, $page_link,
9890 $dirSummary, $showBinDetailColumn, $asterisk) = @$data;
9891 my ($filename, $fileSummary, $fileDetails, $file_link, $cbData) =
9892 @$callbackData;
9893 die("unexpected callback arg types: write_file_table_entry(" .
9894 ref($fileSummary) . ', ' .
9895 ref($fileDetails) .
9896 ", $file_link, " . (defined($cbData) ? $cbData : 'undef') . ')')
9897 unless (!defined($fileDetails) || 'SourceFile' eq ref($fileDetails)) &&
9898 'SummaryInfo' eq ref($fileSummary);
9899 my $esc_name = escape_html($name);
9900 if ($main::flat &&
9901 !$is_secondary) {
9902 my $relDir = $fileSummary->relativeDir();
9903 die("relative directory not set") unless $relDir;
9904 $esc_name = escape_html(File::Spec->catfile($relDir, $name))
9905 if '.' ne $relDir;
9906 }
9907 my $obj_name = $esc_name
9908 .
9909 ($fileSummary->type() eq 'directory' &&
9910 $primary_key eq 'name' ? escape_html($lcovutil::dirseparator) :
9911 '');
9912 my $namecode = $obj_name;
9913 my $owner;
9914 my $full_path =
9915 'directory' eq $fileSummary->type() ? $fileSummary->fullDir() :
9916 $fileSummary->name();
9917 $full_path = escape_html($full_path);
9918
9919 # Add link to source if provided
9920 my $source_link;
9921 my $suppressFileHref =
9922 $main::no_sourceview && $fileSummary->type() eq 'file';
9923 if ($is_secondary == 2) {
9924 if (defined($page_link) &&
9925 $page_link ne "") {
9926 # could use $fileSummary->name() in the popup
9927 $source_link =
9928 $suppressFileHref ? $obj_name :
9929 ("<a href=\"$page_link\" title=\"Click to go to " .
9930 $fileSummary->type() . " $full_path\">$obj_name</a>");
9931 } elsif (defined($file_link) &&
9932 $file_link ne "") {
9933 my $target = $file_link;
9934 if ($main::flat) {
9935 $target =
9936 File::Spec->catfile($fileSummary->relativeDir(), $target);
9937 }
9938 if ($fileSummary->type() eq 'directory') {
9939 $target = File::Basename::dirname($target);
9940 $target = File::Basename::basename($target)
9941 if ($main::hierarchical);
9942 }
9943 $target = escape_html($target);
9944 $source_link =
9945 $suppressFileHref ? $target :
9946 (
9947 "<a href=\"$file_link\" title=\"Click to go to $full_path source detail\">"
9948 . $target . "</a>");
9949 } else {
9950 $source_link = $fileSummary->name();
9951 $source_link = File::Basename::basename($source_link)
9952 if ($main::hierarchical);
9953 $source_link = escape_html($source_link);
9954 }
9955 }
9956 my $anchor = 'NAME';
9957 if (!$is_secondary &&
9958 defined($page_link) &&
9959 $page_link ne "") {
9960 # could use $fileSummary->name() in the popup
9961 $namecode =
9962 $suppressFileHref ? $obj_name :
9963 ("<a href=\"$page_link\" title=\"Click to go to " .
9964 $fileSummary->type() . " $full_path\">$obj_name</a>");
9965 $owner = "";
9966 } elsif ($is_secondary &&
9967 $primary_key ne 'name' &&
9968 defined($file_link) &&
9969 $file_link ne "") {
9970 if ($main::flat) {
9971 $file_link =
9972 File::Spec->catfile($fileSummary->relativeDir(), $file_link);
9973 } elsif ($main::hierarchical &&
9974 'directory' eq $fileSummary->type()) {
9975 die("no parent for " . $fileSummary->name())
9976 unless defined($fileSummary->parent());
9977 my $pname = $fileSummary->parent()->name();
9978 die("unexpected parent '$pname' in $file_link")
9979 unless (length($pname) < length($file_link) &&
9980 $pname eq substr($file_link, 0, length($pname)));
9981 $file_link = substr($file_link, length($pname) + 1);
9982
9983 #lcovutil::info("$filename: path is $file_link, base is '$base_dir' full path $full_path\n");
9984 }
9985 $namecode =
9986 $suppressFileHref ? $obj_name :
9987 (
9988 "<a href=\"$file_link\" title=\"Click to go to $full_path source detail\">"
9989 . $obj_name . "</a>");
9990 } elsif ($is_secondary &&
9991 $primary_key ne 'name' &&
9992 $name eq $filename) {
9993 # get here when we suppressed the sourceview - so the file link
9994 # is not defined
9995 $namecode = $obj_name;
9996 } elsif (defined($primary_key)) {
9997 $namecode = $obj_name;
9998 if (!$suppressFileHref) {
9999 # we want the the HREF anchor on the column 1 entry -
10000 # the column 0 entry may span many rows - so navigation to that
10001 # entry (e.g., to find all the files in the "(7..30] days" bin)
10002 # may be rendered such that the first element in the bin is not
10003 # visible (you have to scroll up to see it).
10004 # the fix is to put the anchor in the next column
10005 if ($primary_key eq 'owner') {
10006 $anchor = '<a id="N' . escape_id($name) . '">NAME</a>';
10007 } elsif ($primary_key eq 'date') {
10008 die("unexpected bin")
10009 unless (!$is_secondary &&
10010 exists($SummaryInfo::ageHeaderToBin{$name})) ||
10011 (defined($cbData) &&
10012 $cbData <= $#SummaryInfo::ageGroupHeader);
10013 my $bin =
10014 $is_secondary ? $cbData :
10015 $SummaryInfo::ageHeaderToBin{$name};
10016 $anchor = "<a id=\"B$bin\">NAME</a>";
10017 }
10018 }
10019 }
10020
10021 my $tableHref;
10022 if (defined($file_link) &&
10023 !$main::no_sourceview &&
10024 $main::show_tla &&
10025 defined($fileDetails)) {
10026
10027 $tableHref = "href=\"$file_link#L__LINE__\"";
10028 # href to anchor in frame doesn't seem to work in either firefox
10029 # or chrome. However, this seems like the right syntax.
10030 $tableHref = undef # $tableHref . ' target="source"'
10031 if $main::frames;
10032 }
10033 # First column: name
10034 my $nameClass =
10035 $fileSummary->type() eq 'directory' ? 'coverDirectory' : 'coverFile';
10036 my $prefix;
10037 if ($is_secondary) {
10038 $prefix = "owner_";
10039 } else {
10040 $prefix = "";
10041 $nameClass = 'ownerName' if $primary_key ne 'name';
10042 }
10043 if ($is_secondary &&
10044 ( $primary_key eq 'name' ||
10045 ($primary_key ne 'name' &&
10046 $fileview == 0))
10047 ) {
10048 if ($fileview == 0 &&
10049 $primary_key ne 'name' &&
10050 $main::flat) {
10051 # link to (flat) file detail
10052 my $relDir = $fileSummary->relativeDir();
10053 die("relative directory not set") unless $relDir;
10054 $namecode =
10055 $suppressFileHref ? $obj_name :
10056 ("<a href=\"" .
10057 File::Spec->catfile($relDir, "$filename.gcov.$html_ext") .
10058 "\" title=\"Click to go to $esc_name source detail\">$obj_name</a>"
10059 );
10060 } else {
10061 # link to the entry in date/owner 'summary' table (keyed other way up)
10062 $namecode = "<a href=\"";
10063
10064 my $bin = "";
10065 if ($fileview == 0 &&
10066 $primary_key ne 'name') {
10067 $namecode .= $filename . $lcovutil::dirseparator;
10068 $bin = $cbData if defined($cbData);
10069 }
10070 $namecode .= "index";
10071 my $help;
10072 if ($page_type eq 'owner') {
10073 $bin = $esc_name
10074 if ($primary_key eq 'name');
10075 $namecode .= "-bin_owner." . $html_ext . "#N" . escape_id($bin);
10076 $help = "owner $bin";
10077 } elsif ($page_type eq 'date') {
10078 $bin = $SummaryInfo::ageHeaderToBin{$name}
10079 if ($primary_key eq 'name');
10080 $namecode .= "-bin_date." . $html_ext . "#B$bin";
10081 $help =
10082 "the period '" . $SummaryInfo::ageGroupHeader[$bin] . "'";
10083 } else {
10084 die("unexpected type '$page_type'");
10085 }
10086 $nameClass = 'ownerName' if $primary_key eq 'name';
10087 $namecode .=
10088 "\" title=\"go to coverage summary for $help\">$obj_name</a>";
10089 }
10090 }
10091 write_html($handle, " <tr>\n");
10092 my $elide_note = '';
10093 if ($is_secondary == 2) {
10094 die("unexpected cbData for $page_type, $primary_key, $name, " .
10095 (defined($cbData) ? $cbData : 'undef'))
10096 unless ($page_type eq 'owner' ||
10097 ($page_type eq 'date' &&
10098 ((defined($cbData) &&
10099 $cbData <= $#SummaryInfo::ageGroupHeader) ||
10100 (!defined($cbData) &&
10101 exists($SummaryInfo::ageHeaderToBin{$name})))));
10102 my $entry;
10103 if ($primary_key eq 'name') {
10104 die("source_link undefined: "
10105 .
10106 (
10107 defined($fileSummary) ?
10108 (
10109 $fileSummary->type() . " $name:" . $fileSummary->name())
10110 :
10111 "")) unless defined($source_link);
10112 $entry = $source_link;
10113 } else {
10114 # select the appropriate bin...
10115 my $id =
10116 defined($cbData) ?
10117 ($page_type eq 'owner' ? $cbData :
10118 $SummaryInfo::ageGroupHeader[$cbData]) :
10119 $name;
10120 # need an anchor here - this is the destination of an HREF from
10121 # the header 'owner' or 'date' summary table
10122 $entry = '<a id="';
10123 if ($page_type eq 'owner') {
10124 $entry .= 'N' . $id;
10125 } else {
10126 die("unexpected page type $page_type")
10127 unless $page_type eq 'date';
10128 $entry .= 'B' . $SummaryInfo::ageHeaderToBin{$id};
10129 }
10130 $entry .= "\">$id</a>";
10131 }
10132 my $class =
10133 $primary_key eq 'name' ?
10134 ($fileSummary->type() eq 'directory' ? 'coverDirectory' :
10135 'coverFile') :
10136 'ownerName';
10137 write_html($handle, " <td class=\"$class\">$entry</td>\n");
10138 $elide_note = '<sup>&lowast;&lowast;</sup>';
10139 }
10140 my $span = (1 == $rowspan) ? "" : " rowspan=$rowspan";
10141 write_html($handle,
10142 " <td class=\"$nameClass\"$span>$namecode$elide_note</td>\n");
10143
10144 # no 'owner' column if the entire directory is not part of the project
10145 # (i.e., no files in this directory are in the repo)
10146 if ((defined($showBinDetailColumn) && $dirSummary->hasOwnerInfo()) ||
10147 (defined($primary_key) &&
10148 $primary_key ne 'name' &&
10149 !$is_secondary)
10150 ) {
10151 $anchor =~ s/NAME/Total/;
10152 $anchor .= "<sup>$asterisk</sup>"
10153 if defined($asterisk);
10154 write_html($handle, <<END_OF_HTML);
10155 <td class="overallOwner">$anchor</td>
10156 END_OF_HTML
10157 }
10158 foreach my $entry (@entries) {
10159 my ($found, $hit, $med, $hi, $graph, $summary, $covType) = @{$entry};
10160 my $bar_graph;
10161 my $class;
10162 my $rate;
10163
10164 # Generate bar graph if requested
10165 if ($graph) {
10166 if (!$is_secondary) {
10167 $class = $prefix . 'coverBar';
10168 $bar_graph = get_bar_graph_code($base_dir, $found, $hit);
10169 } else {
10170 # graph is distracting for the second-level elements - skip them
10171 $bar_graph = "";
10172 $class = 'coverFile';
10173 }
10174 write_html($handle, <<END_OF_HTML);
10175 <td class="$class" align="center">
10176 $bar_graph
10177 </td>
10178 END_OF_HTML
10179 }
10180 # Get rate color and text
10181 if ($found == 0) {
10182 $rate = "-";
10183 $class = "Hi";
10184 } else {
10185 $rate = rate($hit, $found, "&nbsp;%");
10186 $class = $rate_name[classify_rate($found, $hit, $med, $hi)];
10187 }
10188 # Show negative number of items without coverage
10189 $hit -= $found # negative number
10190 if ($main::opt_missed);
10191
10192 write_html($handle, <<END_OF_HTML);
10193 <td class="${prefix}coverPer$class">$rate</td>
10194 END_OF_HTML
10195 if ($summary) {
10196 my @keys = ("found");
10197 if ($main::show_hitTotalCol) {
10198 push(@keys, $opt_missed ? "missed" : "hit");
10199 }
10200 if ($main::show_tla) {
10201 push(@keys, @{$activeTlaCols->{$covType}});
10202 }
10203 foreach my $key (@keys) {
10204 my $count = $summary->get($key);
10205 #print("$name: $key " . $summary->get($key));
10206 $class = $page_type ne "owner" ? "coverNumDflt" : "ownerTla";
10207 my $v = "";
10208 if (defined($count) && 0 != $count) {
10209 $count = -$count if $key eq 'missed';
10210 $v = $count;
10211 # want to colorize the UNC, LBC, UIC rows if not zero
10212 $class = "tla$key"
10213 if (!$main::use_legacyLabels &&
10214 grep(/^$key$/, ("UNC", "LBC", "UIC")));
10215
10216 my $column = '';
10217 # look in file details to build link to first line
10218 # '$tableHref is undef unless the data we need is available
10219 if (defined($tableHref) &&
10220 !grep(/^$key$/, ('DUB', 'DCB')) &&
10221 grep(/^$key$/, @SummaryInfo::tlaPriorityOrder)) {
10222 my $line;
10223 my $label =
10224 $main::use_legacyLabels ?
10225 $SummaryInfo::tlaToLegacySrcLabel{$key} :
10226 $key;
10227 # need to keep $fileDetails object so we know the
10228 # 'first location in ...' for hyperlink from the
10229 # file table to the line in the file
10230 my $title = "\"Go to first $label " .
10231 SummaryInfo::type2str($covType) . ' ';
10232 if ('fileOrDir' eq $page_type) {
10233 # go to first line of the indicated type in the file
10234 $line = $fileDetails->nextTlaGroup($key)
10235 if $covType == SummaryInfo::LINE_DATA;
10236 $line = $fileDetails->nextBranchTlaGroup($key)
10237 if $covType == SummaryInfo::BRANCH_DATA;
10238 $line = $fileDetails->nextMcdcTlaGroup($key)
10239 if $covType == SummaryInfo::MCDC_DATA;
10240 } elsif ('owner' eq $page_type) {
10241 my $owner = $summary->owner();
10242 $column = $owner;
10243 $title .= "in '$owner' bin ";
10244 $line = $fileDetails->nextInOwnerBin($owner, $key)
10245 if $covType == SummaryInfo::LINE_DATA;
10246 $line =
10247 $fileDetails->nextBranchInOwnerBin($owner, $key)
10248 if $covType == SummaryInfo::BRANCH_DATA;
10249 $line =
10250 $fileDetails->nextMcdcInOwnerBin($owner, $key)
10251 if $covType == SummaryInfo::MCDC_DATA;
10252 } elsif ('date' eq $page_type) {
10253 my $agebin = $summary->bin();
10254 $column = $agebin;
10255 $title .=
10256 "in '$SummaryInfo::ageGroupHeader[$agebin]' bin ";
10257 $line = $fileDetails->nextInDateBin($agebin, $key)
10258 if $covType == SummaryInfo::LINE_DATA;
10259 $line =
10260 $fileDetails->nextBranchInDateBin($agebin, $key)
10261 if $covType == SummaryInfo::BRANCH_DATA;
10262 $line =
10263 $fileDetails->nextMcdcInDateBin($agebin, $key)
10264 if $covType == SummaryInfo::MCDC_DATA;
10265 } else {
10266 die("unexpected page detail type '$page_type'");
10267 }
10268 $title .= "in $filename\"";
10269 if ($class eq "tla$key") {
10270 # add another CSS style to set the TLA-specific background
10271 # color
10272 $class .= " tlaBg$key";
10273 }
10274 if (defined($line)) {
10275 my $href = $tableHref;
10276 $href =~ s/__LINE__/$line/;
10277 $v = "<a $href ";
10278 if ($class =~ /tlaBg/) {
10279 $v .= "class=\"tlaBg$key\" ";
10280 }
10281 $v .= "title=$title>$count</a>";
10282 } elsif ($covType != SummaryInfo::FUNCTION_DATA &&
10283 (defined($tableHref) ||
10284 (defined($file_link) &&
10285 defined($fileDetails) &&
10286 $main::show_tla &&
10287 !$main::no_sourceview))
10288 ) {
10289 #debugging: why is link missing?
10290 die("undefined line for $page_type $column type $key $covType"
10291 .
10292 (defined($tableHref) ? '' : ' missing href')
10293 );
10294 }
10295 }
10296 } # if count nonzero
10297 write_html($handle, <<END_OF_HTML);
10298 <td class="$class">$v</td>
10299 END_OF_HTML
10300 } # foreach key
10301
10302 } else {
10303 write_html($handle, <<END_OF_HTML);
10304 <td class="${prefix}coverNum$class">$hit / $found</td>
10305 END_OF_HTML
10306 }
10307 }
10308 # End of row
10309 write_html($handle, <<END_OF_HTML);
10310 </tr>
10311 END_OF_HTML
10312 }
10313
10314 #
10315 # write_file_table_detail_entry(filehandle, base_dir, test_name, bin_type, activeTlaCols, ([found, hit], ...))
10316 #
10317 # Write entry for detail section in file table.
10318 #
10319
10320 sub write_file_table_detail_entry(*$$$$@)
10321 {
10322 my ($handle, $base_dir, $test, $showBinDetail, $activeTlaCols, @entries) =
10323 @_;
10324
10325 if ($test eq "") {
10326 $test = "<span style=\"font-style:italic\">&lt;unnamed&gt;</span>";
10327 } elsif ($test =~ /^(.*),diff$/) {
10328 $test = $1 . " (converted)";
10329 }
10330 # Testname
10331 write_html($handle, <<END_OF_HTML);
10332 <tr>
10333 <td class="testName" colspan=2>$test</td>
10334 END_OF_HTML
10335 # Test data
10336 foreach my $entry (@entries) {
10337 my ($found, $hit, $covtype, $callback) = @{$entry};
10338 my $rate = rate($hit, $found, "&nbsp;%");
10339 if (SummaryInfo::LINE_DATA == $covtype &&
10340 defined($showBinDetail)) {
10341 write_html($handle, " <td class=\"testPer\"></td>\n");
10342 }
10343 write_html($handle, " <td class=\"testPer\">$rate</td>\n");
10344 write_html($handle, " <td class='testNum'>$found</td>\n");
10345 if ($main::show_hitTotalCol) {
10346 write_html($handle,
10347 " <td class='testNum'>$hit</td>\n");
10348 }
10349 if ($main::show_tla) {
10350 foreach my $tla (@{$activeTlaCols->{$covtype}}) {
10351 my $count = $callback->count($tla);
10352 $count = "" if 0 == $count;
10353 write_html($handle, " <td class=coverNumDflt>$count</td>\n");
10354 }
10355 }
10356 }
10357 write_html($handle, " </tr>\n");
10358 }
10359
10360 #
10361 # write_file_table_epilog(filehandle)
10362 #
10363 # Write end of file table HTML code.
10364 #
10365
10366 sub write_file_table_epilog(*)
10367 {
10368 # *************************************************************
10369 write_html($_[0], <<END_OF_HTML);
10370 </table>
10371 </center>
10372 <br>
10373
10374 END_OF_HTML
10375 }
10376
10377 #
10378 # write_test_table_prolog(filehandle, table_heading)
10379 #
10380 # Write heading for test case description table.
10381 #
10382
10383 sub write_test_table_prolog(*$)
10384 {
10385 # *************************************************************
10386
10387 write_html($_[0], <<END_OF_HTML);
10388 <center>
10389 <table width="80%" cellpadding=2 cellspacing=1 border=0>
10390
10391 <tr>
10392 <td class="tableHead">$_[1]</td>
10393 </tr>
10394
10395 <tr>
10396 <td class="testDescription">
10397 <dl>
10398 END_OF_HTML
10399
10400 # *************************************************************
10401 }
10402
10403 #
10404 # write_test_table_entry(filehandle, test_name, test_description)
10405 #
10406 # Write entry for the test table.
10407 #
10408
10409 sub write_test_table_entry(*$$)
10410 {
10411 # *************************************************************
10412 my $name = escape_id($_[1]);
10413
10414 write_html($_[0], <<END_OF_HTML);
10415 <dt>$_[1]<a id="T$name">&nbsp;</a></dt>
10416 <dd>$_[2]<br><br></dd>
10417 END_OF_HTML
10418
10419 # *************************************************************
10420 }
10421
10422 #
10423 # write_test_table_epilog(filehandle)
10424 #
10425 # Write end of test description table HTML code.
10426 #
10427
10428 sub write_test_table_epilog(*)
10429 {
10430 # *************************************************************
10431
10432 write_html($_[0], <<END_OF_HTML);
10433 </dl>
10434 </td>
10435 </tr>
10436 </table>
10437 </center>
10438 <br>
10439
10440 END_OF_HTML
10441
10442 # *************************************************************
10443 }
10444
10445 sub fmt_centered($$)
10446 {
10447 my ($width, $text) = @_;
10448 my $w0 = length($text);
10449 my $w1 = $width > $w0 ? int(($width - $w0) / 2) : 0;
10450 my $w2 = $width > $w0 ? $width - $w0 - $w1 : 0;
10451
10452 return (" " x $w1) . $text . (" " x $w2);
10453 }
10454
10455 #
10456 # write_source_prolog(filehandle)
10457 #
10458 # Write start of source code table.
10459 #
10460
10461 sub write_source_prolog(*$$$)
10462 {
10463 my ($handle, $fileHasProjectData, $showBranches, $showMcdc) = @_;
10464 my $lineno_heading = " " x 9;
10465 my $branch_heading = "";
10466 my $mcdc_heading = "";
10467 my $tlaWidth = 4;
10468 my $age_heading = "";
10469 my $owner_heading = "";
10470 my $tla_heading = "";
10471
10472 if (defined($main::show_dateBins) &&
10473 $fileHasProjectData) {
10474 $age_heading = fmt_centered(5, "Age");
10475 $owner_heading = fmt_centered(20, "Owner");
10476 }
10477 if (defined($main::show_tla)) {
10478 $tla_heading = fmt_centered($tlaWidth, "TLA");
10479 }
10480 my $line_heading = fmt_centered($line_field_width, "Line data");
10481 my $source_heading = " Source code";
10482
10483 if ($showBranches) {
10484 $branch_heading = fmt_centered($br_field_width, "Branch data") . " ";
10485 }
10486 if ($showMcdc) {
10487 $mcdc_heading = fmt_centered($mcdc_field_width, "MC/DC data") . " ";
10488 }
10489
10490 # *************************************************************
10491
10492 write_html($handle, <<END_OF_HTML);
10493 <table cellpadding=0 cellspacing=0 border=0>
10494 <tr>
10495 <td><br></td>
10496 </tr>
10497 <tr>
10498 <td>
10499 <pre class="sourceHeading">${age_heading} ${owner_heading} ${lineno_heading}${branch_heading}${mcdc_heading}${tla_heading}${line_heading} ${source_heading}</pre>
10500 <pre class="source">
10501 END_OF_HTML
10502
10503 # *************************************************************
10504 }
10505
10506 #
10507 # get_block_len(block)
10508 #
10509 # Calculate total text length of all branches in a block of branches.
10510 #
10511
10512 sub get_block_len($)
10513 {
10514 my ($block) = @_;
10515 my $len = 0;
10516
10517 foreach my $branch (@{$block}) {
10518 $len += $branch->[$BR_LEN];
10519 }
10520 return $len;
10521 }
10522
10523 #
10524 # get_block_list(brdata | mcdc_data)
10525 #
10526 # common method for branch and MC/DC records
10527 # Group elements that belong to the same basic record
10528 #
10529 # Returns: [block1, block2, ...] <- in order of increasing block number/group size
10530 # block: [branch1, branch2, ...] <- in order of increasing branch/expression index
10531 # branch: [block_num, branch_num, taken_count, text_length, open, close]
10532 #
10533
10534 sub get_block_list($)
10535 {
10536 my $data = shift;
10537 return () unless defined($data);
10538
10539 my @blocks;
10540
10541 if ('BranchEntry' eq ref($data)) {
10542
10543 my $block = [];
10544 my $last_block_num;
10545
10546 # Group branches
10547 foreach my $block_num (sort $data->blocks()) {
10548 my $blockData = $data->getBlock($block_num);
10549 my $branch = 0;
10550 foreach my $br (@$blockData) {
10551
10552 if (defined($last_block_num) && $block_num != $last_block_num) {
10553 push(@blocks, $block);
10554 $block = [];
10555 }
10556 my $br = [$block_num, $branch, $br, 3, 0, 0];
10557 push(@{$block}, $br);
10558 $last_block_num = $block_num;
10559 ++$branch;
10560 }
10561 }
10562 push(@blocks, $block) if (scalar(@{$block}) > 0);
10563 } else {
10564 die('unexpected ' . ref($data)) unless 'MCDC_Block' eq ref($data);
10565 # Group MC/DC groups
10566 foreach my $groupSize (sort keys %{$data->groups()}) {
10567 my $exprs = $data->groups()->{$groupSize};
10568 my $block = [];
10569 push(@blocks, $block);
10570 foreach my $expr (@$exprs) {
10571 # display 'true' then 'false' sense - to match what we do for branches
10572 # and to match behaviour of ?: operator
10573 foreach my $sense (1, 0) {
10574 my $cond =
10575 [$groupSize, $expr->index(), $sense, $expr, 3, 0, 0];
10576 push(@{$block}, $cond);
10577 }
10578 }
10579 }
10580 }
10581 # Add braces to first and last branch in group
10582 foreach my $block (@blocks) {
10583 $block->[0]->[$BR_OPEN] = 1;
10584 $block->[0]->[$BR_LEN]++;
10585 $block->[$#$block]->[$BR_CLOSE] = 1;
10586 $block->[$#$block]->[$BR_LEN]++;
10587 }
10588 return @blocks;
10589 }
10590
10591 # distribute blocks into lines - trying to keep groups on a single line,
10592 # if possible
10593 sub distribute_blocks($$)
10594 {
10595 my ($blocks, $field_width) = @_;
10596
10597 my $line_len = 0;
10598 my $line = []; # [branch2|" ", branch|" ", ...]
10599 my @lines; # [line1, line2, ...]
10600 my @result;
10601
10602 # Distribute blocks to lines
10603 foreach my $block (@$blocks) {
10604 my $block_len = get_block_len($block);
10605
10606 # Does this block fit into the current line?
10607 if ($line_len + $block_len <= $field_width) {
10608 # Add it
10609 $line_len += $block_len;
10610 push(@{$line}, @{$block});
10611 next;
10612 } elsif ($block_len <= $field_width) {
10613 # It would fit if the line was empty - add it to new line
10614 push(@lines, $line);
10615 $line_len = $block_len;
10616 $line = [@{$block}];
10617 next;
10618 }
10619 # Split the block into several lines
10620 foreach my $branch (@{$block}) {
10621 if ($line_len + $branch->[$BR_LEN] >= $field_width) {
10622 # Start a new line
10623 if (($line_len + 1 <= $field_width) &&
10624 scalar(@{$line}) > 0 &&
10625 !$line->[scalar(@$line) - 1]->[$BR_CLOSE]) {
10626 # Try to align branch symbols to be in
10627 # one # row
10628 push(@{$line}, " ");
10629 }
10630 push(@lines, $line);
10631 $line_len = 0;
10632 $line = [];
10633 }
10634 push(@{$line}, $branch);
10635 $line_len += $branch->[$BR_LEN];
10636 }
10637 }
10638 push(@lines, $line);
10639
10640 return @lines;
10641 }
10642
10643 #
10644 # get_branch_html(brdata, printCallbackStruct)
10645 #
10646 # Return a list of HTML lines which represent the specified branch coverage
10647 # data in source code view.
10648 #
10649
10650 sub get_branch_html($$)
10651 {
10652 my ($brdata, $cbdata) = @_;
10653 my $differentialBranch;
10654 my $fileDetail = $cbdata->sourceDetail();
10655 if (defined($main::show_tla)) {
10656 my $lineNo = $cbdata->lineNo();
10657 my $lineData = $cbdata->lineData()->line($lineNo);
10658 $differentialBranch = $lineData->differential_branch()
10659 if defined($lineData);
10660 }
10661 # build the 'blocks' array from differential data if we have it..
10662 my @blocks = get_block_list(
10663 defined($differentialBranch) ? $differentialBranch : $brdata);
10664
10665 my @lines = distribute_blocks(\@blocks, $br_field_width);
10666
10667 # Convert to HTML
10668 # branch and MC/DC code is similar - but merging only makes things
10669 # more complicated as the details of the text, popups, etc are different
10670 # maybe revisit later
10671 my @result;
10672 my %tlaLinks;
10673
10674 foreach my $line (@lines) {
10675 my $current = "";
10676 my $current_len = 0;
10677
10678 foreach my $branch (@$line) {
10679 # Skip alignment space
10680 if ($branch eq " ") {
10681 $current .= " ";
10682 $current_len++;
10683 next;
10684 }
10685
10686 my ($block_num, $br_num, $br, $len, $open, $close) = @{$branch};
10687
10688 my $class;
10689 my $prefix;
10690 my $tla;
10691 my $base_count;
10692 if ('ARRAY' ne ref($br)) {
10693 # vanilla case - no differential coverage info
10694 die("differential branch coverage but no TLA")
10695 if defined($differentialBranch);
10696 if ($br->data() eq '-') {
10697 $class = "tlaUNC";
10698 } elsif ($br->data() == 0) {
10699 $class = "tlaUNC";
10700 } else {
10701 $class = 'tlaGBC';
10702 }
10703 $prefix = '';
10704 } else {
10705 die("differential branch coverage but no TLA")
10706 unless defined($differentialBranch);
10707 $tla = $br->[1];
10708 $base_count = $br->[2]->[0];
10709 $br = $br->[0];
10710 $class = "tla$tla";
10711 my $label =
10712 $main::use_legacyLabels ?
10713 $SummaryInfo::tlaToLegacySrcLabel{$tla} :
10714 $tla;
10715 $prefix = $label . ": ";
10716 }
10717 my ($char, $title);
10718
10719 my $br_name =
10720 defined($br->expr()) ? '"' . $br->expr() . '"' : $br_num;
10721 my $taken = $br->data();
10722 if ($taken eq '-') {
10723 $char = "#";
10724 $title = "${prefix}Branch $br_name was not executed";
10725 $title .=
10726 " (previously taken $base_count time" .
10727 (1 == $base_count ? '' : 's') . ')'
10728 if (defined($tla) &&
10729 ($tla eq 'LBC' || $tla eq 'ECB'));
10730 } elsif ($taken == 0) {
10731 $char = "-";
10732 $title = "${prefix}Branch $br_name was not taken";
10733 $title .=
10734 " (previously taken $base_count time" .
10735 (1 == $base_count ? '' : 's') . ')'
10736 if (defined($tla) &&
10737 ($tla eq 'LBC' || $tla eq 'ECB'));
10738 } else {
10739 $char = "+";
10740 $title = "${prefix}Branch $br_name was taken $taken time" .
10741 (($taken > 1) ? "s" : "");
10742 }
10743 $title = escape_html($title) if defined($br->expr());
10744 $current .= "[" if ($open);
10745
10746 if (!$main::no_sourceview &&
10747 defined($differentialBranch)) {
10748 my $href;
10749 if (exists($tlaLinks{$tla})) {
10750 $href = $tlaLinks{$tla};
10751 } else {
10752 my $line = $differentialBranch->line();
10753 my $next = $fileDetail->nextBranchTlaGroup($tla, $line);
10754 $href =
10755 "<a href=\"#" . (defined($next) ? "L$next" : 'top') .
10756 "\" title=\"TITLE\" class=\"branchTla\">$char</a>";
10757 $tlaLinks{$tla} = $href;
10758 }
10759 $href =~ s#TITLE#$title#;
10760 $current .= "<span class=\"$class\"> $href </span>";
10761 } else {
10762 $current .=
10763 "<span class=\"$class\" title=\"$title\"> $char </span>";
10764 }
10765 $current .= "]" if ($close);
10766 $current_len += $len;
10767 }
10768
10769 # Right-align result text
10770 if ($current_len < $br_field_width) {
10771 $current = (" " x ($br_field_width - $current_len)) . $current;
10772 }
10773 push(@result, $current);
10774 }
10775
10776 return @result;
10777 }
10778
10779 sub get_mcdc_html($$)
10780 {
10781 # @todo can be shared with branch, MC/DC
10782 my ($mcdc_data, $cbdata) = @_;
10783 my $differentialMcdc;
10784 my $fileDetail = $cbdata->sourceDetail();
10785 if (defined($main::show_tla)) {
10786 my $lineNo = $cbdata->lineNo();
10787 my $lineData = $cbdata->lineData()->line($lineNo);
10788 $differentialMcdc = $lineData->differential_mcdc()
10789 if defined($lineData);
10790 }
10791 # build the 'blocks' array from differential data if we have it..
10792 my @blocks = get_block_list(
10793 defined($differentialMcdc) ? $differentialMcdc : $mcdc_data);
10794
10795 my @lines = distribute_blocks(\@blocks, $mcdc_field_width);
10796
10797 # Convert to HTML
10798 # branch and MC/DC code is similar - but merging only makes things
10799 # more complicated as the details of the text, popups, etc are different
10800 # maybe revisit later
10801 my @result;
10802 my %tlaLinks;
10803
10804 foreach my $line (@lines) {
10805 my $current = "";
10806 my $current_len = 0;
10807
10808 foreach my $cond (@$line) {
10809 # Skip alignment space
10810 unless ('ARRAY' eq ref($cond)) {
10811 die("unexpected 'cond' entry '$cond'") unless ($cond eq " ");
10812 $current .= " ";
10813 $current_len++;
10814 next;
10815 }
10816
10817 my ($groupSize, $exprIdx, $sense, $expr, $len, $open, $close) =
10818 @$cond;
10819 die("unexpected expr type") unless ref($expr) eq 'MCDC_Expression';
10820
10821 my $count = $expr->count($sense);
10822 my $taken;
10823 my $class;
10824 my $prefix;
10825 my $tla;
10826 my $base_count;
10827 if ('ARRAY' ne ref($count)) {
10828 # vanilla case - no differential coverage info
10829 die("differential MC/DC coverage but no TLA")
10830 if defined($differentialMcdc);
10831 $taken = $count;
10832 if ($count == 0) {
10833 $class = "tlaUNC";
10834 } else {
10835 $class = 'tlaGBC';
10836 }
10837 $prefix = '';
10838 } else {
10839 die("differential MC/DC coverage but no TLA")
10840 unless defined($differentialMcdc);
10841 ($tla, $base_count, $taken) = @$count;
10842
10843 $class = "tla$tla";
10844 my $label =
10845 $main::use_legacyLabels ?
10846 $SummaryInfo::tlaToLegacySrcLabel{$tla} :
10847 $tla;
10848 $prefix = $label . ": ";
10849 }
10850 my ($char, $title);
10851
10852 my $expr_name = $expr->expression();
10853 $title = ${prefix} . ($sense ? 'True' : 'False') .
10854 ' sense of expression "' . $expr->expression() . '" ';
10855 if ($expr->parent()->num_groups() > 1) {
10856 $title .= 'in group "' . $expr->groupSize() . '" ';
10857 }
10858
10859 if (!defined($taken)) {
10860 $char = '-';
10861 $title .= 'was dropped';
10862 $title .=
10863 ' (previously ' .
10864 (1 == $base_count ? '' : 'not ') . 'sensitized)'
10865 if (defined($tla) &&
10866 ($tla eq 'LBC' || $tla eq 'ECB'));
10867
10868 } elsif ($taken == 0) {
10869 $char = $sense ? 't' : 'f';
10870 $title .= 'was not sensitized';
10871 $title .=
10872 ' (previously ' .
10873 (1 == $base_count ? '' : 'not ') . 'sensitized)'
10874 if (defined($tla) &&
10875 ($tla eq 'LBC' || $tla eq 'ECB'));
10876 } else {
10877 $char = $sense ? 'T' : 'F';
10878 $title .= 'was sensitized';
10879 }
10880 $title = escape_html($title);
10881 $current .= "[" if ($open);
10882
10883 if (!$main::no_sourceview &&
10884 defined($differentialMcdc)) {
10885 my $href;
10886 if (exists($tlaLinks{$tla})) {
10887 $href = $tlaLinks{$tla};
10888 } else {
10889 my $line = $differentialMcdc->line();
10890 my $next = $fileDetail->nextMcdcTlaGroup($tla, $line);
10891 $href =
10892 "<a href=\"#" . (defined($next) ? "L$next" : 'top') .
10893 "\" title=\"TITLE\" class=\"mcdcTla\">SENSE</a>";
10894 # cache the href as 'next' lookup is moderately expensive
10895 $tlaLinks{$tla} = $href;
10896 }
10897 # keep the link but update the sense character
10898 $href =~ s/SENSE/$char/;
10899 $href =~ s#TITLE#$title#;
10900 $current .= "<span class=\"$class\"> $href </span>";
10901 } else {
10902 $current .=
10903 "<span class=\"$class\" title=\"$title\"> $char </span>";
10904 }
10905 $current .= "]" if ($close);
10906 $current_len += $len;
10907 }
10908
10909 # Right-align result text
10910 if ($current_len < $mcdc_field_width) {
10911 $current = (" " x ($mcdc_field_width - $current_len)) . $current;
10912 }
10913 push(@result, $current);
10914 }
10915
10916 return @result;
10917 }
10918
10919 #
10920 # format_count(count, width)
10921 #
10922 # Return a right-aligned representation of count that fits in width characters.
10923 #
10924
10925 sub format_count($$)
10926 {
10927 my ($count, $width) = @_;
10928 my $result;
10929 my $exp;
10930 my $negative = 0 > $count;
10931 if ($negative) {
10932 $width -= 2;
10933 $count = -$count;
10934 }
10935
10936 $result = sprintf("%*.0f", $width, $count);
10937 while (length($result) > $width) {
10938 last if ($count < 10);
10939 $exp++;
10940 $count = int($count / 10);
10941 $result = sprintf("%*s", $width, ">$count*10^$exp");
10942 }
10943 if ($negative) {
10944 # surround number with parens
10945 $result =~ s/^( *)(\S+)$/$1\($2\)/;
10946 }
10947 return $result;
10948 }
10949
10950 #
10951 # write_source_line(filehandle, cbdata, source, hit_count, brdata, mcdc,
10952 # printCallbackStruct)
10953 #
10954 # Write formatted source code line. Return a line in a format as needed
10955 # by gen_png()
10956 #
10957
10958 sub write_source_line(*$$$$$$$)
10959 {
10960 my ($handle, $srcline, $count, $showBranches, $brdata, $showMcdc, $mcdc,
10961 $cbdata)
10962 = @_;
10963 my $line = $cbdata->lineNo();
10964 my $fileCovInfo = $cbdata->lineData();
10965 my $sourceDetail = $cbdata->sourceDetail();
10966 my $source = $srcline->text();
10967 my $src_owner = $srcline->owner();
10968 my $src_age = $srcline->age();
10969 my $source_format;
10970 my $count_format;
10971 my $result;
10972 my $anchor_start = "";
10973 my $anchor_end = "";
10974 my $count_field_width = $line_field_width - 1;
10975 my $html;
10976 my $tla;
10977 my $base_count;
10978 my $curr_count;
10979 my $bucket;
10980
10981 my @prevData = ($cbdata->current('tla'),
10982 $cbdata->current('owner'),
10983 $cbdata->current('age'));
10984
10985 # Get branch HTML data for this line
10986 my @br_html = get_branch_html($brdata, $cbdata) if ($showBranches);
10987
10988 my @mcdc_html = get_mcdc_html($mcdc, $cbdata) if ($showMcdc);
10989
10990 my $thisline = $fileCovInfo->lineMap()->{$line};
10991 my $tlaIsHref;
10992 if (!defined($thisline) ||
10993 (!defined($count) &&
10994 !($thisline->in_base() || $thisline->in_curr()))
10995 ) {
10996 $result = "";
10997 $source_format = "";
10998 $count_format = " " x $count_field_width;
10999 $tla = $cbdata->tla(undef, $line);
11000 } else {
11001 $base_count = $thisline->base_count();
11002 $curr_count = $thisline->curr_count();
11003 $bucket = $thisline->tla();
11004 # use callback data to keep track of the most recently seen TLA -
11005 # $tla is either " " (3 spaces) if same as previous or if no TLA
11006 # we just stick "TLA " (4 characters) into the fixed-with source
11007 # line - right before the count.
11008 $tla = $cbdata->tla($bucket, $line);
11009 my $class = "tla$bucket";
11010 if ($main::show_tla && $tla =~ /$bucket/) {
11011 # maybe we want to link only the uncovered code categories?
11012 my $next = $sourceDetail->nextTlaGroup($bucket, $line);
11013 $tlaIsHref = 1;
11014 # if no next segment in this category - then go to top to page.
11015 $next = defined($next) ? "L$next" : "top";
11016 my $anchorClass = "";
11017 if ($bucket ne 'UNK') {
11018 $class .= " tlaBg$bucket";
11019 $anchorClass = " class=\"tlaBg$bucket\" ";
11020 }
11021 my $label =
11022 $main::use_legacyLabels ?
11023 $SummaryInfo::tlaToLegacySrcLabel{$bucket} :
11024 $bucket;
11025 my $popup = " title=\"Next $label group\"";
11026 $label .= ' ' x ($main::tla_field_width - length($label));
11027 $tla = "<a href=\"#$next\"$anchorClass$popup>$label</a>";
11028 }
11029 $source_format = "<span class=\"$class\">";
11030
11031 my $pchar;
11032 if (exists($lcovutil::pngChar{$bucket})) {
11033 $pchar = $lcovutil::pngChar{$bucket};
11034 } else {
11035 lcovutil::ignorable_error($lcovutil::ERROR_UNKNOWN_CATEGORY,
11036 "unexpected TLA '$bucket'");
11037 $pchar = '';
11038 $count = 0 unless defined($count);
11039 }
11040 if ($bucket eq "ECB" ||
11041 $bucket eq "EUB") {
11042 !defined($count) or
11043 die("excluded code should have undefined count");
11044 # show previous count for excluded code that had been hit
11045 if ($bucket eq "ECB") {
11046 $count_format = format_count(-$base_count, $count_field_width);
11047 } else {
11048 $count_format = " " x $count_field_width;
11049 }
11050 $result = $pchar . $base_count;
11051 } else {
11052 if (!defined($count)) {
11053 # this is manufactured data...make something up
11054 $count = $curr_count;
11055 }
11056 defined($count) && "" ne $count or
11057 die("code should have defined count");
11058 if ($bucket eq 'LBC') {
11059 $count_format = format_count(-$base_count, $count_field_width);
11060 } else {
11061 $count_format = format_count($count, $count_field_width);
11062 }
11063 $result = $pchar . $count;
11064 }
11065 # '$result' is used to generate the PNG frame
11066 info(2,
11067 " $bucket: line=$line " .
11068 (defined($count) ? "count= $count " : "") . ' curr=' .
11069 (defined($curr_count) ? $curr_count : '-') . ' base=' .
11070 (defined($base_count) ? $base_count : '-') . "\n");
11071 }
11072 $result .= ":" . $source;
11073
11074 my $tooltip =
11075 @SourceFile::annotateScript ? $SourceFile::annotateTooltip : '';
11076 if ($tooltip ne '') {
11077 my $lineData = $sourceDetail->line($line);
11078 my $commitId = $lineData->commit();
11079 if (defined($commitId) &&
11080 $commitId ne 'NONE') {
11081 my $date = $lineData->date();
11082 $date =~ s/(T.+)$//; # just the year/month/day part
11083 foreach my $p (['%U', $lineData->owner()],
11084 ['%F', $lineData->full_name()],
11085 ['%D', $lineData->date()],
11086 ['%d', $date],
11087 ['%A', $lineData->age()],
11088 ['%C', $commitId],
11089 ['%l', $line],
11090 ) {
11091 $tooltip =~ s/$p->[0]/$p->[1]/g;
11092 }
11093 $tooltip = " title=\"$tooltip\"";
11094 } else {
11095 $tooltip = '';
11096 }
11097 }
11098 # Write out a line number navigation anchor every $nav_resolution
11099 # lines if necessary
11100 $anchor_start = "<span id=\"L$line\"$tooltip>";
11101 $anchor_end = "</span>";
11102
11103 # *************************************************************
11104
11105 $html = $anchor_start;
11106 # we want to colorize the date/owner part of un-hit lines only
11107 my $html_continuation_leader = ""; # for continued lines
11108 if (defined($main::show_dateBins) &&
11109 $sourceDetail->isProjectFile()) {
11110 DATE_SECTION: {
11111
11112 my $ageLen = $main::age_field_width;
11113 my $ownerLen = $main::owner_field_width;
11114
11115 # need to space over on continuation lines
11116 $html_continuation_leader = ' ' x ($ageLen + $ownerLen + 2);
11117
11118 if (!defined($count) &&
11119 (!defined($main::show_nonCodeOwners) ||
11120 0 == $main::show_nonCodeOwners)
11121 &&
11122 ( !defined($bucket) ||
11123 ($bucket ne 'EUB' &&
11124 $bucket ne 'ECB'))
11125 ) {
11126 # suppress date- and owner entry on non-code lines
11127 $html .= $html_continuation_leader;
11128 last DATE_SECTION;
11129 }
11130
11131 my $span = "";
11132 my $endspan = "";
11133 my $bgclass = "";
11134 if (defined($count) && 0 == $count) {
11135 # probably want to pick a color based on which
11136 # date bin it is in.
11137 # right now, picking based on TLA.
11138 $bgclass = " class=\"tlaBg$bucket\""
11139 if (defined($bucket) &&
11140 $bucket ne "EUB" &&
11141 $bucket ne "ECB");
11142
11143 #$html .= "<span class=\"missBins\">";
11144 if ("" ne $source_format) {
11145 OWNER: {
11146 if (!defined($src_owner) || !defined($src_age)) {
11147 # maybe this should be a different error type?
11148 lcovutil::ignorable_eror(
11149 $lcovutil::ERROR_UNMAPPED_LINE,
11150 "undefined owner/age for $bucket $line " .
11151 $sourceDetail->path());
11152 last OWNER;
11153 }
11154 # add a 'title="tooltip"' popup - to give owner, date, etc
11155 my $title = "span title=\"$src_owner $src_age days ago";
11156 if (defined($main::show_dateBins)) {
11157 my $bin = SummaryInfo::findAgeBin($src_age);
11158 $title .=
11159 " (bin $bin: " .
11160 $SummaryInfo::ageGroupHeader[$bin] . ")";
11161 }
11162 $title .= "\"";
11163 $span = $source_format;
11164 $span =~ s/span/$title/;
11165 $endspan = "</span>";
11166 }
11167 }
11168 } # OWNER block
11169
11170 # determine if this line is going to be the target of a 'date', 'owner'
11171 # or TLA navigation href.
11172 # - is is possible for any of these to have changed from the previous
11173 # line, even if the others are unchanged:
11174 # - same TLA but different author
11175 # - same author but different date bin, .. and so on
11176 # If it is a leader, then we need to insert the 'owner' and/or 'date'
11177 # link to go to the next group in this bin - even if the owner or
11178 # date bin has not changed from the previous line)
11179 my $tlaChanged = defined($bucket) && $prevData[0] ne $bucket;
11180
11181 my $needOwnerHref = @SourceFile::annotateScript &&
11182 ($tlaChanged ||
11183 (defined($bucket) && $prevData[1] ne $src_owner));
11184
11185 my $newBin = SummaryInfo::findAgeBin($src_age);
11186 defined($prevData[2]) || $line == 1 or
11187 die("unexpected uninitialized age");
11188
11189 my $needDateHref = (
11190 $tlaChanged || (defined($bucket) &&
11191 SummaryInfo::findAgeBin($prevData[2]) != $newBin)
11192 );
11193
11194 if ($needDateHref) {
11195 my $matchLine = $cbdata->nextDate($newBin, $bucket);
11196 $needDateHref = 0
11197 if (defined($matchLine) && $matchLine != $line);
11198 }
11199 if ($needOwnerHref) {
11200 # slightly complicated logic:
11201 # - there can be non-code lines owned by someone else
11202 # between code lines owned by '$src_owner', such that the
11203 # all the code lines have the same TLA.
11204 # In that case, we just insert an href at the top of the
11205 # block to take us past all of of them - to the next code block
11206 # owned by $src_owner with this TLA, which separated by at least
11207 # one line of code either owned by someone else, or with a different
11208 # TLA.
11209 my $matchLine = $cbdata->nextOwner($src_owner, $bucket);
11210 # don't insert the owner href if this isn't the line we wanted
11211 $needOwnerHref = 0
11212 if (defined($matchLine) && $matchLine != $line);
11213 }
11214
11215 my $age = $cbdata->age($src_age, $line);
11216 my $owner = $cbdata->owner($src_owner);
11217
11218 # this HTML block turns into
11219 # "<span ...>int name</span> " <- note trailing space
11220 # .. but the age and name might be hrefs
11221
11222 $html .= $span;
11223 # then 5 characters of 'age' (might be empty)
11224 if ($needDateHref) {
11225 # next line with this TLA, in this date bin
11226 my $next =
11227 $sourceDetail->nextInDateBin($newBin, $bucket, $line);
11228 $cbdata->nextDate($newBin, $bucket, $next);
11229
11230 $next = defined($next) ? "L$next" : "top";
11231 my $dateBin = $SummaryInfo::ageGroupHeader[$newBin];
11232 my $label =
11233 $main::use_legacyLabels ?
11234 $SummaryInfo::tlaToLegacySrcLabel{$bucket} :
11235 $bucket;
11236 my $popup =
11237 " title=\"next $label in &ldquo;$dateBin&rdquo; bin\"";
11238 $html .= ((' ' x ($ageLen - length($src_age))) .
11239 "<a href=\"#$next\"$popup$bgclass>$src_age</a> ");
11240 } else {
11241 $html .= sprintf("%${ageLen}s ", $age);
11242 }
11243
11244 if ($needOwnerHref) {
11245 # next line with this TLA, by this owner..
11246 my $next =
11247 $sourceDetail->nextInOwnerBin($src_owner, $bucket, $line);
11248 $cbdata->nextOwner($src_owner, $bucket, $next);
11249 $next = defined($next) ? "L$next" : "top";
11250 my $label =
11251 $main::use_legacyLabels ?
11252 $SummaryInfo::tlaToLegacySrcLabel{$bucket} :
11253 $bucket;
11254 my $popup =
11255 " title=\"next $label in &ldquo;" .
11256 escape_html($src_owner) . "&rdquo; bin\"";
11257 # NOTE: see note below about firefox nested span bug.
11258 # this code just arranges to wrap an explicit 'span' around
11259 # the space.
11260 my $nspace = $ownerLen - length($src_owner);
11261 my $space = $nspace > 0 ? (' ' x $nspace) : '';
11262 my $href = "<a href=\"#$next\"$popup$bgclass>" .
11263 escape_html(substr($src_owner, 0, $ownerLen)) . '</a>';
11264 if ('' ne $bgclass &&
11265 '' ne $space) {
11266 $html .= "$endspan$href$span";
11267 } else {
11268 $html .= $href;
11269 }
11270 $html .= $space;
11271 } else {
11272 $html .= sprintf("%-${ownerLen}s", $owner);
11273 }
11274 $html .= $endspan . ' '; # add trailing space
11275 }
11276 } # DATE_SECTION
11277
11278 # use a different HTML tag if there are deleted lines here
11279 my $deletedLines = $fileCovInfo->deletedLineData($line);
11280 my $lineNumTag = 'lineNum';
11281 my $lineNumTitle = '';
11282 if (defined($deletedLines)) {
11283 my $first = $deletedLines->[0]->lineNo('base');
11284 my $last = $deletedLines->[-1]->lineNo('base');
11285 die("invalid deleted lines array") unless $first <= $last;
11286 $lineNumTitle = ' title="'
11287 .
11288 (($first != $last) ? "removed lines [$first:$last]" :
11289 "removed line $first") .
11290 ' from baseline version"';
11291 $lineNumTag = 'lineNumWithDelete';
11292 }
11293 my $lineNumSpan = "<span class=\"$lineNumTag\"$lineNumTitle>";
11294
11295 $html .= sprintf("$lineNumSpan%8d</span> ", $line);
11296 #printf("tla= " . $tla);
11297 #printf("html= " . $html);
11298
11299 $html .= shift(@br_html) . ":" if ($showBranches);
11300 $html .= shift(@mcdc_html) . ":" if ($showMcdc);
11301
11302 $tla = ""
11303 if (!defined($main::show_tla));
11304
11305 # 'source_format is the colorization, then the 3-letter TLA,
11306 # then the hit count, then the source line
11307 if ($tlaIsHref) {
11308 # there seems to be a bug in firefox:
11309 # <span class="foo"><a href...>link</a> whatever</span>
11310 # renders as if the 'span' didn't exist (so the colorization of the
11311 # link end - and the rest of the line doesn't pick up attributes
11312 # from class 'foo'.
11313 # If I emit it as:
11314 # <a href...>link</a><span ....> wheatever</span>
11315 # (i.e., do not nest anchor inside the span) - then it works
11316 $html .= "$tla$source_format $count_format : ";
11317 } else {
11318 $html .= "$source_format$tla $count_format : ";
11319 }
11320
11321 $html .= escape_html($source);
11322 $html .= "</span>" if ($source_format);
11323 $html .= $anchor_end . "\n";
11324
11325 write_html($handle, $html);
11326
11327 # Add lines for overlong branch and/or MC/DC information
11328 while (@br_html || @mcdc_html) {
11329 my $br = @br_html ? shift(@br_html) : '';
11330 my $mc = @mcdc_html ? shift(@mcdc_html) : '';
11331 if ($mc) {
11332 # space over far enough to line up with MC/DC extension column
11333 # remove the span and other HTML
11334 my $s = $br;
11335 foreach my $tag ('a', 'span') {
11336 $s =~ s/(<\/$tag>|<$tag.+?>)//g;
11337 }
11338 $br .= ' ' x ($br_field_width - length($s)) . ' ';
11339 die("unexpected lengths") unless $br_field_width >= length($s);
11340 }
11341 write_html($handle,
11342 "$html_continuation_leader$lineNumSpan" .
11343 ' ' x 8 . "</span> $br$mc\n");
11344 }
11345 # *************************************************************
11346
11347 return ($result);
11348 }
11349
11350 #
11351 # write_source_epilog(filehandle)
11352 #
11353 # Write end of source code table.
11354 #
11355
11356 sub write_source_epilog(*)
11357 {
11358 # *************************************************************
11359
11360 write_html($_[0], <<END_OF_HTML);
11361 </pre>
11362 </td>
11363 </tr>
11364 </table>
11365 <br>
11366
11367 END_OF_HTML
11368
11369 # *************************************************************
11370 }
11371
11372 #
11373 # write_html_epilog(filehandle, base_dir[, break_frames])
11374 #
11375 # Write HTML page footer to FILEHANDLE. BREAK_FRAMES should be set when
11376 # this page is embedded in a frameset, clicking the URL link will then
11377 # break this frameset.
11378 #
11379
11380 sub write_html_epilog(*$;$)
11381 {
11382 my $basedir = $_[1];
11383 my $break_code = "";
11384 my $epilog;
11385
11386 if (defined($_[2])) {
11387 $break_code = " target=\"_parent\"";
11388 }
11389 my $f =
11390 defined($main::footer) ? $footer :
11391 "Generated by: <a href=\"$lcov_url\"$break_code>$lcov_version</a>";
11392
11393 # *************************************************************
11394
11395 write_html($_[0], <<END_OF_HTML);
11396 <table width="100%" border=0 cellspacing=0 cellpadding=0>
11397 <tr><td class="ruler"><img src="$_[1]glass.png" width=3 height=3 alt=""></td></tr>
11398 <tr><td class="versionInfo">$f</td></tr>
11399 </table>
11400 <br>
11401 END_OF_HTML
11402
11403 $epilog = $html_epilog;
11404 $epilog =~ s/\@basedir\@/$basedir/g;
11405
11406 write_html($_[0], $epilog);
11407 }
11408
11409 #
11410 # write_frameset(filehandle, basedir, basename, pagetitle)
11411 #
11412 #
11413
11414 sub write_frameset(*$$$)
11415 {
11416 my $frame_width = $overview_width + 40;
11417
11418 # *************************************************************
11419
11420 write_html($_[0], <<END_OF_HTML);
11421 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN">
11422
11423 <html lang="en">
11424
11425 <head>
11426 <meta http-equiv="Content-Type" content="text/html; charset=$charset">
11427 <title>$_[3]</title>
11428 <link rel="stylesheet" type="text/css" href="$_[1]gcov.css">
11429 </head>
11430
11431 <frameset cols="$frame_width,*">
11432 <frame src="$_[2].gcov.overview.$html_ext" name="overview">
11433 <frame src="$_[2].gcov.$html_ext" name="source">
11434 <noframes>
11435 <center>Frames not supported by your browser!<br></center>
11436 </noframes>
11437 </frameset>
11438
11439 </html>
11440 END_OF_HTML
11441
11442 # *************************************************************
11443 }
11444
11445 #
11446 # sub write_overview_line(filehandle, basename, line, link)
11447 #
11448 #
11449
11450 sub write_overview_line(*$$$)
11451 {
11452 my $y1 = $_[2] - 1;
11453 my $y2 = $y1 + $nav_resolution - 1;
11454 my $x2 = $overview_width - 1;
11455
11456 # *************************************************************
11457
11458 write_html($_[0], <<END_OF_HTML);
11459 <area shape="rect" coords="0,$y1,$x2,$y2" href="$_[1].gcov.$html_ext#L$_[3]" target="source" alt="overview">
11460 END_OF_HTML
11461
11462 # *************************************************************
11463 }
11464
11465 #
11466 # write_overview(filehandle, basedir, basename, pagetitle, lines)
11467 #
11468 #
11469
11470 sub write_overview(*$$$$)
11471 {
11472 my $index;
11473 my $max_line = $_[4] - 1;
11474 my $offset;
11475
11476 # *************************************************************
11477
11478 write_html($_[0], <<END_OF_HTML);
11479 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
11480
11481 <html lang="en">
11482
11483 <head>
11484 <title>$_[3]</title>
11485 <meta http-equiv="Content-Type" content="text/html; charset=$charset">
11486 <link rel="stylesheet" type="text/css" href="$_[1]gcov.css">
11487 </head>
11488
11489 <body>
11490 <map name="overview">
11491 END_OF_HTML
11492
11493 # *************************************************************
11494
11495 # Make $offset the next higher multiple of $nav_resolution
11496 $offset = ($nav_offset + $nav_resolution - 1) / $nav_resolution;
11497 $offset = sprintf("%d", $offset) * $nav_resolution;
11498
11499 # Create image map for overview image
11500 for ($index = 1; $index <= $_[4]; $index += $nav_resolution) {
11501 # Enforce nav_offset
11502 if ($index < $offset + 1) {
11503 write_overview_line($_[0], $_[2], $index, 1);
11504 } else {
11505 write_overview_line($_[0], $_[2], $index, $index - $offset);
11506 }
11507 }
11508
11509 # *************************************************************
11510 my $f = $lcovutil::case_insensitive ? lc($_[2]) : $_[2];
11511 write_html($_[0], <<END_OF_HTML);
11512 </map>
11513
11514 <center>
11515 <a href="$f.gcov.$html_ext" target="source">Top</a><br><br>
11516 <img src="$f.gcov.png" width=$overview_width height=$max_line alt="Overview" border=0 usemap="#overview">
11517 </center>
11518 </body>
11519 </html>
11520 END_OF_HTML
11521
11522 # *************************************************************
11523 }
11524
11525 sub max($$)
11526 {
11527 my ($a, $b) = @_;
11528
11529 return $a if ($a > $b);
11530 return $b;
11531 }
11532
11533 sub buildDateSummaryTable($$$$$$$$$)
11534 {
11535 my ($summary, $covType, $covCountCallback,
11536 $fileDetail, $nextLocationCallback, $title,
11537 $detailLink, $numRows, $activeTlaList) = @_;
11538
11539 $title =
11540 "<a href=\"$detailLink\" title=\"Click to include date bin details in file table below\">$title</a>"
11541 if (defined($detailLink));
11542
11543 my @table;
11544
11545 my @dateSummary = [undef, #width
11546 "subTableHeader", # class
11547 $title, # text
11548 $numRows, # colspan
11549 ];
11550 # only insert the label if there is data
11551 my $first = 1;
11552 my $page = $detailLink;
11553 if (defined($page)) {
11554 $page =~ s/^index/index-bin_/;
11555 $page =~ s/^index-bin_-/index-bin_/;
11556 }
11557
11558 my ($lim_med, $lim_high);
11559 if ($covType == SummaryInfo::LINE_DATA) {
11560 $lim_med = $ln_med_limit;
11561 $lim_high = $ln_hi_limit;
11562 } elsif ($covType == SummaryInfo::BRANCH_DATA) {
11563 $lim_med = $br_med_limit;
11564 $lim_high = $br_hi_limit;
11565 } elsif ($covType == SummaryInfo::MCDC_DATA) {
11566 $lim_med = $mcdc_med_limit;
11567 $lim_high = $mcdc_hi_limit;
11568 } elsif ($covType == SummaryInfo::FUNCTION_DATA) {
11569 $lim_med = $fn_med_limit;
11570 $lim_high = $fn_hi_limit;
11571 } else {
11572 die("unexpected cover type $covType");
11573 }
11574 for (my $bin = 0; $bin <= $#SummaryInfo::ageGroupHeader; ++$bin) {
11575 my $ageval = $summary->age_sample($bin);
11576 my $found = &$covCountCallback($summary, "found", "age", $ageval);
11577 next
11578 if 0 == $found;
11579 my $hit = &$covCountCallback($summary, "hit", "age", $ageval);
11580 my $style =
11581 $rate_name[classify_rate($found, $hit, $lim_med, $lim_high)];
11582 my $rate = rate($hit, $found, "&nbsp;%");
11583 my $href = $SummaryInfo::ageGroupHeader[$bin];
11584 if (defined($detailLink)) {
11585 $href =
11586 "<a href=\"$page#B$bin\" title=\"Click to go to coverage summary for the period '$href'\">$href</a>";
11587 }
11588 $hit -= $found # negative number
11589 if ($main::opt_missed);
11590 my @dataRow = ([undef, "headerItem", $href . ":"],
11591 [undef, "headerCovTableEntry$style", $rate],
11592 [undef, "headerCovTableEntry", $found]);
11593 if ($main::show_hitTotalCol) {
11594 push(@dataRow, [undef, "headerCovTableEntry", $hit]);
11595 }
11596 if ($main::show_tla) {
11597 for my $tla (@$activeTlaList) {
11598 my $value = &$covCountCallback($summary, $tla, "age", $ageval);
11599 my $class =
11600 !$main::use_legacyLabels &&
11601 0 != $value &&
11602 grep(/^$tla$/, ("UNC", "LBC", "UIC")) ? "tla$tla" :
11603 "headerCovTableEntry";
11604 # suppress zeros - make table less busy/easier to read
11605 if ("0" eq $value) {
11606 $value = "";
11607 } elsif (!$main::no_sourceview &&
11608 defined($fileDetail) &&
11609 defined($nextLocationCallback) &&
11610 !grep(/^$tla$/, ('DUB', 'DCB'))) {
11611 # no link for deleted lines (DUB, DCB) because there
11612 # is no TLA for those categories at the location in
11613 # the 'current' sourceview. That location is just a
11614 # normal line - maybe "not code", maybe 'CBC' or some
11615 # other TLA.
11616
11617 # link to first entry
11618 my $firstAppearance =
11619 &$nextLocationCallback($fileDetail, $bin, $tla);
11620 defined($firstAppearance) or
11621 die(
11622 "$tla: unexpected date bin $bin undef appearance for "
11623 . $fileDetail->path());
11624 my $dateBin = $SummaryInfo::ageGroupHeader[$bin];
11625 my ($label, $color);
11626 if ($main::use_legacyLabels) {
11627 $label = $SummaryInfo::tlaToLegacy{$tla};
11628 $color = "";
11629 } else {
11630 $label = $tla;
11631 $color = " class=\"tlaBg$tla\"";
11632 }
11633 my $popup =
11634 " title=\"goto first $label " .
11635 SummaryInfo::type2str($covType) .
11636 " in &ldquo;$dateBin&rdquo; bin\"";
11637 $value =
11638 "<a href=\"#L$firstAppearance\"$popup$color>$value</a>";
11639 }
11640 push(@dataRow, [undef, $class, $value]);
11641 }
11642 }
11643 if ($first) {
11644 push(@table, \@dateSummary);
11645 $first = 0;
11646 }
11647 push(@table, \@dataRow);
11648 }
11649 return \@table;
11650 }
11651
11652 sub buildOwnerSummaryTable($$$$$$$$$$)
11653 {
11654 my ($ownerList, $num_truncated, $summary,
11655 $covType, $fileDetail, $nextLocationCallback,
11656 $title, $detailLink, $numRows,
11657 $activeTlaList) = @_;
11658
11659 $title .= " (containing " .
11660 ($main::show_ownerBins ? "" : "un-exercised ") . "code)";
11661 $title .=
11662 ": $num_truncated author" .
11663 ($num_truncated == 1 ? '' : 's') . ' truncated'
11664 if $num_truncated;
11665
11666 $title =
11667 "<a href=\"$detailLink\" title=\"Click to include ownership details in file table\">$title</a>"
11668 if (defined($detailLink));
11669
11670 my $page = $detailLink;
11671 if (defined($page)) {
11672 $page =~ s/^index/index-bin_/;
11673 $page =~ s/^index-bin_-/index-bin_/;
11674 }
11675
11676 my @table;
11677 my @ownerSummary = [undef, #width
11678 "subTableHeader", # class
11679 $title, # text
11680 $numRows, # colspan
11681 ];
11682
11683 my ($lim_med, $lim_high);
11684 if ($covType == SummaryInfo::LINE_DATA) {
11685 $lim_med = $ln_med_limit;
11686 $lim_high = $ln_hi_limit;
11687 } elsif ($covType eq SummaryInfo::BRANCH_DATA) {
11688 $lim_med = $br_med_limit;
11689 $lim_high = $br_hi_limit;
11690 } elsif ($covType eq SummaryInfo::MCDC_DATA) {
11691 $lim_med = $mcdc_med_limit;
11692 $lim_high = $mcdc_hi_limit;
11693 } elsif ($covType eq SummaryInfo::FUNCTION_DATA) {
11694 $lim_med = $fn_med_limit;
11695 $lim_high = $fn_hi_limit;
11696 } else {
11697 die("unexpected cover type $covType");
11698 }
11699 my $first = 1;
11700 # owners are sorted from most uncovered lines to least
11701 foreach my $od (@$ownerList) {
11702 my ($name, $lineData, $branchData) = @$od;
11703 my $d = ($covType == SummaryInfo::LINE_DATA) ? $lineData : $branchData;
11704 my ($missed, $found) = @$d;
11705
11706 # only put user in table if they are responsible for at least one point
11707 next if $found == 0 or ($missed == 0 && $main::show_ownerBins ne 'all');
11708
11709 if ($first) {
11710 $first = 0;
11711 push(@table, \@ownerSummary);
11712 }
11713 my $hit = $found - $missed;
11714
11715 my $style =
11716 $rate_name[classify_rate($found, $hit, $lim_med, $lim_high)];
11717 my $rate = rate($hit, $found, '&nbsp;%');
11718
11719 my $esc_name = escape_html($name);
11720 my $href = $esc_name;
11721 if (defined($detailLink)) {
11722 $href =
11723 "<a href=\"$page#N" . escape_id($name) .
11724 "\" title=\"Click to go to coverage summary for owner '$esc_name'\">$esc_name</a>";
11725 }
11726 $hit -= $found # negative number
11727 if ($main::opt_missed);
11728 my @dataRow = ([undef, "headerItem", $href . ":"],
11729 [undef, "owner_coverPer$style", $rate],
11730 [undef, "ownerTla", $found]);
11731 if ($main::show_hitTotalCol) {
11732 push(@dataRow, [undef, "ownerTla", $hit]);
11733 }
11734 if ($main::show_tla) {
11735 for my $tla (@$activeTlaList) {
11736 my $value = $summary->owner_tlaCount($name, $tla, $covType);
11737 # suppress zeros - make table less busy/easier to read
11738 my $class =
11739 !$main::use_legacyLabels &&
11740 0 != $value &&
11741 grep(/^$tla$/, ("UNC", "LBC", "UIC")) ? "tla$tla" :
11742 "ownerTla";
11743 if ("0" eq $value) {
11744 $value = "";
11745 } elsif (!$main::no_sourceview &&
11746 defined($fileDetail) &&
11747 defined($nextLocationCallback)) {
11748 my $firstAppearance =
11749 &$nextLocationCallback($fileDetail, $name, $tla);
11750 defined($firstAppearance) or
11751 die(
11752 "$tla: unexpected owner $name undef appearance for " .
11753 $fileDetail->path());
11754 my ($label, $color);
11755 if ($main::use_legacyLabels) {
11756 $label = $SummaryInfo::tlaToLegacy{$tla};
11757 $color = "";
11758 } else {
11759 $label = $tla;
11760 $color = " class=\"tlaBg$tla\"";
11761 }
11762 my $popup =
11763 " title=\"goto first $label " .
11764 SummaryInfo::type2str($covType) .
11765 " in &ldquo;$name&rdquo; bin\"";
11766 $value =
11767 "<a href=\"#L$firstAppearance\"$popup$color>$value</a>";
11768 }
11769 push(@dataRow, [undef, $class, $value]);
11770 }
11771 }
11772 push(@table, \@dataRow);
11773 }
11774 return \@table;
11775 }
11776
11777 sub buildHeaderSummaryTableRow
11778 {
11779 my ($summary, $covType, $fileDetail, $nextLocationCallback, $activeTlaList)
11780 = @_;
11781
11782 $fileDetail = undef
11783 if (!$main::show_tla &&
11784 (defined($fileDetail) && !$fileDetail->isProjectFile()));
11785 my @row;
11786 for my $tla (@$activeTlaList) {
11787 my $value = $summary->get($tla, $covType);
11788 # for the moment, no background colorization for non-zero counts
11789 # in "concerning" categories. The table header is immediately
11790 # above - so no need to colorize to draw emphasis - just makes the
11791 # table busier
11792 my $showConcerningTla = 0;
11793 my $class =
11794 $showConcerningTla &&
11795 !$main::use_legacyLabels &&
11796 0 != $value &&
11797 grep(/^$tla$/, ("UNC", "LBC", "UIC")) ? "tla$tla" :
11798 "headerCovTableEntry";
11799 if ("0" eq $value) {
11800 # suppress zeros - make table less busy/easier to read
11801 $value = "";
11802 } elsif (!$main::no_sourceview &&
11803 defined($fileDetail) &&
11804 !($tla eq "DCB" || $tla eq "DUB")) {
11805 # deleted lines don't appear..
11806 my $firstAppearance = &$nextLocationCallback($fileDetail, $tla);
11807 defined($firstAppearance) or
11808 die(
11809 "$tla: unexpected undef appearance for " . $fileDetail->path());
11810 my $label =
11811 $main::use_legacyLabels ? $SummaryInfo::tlaToLegacy{$tla} :
11812 $tla;
11813 my $popup = " title=\"goto first $label " .
11814 SummaryInfo::type2str($covType) . "\"";
11815 $value = "<a href=\"#L$firstAppearance\"$popup>$value</a>";
11816 }
11817 push(@row, [undef, $class, $value]);
11818 }
11819 return @row;
11820 }
11821
11822 # build an HTML string for the directory or file pathname, such
11823 # that each element is clickable - and takes you to the 'index' file
11824 # in the corresponding (transitive) parent directory
11825 sub build_html_path($$$$$)
11826 {
11827 my ($path, $key, $bin_type, $isFile, $isAbsolute) = @_;
11828
11829 $path =~ s|^/||;
11830 my @path = File::Spec->splitdir($path);
11831 my $html_path = "";
11832 if ($main::hierarchical &&
11833 scalar(@path) > 1) {
11834 pop(@path); # remove 'self' - at the tail
11835 my $p = "";
11836 my $sep = "";
11837 # need one fewer "../" entries for file pathname because the
11838 # index file we are looking for is in the current directory (i.e.,
11839 # not '../index.html'
11840 my $len = scalar(@path) - $isFile;
11841 foreach my $elem (@path) {
11842 my $base = "../" x $len;
11843 $elem = $lcovutil::dirseparator . $elem if $isAbsolute;
11844 $isAbsolute = 0;
11845 my $e = escape_html($elem);
11846 $html_path .=
11847 "$sep<a href=\"${base}index$key$bin_type.$html_ext\" title=\"Click to go to directory $e\">$e</a>";
11848 $sep = $lcovutil::dirseparator;
11849 --$len;
11850 }
11851 }
11852 return $html_path;
11853 }
11854
11855 #
11856 # write_header(filehandle, ctrl, trunc_file_name, rel_file_name,
11857 # summaryInfo, optionalFileDetailInfo, optionalFunctionData))
11858 # ctrl = (type, primary_key, sort_type, bin_type)
11859 #
11860 # Write a complete standard page header. TYPE may be (0, 1, 2, 3, 4)
11861 # corresponding to (directory view header, file view header, source view
11862 # header, test case description header, function view header)
11863 #
11864 # bin_type in (undef, "", "-owner", "-date")
11865 # - if 'bin' is set, then create link to 'vanilla' view of self, and
11866 # to corresponding view of parent
11867 # - i.e., from 'owner detail' directory page to "owner detail"
11868 # toplevel, and to my correspondign vanilla directory page.
11869 # return hash of coverType -> list of non-zero TLAs for that type (or to
11870 # list of all TLA types if user has asked not to suppress all-zero
11871 # columns)
11872
11873 sub write_header(*$$$$$$$)
11874 {
11875 local *HTML_HANDLE = shift;
11876 my ($callback_type, $ctrl, $trunc_name, $rel_filename, $summary,
11877 $fileDetail, $differentialFunctionMap)
11878 = @_;
11879 my ($type, $primary_key, $sort_type, $bin_type) = @$ctrl;
11880 my $base_dir;
11881 my $view;
11882 my @row_left;
11883 my @row_right;
11884 my $esc_trunc_name = escape_html($trunc_name);
11885
11886 $bin_type = ""
11887 unless defined($bin_type);
11888 my $base_name = File::Basename::basename($rel_filename);
11889 my $show_dateBins = $main::show_dateBins &&
11890 (!defined($fileDetail) || $fileDetail->isProjectFile());
11891
11892 my $key = $primary_key ne "name" ? "-bin_$primary_key" : "";
11893 my $isAbsolutePath = (
11894 $summary->is_directory(1) || ($summary->type() eq 'file' &&
11895 $summary->parent()->is_directory(1))
11896 );
11897 my $html_path =
11898 build_html_path($trunc_name, $key, $bin_type,
11899 $summary->type() eq 'file',
11900 $isAbsolutePath);
11901
11902 # Prepare text for "current view" field
11903 if ($type == $HDR_DIR) {
11904 # Main overview
11905 $base_dir = "";
11906 if ($bin_type ne "" ||
11907 $primary_key ne 'name') {
11908 # this is the header of the 'top-level' page, for either 'owner'
11909 # or 'date' binning - link back to vanilla top-level page
11910 $view =
11911 "<a href=\"index.$html_ext\" title=\"Click to go to default view of top-level page.\">$overview_title</a>";
11912 } else {
11913 $view = $overview_title;
11914 }
11915 } elsif ($type == $HDR_FILE) {
11916 # Directory overview
11917 $base_dir = get_relative_base_path($rel_filename);
11918 my $self_link;
11919 if ($main::hierarchical) {
11920 my $base = escape_html(File::Basename::basename($rel_filename));
11921 if ($base eq $rel_filename &&
11922 $isAbsolutePath) {
11923 $base = $lcovutil::dirseparator . $base;
11924 }
11925 $self_link = $html_path;
11926 $self_link .= $lcovutil::dirseparator if ('' ne $html_path);
11927 if ('name' ne $primary_key ||
11928 '' ne $bin_type) {
11929 $self_link .=
11930 "<a href=\"index.$html_ext\" title=\"Click to go to default view of this directory.\">$base</a>";
11931 } else {
11932 $self_link .= $base;
11933 }
11934 } else {
11935 $esc_trunc_name = $lcovutil::dirseparator . $esc_trunc_name
11936 if $isAbsolutePath;
11937 $self_link = $esc_trunc_name;
11938 if ('name' ne $primary_key ||
11939 '' ne $bin_type) {
11940 # go back to the 'vanilla' view of this directory
11941 $self_link =
11942 "<a href=\"index.$html_ext\" title=\"Click to go to default view of this directory.\">$esc_trunc_name</a>";
11943 }
11944 }
11945 $view =
11946 "<a href=\"$base_dir" .
11947 "index$key$bin_type.$html_ext\" title=\"Click to go to top-level\">"
11948 . "$overview_title</a> - $self_link";
11949 } elsif ($type == $HDR_SOURCE || $type == $HDR_FUNC) {
11950 # File view
11951 my $dir_name = dirname($rel_filename);
11952
11953 my $esc_base_name = escape_html($base_name);
11954 my $esc_dir_name = escape_html($dir_name);
11955 $esc_dir_name = $lcovutil::dirseparator . $esc_dir_name
11956 if $isAbsolutePath;
11957
11958 $base_dir = get_relative_base_path($dir_name);
11959 # if using frames, to break frameset when clicking any of the links
11960 my $parent = $frames ? " target=\"_parent\"" : "";
11961 $view =
11962 "<a href=\"$base_dir" .
11963 "index.$html_ext\"$parent title=\"Click to go to top-level\">" .
11964 "$overview_title</a> - ";
11965 if ($main::flat) {
11966 # for flat view, point only to the top-levevl and show path
11967 # to this file. No other links
11968 $view .= File::Spec->catfile($esc_dir_name, $esc_base_name);
11969 } else {
11970 if ($main::hierarchical) {
11971 $html_path =~ s/<a/<a$parent/g;
11972 $view .= $html_path;
11973 } else {
11974 $view .=
11975 "<a href=\"index.$html_ext\"$parent title=\"Click to go to directory $esc_dir_name\">$esc_dir_name</a>";
11976 }
11977 $view .= " - $esc_base_name";
11978 }
11979
11980 # Add function suffix
11981 if ($lcovutil::func_coverage &&
11982 defined($differentialFunctionMap) &&
11983 %$differentialFunctionMap) {
11984 $view .= "<span style=\"font-size: 80%;\">";
11985 if ($type == $HDR_SOURCE) {
11986 my $suffix = $sort_tables ? '-c' : '';
11987 $view .=
11988 " (source / <a href=\"$base_name.func$suffix.$html_ext\" title=\"Click to go to function table\">functions</a>)";
11989 } elsif ($type == $HDR_FUNC) {
11990 $view .=
11991 " (<a href=\"$base_name.gcov.$html_ext\" title=\"Click to go to source detail\">source</a> / functions)";
11992 }
11993 $view .= "</span>";
11994 }
11995 } elsif ($type == $HDR_TESTDESC) {
11996 # Test description header
11997 $base_dir = "";
11998 $view = "<a href=\"$base_dir" . "index.$html_ext\">" .
11999 "$overview_title</a> - test case descriptions";
12000 }
12001
12002 # Prepare text for "test" field
12003 my $test = escape_html($test_title);
12004
12005 # Append link to test description page if available
12006 if (%test_description && ($type != $HDR_TESTDESC)) {
12007 if ($frames && ($type == $HDR_SOURCE || $type == $HDR_FUNC)) {
12008 # Need to break frameset when clicking this link
12009 $test .=
12010 " ( <span style=\"font-size:80%;\">" . "<a href=\"$base_dir" .
12011 "descriptions.$html_ext\" target=\"_parent\">" .
12012 "view descriptions</a></span> )";
12013 } else {
12014 $test .=
12015 " ( <span style=\"font-size:80%;\">" . "<a href=\"$base_dir" .
12016 "descriptions.$html_ext\">" . "view descriptions</a></span> )";
12017 }
12018 }
12019
12020 # Write header
12021 write_header_prolog(*HTML_HANDLE, $base_dir);
12022
12023 # Left row
12024 push(@row_left,
12025 [["10%", "headerItem", "Current view:"], ["10%", "headerValue", $view]
12026 ]);
12027 my $label = defined($baseline_title) ? "Current" : "Test";
12028 push(@row_left,
12029 [[undef, "headerItem", "$label:"], [undef, "headerValue", $test]]);
12030 push(@row_left,
12031 [[undef, "headerItem", "$label Date:"],
12032 [undef, "headerValue", $current_date]
12033 ]);
12034 if (defined($baseline_title)) {
12035 push(@row_left,
12036 [[undef, "headerItem", "Baseline:"],
12037 [undef, "headerValue", $baseline_title]
12038 ]);
12039 push(@row_left,
12040 [[undef, "headerItem", "Baseline Date:"],
12041 [undef, "headerValue", $baseline_date]
12042 ]);
12043 }
12044 my $hasBranchData = $lcovutil::br_coverage && 0 != $summary->branch_found();
12045 my $hasMcdcData = $lcovutil::mcdc_coverage && 0 != $summary->mcdc_found();
12046
12047 # if top-level page, link to command line and profile
12048 if ($summary->type() eq 'top' &&
12049 $bin_type eq '' &&
12050 $primary_key eq 'name' &&
12051 $sort_type eq $main::SORT_FILE &&
12052 defined($lcovutil::profile)) {
12053
12054 push(@row_left,
12055 [[undef, 'headerItem', 'genhtml Process:'],
12056 [undef, 'headerValue',
12057 '<span><a href="cmdline.html">command line</a></span>'
12058 ]
12059 ],
12060 [[undef, 'headerItem', ''], #blank
12061 [undef, 'headerValue',
12062 '<span><a href="profile.html">profile data</a></span>'
12063 ]
12064 ]);
12065 }
12066 if ($type != $HDR_SOURCE &&
12067 $type != $HDR_FUNC &&
12068 (defined($main::show_ownerBins) ||
12069 @SourceFile::annotateScript)
12070 ) {
12071 # we are going to have 3 versions of of the page:
12072 # flat, with owner bin data, with date bin data
12073 # so label which one this is
12074 my ($tableLabel, $tableKey);
12075 if ($bin_type eq '-owner') {
12076 $tableLabel = 'Group by:';
12077 $tableKey = 'Owner';
12078 } elsif ($bin_type eq '-date') {
12079 $tableLabel = 'Group by:';
12080 $tableKey = 'Date bin';
12081 } else {
12082 $bin_type eq "" or
12083 die("unexpected bin detail type $bin_type");
12084 $tableLabel = 'Summarize by:';
12085 if ($primary_key eq 'date') {
12086 $tableKey = 'Date bin';
12087 } elsif ($primary_key eq 'owner') {
12088 $tableKey = 'Owner';
12089 } # else ($primary_key eq 'name';
12090 }
12091 # label this only if there is both a primary and secondary
12092 push(@row_left,
12093 [[undef, 'headerItem', $tableLabel],
12094 [undef, 'headerValue', $tableKey]
12095 ]) if (defined($tableKey));
12096 }
12097
12098 # Right row
12099 if ($legend && ($type == $HDR_SOURCE || $type == $HDR_FUNC)) {
12100 # kind of hacky - using spaces to try to align
12101 my $text = <<END_OF_HTML;
12102 Lines:&nbsp&nbsp&nbsp&nbsp
12103 <span class="coverLegendCov">hit</span>
12104 <span class="coverLegendNoCov">not hit</span>
12105 END_OF_HTML
12106 if ($hasBranchData) {
12107 $text .= <<END_OF_HTML;
12108 <br>Branches:
12109 <span class="coverLegendCov">+</span> taken
12110 <span class="coverLegendNoCov">-</span> not taken
12111 <span class="coverLegendNoCov">#</span> not executed
12112 END_OF_HTML
12113 }
12114 if ($hasMcdcData) {
12115 $text .= <<END_OF_HTML;
12116 <br>MC/DC:&nbsp&nbsp&nbsp
12117 <span class="coverLegendCov">T</span> 'true' sensitized
12118 <span class="coverLegendNoCov">t</span> 'true' not sensitized
12119 <span class="coverLegendCov">F</span> 'false' sensitized
12120 <span class="coverLegendNoCov">f</span> 'false' not sensitized
12121 END_OF_HTML
12122 }
12123 push(@row_left,
12124 [[undef, "headerItem", "Legend:"],
12125 [undef, "headerValueLeg", $text]
12126 ]);
12127 } elsif ($legend && ($type != $HDR_TESTDESC)) {
12128 my $text = <<END_OF_HTML;
12129 Rating:
12130 <span class="coverLegendCovLo" title="Coverage rates below $med_limit % are classified as low">low: &lt; $med_limit %</span>
12131 <span class="coverLegendCovMed" title="Coverage rates between $med_limit % and $hi_limit % are classified as medium">medium: &gt;= $med_limit %</span>
12132 <span class="coverLegendCovHi" title="Coverage rates of $hi_limit % and more are classified as high">high: &gt;= $hi_limit %</span>
12133 END_OF_HTML
12134 push(@row_left,
12135 [[undef, "headerItem", "Legend:"],
12136 [undef, "headerValueLeg", $text]
12137 ]);
12138 }
12139 my %activeTlaColsForType;
12140 my @nonZeroTlas;
12141 if ($type != $HDR_TESTDESC && $main::show_tla) {
12142 # compute which TLAs have non-zero entries for line/branch/function
12143 my @visit = (SummaryInfo::LINE_DATA);
12144 push(@visit, SummaryInfo::BRANCH_DATA)
12145 if $hasBranchData;
12146 push(@visit, SummaryInfo::MCDC_DATA)
12147 if $hasMcdcData;
12148 push(@visit, SummaryInfo::FUNCTION_DATA)
12149 if $lcovutil::func_coverage;
12150
12151 foreach my $covtype (@visit) {
12152 if ($main::show_zeroTlaColumns) {
12153 $activeTlaColsForType{$covtype} =
12154 \@SummaryInfo::tlaPriorityOrder;
12155 } else {
12156 my @found;
12157 for my $tla (@SummaryInfo::tlaPriorityOrder) {
12158 push(@found, $tla)
12159 if (0 != $summary->get($tla, $covtype));
12160 }
12161 $activeTlaColsForType{$covtype} = \@found;
12162 }
12163 }
12164 foreach my $tla (@SummaryInfo::tlaPriorityOrder) {
12165 # check to see that there are non-zero entries
12166 foreach my $covtype (@visit) {
12167 if (grep({ $tla eq $_ } @{$activeTlaColsForType{$covtype}})) {
12168 push(@nonZeroTlas, $tla);
12169 last;
12170 }
12171 }
12172 }
12173 }
12174 # if $showAllTlasInSummary is set, then put all TLA categories in the
12175 # summary tables at the top of the page (but only the non-zero categories
12176 # in the 'file detail' tables.
12177 # Otherwise, only show non-zero categories in both places
12178 my $showAllTlasInSummary = 0; # turn off for now
12179 my $tlaSummaryTypes =
12180 $showAllTlasInSummary ? \@$SummaryInfo::tlaPriorityOrder :
12181 \@nonZeroTlas;
12182
12183 if ($type == $HDR_TESTDESC) {
12184 push(@row_right, [["80%"]]);
12185 } else {
12186 my $totalTitle = "Covered + Uncovered code";
12187 my $hitTitle = "Exercised code only";
12188 if (@main::base_filenames) {
12189 $totalTitle .= " (not including EUB, ECB, DUB, DCB categories)";
12190 $hitTitle .= " (CBC + GBC + GNC + GIC)";
12191 }
12192
12193 my @headerRow = (["5%", undef, undef],
12194 ["5%", "headerCovTableHead", "Coverage"],
12195 ["5%", "headerCovTableHead",
12196 "Total", undef,
12197 $totalTitle
12198 ]);
12199 if ($main::show_hitTotalCol) {
12200 # legacy view, or we have all the differential categories
12201 #- thus also want a summary
12202 $hitTitle = $main::use_legacyLabels ? undef : $hitTitle;
12203 push(@headerRow,
12204 ["5%", "headerCovTableHead",
12205 $main::opt_missed ? "Missed" : "Hit",
12206 undef, $hitTitle
12207 ]);
12208 }
12209 if ($main::show_tla) {
12210 # Show selected TLAs in title row - either all of them, or
12211 # only types which have non-zero entries
12212 for my $tla (@$tlaSummaryTypes) {
12213
12214 my ($title, $label, $class);
12215 if ($main::use_legacyLabels) {
12216 $label = $SummaryInfo::tlaToLegacy{$tla};
12217 $class = "headerCovTableHead";
12218 } else {
12219 $label = $tla;
12220 $title = $SummaryInfo::tlaToTitle{$tla};
12221 $class = "headerCovTableHead$tla";
12222 }
12223 push(@headerRow, ["5%", $class, $label, undef, $title]);
12224 }
12225 }
12226 push(@row_right, \@headerRow);
12227 }
12228 # Line coverage
12229 my $tot = $summary->lines_found(); #might have been modified...
12230 my $hit = $summary->lines_hit();
12231 my $style =
12232 $rate_name[classify_rate($tot, $hit, $ln_med_limit, $ln_hi_limit)];
12233 my $rate = rate($hit, $tot, "&nbsp;%");
12234 $hit -= $tot
12235 if $main::opt_missed; # negative number
12236 my @dataRow = ([undef, "headerItem", "Lines:"],
12237 [undef, "headerCovTableEntry$style", $rate],
12238 [undef, "headerCovTableEntry", $tot]);
12239 if ($main::show_hitTotalCol) {
12240 push(@dataRow, [undef, "headerCovTableEntry", $hit]);
12241 }
12242 if ($main::show_tla) {
12243 my @tlaRow =
12244 buildHeaderSummaryTableRow($summary, SummaryInfo::LINE_DATA,
12245 $fileDetail, \&SourceFile::nextTlaGroup,
12246 $tlaSummaryTypes);
12247 push(@dataRow, @tlaRow);
12248 }
12249 push(@row_right, \@dataRow)
12250 if ($type != $HDR_TESTDESC);
12251 # Function coverage
12252 if ($lcovutil::func_coverage) {
12253 my $tot = $summary->function_found();
12254 my $hit = $summary->function_hit();
12255 $style =
12256 $rate_name[classify_rate($tot, $hit, $fn_med_limit, $fn_hi_limit)];
12257 $rate = rate($hit, $tot, "&nbsp;%");
12258 $hit -= $tot
12259 if $main::opt_missed; # negative number
12260 my @dataRow = ([undef, "headerItem", "Functions:"],
12261 [undef, "headerCovTableEntry$style", $rate],
12262 [undef, "headerCovTableEntry", $tot]);
12263 if ($main::show_hitTotalCol) {
12264 push(@dataRow, [undef, "headerCovTableEntry", $hit]);
12265 }
12266 if ($main::show_tla) {
12267 # no file position for function (yet)
12268 my @tlaRow =
12269 buildHeaderSummaryTableRow($summary,
12270 SummaryInfo::FUNCTION_DATA, undef, undef, $tlaSummaryTypes);
12271 push(@dataRow, @tlaRow);
12272 }
12273 push(@row_right, \@dataRow)
12274 if ($type != $HDR_TESTDESC);
12275 }
12276 # Branch coverage
12277 if ($hasBranchData) {
12278 my $tot = $summary->branch_found();
12279 my $hit = $summary->branch_hit();
12280 $style =
12281 $rate_name[classify_rate($tot, $hit, $br_med_limit, $br_hi_limit)];
12282 $rate = rate($hit, $tot, "&nbsp;%");
12283 $hit -= $tot
12284 if $main::opt_missed; # negative number
12285 my @dataRow = ([undef, "headerItem", "Branches:"],
12286 [undef, "headerCovTableEntry$style", $rate],
12287 [undef, "headerCovTableEntry", $tot]);
12288 if ($main::show_hitTotalCol) {
12289 push(@dataRow, [undef, "headerCovTableEntry", $hit]);
12290 }
12291 if ($main::show_tla) {
12292 my @tlaRow =
12293 buildHeaderSummaryTableRow($summary, SummaryInfo::BRANCH_DATA,
12294 $fileDetail, \&SourceFile::nextBranchTlaGroup,
12295 $tlaSummaryTypes);
12296 push(@dataRow, @tlaRow);
12297 }
12298 push(@row_right, \@dataRow)
12299 if ($type != $HDR_TESTDESC);
12300 }
12301
12302 # MC/DC coverage
12303 if ($hasMcdcData) {
12304 my $tot = $summary->mcdc_found();
12305 my $hit = $summary->mcdc_hit();
12306 $style =
12307 $rate_name[classify_rate($tot, $hit, $br_med_limit, $br_hi_limit)];
12308 $rate = rate($hit, $tot, "&nbsp;%");
12309 $hit -= $tot
12310 if $main::opt_missed; # negative number
12311 my @dataRow = ([undef, "headerItem", "MC/DC:"],
12312 [undef, "headerCovTableEntry$style", $rate],
12313 [undef, "headerCovTableEntry", $tot]);
12314 if ($main::show_hitTotalCol) {
12315 push(@dataRow, [undef, "headerCovTableEntry", $hit]);
12316 }
12317 if ($main::show_tla) {
12318 my @tlaRow =
12319 buildHeaderSummaryTableRow($summary, SummaryInfo::MCDC_DATA,
12320 $fileDetail, \&SourceFile::nextBranchTlaGroup,
12321 $tlaSummaryTypes);
12322 push(@dataRow, @tlaRow);
12323 }
12324 push(@row_right, \@dataRow)
12325 if ($type != $HDR_TESTDESC);
12326 }
12327
12328 # Aged coverage
12329 if ($show_dateBins) {
12330 # make a space in the table between before date bins
12331 my $dateBinDetailPage = "index-date.$html_ext"
12332 if ($type != $HDR_SOURCE &&
12333 $type != $HDR_FUNC);
12334 my $table =
12335 buildDateSummaryTable(
12336 $summary, SummaryInfo::LINE_DATA,
12337 \&SummaryInfo::lineCovCount, $fileDetail,
12338 \&SourceFile::nextInDateBin, "Line coverage date bins:",
12339 $dateBinDetailPage, scalar(@dataRow),
12340 $tlaSummaryTypes);
12341 push(@row_right, @$table)
12342 if ($type != $HDR_TESTDESC);
12343
12344 if ($lcovutil::func_coverage) {
12345 my $fn_table =
12346 buildDateSummaryTable($summary,
12347 SummaryInfo::FUNCTION_DATA,
12348 \&SummaryInfo::functionCovCount,
12349 $fileDetail,
12350 undef,
12351 "Function coverage date bins:",
12352 $dateBinDetailPage,
12353 scalar(@dataRow),
12354 $tlaSummaryTypes);
12355 push(@row_right, @$fn_table)
12356 if ($type != $HDR_TESTDESC);
12357 }
12358
12359 if ($hasBranchData) {
12360 my $br_table =
12361 buildDateSummaryTable($summary,
12362 SummaryInfo::BRANCH_DATA,
12363 \&SummaryInfo::branchCovCount,
12364 $fileDetail,
12365 \&SourceFile::nextBranchInDateBin,
12366 "Branch coverage date bins:",
12367 $dateBinDetailPage,
12368 scalar(@dataRow),
12369 $tlaSummaryTypes);
12370 push(@row_right, @$br_table)
12371 if ($type != $HDR_TESTDESC);
12372 }
12373
12374 if ($hasMcdcData) {
12375 my $mcdc_table =
12376 buildDateSummaryTable($summary,
12377 SummaryInfo::MCDC_DATA,
12378 \&SummaryInfo::mcdcCovCount,
12379 $fileDetail,
12380 \&SourceFile::nextMcdcInDateBin,
12381 "MC/DC coverage date bins:",
12382 $dateBinDetailPage,
12383 scalar(@dataRow),
12384 $tlaSummaryTypes);
12385 push(@row_right, @$mcdc_table)
12386 if ($type != $HDR_TESTDESC);
12387 }
12388 }
12389 # owner bins..
12390 if (defined($main::show_ownerBins)) {
12391 # first, make sure there is owner data here (ie., owner data
12392 # was collected, or both that there is owner data and some
12393 # owners have uncovered code)
12394 # This it the header table - so we want to truncate the owner
12395 # list if it is too long (and the user asked us to)
12396 my ($ownerList, $truncated) =
12397 $summary->findOwnerList($callback_type, 1,
12398 $main::show_ownerBins && $main::show_ownerBins eq 'all');
12399 if (defined($ownerList)) {
12400 my $ownerBinDetailPage = "index-owner.$html_ext"
12401 if ($type != $HDR_SOURCE &&
12402 $type != $HDR_FUNC);
12403 my $table =
12404 buildOwnerSummaryTable($ownerList,
12405 $truncated,
12406 $summary,
12407 SummaryInfo::LINE_DATA,
12408 $fileDetail,
12409 \&SourceFile::nextInOwnerBin,
12410 "Line coverage ownership bins",
12411 $ownerBinDetailPage,
12412 scalar(@dataRow),
12413 $tlaSummaryTypes);
12414 push(@row_right, @$table)
12415 if ($type != $HDR_TESTDESC);
12416
12417 if ($hasBranchData) {
12418 my $br_table =
12419 buildOwnerSummaryTable($ownerList,
12420 $truncated,
12421 $summary,
12422 SummaryInfo::BRANCH_DATA,
12423 $fileDetail,
12424 \&SourceFile::nextBranchInOwnerBin,
12425 "Branch coverage ownership bins",
12426 $ownerBinDetailPage,
12427 scalar(@dataRow),
12428 $tlaSummaryTypes);
12429 push(@row_right, @$br_table)
12430 if ($type != $HDR_TESTDESC);
12431 }
12432
12433 if ($hasMcdcData) {
12434 my $mcdc_table =
12435 buildOwnerSummaryTable($ownerList,
12436 $truncated,
12437 $summary,
12438 SummaryInfo::MCDC_DATA,
12439 $fileDetail,
12440 \&SourceFile::nextBranchInOwnerBin,
12441 "MC/DC coverage ownership bins",
12442 $ownerBinDetailPage,
12443 scalar(@dataRow),
12444 $tlaSummaryTypes);
12445 push(@row_right, @$mcdc_table)
12446 if ($type != $HDR_TESTDESC);
12447 }
12448 }
12449 }
12450
12451 # Print rows
12452 my $num_rows = max(scalar(@row_left), scalar(@row_right));
12453 for (my $i = 0; $i < $num_rows; $i++) {
12454 my $left = $row_left[$i];
12455 my $right = $row_right[$i];
12456
12457 if (!defined($left)) {
12458 $left = [[undef, undef, undef], [undef, undef, undef]];
12459 }
12460 if (!defined($right)) {
12461 $right = [];
12462 }
12463 write_header_line(*HTML_HANDLE, @{$left},
12464 [$i == 0 ? "5%" : undef, undef, undef],
12465 @{$right});
12466 }
12467
12468 # Fourth line
12469 write_header_epilog(*HTML_HANDLE, $base_dir);
12470 return \%activeTlaColsForType;
12471 }
12472
12473 sub get_sort_code($$$)
12474 {
12475 my ($link, $alt, $base) = @_;
12476 my $png;
12477 my $link_start;
12478 my $link_end;
12479
12480 if (!defined($link)) {
12481 $png = "glass.png";
12482 $link_start = "";
12483 $link_end = "";
12484 } else {
12485 $png = "updown.png";
12486 $link_start = '<a href="' . $link . '">';
12487 $link_end = "</a>";
12488 }
12489 my $help = " title=\"Click to sort table by $alt\"";
12490 $alt = "Sort by $alt";
12491 return " <span $help class=\"tableHeadSort\">" .
12492 $link_start . '<img src="' . $base . $png . '" width=10 height=14 ' .
12493 'alt="' . $alt . '"' . $help . ' border=0>' . $link_end . '</span>';
12494 }
12495
12496 sub get_file_code($$$$$$)
12497 {
12498 my ($type, $text, $sort_button, $bin_type, $primary_key, $base) = @_;
12499 my $result = $text;
12500 my $link;
12501
12502 my $key = 'name' ne $primary_key ? "-bin_$primary_key" : "";
12503 if ($sort_button) {
12504 $link = "index$key$bin_type";
12505 $link .= '-detail'
12506 unless ($type == $HEAD_NO_DETAIL);
12507 $link .= ".$html_ext";
12508 }
12509 $result .= get_sort_code($link, "file name", $base);
12510
12511 return $result;
12512 }
12513
12514 sub get_line_code($$$$$$$)
12515 {
12516 my ($type, $sort_type, $text, $sort_button, $bin_type, $primary_key, $base)
12517 = @_;
12518 my $result = $text;
12519 my $key = ('name' eq $primary_key) ? '' : "-bin_$primary_key";
12520 my $sort_link = "index" . $key . $bin_type . "-sort-l.$html_ext"
12521 if $sort_button;
12522
12523 if ($type == $HEAD_NO_DETAIL) {
12524 # Just text
12525 } elsif ($type == $HEAD_DETAIL_HIDDEN) {
12526 # Text + link to detail view
12527 my $help = "title=\"Click to go to per-testcase coverage details\"";
12528 my $detail_link = 'index' . $key . $bin_type .
12529 '-detail' . $fileview_sortname[$sort_type] . '.' . $html_ext;
12530 $result .=
12531 " ( <a $help " .
12532 'class="detail" href="' . $detail_link . '">show details</a> )';
12533 } else {
12534 # Text + link to standard view
12535 my $help = "title=\"Click to hide per-testcase coverage details\"";
12536 $result .=
12537 " ( <a $help " . 'class="detail" href="index' .
12538 $key . $bin_type . $fileview_sortname[$sort_type] .
12539 '.' . $html_ext . '">hide details</a> )';
12540 }
12541 # Add sort button
12542 $result .= get_sort_code($sort_link, "line coverage", $base);
12543 # we don't have a 'detail' bin page
12544 $result =~ s/index-bin_(.+?)-detail((-sort-.)?\.)/index-$1$2/g;
12545
12546 return $result;
12547 }
12548
12549 sub get_func_code($$$$$$)
12550 {
12551 my ($type, $text, $sort_button, $bin_type, $primary_key, $base) = @_;
12552 my $result = $text;
12553 my $link;
12554 my $key = 'name' ne $primary_key ? "-bin_$primary_key" : "";
12555
12556 if ($sort_button) {
12557 $link = "index$key$bin_type";
12558 $link .= '-detail'
12559 unless ($type == $HEAD_NO_DETAIL);
12560 $link .= "-sort-f.$html_ext";
12561 }
12562 $result .= get_sort_code($link, "function coverage", $base);
12563 return $result;
12564 }
12565
12566 sub get_br_code($$$$$$)
12567 {
12568 my ($type, $text, $sort_button, $bin_type, $primary_key, $base) = @_;
12569 my $result = $text;
12570 my $link;
12571 my $key = 'name' ne $primary_key ? "-bin_$primary_key" : "";
12572
12573 if ($sort_button) {
12574 $link = "index$key$bin_type";
12575 $link .= '-detail'
12576 unless ($type == $HEAD_NO_DETAIL);
12577 $link .= "-sort-b.$html_ext";
12578 }
12579 $result .= get_sort_code($link, "branch coverage", $base);
12580 return $result;
12581 }
12582
12583 sub get_mcdc_code($$$$$$)
12584 {
12585 my ($type, $text, $sort_button, $bin_type, $primary_key, $base) = @_;
12586 my $result = $text;
12587 my $link;
12588 my $key = 'name' ne $primary_key ? "-bin_$primary_key" : "";
12589
12590 if ($sort_button) {
12591 $link = "index$key$bin_type";
12592 $link .= '-detail'
12593 unless ($type == $HEAD_NO_DETAIL);
12594 $link .= "-sort-m.$html_ext";
12595 }
12596 $result .= get_sort_code($link, "MC/DC coverage", $base);
12597 return $result;
12598 }
12599
12600 #
12601 # write_file_table(filehandle, callback_type, base_dir, perTestcaseData,
12602 # parentSummary, ctrlSettings, activeTlaCols)
12603 # ctrlSettings = [fileview, sort_type, details_type, sort_name]
12604 # perTestcaseData = [testhash, testfnchash, testbrhash]
12605 # activeTlaCols = {coverage_type, [tlas with nonzero count]}
12606 #
12607 # Write a complete file table. OVERVIEW is a reference to a hash containing
12608 # the following mapping:
12609 #
12610 # filename -> "lines_found,lines_hit,funcs_found,funcs_hit,page_link,
12611 # func_link" + other file details
12612 #
12613 # TESTHASH is a reference to the following hash:
12614 #
12615 # filename -> \%testdata
12616 # %testdata: name of test affecting this file -> \%testcount
12617 # %testcount: line number -> execution count for a single test
12618 #
12619 # Heading of first column is "Filename" if FILEVIEW is true, "Directory name"
12620 # otherwise.
12621 #
12622
12623 sub write_file_table(*$$$$$$)
12624 {
12625 local *HTML_HANDLE = $_[0];
12626 my $callback_type = $_[1];
12627 my $base_dir = $_[2];
12628 my $perTestcaseData =
12629 $_[3]; # undef or [lineCov, funcCov, branchCov, mcdcCov]
12630 my $dirSummary = $_[4]; # SummaryInfo object
12631 my ($fileview, $primary_key, $sort_type, $bin_type) = @{$_[5]};
12632 my $activeTlaCols = $_[6];
12633 # $fileview == 0 if listing directories, 1 if listing files
12634 # $primary_key in ("name", "owner", "date"). If $primary_key is:
12635 # - 'name': leftmost column is file/directory name -
12636 # this is the original/vanilla genhtml behaviour
12637 # - 'owner': leftmost column is author name. Details for that owner
12638 # (for all files in the project, or for all files in this drectory)
12639 # are shown in a contiguous block.
12640 # - 'date': leftmost column is date bin. Details for that bin are
12641 # shown in a contiguous block.
12642 # $sort_type in ("", "-sort-l", "-sort-b", "-sort-f")
12643 # $bin_type in ("", "-owner", "-date")
12644 # - if $bin_type not "", expand non-empty entries after file/directory
12645 # overall count (i.e. - show all the "owners" for this file/directory,
12646 # or all date bins for this file/directory)
12647 # - $bin_type is applied only if $primary_key is "name"
12648
12649 $primary_key eq "name" || $bin_type eq "" or
12650 die(
12651 "primary key '$primary_key' does not support '$bin_type' detail reporting"
12652 );
12653
12654 my $hasBranchData =
12655 $lcovutil::br_coverage && 0 != $dirSummary->branch_found();
12656 my $hasMcdcData =
12657 $lcovutil::mcdc_coverage && 0 != $dirSummary->mcdc_found();
12658 my $includeFunctionColumns = $lcovutil::func_coverage &&
12659 0 != $dirSummary->function_found() &&
12660 'owner' ne $primary_key;
12661
12662 # Determine HTML code for column headings
12663 my $hide = $HEAD_NO_DETAIL;
12664 my $show = $HEAD_NO_DETAIL;
12665 if (($dirSummary->type() eq 'directory' ||
12666 $main::flat ||
12667 $main::hierarchical) &&
12668 $show_details
12669 ) {
12670 # "detailed" if line coverage hash not empty
12671 my $detailed =
12672 defined($perTestcaseData) && scalar(%{$perTestcaseData->[0]});
12673 $hide = $detailed ? $HEAD_DETAIL_HIDDEN : $HEAD_NO_DETAIL;
12674 $show = $detailed ? $HEAD_DETAIL_SHOWN : $HEAD_DETAIL_HIDDEN;
12675 }
12676 my $file_col_title = ($fileview || $main::flat) ? 'File' : 'Directory';
12677 # don't insert the 'sort' controls if there is just a single source file
12678 my $use_sort_button = $sort_tables && 1 < scalar($dirSummary->sources());
12679 my $file_code =
12680 get_file_code($hide, $file_col_title,
12681 $use_sort_button && $sort_type != $SORT_FILE,
12682 $bin_type, $primary_key, $base_dir);
12683 my $line_code = get_line_code($show, $sort_type,
12684 "Line Coverage",
12685 $use_sort_button && $sort_type != $SORT_LINE,
12686 $bin_type, $primary_key, $base_dir);
12687 my $func_code = get_func_code($hide,
12688 "Function Coverage",
12689 $use_sort_button && $sort_type != $SORT_FUNC,
12690 $bin_type, $primary_key, $base_dir);
12691 my $br_code = get_br_code($hide,
12692 "Branch Coverage",
12693 $use_sort_button && $sort_type != $SORT_BRANCH,
12694 $bin_type, $primary_key, $base_dir);
12695 my $mcdc_code = get_mcdc_code($hide,
12696 "MC/DC Coverage",
12697 $use_sort_button && $sort_type != $SORT_MCDC,
12698 $bin_type, $primary_key, $base_dir);
12699
12700 my @head_columns;
12701
12702 my @lineCovCols = (["Rate", 2], "Total");
12703 my @mcdcCovCols = ("Rate", "Total");
12704 my @branchCovCols = ("Rate", "Total");
12705 my @functionCovCols = ("Rate", "Total");
12706 if ($main::show_hitTotalCol) {
12707 my $t = $main::opt_missed ? "Missed" : "Hit";
12708 push(@lineCovCols, $t);
12709 push(@mcdcCovCols, $t);
12710 push(@branchCovCols, $t);
12711 push(@functionCovCols, $t);
12712 }
12713 if ($main::show_tla) {
12714 my @visit = ([SummaryInfo::LINE_DATA, \@lineCovCols]);
12715 push(@visit, [SummaryInfo::MCDC_DATA, \@mcdcCovCols])
12716 if $hasMcdcData;
12717 push(@visit, [SummaryInfo::BRANCH_DATA, \@branchCovCols])
12718 if $hasBranchData;
12719 push(@visit, [SummaryInfo::FUNCTION_DATA, \@functionCovCols])
12720 if $includeFunctionColumns;
12721 foreach my $d (@visit) {
12722 my ($covtype, $cols) = @$d;
12723 foreach my $tla (@{$activeTlaCols->{$covtype}}) {
12724 my $label =
12725 $main::use_legacyLabels ? $SummaryInfo::tlaToLegacy{$tla} :
12726 $tla;
12727 push(@$cols,
12728 [$label,
12729 1,
12730 $main::use_legacyLabels ?
12731 undef :
12732 $SummaryInfo::tlaToTitle{$tla}
12733 ]);
12734 }
12735 }
12736 }
12737 push(@head_columns, [$line_code, $#lineCovCols + 2, \@lineCovCols]);
12738 push(@head_columns, [$mcdc_code, $#mcdcCovCols + 1, \@mcdcCovCols])
12739 if $hasMcdcData;
12740 push(@head_columns, [$br_code, $#branchCovCols + 1, \@branchCovCols])
12741 if $hasBranchData;
12742 push(@head_columns, [$func_code, $#functionCovCols + 1, \@functionCovCols])
12743 if $includeFunctionColumns;
12744
12745 my $showBinDetail = undef;
12746 if ($bin_type eq '-date' &&
12747 $dirSummary &&
12748 $dirSummary->hasDateInfo()) {
12749 $showBinDetail = 'date';
12750 } elsif ($bin_type eq '-owner' &&
12751 $dirSummary &&
12752 $dirSummary->hasOwnerInfo()) {
12753 $showBinDetail = 'owner';
12754 }
12755 my $num_columns =
12756 write_file_table_prolog(*HTML_HANDLE, $file_code,
12757 defined($showBinDetail) ? $showBinDetail : undef,
12758 $primary_key, @head_columns);
12759
12760 my @tableRows;
12761 if ($primary_key eq 'name') {
12762
12763 # sorted list of all the file or directory names
12764 foreach my $name ($dirSummary->get_sorted_keys($sort_type, 1)) {
12765 my $entrySummary = $dirSummary->get_source($name);
12766
12767 if ($entrySummary->type() eq 'directory') {
12768 if ('directory' eq $dirSummary->type()) {
12769 $name = File::Basename::basename($name);
12770 } elsif ($entrySummary->is_directory(1)) {
12771 $name = $lcovutil::dirseparator . $name;
12772 }
12773 } else {
12774 die("unexpected summary type")
12775 unless 'file' eq $entrySummary->type();
12776 $name = File::Basename::basename($name);
12777 }
12778 push(@tableRows,
12779 FileOrDirectoryCallback->new($name, $entrySummary));
12780 }
12781
12782 } elsif ($primary_key eq 'owner') {
12783
12784 # retrieve sorted list of owner names - alphabetically, by name
12785 # or by number of missed lines or missed branches
12786 my $all = defined($main::show_ownerBins) && $main::show_ownerBins;
12787
12788 my %owners;
12789 foreach my $d ([1, SummaryInfo::LINE_DATA, 0],
12790 [$lcovutil::mcdc_coverage, SummaryInfo::MCDC_DATA, 1],
12791 [$lcovutil::br_coverage, SummaryInfo::BRANCH_DATA, 2],
12792 ) {
12793 my ($enable, $dataType, $idx) = @$d;
12794 next unless $enable;
12795
12796 foreach my $owner ($dirSummary->owners($all, $dataType)) {
12797 # (line count, branch count, mcdc count, function count)
12798 $owners{$owner} = [[0, 0], [0, 0], [0, 0], [0, 0]]
12799 unless exists($owners{$owner});
12800
12801 $owners{$owner}->[$idx] = [
12802 $dirSummary->owner_tlaCount($owner, 'found', $dataType),
12803 $dirSummary->owner_tlaCount($owner, 'hit', $dataType)
12804 ];
12805 }
12806 }
12807 my @sorted = sort(keys(%owners)); # default sort order
12808 # now, sort the owner list...
12809 foreach my $d ([1, $SORT_LINE, 0],
12810 [$lcovutil::mcdc_coverage, $SORT_MCDC, 1],
12811 [$lcovutil::br_coverage, $SORT_BRANCH, 2],
12812 ) {
12813 my ($enable, $s, $idx) = @$d;
12814 if ($sort_type eq $s) {
12815 # sort by number of missed lines/branches/MCDC expressions
12816 @sorted = sort({
12817 my $la = $owners{$a}->[$idx];
12818 my $lb = $owners{$b}->[$idx];
12819 ($lb->[0] - $lb->[1])
12820 <=> ($la->[0] - $la->[1]) ||
12821 $a cmp $b # then by name
12822 } keys(%owners));
12823 last;
12824 }
12825 }
12826
12827 # don't truncate the 'owner detail table'
12828 # if user asked to see the page, then they want to be able to navigate
12829 # to all users
12830 #if (defined($ownderTableElements) &&
12831 # $ownerTableElements < scalar(@sorted)) &&
12832 # (0 == scalar(@truncateOwnerTableLevels) ||
12833 # grep(/$callback_type/, @truncateOwnerTableLevels)))) {
12834 # # truncate owner list in header table
12835 # splice(@sorted, $ownerTableElements);
12836 #}
12837
12838 foreach my $owner (@sorted) {
12839 push(@tableRows,
12840 FileOrDirectoryOwnerCallback->new($owner, $dirSummary));
12841 }
12842
12843 } elsif ($primary_key eq 'date') {
12844
12845 for (my $bin = 0; $bin <= $#SummaryInfo::ageGroupHeader; ++$bin) {
12846 my $ageval = $dirSummary->age_sample($bin);
12847 my $lines = $dirSummary->lineCovCount('found', 'age', $ageval);
12848 if (0 != $lines ||
12849 ($lcovutil::br_coverage &&
12850 0 != $dirSummary->branchCovCount('found', 'age', $ageval))
12851 ||
12852 ($lcovutil::mcdc_coverage &&
12853 0 != $dirSummary->mcdcCovCount('found', 'age', $ageval)) ||
12854 ($lcovutil::func_coverage &&
12855 0 != $dirSummary->functionCovCount('found', 'age', $ageval))
12856 ) {
12857 push(@tableRows,
12858 FileOrDirectoryDateCallback->new($bin, $dirSummary));
12859 }
12860 }
12861 } else {
12862 die("unsupported primary key '$primary_key'");
12863 }
12864
12865 my $all = defined($main::show_ownerBins) && $main::show_ownerBins eq 'all';
12866 # show only the 'Total' row if all row entries are suppressed
12867 # because they have no un-exercised coverpoints
12868 my $elideEmptyRows = 0;
12869 if ($primary_key eq 'owner') {
12870 $elideEmptyRows = $main::show_ownerBins ne 'all';
12871 } elsif ($primary_key eq 'date') {
12872 $elideEmptyRows = 1;
12873 }
12874 my $suppressedEmptyRow = 0;
12875 # if only one secondary entry, we don't need the 'Total' header
12876 my $suppressedSecondaryHeader = 0;
12877
12878 foreach my $primaryCb (@tableRows) {
12879
12880 # we need to find the 'owner' and 'date' row data for this file before
12881 # we write anything else, because we need to know the number of
12882 # rows that the $primary cell will span
12883
12884 my @secondaryRows;
12885 my $skippedSecondaryRows = 0;
12886
12887 if (defined($showBinDetail)) {
12888
12889 if (defined($primaryCb->summary())) {
12890 my $source = $primaryCb->summary();
12891
12892 if ($showBinDetail eq 'owner') {
12893 # do I need an option to suppress the list of owners?
12894 # maybe too much information, in some circumstances?
12895 # are there any non-empty owner tables here?
12896 # If user explicitly asks to see the 'owner detail' page,
12897 # then they must be interested in which code is written by
12898 # each author - so we should not truncate the list
12899 my ($ownerList, $truncated) =
12900 $primaryCb->findOwnerList($callback_type, 0, $all);
12901 die("unexpected truncate count") unless $truncated == 0;
12902 push(@secondaryRows, @$ownerList)
12903 if defined($ownerList);
12904 }
12905
12906 if ($showBinDetail eq 'date') {
12907 for (my $bin = 0;
12908 $bin <= $#SummaryInfo::ageGroupHeader;
12909 ++$bin) {
12910 my $ageval = $source->age_sample($bin);
12911 my $lineCb =
12912 $primaryCb->dateDetailCallback($ageval,
12913 SummaryInfo::LINE_DATA);
12914 my $lineTotal = $lineCb->get('found');
12915 my $hit = $lineCb->get('hit');
12916 my $lineMissed = $lineTotal - $hit;
12917
12918 my $branchCb =
12919 $primaryCb->dateDetailCallback($ageval,
12920 SummaryInfo::BRANCH_DATA);
12921 my $branchTotal =
12922 $lcovutil::br_coverage ? $branchCb->get('found') :
12923 0;
12924 $hit =
12925 $lcovutil::br_coverage ? $branchCb->get('hit') : 0;
12926 my $branchMissed = $branchTotal - $hit;
12927
12928 my $mcdcCb =
12929 $primaryCb->dateDetailCallback($ageval,
12930 SummaryInfo::MCDC_DATA);
12931 my $mcdcTotal =
12932 $lcovutil::mcdc_coverage ? $mcdcCb->get('found') :
12933 0;
12934 $hit =
12935 $lcovutil::mcdc_coverage ? $mcdcCb->get('hit') : 0;
12936 my $mcdcMissed = $mcdcTotal - $hit;
12937
12938 my $functionCb =
12939 $primaryCb->dateDetailCallback($ageval,
12940 SummaryInfo::FUNCTION_DATA);
12941 my $functionTotal =
12942 $lcovutil::func_coverage ?
12943 $functionCb->get('found') :
12944 0;
12945 $hit =
12946 $lcovutil::func_coverage ? $functionCb->get('hit') :
12947 0;
12948 my $functionMissed = $functionTotal - $hit;
12949
12950 next
12951 if 0 == $lineTotal &&
12952 0 == $branchTotal &&
12953 0 == $mcdcTotal &&
12954 0 == $functionTotal;
12955
12956 push(@secondaryRows,
12957 [$SummaryInfo::ageGroupHeader[$bin],
12958 [$lineMissed, $lineTotal, $lineCb],
12959 [$mcdcMissed, $mcdcTotal, $mcdcCb],
12960 [$branchMissed, $branchTotal, $branchCb],
12961 [$functionMissed, $functionTotal, $functionCb]
12962 ]);
12963 }
12964 }
12965 }
12966 } # if showBinDetail
12967 elsif ($primary_key ne 'name') {
12968 ($skippedSecondaryRows, @secondaryRows) =
12969 @{$primaryCb->findFileList($all)};
12970 }
12971
12972 my ($found, $hit, $fn_found, $fn_hit,
12973 $br_found, $br_hit, $mcdc_found, $mcdc_hit,
12974 $page_link, $fileSummary, $fileDetails) = $primaryCb->data();
12975 # a bit of a hack: if this is top-level page (such that the links
12976 # are to directory pages rather than to source code detail pages)
12977 # and this is the 'owner bin detail' (or the 'date bin detail') view,
12978 # then link to the same 'bin detail' view of the directory page
12979 # This enables the user who is tracking down code written by a
12980 # particular user (or on a particular date) to go link-to-link
12981 # without having to select the 'bin' link in the destination header.
12982 if ($fileview == 0 &&
12983 $bin_type ne "") {
12984 $page_link =~ s/index.$html_ext$/index$bin_type.$html_ext/;
12985 }
12986
12987 my @columns;
12988
12989 my @tableCallbackData = ($primaryCb->name(), $primaryCb->summary(),
12990 $fileDetails, $page_link);
12991 my $showLineGraph = 1;
12992 # Line coverage
12993 push(@columns,
12994 [$found, $hit, $med_limit, $hi_limit, $showLineGraph,
12995 $primaryCb->totalCallback(SummaryInfo::LINE_DATA),
12996 SummaryInfo::LINE_DATA
12997 ]);
12998 # MC/DC coverage
12999 if ($hasMcdcData) {
13000 push(@columns,
13001 [$mcdc_found,
13002 $mcdc_hit,
13003 $mcdc_med_limit,
13004 $mcdc_hi_limit,
13005 0,
13006 $primaryCb->totalCallback(SummaryInfo::MCDC_DATA),
13007 SummaryInfo::MCDC_DATA
13008 ]);
13009 }
13010 # Branch coverage
13011 if ($hasBranchData) {
13012 push(@columns,
13013 [$br_found,
13014 $br_hit,
13015 $br_med_limit,
13016 $br_hi_limit,
13017 0,
13018 $primaryCb->totalCallback(SummaryInfo::BRANCH_DATA),
13019 SummaryInfo::BRANCH_DATA
13020 ]);
13021 }
13022 # Function coverage
13023 if ($includeFunctionColumns) {
13024 # no 'owner' callbacks for function...
13025 my $cbStruct =
13026 $primaryCb->totalCallback(SummaryInfo::FUNCTION_DATA);
13027
13028 push(@columns,
13029 [$fn_found, $fn_hit, $fn_med_limit, $fn_hi_limit, 0,
13030 $cbStruct, SummaryInfo::FUNCTION_DATA
13031 ]);
13032 }
13033 my $elide_secondary_header = $compactSummaryTables &&
13034 (scalar(@secondaryRows) == 1 && $skippedSecondaryRows == 0);
13035 $suppressedSecondaryHeader ||= $elide_secondary_header;
13036 if (!$elide_secondary_header) {
13037 # pass 'dirSummary' to print method: we omit the 'owner' column if
13038 # none of the files in this directory have any owner information
13039 # (i.e., none of them are found in the repo)
13040 my $numRows = (1 + scalar(@secondaryRows));
13041 my $asterisk;
13042 if ($elideEmptyRows && (1 == $numRows || $skippedSecondaryRows)) {
13043 $asterisk = '&lowast;';
13044 $suppressedEmptyRow = 1;
13045 }
13046 write_file_table_entry(*HTML_HANDLE,
13047 $base_dir,
13048 [$primaryCb->name(), \@tableCallbackData,
13049 $activeTlaCols, $numRows,
13050 $primary_key, 0,
13051 $fileview, "fileOrDir",
13052 $page_link, $dirSummary,
13053 $showBinDetail, $asterisk
13054 ],
13055 @columns);
13056 }
13057
13058 # sort secondary rows...
13059 if ($sort_type == $SORT_FILE) {
13060 # alphabetic
13061 @secondaryRows = sort({ $a->[0] cmp $b->[0] } @secondaryRows);
13062 } else {
13063 my $sortElem;
13064 if ($sort_type == $SORT_LINE) {
13065 $sortElem = 1;
13066 } elsif ($sort_type == $SORT_BRANCH) {
13067 $sortElem = 2;
13068 } elsif ($sort_type == $SORT_MCDC) {
13069 $sortElem = 3;
13070 } elsif ($sort_type == $SORT_FUNC) {
13071 $sortElem = 4;
13072 }
13073 @secondaryRows =
13074 sort({
13075 my $ca = $a->[$sortElem];
13076 my $cb = $b->[$sortElem];
13077 # sort based on 'missed'
13078 $cb->[0] <=> $ca->[0];
13079 } @secondaryRows);
13080 }
13081 foreach my $secondary (@secondaryRows) {
13082 my ($name, $line, $branch, $mcdc, $func) = @$secondary;
13083 my ($lineMissed, $lineTotal, $lineCb) = @$line;
13084 my $lineHit = $lineTotal - $lineMissed;
13085
13086 my $fileInfo = $primaryCb->secondaryElementFileData($name);
13087
13088 my $entry_type = $lineCb->cb_type();
13089
13090 my @ownerColData;
13091 push(@ownerColData,
13092 [$lineTotal, $lineHit, $med_limit,
13093 $hi_limit, $showLineGraph, $lineCb,
13094 SummaryInfo::LINE_DATA
13095 ]);
13096 if ($hasMcdcData) {
13097 my ($mcdcMissed, $mcdcTotal, $mcdcCallback) = @$mcdc;
13098 # need to compute the totals...
13099 push(@ownerColData,
13100 [$mcdcTotal, $mcdcTotal - $mcdcMissed,
13101 $mcdc_med_limit, $mcdc_hi_limit,
13102 0, $mcdcCallback,
13103 SummaryInfo::MCDC_DATA
13104 ]);
13105 }
13106 if ($hasBranchData) {
13107 my ($branchMissed, $branchTotal, $brCallback) = @$branch;
13108 # need to compute the totals...
13109 push(@ownerColData,
13110 [$branchTotal, $branchTotal - $branchMissed,
13111 $br_med_limit, $br_hi_limit,
13112 0, $brCallback,
13113 SummaryInfo::BRANCH_DATA
13114 ]);
13115 }
13116 if ($includeFunctionColumns) {
13117 my ($funcMissed, $funcTotal, $funcCallback) = @$func;
13118 # need to compute the totals...
13119 push(@ownerColData,
13120 [$funcTotal, $funcTotal - $funcMissed,
13121 $fn_med_limit, $fn_hi_limit, 0, $funcCallback,
13122 SummaryInfo::FUNCTION_DATA
13123 ]);
13124 }
13125 if ($dirSummary->type() eq 'directory') {
13126 # use the basename (not the path or full path) in the
13127 # secondary key list:
13128 # - these are files in the current directory, so we lose
13129 # no information by eliding the directory part
13130 $name = File::Basename::basename($name);
13131 }
13132 $name = apply_prefix($name, @dir_prefix);
13133 write_file_table_entry(*HTML_HANDLE, $base_dir,
13134 # 'owner' page type - no span, no page link
13135 [$name,
13136 $fileInfo,
13137 $activeTlaCols,
13138 1,
13139 $primary_key,
13140 1 + $elide_secondary_header,
13141 $fileview,
13142 $entry_type,
13143 ],
13144 @ownerColData);
13145 }
13146
13147 next
13148 unless ($show_details &&
13149 defined($perTestcaseData) &&
13150 $primary_key eq "name");
13151
13152 # we know that the top-level callback item must hold a file.
13153 my $filename = $primaryCb->name();
13154
13155 my ($testhash, $testfnchash, $testbrhash, $testcase_mcdc) =
13156 @$perTestcaseData;
13157
13158 my $testdata = $testhash->{$filename};
13159
13160 # Check whether we should write test specific coverage as well
13161 next if (!defined($testdata));
13162
13163 my $testfncdata = $testfnchash->{$filename};
13164 my $testbrdata = $testbrhash->{$filename};
13165 my $test_mcdc = $testcase_mcdc->{$filename};
13166
13167 # Filter out those tests that actually affect this file
13168 my %affecting_tests = %{
13169 get_affecting_tests($testdata, $testfncdata, $testbrdata,
13170 $test_mcdc)
13171 };
13172
13173 # Does any of the tests affect this file at all?
13174 if (!%affecting_tests) { next; }
13175
13176 foreach my $testname (keys(%affecting_tests)) {
13177
13178 ($found, $hit, $fn_found, $fn_hit, $br_found, $br_hit, $mcdc_found,
13179 $mcdc_hit) = @{$affecting_tests{$testname}};
13180
13181 my $showgraph = 0;
13182 my @results;
13183 push(@results,
13184 [$found, $hit,
13185 SummaryInfo::LINE_DATA,
13186 TestcaseTlaCount->new(
13187 $testdata->value($testname), $fileDetails,
13188 SummaryInfo::LINE_DATA)
13189 ]);
13190 # there might not be optional test data for some tests - that type was
13191 # not enabled
13192 push(@results,
13193 [$mcdc_found,
13194 $mcdc_hit,
13195 SummaryInfo::MCDC_DATA,
13196 TestcaseTlaCount->new(
13197 $test_mcdc->value($testname), $fileDetails,
13198 SummaryInfo::MCDC_DATA)
13199 ])
13200 if ($hasMcdcData &&
13201 defined($test_mcdc->value($testname)));
13202
13203 push(@results,
13204 [$br_found,
13205 $br_hit,
13206 SummaryInfo::BRANCH_DATA,
13207 TestcaseTlaCount->new(
13208 $testbrdata->value($testname), $fileDetails,
13209 SummaryInfo::BRANCH_DATA)
13210 ])
13211 if ($hasBranchData &&
13212 defined($testbrdata->value($testname)));
13213
13214 push(@results,
13215 [$fn_found,
13216 $fn_hit,
13217 SummaryInfo::FUNCTION_DATA,
13218 TestcaseTlaCount->new(
13219 $testfncdata->value($testname), $fileDetails,
13220 SummaryInfo::FUNCTION_DATA)
13221 ])
13222 if ($includeFunctionColumns &&
13223 defined($testfncdata->value($testname)));
13224
13225 my $href = $testname;
13226 # Insert link to description of available
13227 if ($test_description{$testname}) {
13228 $href = "<a href=\"$base_dir" . "descriptions.$html_ext#T" .
13229 escape_id($testname) . "\">" . "$testname</a>";
13230 }
13231 write_file_table_detail_entry(*HTML_HANDLE, $base_dir,
13232 $href, $showBinDetail, $activeTlaCols, @results);
13233 }
13234 }
13235 foreach my $note (
13236 [ $suppressedEmptyRow,
13237 "<sup>&lowast;</sup> 'Detail' entries with no 'missed' coverpoints are elided. Use the '--show-owners all' flag to retain them."
13238 ],
13239 [ $suppressedSecondaryHeader,
13240 '<sup>&lowast;&lowast;</sup> Bin \'Total\' header elided when bin contains only one entry.'
13241 ],
13242 [ $lcovutil::func_coverage && !$includeFunctionColumns,
13243 "Note: 'Function Coverage' columns elided as function owner is not identified."
13244 ]
13245 ) {
13246 next unless $note->[0];
13247 write_html(*HTML_HANDLE, <<END_OF_HTML);
13248 <tr>
13249 <td class="footnote" colspan=$num_columns>$note->[1]</td>
13250 </tr>
13251 END_OF_HTML
13252
13253 }
13254
13255 write_file_table_epilog(*HTML_HANDLE);
13256 }
13257
13258 #
13259 # get_affecting_tests(testdata, testfncdata, testbrdata, pertest_mcdc)
13260 #
13261 # HASHREF contains a mapping filename -> (linenumber -> exec count). Return
13262 # a hash containing mapping filename -> "lines found, lines hit" for each
13263 # filename which has a nonzero hit count.
13264 #
13265
13266 sub get_affecting_tests($$$$)
13267 {
13268 my ($testdata, $testfncdata, $testbrdata, $testmcdcdata) = @_;
13269 my %result;
13270
13271 foreach my $testname ($testdata->keylist()) {
13272 # Get (line number -> count) hash for this test case
13273 my $testcount = $testdata->value($testname);
13274 my $testfnccount = $testfncdata->value($testname);
13275 my $testbrcount = $testbrdata->value($testname);
13276 my $testmcdccount = $testmcdcdata->value($testname);
13277
13278 # Calculate sum
13279 my ($found, $hit) = $testcount->get_found_and_hit();
13280 # might be no data for this testcase
13281 my ($fn_found, $fn_hit) =
13282 defined($testfnccount) ? $testfnccount->get_found_and_hit() :
13283 (0, 0);
13284 my ($br_found, $br_hit) =
13285 defined($testbrcount) ? $testbrcount->get_found_and_hit() : (0, 0);
13286 my ($mcdc_found, $mcdc_hit) =
13287 defined($testmcdccount) ? $testmcdccount->get_found_and_hit() :
13288 (0, 0);
13289
13290 $result{$testname} = [$found, $hit, $fn_found, $fn_hit,
13291 $br_found, $br_hit, $mcdc_found, $mcdc_hit
13292 ]
13293 if ($hit > 0);
13294 }
13295 return (\%result);
13296 }
13297
13298 #
13299 # write_source(filehandle, source_filename, count_data, checksum_data,
13300 # converted_data, func_data, sumbrcount, mcdc_summary)
13301 #
13302 # Write an HTML view of a source code file. Returns a list containing
13303 # data as needed by gen_png().
13304 #
13305 # Die on error.
13306 #
13307
13308 sub write_source($$$$$$$$)
13309 {
13310 local *HTML_HANDLE = shift;
13311 my ($srcfile, $count_data, $checkdata, $fileCovInfo,
13312 $funcdata, $sumbrcount, $mcdc_summary) = @_;
13313 my @result;
13314
13315 # suppress branch and MCDC columns if there is no data in the file
13316 my $showBranches = $lcovutil::br_coverage && 0 != $sumbrcount->found();
13317 my $showMcdc = $lcovutil::mcdc_coverage && 0 != $mcdc_summary->found();
13318
13319 write_source_prolog(*HTML_HANDLE, $srcfile->isProjectFile(),
13320 $showBranches, $showMcdc);
13321 my $line_number = 0;
13322 my $cbdata = PrintCallback->new($srcfile, $fileCovInfo);
13323
13324 my ($region, $empty);
13325 if ($selectCallback) {
13326 $region = InInterestingRegion->new($srcfile, $fileCovInfo->lineMap());
13327 $empty = '';
13328 if ($srcfile->isProjectFile()) {
13329 $empty .= ' ' x $main::age_field_width;
13330 $empty .= ' ' x $main::owner_field_width;
13331 }
13332 # using 8 characters for line number field, with different
13333 # foreground/background - to make distinctive
13334 $empty .= ' <span class="lineNumWithDelete">' .
13335 (' ' x (8 - 3)) . '...</span>';
13336 $empty .= ' ' x $main::br_field_width if $showBranches;
13337 $empty .= ' ' x $main::mcdc_field_width if $showMcdc;
13338 $empty .= ' ' x $main::tla_field_width;
13339 $empty .= ' ' x ($line_field_width - 1);
13340 $empty .=
13341 '<span class="elidedSource"> (elided NUM_LINES ignored lines)</span>';
13342 }
13343
13344 my $prevLine = 0;
13345 foreach my $srcline (@{$srcfile->lines()}) {
13346 $line_number++;
13347 $cbdata->lineNo($line_number);
13348 if (defined($region) && !$region->interesting($line_number)) {
13349 lcovutil::info(1, "skip line $line_number\n");
13350 next;
13351 }
13352 if ($prevLine != $line_number - 1) {
13353 $cbdata->age(-1, $line_number);
13354 $cbdata->owner(undef, $line_number);
13355 $cbdata->tla(undef, $line_number);
13356
13357 lcovutil::info(1, "continuation_line $line_number\n");
13358 my $l = $empty;
13359 my $c = $line_number - ($prevLine + 1);
13360 $l =~ s/NUM_LINES/$c/;
13361 push(@result, $l);
13362 write_html(*HTML_HANDLE, $l . "\n");
13363 }
13364 $prevLine = $line_number;
13365
13366 # Source code matches coverage data?
13367 lcovutil::ignorable_error($lcovutil::ERROR_MISMATCH,
13368 "checksum mismatch at " . $srcfile->path() . ":$line_number\n")
13369 if (
13370 defined($checkdata->value($line_number)) &&
13371 ($checkdata->value($line_number) ne md5_base64($srcline->text()))
13372 );
13373 push(@result,
13374 write_source_line(HTML_HANDLE, $srcline,
13375 $count_data->value($line_number), $showBranches,
13376 $sumbrcount->value($line_number), $showMcdc,
13377 $mcdc_summary->value($line_number), $cbdata));
13378 }
13379 if ($prevLine != $line_number) {
13380 # need another blank line at the bottom...
13381 my $l = $empty;
13382 my $c = $line_number - $prevLine;
13383 $l =~ s/NUM_LINES/$c/;
13384 push(@result, $l);
13385 write_html(*HTML_HANDLE, $l . "\n");
13386 }
13387
13388 write_source_epilog(*HTML_HANDLE);
13389 return (@result);
13390 }
13391
13392 sub funcview_get_label($$$$)
13393 {
13394 my ($name, $base, $col, $sort_type) = @_;
13395 my $link;
13396
13397 if (!defined($col)) {
13398 if ($sort_tables && $sort_type != $SORT_FILE) {
13399 $link = "$name.func.$html_ext";
13400 }
13401 return "Function Name" . get_sort_code($link, "function name", $base);
13402 } elsif ($col eq 'hit') {
13403 if ($sort_tables && $sort_type != $SORT_LINE) {
13404 $link = "$name.func-c.$html_ext";
13405 }
13406 return "Hit count" . get_sort_code($link, "function hit count", $base);
13407 } elsif ($col eq 'missed_line') {
13408 if ($sort_tables && $sort_type != $SORT_MISSING_LINE) {
13409 $link = "$name.func-l.$html_ext";
13410 }
13411 return "Lines" .
13412 get_sort_code($link, "unexercised lines in function", $base);
13413 } elsif ($col eq 'missed_mcdc') {
13414 if ($sort_tables && $sort_type != $SORT_MISSING_MCDC) {
13415 $link = "$name.func-m.$html_ext";
13416 }
13417 return "MC/DC"
13418 .
13419 get_sort_code($link, "unexercised MC/DC expressions in function",
13420 $base);
13421 } else {
13422 die("unexpected sort $col") unless ($col eq 'missed_branch');
13423 if ($sort_tables && $sort_type != $SORT_MISSING_BRANCH) {
13424 $link = "$name.func-b.$html_ext";
13425 }
13426 return "Branches" .
13427 get_sort_code($link, "unexercised branches in function", $base);
13428 }
13429 }
13430
13431 #
13432 # funcview_get_sorted(funcdata, sort_type, mergedView)
13433 #
13434 # Depending on the value of sort_type, return a list of functions sorted
13435 # by name (type 0) or by the associated call count (type 1).
13436 #
13437
13438 sub funcview_get_sorted($$$)
13439 {
13440 my ($funcData, $type, $merged) = @_;
13441
13442 my ($differential_func, $lineFuncData, $branchFuncData, $mcdcFuncData) =
13443 @$funcData;
13444 my @rtn = keys(%$differential_func);
13445
13446 if ($type == $SORT_LINE) {
13447 @rtn = sort({
13448 my $da = $differential_func->{$a}->hit();
13449 my $db = $differential_func->{$b}->hit();
13450 $da->[0] <=> $db->[0] or
13451 # sort by function name if count matches
13452 $a cmp $b
13453 } @rtn);
13454 } elsif ($type == $SORT_MISSING_LINE) {
13455 @rtn = sort({
13456 my $linea =
13457 exists($lineFuncData->{$a}) ? $lineFuncData->{$a} :
13458 undef;
13459 my $lineb =
13460 exists($lineFuncData->{$b}) ? $lineFuncData->{$b} :
13461 undef;
13462 my $missedA =
13463 defined($linea) ? $linea->[0] - $linea->[1] : -1;
13464 my $missedB =
13465 defined($lineb) ? $lineb->[0] - $lineb->[1] : -1;
13466
13467 # highest to lowest 'missed lines', then by
13468 # function name if count matches
13469 $missedB <=> $missedA or $a cmp $b
13470 } @rtn);
13471 } elsif ($type == $SORT_MISSING_BRANCH) {
13472 @rtn = sort({
13473 my $bra =
13474 exists($branchFuncData->{$a}) ?
13475 $branchFuncData->{$a} :
13476 undef;
13477 my $brb =
13478 exists($branchFuncData->{$b}) ?
13479 $branchFuncData->{$b} :
13480 undef;
13481 my $missedA =
13482 defined($bra) ? $bra->[0] - $bra->[1] : -1;
13483 my $missedB =
13484 defined($brb) ? $brb->[0] - $brb->[1] : -1;
13485
13486 # highest to lowest 'missed branches', then by
13487 # function name if count matches
13488 $missedB <=> $missedA or $a cmp $b
13489 } @rtn);
13490 } elsif ($type == $SORT_MISSING_MCDC) {
13491 @rtn = sort({
13492 my $bra =
13493 exists($mcdcFuncData->{$a}) ?
13494 $mcdcFuncData->{$a} :
13495 undef;
13496 my $brb =
13497 exists($mcdcFuncData->{$b}) ?
13498 $mcdcFuncData->{$b} :
13499 undef;
13500 my $missedA =
13501 defined($bra) ? $bra->[0] - $bra->[1] : -1;
13502 my $missedB =
13503 defined($brb) ? $brb->[0] - $brb->[1] : -1;
13504
13505 # highest to lowest 'missed expressions', then by
13506 # function name if count matches
13507 $missedB <=> $missedA or $a cmp $b
13508 } @rtn);
13509
13510 } elsif (!defined($main::no_sort)) {
13511 # sort alphabetically by function name
13512 @rtn = sort(@rtn);
13513 }
13514 return @rtn;
13515 }
13516
13517 #
13518 # write_function_table(filehandle, funcData, source_file, sumcount, funcdata,
13519 # testfncdata, sumbrcount, testbrdata, mcdc_summary, testase_mcdc,
13520 # base_name, base_dir, sort_type)
13521 #
13522 # Write an HTML table listing all functions in a source file, including
13523 # also function call counts and line coverages inside of each function.
13524 #
13525 # Die on error.
13526 #
13527
13528 sub write_function_table(*$$$$$$$$$$$$)
13529 {
13530 local *HTML_HANDLE = shift;
13531 my ($funcData, $source, $sumcount, $funcdata,
13532 $testfncdata, $sumbrcount, $testbrdata, $mcdc_summary,
13533 $testcase_mcdc, $name, $base, $type) = @_;
13534 my ($differentialMap, $funcLineCovMap, $funcBranchCovMap, $funcMcdcCovMap)
13535 = @$funcData;
13536 # Get HTML code for headings
13537 my $func_code = funcview_get_label($name, $base, undef, $type);
13538 my $count_code = funcview_get_label($name, $base, 'hit', $type);
13539 my $line_code = funcview_get_label($name, $base, 'missed_line', $type);
13540 my $branch_code = funcview_get_label($name, $base, 'missed_branch', $type);
13541 my $mcdc_code = funcview_get_label($name, $base, 'missed_mcdc', $type);
13542 my $showTlas = $main::show_tla && 0 != scalar(keys %$differentialMap);
13543 my $tlaRow = "";
13544 my $lineProportionRow = '';
13545 my $branchProportionRow = '';
13546 my $mcdcProportionRow = '';
13547 my $countWidth = 20;
13548
13549 if ($showTlas) {
13550 my $label = $main::use_legacyLabels ? 'Hit?' : 'TLA';
13551 $tlaRow = "<td width=\"10%\" class=\"tableHead\">$label</td>";
13552 $countWidth = 10;
13553 }
13554 if ($main::show_functionProportions) {
13555 $lineProportionRow = "<td class=\"tableHead\">$line_code</td>"
13556 if (%$funcLineCovMap);
13557 $branchProportionRow = "<td class=\"tableHead\">$branch_code</td>"
13558 if $lcovutil::br_coverage && %$funcBranchCovMap;
13559 $mcdcProportionRow = "<td class=\"tableHead\">$mcdc_code</td>"
13560 if $lcovutil::mcdc_coverage && %$funcMcdcCovMap;
13561 }
13562
13563 die("no functions in file") unless (%$differentialMap);
13564 write_html(*HTML_HANDLE, <<END_OF_HTML);
13565 <center>
13566 <table cellpadding=1 cellspacing=1 border=0>
13567 <tr><td><br></td></tr>
13568 <tr>
13569 <td class="tableHead">$func_code</td>
13570 $tlaRow
13571 <td class="tableHead">$count_code</td>
13572 $lineProportionRow
13573 $branchProportionRow
13574 $mcdcProportionRow
13575 </tr>
13576 END_OF_HTML
13577
13578 foreach my $func (
13579 funcview_get_sorted($funcData, $type, $main::merge_function_aliases)) {
13580
13581 my $funcEntry = $differentialMap->{$func};
13582 my ($count, $tla) = @{$funcEntry->hit()};
13583 next
13584 if grep(/^$tla$/, ('DUB', 'DCB')); # don't display deleted functions
13585 my $startline = $funcEntry->line() - $func_offset;
13586 my $name = $func;
13587 my $countstyle;
13588
13589 # Escape special characters
13590 $name = escape_html($name);
13591 if ($startline < 1) {
13592 $startline = 1;
13593 }
13594 if ($count == 0) {
13595 $countstyle = "coverFnLo";
13596 } else {
13597 $countstyle = "coverFnHi";
13598 }
13599 my $tlaRow = "";
13600 my $lineProportionRow = '';
13601 my $branchProportionRow = '';
13602 my $mcdcProportionRow = '';
13603 if ($showTlas) {
13604 my $label =
13605 $main::use_legacyLabels ? $SummaryInfo::tlaToLegacy{$tla} :
13606 $tla;
13607 $tlaRow = "<td class=\"tla$tla\">$label</td>";
13608 }
13609 if ($main::show_functionProportions) {
13610 if (exists($funcLineCovMap->{$func})) {
13611 my ($found, $hit) = @{$funcLineCovMap->{$func}};
13612 # colorize based on hit proportion
13613 my $style =
13614 $rate_name[classify_rate($found, $hit, $ln_med_limit,
13615 $ln_hi_limit)];
13616 my $rate = rate($hit, $found, "&nbsp;%");
13617 $lineProportionRow =
13618 "<td class=coverPer$style>$rate ($hit / $found)</td>";
13619 } else {
13620 $lineProportionRow = "<td class=\"coverFn\"></td>"
13621 if %$funcLineCovMap;
13622 }
13623 if ($lcovutil::br_coverage && %$funcBranchCovMap) {
13624 if (exists($funcBranchCovMap->{$func})) {
13625 my ($found, $hit) = @{$funcBranchCovMap->{$func}};
13626 # colorize based on hit proportion
13627 my $style = $rate_name[
13628 classify_rate($found, $hit, $br_med_limit, $br_hi_limit)
13629 ];
13630 my $rate = rate($hit, $found, "&nbsp;%");
13631 $branchProportionRow =
13632 "<td class=coverPer$style>$rate ($hit / $found)</td>";
13633 } else {
13634 $branchProportionRow = "<td class=\"coverFn\"></td>";
13635 }
13636 }
13637 if ($lcovutil::mcdc_coverage && %$funcMcdcCovMap) {
13638 if (exists($funcMcdcCovMap->{$func})) {
13639 my ($found, $hit) = @{$funcMcdcCovMap->{$func}};
13640 # colorize based on hit proportion
13641 my $style = $rate_name[
13642 classify_rate($found, $hit, $mcdc_med_limit,
13643 $mcdc_hi_limit)
13644 ];
13645 my $rate = rate($hit, $found, "&nbsp;%");
13646 $mcdcProportionRow =
13647 "<td class=coverPer$style>$rate ($hit / $found)</td>";
13648 } else {
13649 $mcdcProportionRow = "<td class=\"coverFn\"></td>";
13650 }
13651 }
13652 }
13653
13654 write_html(*HTML_HANDLE, <<END_OF_HTML);
13655 <tr>
13656 <td class="coverFn"><a href="$source#L$startline">$name</a></td>
13657 $tlaRow
13658 <td class="$countstyle">$count</td>
13659 $lineProportionRow
13660 $branchProportionRow
13661 $mcdcProportionRow
13662 </tr>
13663 END_OF_HTML
13664
13665 if ((!defined($main::suppress_function_aliases) ||
13666 0 == $main::suppress_function_aliases) &&
13667 $funcEntry->numAliases() > 1
13668 ) {
13669 my $aliases = $funcEntry->aliases();
13670 my @aliasList = keys(%$aliases);
13671 if ($main::show_functionProportions) {
13672 $lineProportionRow = "<td class=\"coverFn\"></td>"
13673 if %$funcLineCovMap;
13674 $branchProportionRow = $lineProportionRow
13675 if $lcovutil::br_coverage && %$funcBranchCovMap;
13676 $mcdcProportionRow = $mcdcProportionRow
13677 if $lcovutil::mcdc_coverage && %$funcMcdcCovMap;
13678 }
13679 if (0 != $type) {
13680 @aliasList =
13681 sort({
13682 my $da = $aliases->{$a};
13683 my $db = $aliases->{$b};
13684 $da->[0] <=> $db->[0] or $a cmp $b
13685 } @aliasList);
13686 } else {
13687 @aliasList = sort(@aliasList);
13688 }
13689 foreach my $alias (@aliasList) {
13690 my ($hit, $tla) = @{$aliases->{$alias}};
13691 # don't display deleted functions
13692 next if grep(/^$tla$/, ('DUB', 'DCB')); #
13693 my $style = "coverFnAlias" . ($hit == 0 ? "Lo" : "Hi");
13694 $tlaRow = "";
13695 if ($showTlas) {
13696 my $label =
13697 $main::use_legacyLabels ?
13698 $SummaryInfo::tlaToLegacy{$tla} :
13699 $tla;
13700 $tlaRow = "<td class=\"tla$tla\">$label</td>";
13701 }
13702
13703 # Escape special characters
13704 $alias = escape_html($alias);
13705
13706 write_html(*HTML_HANDLE, <<END_OF_HTML);
13707 <tr>
13708 <td class="coverFnAlias"><a href="$source#L$startline">$alias</a></td>
13709 $tlaRow
13710 <td class="$style">$hit</td>
13711 $lineProportionRow
13712 $branchProportionRow
13713 $mcdcProportionRow
13714 </tr>
13715 END_OF_HTML
13716 }
13717 }
13718 }
13719 write_html(*HTML_HANDLE, <<END_OF_HTML);
13720 </table>
13721 <br>
13722 </center>
13723 END_OF_HTML
13724 }
13725
13726 #
13727 # remove_unused_descriptions()
13728 #
13729 # Removes all test descriptions from the global hash %test_description which
13730 # are not present in %current_data.
13731 #
13732
13733 sub remove_unused_descriptions()
13734 {
13735 my $filename; # The current filename
13736 my %test_list; # Hash containing found test names
13737 my $test_data; # Reference to hash test_name -> count_data
13738 my $before; # Initial number of descriptions
13739 my $after; # Remaining number of descriptions
13740
13741 $before = scalar(keys(%test_description));
13742
13743 foreach $filename ($current_data->files()) {
13744 ($test_data) = $current_data->data($filename)->get_info();
13745 foreach ($test_data->keylist()) {
13746 $test_list{$_} = "";
13747 }
13748 }
13749
13750 # Remove descriptions for tests which are not in our list
13751 foreach (keys(%test_description)) {
13752 if (!defined($test_list{$_})) {
13753 delete($test_description{$_});
13754 }
13755 }
13756
13757 $after = scalar(keys(%test_description));
13758 if ($after < $before) {
13759 info("Removed " . ($before - $after) .
13760 " unused descriptions, $after remaining.\n");
13761 }
13762 }
13763
13764 #
13765 # apply_prefix(filename, PREFIXES)
13766 #
13767 # If FILENAME begins with PREFIX from PREFIXES, remove PREFIX from FILENAME
13768 # and return resulting string, otherwise return FILENAME.
13769 #
13770
13771 sub apply_prefix($@)
13772 {
13773 my $filename = shift;
13774
13775 foreach my $prefix (@_) {
13776 if ($prefix eq $filename) {
13777 return 'root';
13778 }
13779 if ($prefix ne "" &&
13780 $filename =~ /^\Q$prefix\E$lcovutil::dirseparator(.*)$/) {
13781 return substr($filename, length($prefix) + 1);
13782 }
13783 }
13784
13785 return $filename;
13786 }
13787
13788 #
13789 # get_html_prolog(FILENAME)
13790 #
13791 # If FILENAME is defined, return contents of file. Otherwise return default
13792 # HTML prolog. Die on error.
13793 #
13794
13795 sub get_html_prolog($)
13796 {
13797 my $filename = $_[0];
13798 my $result = "";
13799
13800 if (defined($filename)) {
13801 local *HANDLE;
13802
13803 open(HANDLE, "<", $filename) or
13804 die("cannot open html prolog $filename: $!\n");
13805 while (<HANDLE>) {
13806 $result .= $_;
13807 }
13808 close(HANDLE) or die("unable to close HTML handle: $!\n");
13809 } else {
13810 $result = <<END_OF_HTML;
13811 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
13812
13813 <html lang="en">
13814
13815 <head>
13816 <meta http-equiv="Content-Type" content="text/html; charset=$charset">
13817 <title>\@pagetitle\@</title>
13818 <link rel="stylesheet" type="text/css" href="\@basedir\@gcov.css">
13819 </head>
13820
13821 <body>
13822
13823 END_OF_HTML
13824 }
13825 return $result;
13826 }
13827
13828 #
13829 # get_html_epilog(FILENAME)
13830 #
13831 # If FILENAME is defined, return contents of file. Otherwise return default
13832 # HTML epilog. Die on error.
13833 #
13834 sub get_html_epilog($)
13835 {
13836 my $filename = $_[0];
13837 my $result = "";
13838
13839 if (defined($filename)) {
13840 local *HANDLE;
13841
13842 open(HANDLE, "<", $filename) or
13843 die("cannot open html epilog $filename: $!\n");
13844 while (<HANDLE>) {
13845 $result .= $_;
13846 }
13847 close(HANDLE) or die("unable to close HTML handle: $!\n");
13848 } else {
13849 $result = <<END_OF_HTML;
13850
13851 </body>
13852 </html>
13853 END_OF_HTML
13854 }
13855
13856 return $result;
13857 }
13858
13859 #
13860 # parse_dir_prefix(@dir_prefix)
13861 #
13862 # Parse user input about the prefix list
13863 #
13864
13865 sub parse_dir_prefix(@)
13866 {
13867 my (@opt_dir_prefix) = @_;
13868
13869 return if (!@opt_dir_prefix);
13870
13871 foreach my $item (@opt_dir_prefix) {
13872 if ($item =~ /$lcovutil::split_char/) {
13873 # Split and add comma-separated parameters
13874 push(@dir_prefix, split($lcovutil::split_char, $item));
13875 } else {
13876 # Add single parameter
13877 push(@dir_prefix, $item);
13878 }
13879 }
13880 }