-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathlcovutil.pm
9547 lines (8625 loc) · 324 KB
/
lcovutil.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# some common utilities for lcov-related scripts
use strict;
use warnings;
require Exporter;
package lcovutil;
use File::Path qw(rmtree);
use File::Basename qw(basename dirname);
use File::Temp qw /tempdir/;
use File::Spec;
use Scalar::Util qw/looks_like_number/;
use Cwd qw/abs_path getcwd/;
use Storable qw(dclone);
use Capture::Tiny;
use Module::Load::Conditional qw(check_install);
use Digest::MD5 qw(md5_base64);
use FindBin;
use Getopt::Long;
use DateTime;
use Config;
use POSIX;
use Fcntl qw(:flock SEEK_END);
our @ISA = qw(Exporter);
our @EXPORT_OK = qw($tool_name $tool_dir $lcov_version $lcov_url $VERSION
@temp_dirs set_tool_name
info warn_once set_info_callback init_verbose_flag $verbose
debug $debug
append_tempdir create_temp_dir temp_cleanup folder_is_empty $tmp_dir $preserve_intermediates
summarize_messages define_errors
parse_ignore_errors ignorable_error ignorable_warning
is_ignored message_count explain_once
die_handler warn_handler abort_handler
$maxParallelism $maxMemory init_parallel_params current_process_size
$memoryPercentage $max_fork_fails $fork_fail_timeout
save_profile merge_child_profile save_cmd_line
@opt_rc apply_rc_params $split_char parseOptions
strip_directories
@file_subst_patterns subst_file_name
@comments
$br_coverage $func_coverage $mcdc_coverage
@cpp_demangle do_mangle_check $demangle_cpp_cmd
$cpp_demangle_tool $cpp_demangle_params
get_overall_line rate
$FILTER_BRANCH_NO_COND $FILTER_FUNCTION_ALIAS
$FILTER_EXCLUDE_REGION $FILTER_EXCLUDE_BRANCH $FILTER_LINE
$FILTER_LINE_CLOSE_BRACE $FILTER_BLANK_LINE $FILTER_LINE_RANGE
$FILTER_TRIVIAL_FUNCTION $FILTER_DIRECTIVE
$FILTER_MISSING_FILE $FILTER_INITIALIZER_LIST
$FILTER_EXCEPTION_BRANCH $FILTER_ORPHAN_BRANCH
@cov_filter
$EXCL_START $EXCL_STOP $EXCL_BR_START $EXCL_BR_STOP
$EXCL_EXCEPTION_BR_START $EXCL_EXCEPTION_BR_STOP
$EXCL_LINE $EXCL_BR_LINE $EXCL_EXCEPTION_LINE
@exclude_file_patterns @include_file_patterns %excluded_files
@omit_line_patterns @exclude_function_patterns $case_insensitive
munge_file_patterns warn_file_patterns transform_pattern
parse_cov_filters summarize_cov_filters
disable_cov_filters reenable_cov_filters is_filter_enabled
filterStringsAndComments simplifyCode balancedParens
set_extensions
$source_filter_lookahead $source_filter_bitwise_are_conditional
$exclude_exception_branch
$derive_function_end_line $derive_function_end_line_all_files
$trivial_function_threshold
$filter_blank_aggressive
$lcov_filter_parallel $lcov_filter_chunk_size
%lcovErrors $ERROR_GCOV $ERROR_SOURCE $ERROR_GRAPH $ERROR_MISMATCH
$ERROR_BRANCH $ERROR_EMPTY $ERROR_FORMAT $ERROR_VERSION $ERROR_UNUSED
$ERROR_PACKAGE $ERROR_CORRUPT $ERROR_NEGATIVE $ERROR_COUNT $ERROR_PATH
$ERROR_UNSUPPORTED $ERROR_DEPRECATED $ERROR_INCONSISTENT_DATA
$ERROR_CALLBACK $ERROR_RANGE $ERROR_UTILITY $ERROR_USAGE $ERROR_INTERNAL
$ERROR_PARALLEL $ERROR_PARENT $ERROR_CHILD $ERROR_FORK
$ERROR_EXCESSIVE_COUNT $ERROR_MISSING
report_parallel_error report_exit_status check_parent_process
report_unknown_child
$ERROR_UNMAPPED_LINE $ERROR_UNKNOWN_CATEGORY $ERROR_ANNOTATE_SCRIPT
$stop_on_error
@extractVersionScript $verify_checksum $compute_file_version
configure_callback cleanup_callbacks
is_external @internal_dirs $opt_no_external @build_directory
$default_precision check_precision
system_no_output $devnull $dirseparator
%tlaColor %tlaTextColor use_vanilla_color %pngChar %pngMap
%dark_palette %normal_palette parse_w3cdtf
);
our @ignore;
our @message_count;
our @expected_message_count;
our %message_types;
our $message_log;
our $message_filename;
our $suppressAfter = 100; # stop warning after this number of messages
our %ERROR_ID;
our %ERROR_NAME;
our $tool_dir = "$FindBin::RealBin";
our $tool_name = basename($0); # import from lcovutil module
our $VERSION = `"$tool_dir"/get_version.sh --full`;
chomp($VERSION);
our $lcov_version = 'LCOV version ' . $VERSION;
our $lcov_url = "https://github.com//linux-test-project/lcov";
our @temp_dirs;
our $tmp_dir = '/tmp'; # where to put temporary/intermediate files
our $preserve_intermediates; # this is useful only for debugging
our $devnull = File::Spec->devnull(); # portable way to do it
our $dirseparator = ($^O =~ /Win/) ? '\\' : '/';
our $interp = ($^O =~ /Win/) ? $^X : undef;
our $debug = 0; # if set, emit debug messages
our $verbose = 0; # default level - higher to enable additional logging
our $split_char = ','; # by default: split on comma
# share common definition for all error types.
# Note that geninfo cannot produce some types produced by genhtml, and vice
# versa. Easier to maintain a common definition.
our $ERROR_GCOV;
our $ERROR_SOURCE;
our $ERROR_GRAPH;
our $ERROR_FORMAT; # bad record in .info file
our $ERROR_EMPTY; # no records found in info file
our $ERROR_VERSION;
our $ERROR_UNUSED; # exclude/include/substitute pattern not used
our $ERROR_MISMATCH;
our $ERROR_BRANCH; # branch numbering is not correct
our $ERROR_PACKAGE; # missing utility package
our $ERROR_CORRUPT; # corrupt file
our $ERROR_NEGATIVE; # unexpected negative count in coverage data
our $ERROR_COUNT; # too many messages of type
our $ERROR_UNSUPPORTED; # some unsupported feature or usage
our $ERROR_PARALLEL; # error in fork/join
our $ERROR_DEPRECATED; # deprecated feature
our $ERROR_CALLBACK; # callback produced an error
our $ERROR_INCONSISTENT_DATA; # something wrong with .info
our $ERROR_RANGE; # line number out of range
our $ERROR_UTILITY; # some tool failed - e.g., 'find'
our $ERROR_USAGE; # misusing some feature
our $ERROR_PATH; # path issues
our $ERROR_INTERNAL; # tool issue
our $ERROR_PARENT; # parent went away so child should die
our $ERROR_CHILD; # nonzero child exit status
our $ERROR_FORK; # fork failed
our $ERROR_EXCESSIVE_COUNT; # suspiciously large hit count
our $ERROR_MISSING; # file missing/not found
# genhtml errors
our $ERROR_UNMAPPED_LINE; # inconsistent coverage data
our $ERROR_UNKNOWN_CATEGORY; # we did something wrong with inconsistent data
our $ERROR_ANNOTATE_SCRIPT; # annotation failed somehow
my @lcovErrs = (["annotate", \$ERROR_ANNOTATE_SCRIPT],
["branch", \$ERROR_BRANCH],
["callback", \$ERROR_CALLBACK],
["category", \$ERROR_UNKNOWN_CATEGORY],
["child", \$ERROR_CHILD],
["corrupt", \$ERROR_CORRUPT],
["count", \$ERROR_COUNT],
["deprecated", \$ERROR_DEPRECATED],
["empty", \$ERROR_EMPTY],
['excessive', \$ERROR_EXCESSIVE_COUNT],
["format", \$ERROR_FORMAT],
["fork", \$ERROR_FORK],
["gcov", \$ERROR_GCOV],
["graph", \$ERROR_GRAPH],
["inconsistent", \$ERROR_INCONSISTENT_DATA],
["internal", \$ERROR_INTERNAL],
["mismatch", \$ERROR_MISMATCH],
["missing", \$ERROR_MISSING],
["negative", \$ERROR_NEGATIVE],
["package", \$ERROR_PACKAGE],
["parallel", \$ERROR_PARALLEL],
["parent", \$ERROR_PARENT],
["path", \$ERROR_PATH],
["range", \$ERROR_RANGE],
["source", \$ERROR_SOURCE],
["unmapped", \$ERROR_UNMAPPED_LINE],
["unsupported", \$ERROR_UNSUPPORTED],
["unused", \$ERROR_UNUSED],
['usage', \$ERROR_USAGE],
['utility', \$ERROR_UTILITY],
["version", \$ERROR_VERSION],);
our %lcovErrors;
our $stop_on_error; # attempt to keep going
our $treat_warning_as_error = 0;
our $warn_once_per_file = 1;
our $excessive_count_threshold; # default not set: don't check
our $br_coverage = 0; # If set, generate branch coverage statistics
our $mcdc_coverage = 0; # MC/DC
our $func_coverage = 1; # If set, generate function coverage statistics
# for external file filtering
our @internal_dirs;
our $opt_no_external;
# Where code was built/where .gcno files can be found
# (if .gcno files are in a different place than the .gcda files)
# also used by genhtml to match diff file entries to .info file
our @build_directory;
our @configured_callbacks;
# optional callback to keep track of whatever user decides is important
our @contextCallback;
our $contextCallback;
# filename substitutions
our @file_subst_patterns;
# resolve callback
our @resolveCallback;
our $resolveCallback;
our %resolveCache;
# C++ demangling
our @cpp_demangle; # the options passed in
our $demangle_cpp_cmd; # the computed command string
# deprecated: demangler for C++ function names is c++filt
our $cpp_demangle_tool;
# Deprecated: prefer -Xlinker approach with @cpp_dmangle_tool
our $cpp_demangle_params;
# version extract may be expensive - so only do it once
our %versionCache;
our @extractVersionScript; # script/callback to find version ID of file
our $versionCallback;
our $verify_checksum; # compute and/or check MD5 sum of source code lines
our $check_file_existence_before_callback = 1;
our $check_data_consistency = 1;
# Specify coverage rate default precision
our $default_precision = 1;
# undef indicates not set by command line or RC option - so default to
# sequential processing
our $maxParallelism;
our $max_fork_fails = 5; # consecutive failures
our $fork_fail_timeout = 10; # how long to wait, in seconds
our $maxMemory; # zero indicates no memory limit to parallelism
our $memoryPercentage;
our $in_child_process = 0;
our $max_tasks_per_core = 20; # maybe default to 0?
our $lcov_filter_parallel = 1; # enable by default
our $lcov_filter_chunk_size;
our $fail_under_lines;
our $fail_under_branches;
our $fix_inconsistency = 1;
sub default_info_impl(@);
our $info_callback = \&default_info_impl;
# filter classes that may be requested
# don't report BRDA data for line which seem to have no conditionals
# These may be from C++ exception handling (for example) - and are not
# interesting to users.
our $FILTER_BRANCH_NO_COND;
# don't report line coverage for closing brace of a function
# or basic block, if the immediate predecessor line has the same count.
our $FILTER_LINE_CLOSE_BRACE;
# merge functions which appear on same file/line - guess that that
# they are all the same
our $FILTER_FUNCTION_ALIAS;
# region between LCOV EXCL_START/STOP
our $FILTER_EXCLUDE_REGION;
# region between LCOV EXCL_BR_START/STOP
our $FILTER_EXCLUDE_BRANCH;
# empty line
our $FILTER_BLANK_LINE;
# out of range line - beyond end of file
our $FILTER_LINE_RANGE;
# backward compatibility: empty line, close brace
our $FILTER_LINE;
# filter initializer list-like stuff
our $FILTER_INITIALIZER_LIST;
# remove functions which have only a single line
our $FILTER_TRIVIAL_FUNCTION;
# remove compiler directive lines which llvm-cov seems to generate
our $FILTER_DIRECTIVE;
# remove missing source file
our $FILTER_MISSING_FILE;
# remove branches marked as related to exceptions
our $FILTER_EXCEPTION_BRANCH;
# remove lone branch in block - it can't be an actual conditional
our $FILTER_ORPHAN_BRANCH;
# MC/DC with single expression is identical to branch
our $FILTER_MCDC_SINGLE;
our $FILTER_OMIT_PATTERNS; # special/somewhat faked filter
our %COVERAGE_FILTERS = ("branch" => \$FILTER_BRANCH_NO_COND,
'brace' => \$FILTER_LINE_CLOSE_BRACE,
'blank' => \$FILTER_BLANK_LINE,
'directive' => \$FILTER_DIRECTIVE,
'range' => \$FILTER_LINE_RANGE,
'line' => \$FILTER_LINE,
'initializer' => \$FILTER_INITIALIZER_LIST,
'function' => \$FILTER_FUNCTION_ALIAS,
'missing' => \$FILTER_MISSING_FILE,
'region' => \$FILTER_EXCLUDE_REGION,
'branch_region' => \$FILTER_EXCLUDE_BRANCH,
'exception' => \$FILTER_EXCEPTION_BRANCH,
'orphan' => \$FILTER_ORPHAN_BRANCH,
'mcdc' => \$FILTER_MCDC_SINGLE,
"trivial" => \$FILTER_TRIVIAL_FUNCTION,);
our @cov_filter; # 'undef' if filter is not enabled,
# [line_count, coverpoint_count] histogram if
# filter is enabled: number of applications
# of this filter
our $EXCL_START = "LCOV_EXCL_START";
our $EXCL_STOP = "LCOV_EXCL_STOP";
# Marker to exclude branch coverage but keep function and line coverage
our $EXCL_BR_START = "LCOV_EXCL_BR_START";
our $EXCL_BR_STOP = "LCOV_EXCL_BR_STOP";
# marker to exclude exception branches but keep other branches
our $EXCL_EXCEPTION_BR_START = 'LCOV_EXCL_EXCEPTION_BR_START';
our $EXCL_EXCEPTION_BR_STOP = 'LCOV_EXCL_EXCEPTION_BR_STOP';
# exclude on this line
our $EXCL_LINE = 'LCOV_EXCL_LINE';
our $EXCL_BR_LINE = 'LCOV_EXCL_BR_LINE';
our $EXCL_EXCEPTION_LINE = 'LCOV_EXCL_EXCEPTION_BR_LINE';
our @exclude_file_patterns;
our @include_file_patterns;
our %excluded_files;
our $case_insensitive = 0;
our $exclude_exception_branch = 0;
our $derive_function_end_line = 1;
our $derive_function_end_line_all_files = 0; # by default, C only
our $trivial_function_threshold = 5;
# list of regexps applied to line text - if exclude if matched
our @omit_line_patterns;
our @exclude_function_patterns;
# need a pattern copy that we don't disable for function message suppressions
our @suppress_function_patterns;
our %languageExtensions = ('c' => 'c|h|i|C|H|I|icc|cpp|cc|cxx|hh|hpp|hxx',
'rtl' => 'v|vh|sv|vhdl?',
'perl' => 'pl|pm',
'python' => 'py',
'java' => 'java');
our $info_file_pattern = '*.info';
# don't look more than 10 lines ahead when filtering (default)
our $source_filter_lookahead = 10;
# by default, don't treat expressions containing bitwise operators '|', '&', '~'
# as conditional in bogus branch filtering
our $source_filter_bitwise_are_conditional = 0;
# filter out blank lines whether they are hit or not
our $filter_blank_aggressive = 0;
our %dark_palette = ('COLOR_00' => "e4e4e4",
'COLOR_01' => "58a6ff",
'COLOR_02' => "8b949e",
'COLOR_03' => "3b4c71",
'COLOR_04' => "006600",
'COLOR_05' => "4b6648",
'COLOR_06' => "495366",
'COLOR_07' => "143e4f",
'COLOR_08' => "1c1e23",
'COLOR_09' => "202020",
'COLOR_10' => "801b18",
'COLOR_11' => "66001a",
'COLOR_12' => "772d16",
'COLOR_13' => "796a25",
'COLOR_14' => "000000",
'COLOR_15' => "58a6ff",
'COLOR_16' => "eeeeee",
'COLOR_17' => "E5DBDB",
'COLOR_18' => "82E0AA",
'COLOR_19' => 'F9E79F',
'COLOR_20' => 'EC7063',);
our %normal_palette = ('COLOR_00' => "000000",
'COLOR_01' => "00cb40",
'COLOR_02' => "284fa8",
'COLOR_03' => "6688d4",
'COLOR_04' => "a7fc9d",
'COLOR_05' => "b5f7af",
'COLOR_06' => "b8d0ff",
'COLOR_07' => "cad7fe",
'COLOR_08' => "dae7fe",
'COLOR_09' => "efe383",
'COLOR_10' => "ff0000",
'COLOR_11' => "ff0040",
'COLOR_12' => "ff6230",
'COLOR_13' => "ffea20",
'COLOR_14' => "ffffff",
'COLOR_15' => "284fa8",
'COLOR_16' => "ffffff",
'COLOR_17' => "E5DBDB", # very light pale grey/blue
'COLOR_18' => "82E0AA", # light green
'COLOR_19' => 'F9E79F', # light yellow
'COLOR_20' => 'EC7063', # lighter red
);
our %tlaColor = ("UBC" => "#FDE007",
"GBC" => "#448844",
"LBC" => "#CC6666",
"CBC" => "#CAD7FE",
"GNC" => "#B5F7AF",
"UNC" => "#FF6230",
"ECB" => "#CC66FF",
"EUB" => "#DDDDDD",
"GIC" => "#30CC37",
"UIC" => "#EEAA30",
# we don't actually use a color for deleted code.
# ... it is deleted. Does not appear
"DUB" => "#FFFFFF",
"DCB" => "#FFFFFF",);
# colors for the text in the PNG image of the corresponding TLA line
our %tlaTextColor = ("UBC" => "#aaa005",
"GBC" => "#336633",
"LBC" => "#994444",
"CBC" => "#98a0aa",
"GNC" => "#90a380",
"UNC" => "#aa4020",
"ECB" => "#663388",
"EUB" => "#777777",
"GIC" => "#18661c",
"UIC" => "#aa7718",
# we don't actually use a color for deleted code.
# ... it is deleted. Does not appear
"DUB" => "#FFFFFF",
"DCB" => "#FFFFFF",);
our %pngChar = ('CBC' => '=',
'LBC' => '=',
'GBC' => '-',
'UBC' => '-',
'ECB' => '<',
'EUB' => '<',
'GIC' => '>',
'UIC' => '>',
'GNC' => '+',
'UNC' => '+',);
our %pngMap = ('=' => ['CBC', 'LBC']
, # 0th element 'covered', 1st element 'not covered
'-' => ['GBC', 'UBC'],
'<' => ['ECB', 'EUB'],
'>' => ['GIC', 'UIC'],
'+' => ['GNC', 'UNC'],);
our @opt_rc; # list of command line RC overrides
our %profileData;
our $profile; # the 'enable' flag/name of output file
# need to defer any errors until after the options have been
# processed as user might have suppressed the error we were
# trying to emit
my @deferred_rc_errors; # ([err|warn, key, string])
sub set_tool_name($)
{
$tool_name = shift;
}
#
# system_no_output(mode, parameters)
#
# Call an external program using PARAMETERS while suppressing depending on
# the value of MODE:
#
# MODE & 1: suppress STDOUT (return empty string)
# MODE & 2: suppress STDERR (return empty string)
# MODE & 4: redirect to string
#
# Return (stdout, stderr, rc):
# stdout: stdout string or ''
# stderr: stderr string or ''
# 0 on success, non-zero otherwise
#
sub system_no_output($@)
{
my $mode = shift;
# all current uses redirect both stdout and stderr
my @args = @_;
my ($stdout, $stderr, $code) = Capture::Tiny::capture {
system(@args);
};
if (0 == ($mode & 4)) {
$stdout = '' if $mode & 0x1;
$stderr = '' if $mode & 0x2;
} else {
print(STDOUT $stdout) unless $mode & 0x1;
print(STDERR $stderr) unless $mode & 0x2;
}
return ($stdout, $stderr, $code);
}
#
# info(printf_parameter)
#
# Use printf to write PRINTF_PARAMETER to stdout only when not --quiet
#
sub default_info_impl(@)
{
# Print info string
printf(@_);
}
sub set_info_callback($)
{
$info_callback = shift;
}
sub init_verbose_flag($)
{
my $quiet = shift;
$lcovutil::verbose -= $quiet;
}
sub info(@)
{
my $level = 0;
if ($_[0] =~ /^-?[0-9]+$/) {
$level = shift;
}
&{$info_callback}(@_)
if ($level <= $lcovutil::verbose);
}
sub debug
{
my $level = 0;
if ($_[0] =~ /^[0-9]+$/) {
$level = shift;
}
my $msg = shift;
print(STDERR "DEBUG: $msg")
if ($level < $lcovutil::debug);
}
sub temp_cleanup()
{
if (@temp_dirs) {
# Ensure temp directory is not in use by current process
my $cwd = Cwd::getcwd();
chdir(File::Spec->rootdir());
info("Removing temporary directories.\n");
foreach (@temp_dirs) {
rmtree($_);
}
@temp_dirs = ();
chdir($cwd);
}
}
#
# create_temp_dir()
#
# Create a temporary directory and return its path.
#
# Die on error.
#
sub create_temp_dir()
{
my $dir = tempdir(DIR => $lcovutil::tmp_dir,
CLEANUP => !defined($lcovutil::preserve_intermediates));
if (!defined($dir)) {
die("cannot create temporary directory\n");
}
append_tempdir($dir);
return $dir;
}
sub append_tempdir($)
{
push(@temp_dirs, @_);
}
sub _msg_handler
{
my ($msg, $error) = @_;
if (!($debug || $verbose > 0 || exists($ENV{LCOV_SHOW_LOCATION}))) {
$msg =~ s/ at \S+ line \d+\.$//;
}
# Enforce consistent "WARNING/ERROR:" message prefix
$msg =~ s/^(error|warning):\s+//i;
my $type = $error ? 'ERROR' : 'WARNING';
my $txt = "$tool_name: $type: $msg";
if ($message_log && 'GLOB' eq ref($message_log)) {
flock($message_log, LOCK_EX);
# don't bother to seek...assume modern O_APPEND semantics
#seek($message_log, 0, SEEK_END);
print $message_log $txt;
flock($message_log, LOCK_UN);
}
return $txt;
}
sub warn_handler($$)
{
print(STDERR _msg_handler(@_));
}
sub die_handler($)
{
die(_msg_handler(@_, 1));
}
sub abort_handler($)
{
temp_cleanup();
exit(1);
}
sub count_cores()
{
# how many cores?
$maxParallelism = 1;
#linux solution...
if (open my $handle, '/proc/cpuinfo') {
$maxParallelism = scalar(map /^processor/, <$handle>);
close($handle) or die("unable to close /proc/cpuinfo: $!\n");
}
}
our $use_MemoryProcess;
sub read_proc_vmsize
{
if (open(PROC, "<", '/proc/self/stat')) {
my $str = do { local $/; <PROC> }; # slurp whole thing
close(PROC) or die("unable to close /proc/self/stat: $!\n");
my @data = split(' ', $str);
return $data[23 - 1]; # man proc - vmsize is at index 22
} else {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE,
"unable to open: $!");
return 0;
}
}
sub read_system_memory
{
# NOTE: not sure how to do this on windows...
my $total = 0;
eval {
my $f = InOutFile->in('/proc/meminfo');
my $h = $f->hdl();
while (<$h>) {
if (/MemTotal:\s+(\d+) kB/) {
$total = $1 * 1024; # read #kB
last;
}
}
};
if ($@) {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE, $@);
}
return $total;
}
sub init_parallel_params()
{
if (!defined($lcovutil::maxParallelism)) {
$lcovutil::maxParallelism = 1;
} elsif (0 == $lcovutil::maxParallelism) {
lcovutil::count_cores();
info("Found $maxParallelism cores.\n");
}
if (1 != $lcovutil::maxParallelism &&
(defined($lcovutil::maxMemory) ||
defined($lcovutil::memoryPercentage))
) {
# need Memory::Process to enable the maxMemory feature
my $cwd = Cwd::getcwd();
#debug("init: CWD is $cwd\n");
eval {
require Memory::Process;
Memory::Process->import();
$use_MemoryProcess = 1;
};
# will have done 'cd /' in the die_handler - if Mem::Process not found
#debug("init: chdir back to $cwd\n");
chdir($cwd);
if ($@) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_PACKAGE,
"package Memory::Process is required to control memory consumption during parallel operations: $@"
]);
$use_MemoryProcess = 0;
}
}
if (defined($lcovutil::maxMemory)) {
$lcovutil::maxMemory *= 1 << 20;
} elsif (defined($lcovutil::memoryPercentage)) {
if ($lcovutil::memoryPercentage !~ /^\d+\.?\d*$/ ||
$lcovutil::memoryPercentage <= 0) {
push(
@deferred_rc_errors,
[ 1,
$lcovutil::ERROR_USAGE,
"memory_percentage '$lcovutil::memoryPercentage' is not a valid value"
]);
$lcovutil::memoryPercentage = 100;
}
$lcovutil::maxMemory =
read_system_memory() * ($lcovutil::memoryPercentage / 100.0);
if ($maxMemory) {
my $v = $maxMemory / ((1 << 30) * 1.0);
my $unit = 'Gb';
if ($v < 1.0) {
$unit = 'Mb';
$v = $maxMemory / ((1 << 20) * 1.0);
}
info(sprintf("Setting memory throttle limit to %0.1f %s.\n",
$v, $unit
));
}
} else {
$lcovutil::maxMemory = 0;
}
if (1 != $lcovutil::maxParallelism && # no memory limits if not parallel
0 != $lcovutil::maxMemory
) {
if (!$use_MemoryProcess) {
lcovutil::info(
"Attempting to retrieve memory size from /proc instead\n");
# check if we can get this from /proc (i.e., are we on linux?)
if (0 == read_proc_vmsize()) {
$lcovutil::maxMemory = 0; # turn off that feature
lcovutil::info(
"Continuing execution without Memory::Process or /proc. Note that your maximum memory constraint will be ignored\n"
);
}
}
}
InOutFile::checkGzip() # we know we are going to use gzip for intermediates
if 1 != $lcovutil::maxParallelism;
}
our $memoryObj;
sub current_process_size
{
if ($use_MemoryProcess) {
$memoryObj = Memory::Process->new
unless defined($memoryObj);
$memoryObj->record('size');
my $arr = $memoryObj->state;
$memoryObj->reset();
# current vmsize in kB is element 2 of array
return $arr->[0]->[2] * 1024; # return total in bytes
} else {
# assume we are on linux - and get it from /proc
return read_proc_vmsize();
}
}
sub merge_child_profile($)
{
my $profile = shift;
while (my ($key, $d) = each(%$profile)) {
if ('HASH' eq ref($d)) {
while (my ($f, $t) = each(%$d)) {
if ('HASH' eq ref($t)) {
while (my ($x, $y) = each(%$t)) {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $x=$y at $key->$f")
if exists($lcovutil::profileData{$key}{$f}{$x});
$lcovutil::profileData{$key}{$f}{$x} = $y;
}
} else {
# 'total' key appears in genhtml report
# the others in geninfo.
if (exists($lcovutil::profileData{$key}{$f})
&&
grep(/^$key$/,
( 'version', 'parse',
'append', 'total',
'resolve', 'derive_end',
'check_consistency'))
) {
$lcovutil::profileData{$key}{$f} += $t;
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $f=$t in $key:$lcovutil::profileData{$key}{$f}"
) if exists($lcovutil::profileData{$key}{$f});
$lcovutil::profileData{$key}{$f} = $t;
}
}
}
} else {
lcovutil::ignorable_error($lcovutil::ERROR_INTERNAL,
"unexpected duplicate key $key=$d in profileData")
if exists($lcovutil::profileData{$key});
$lcovutil::profileData{$key} = $d;
}
}
}
sub save_cmd_line($$)
{
my ($argv, $bin) = @_;
my $cmd = $lcovutil::tool_name;
$lcovutil::profileData{config}{bin} = "$FindBin::RealBin";
foreach my $arg (@$argv) {
$cmd .= ' ';
if ($arg =~ /\s/) {
$cmd .= "'$arg'";
} else {
$cmd .= $arg;
}
}
$lcovutil::profileData{config}{cmdLine} = $cmd;
$lcovutil::profileData{config}{buildDir} = Cwd::getcwd();
}
sub save_profile($@)
{
my ($dest, $html) = @_;
if (defined($lcovutil::profile)) {
$lcovutil::profileData{config}{maxParallel} = $maxParallelism;
$lcovutil::profileData{config}{tool} = $lcovutil::tool_name;
$lcovutil::profileData{config}{version} = $lcovutil::lcov_version;
$lcovutil::profileData{config}{tool_dir} = $lcovutil::tool_dir;
$lcovutil::profileData{config}{url} = $lcovutil::lcov_url;
foreach my $t ('date', 'uname -a', 'hostname') {
my $v = `$t`;
chomp($v);
$lcovutil::profileData{config}{(split(' ', $t))[0]} = $v;
}
my $save = $maxParallelism;
count_cores();
$lcovutil::profileData{config}{cores} = $maxParallelism;
$maxParallelism = $save;
my $json = JsonSupport::encode(\%lcovutil::profileData);
if ('' ne $lcovutil::profile) {
$dest = $lcovutil::profile;
} else {
$dest .= ".json";
}
if (open(JSON, ">", "$dest")) {
print(JSON $json);
close(JSON) or die("unable to close $dest: $!\n");
} else {
warn("unable to open profile output $dest: '$!'\n");
}
# only generate the extra data if profile enabled
if ($html) {
my $leader =
'<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">'
. "\n";
my $tail = "</object>\n";
my $outDir = File::Basename::dirname($html);
open(CMD, '>', File::Spec->catfile($outDir, 'cmdline.html')) or
die("unable to create cmdline.html: $!");
print(CMD $leader, $lcovutil::profileData{config}{cmdLine},
"\n", $tail);
close(CMD) or die("unable to close cmdline.html: $!");
# and the profile data
open(PROF, '>', $html) or die("unable to create $html: $!");
print(PROF $leader);
open(IN, '<', $dest) or die("unable to open $dest: $!");
while (<IN>) {
print(PROF $_);
}
close(IN) or die("unable to close $dest: $!");
print(PROF "\n", $tail);
close(PROF) or die("unable to close cmdline.html: $!");
}
}
}
sub set_extensions
{
my ($type, $str) = @_;
die("unknown language '$type'") unless exists($languageExtensions{$type});
$languageExtensions{$type} = join('|', split($split_char, $str));
}
sub do_mangle_check
{
return unless @lcovutil::cpp_demangle;
if (1 == scalar(@lcovutil::cpp_demangle)) {
if ('' eq $lcovutil::cpp_demangle[0]) {
# no demangler specified - use c++filt by default
if (defined($lcovutil::cpp_demangle_tool)) {
$lcovutil::cpp_demangle[0] = $lcovutil::cpp_demangle_tool;
} else {
$lcovutil::cpp_demangle[0] = 'c++filt';
}
}
} elsif (1 < scalar(@lcovutil::cpp_demangle)) {
die("unsupported usage: --demangle-cpp with genhtml_demangle_cpp_tool")
if (defined($lcovutil::cpp_demangle_tool));
die(
"unsupported usage: --demangle-cpp with genhtml_demangle_cpp_params")
if (defined($lcovutil::cpp_demangle_params));
}
if ($lcovutil::cpp_demangle_params) {
# deprecated usage
push(@lcovutil::cpp_demangle,
split(' ', $lcovutil::cpp_demangle_params));
}
# Extra flag necessary on OS X so that symbols listed by gcov get demangled
# properly.
push(@lcovutil::cpp_demangle, '--no-strip-underscores')
if ($^ eq "darwin");
$lcovutil::demangle_cpp_cmd = '';
foreach my $e (@lcovutil::cpp_demangle) {
$lcovutil::demangle_cpp_cmd .= (($e =~ /\s/) ? "'$e'" : $e) . ' ';
}
my $tool = $lcovutil::cpp_demangle[0];
die("could not find $tool tool needed for --demangle-cpp")
if (lcovutil::system_no_output(3, "echo \"\" | '$tool'"));
}
sub configure_callback
{
# if there is just one argument, then assume it might be a
# concatenation - otherwise, just use straight.
my $cb = shift;
my @args =
1 == scalar(@_) ?
split($lcovutil::split_char, join($lcovutil::split_char, @_)) :
@_;
my $script = $args[0];
if ($script =~ /\.pm$/) {
my $dir = File::Basename::dirname($script);
my $package = File::Basename::basename($script);
my $class = $package;
$class =~ s/\.pm$//;
unshift(@INC, $dir);
eval {
require $package;
#$package->import(qw(new));
# the first value in @_ is the script name
$$cb = $class->new(@args);
};
if ($@ ||
!defined($$cb)) {
lcovutil::ignorable_error($lcovutil::ERROR_PACKAGE,
"unable to create callback from module '$script'" .
(defined($@) ? ": $@" : ''));
}
shift(@INC);
} else {
# not module
$$cb = ScriptCaller->new(@args);
}
push(@configured_callbacks, $cb);
}
sub cleanup_callbacks
{
if ($lcovutil::contextCallback) {
my $ctx;
eval { $ctx = $lcovutil::contextCallback->context(); };
if ($@) {
lcovutil::ignorable_error($lcovutil::ERROR_CALLBACK,
"context callback '" .
$lcovutil::contextCallback[0] .
" ...' failed: $@");