2 ##--------------------------------------------------------------------##
3 ##--- The cache simulation framework: instrumentation, recording ---##
4 ##--- and results printing. ---##
5 ##--- callgrind_annotate ---##
6 ##--------------------------------------------------------------------##
8 # This file is part of Callgrind, a cache-simulator and call graph
9 # tracer built on Valgrind.
11 # Copyright (C) 2003-2017 Josef Weidendorfer
12 # Josef.Weidendorfer@gmx.de
14 # This file is based heavily on cg_annotate, part of Valgrind.
15 # Copyright (C) 2002-2017 Nicholas Nethercote
18 # This program is free software; you can redistribute it and/or
19 # modify it under the terms of the GNU General Public License as
20 # published by the Free Software Foundation; either version 2 of the
21 # License, or (at your option) any later version.
23 # This program is distributed in the hope that it will be useful, but
24 # WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 # General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, see <http://www.gnu.org/licenses/>.
31 # The GNU General Public License is contained in the file COPYING.
33 #----------------------------------------------------------------------------
34 # Annotator for cachegrind/callgrind.
36 # File format is described in /docs/techdocs.html.
38 # Performance improvements record, using cachegrind.out for cacheprof, doing no
39 # source annotation (irrelevant ones removed):
41 # 1. turned off warnings in add_hash_a_to_b() 3.81 --> 3.48s
42 # [now add_array_a_to_b()]
43 # 6. make line_to_CC() return a ref instead of a hash 3.01 --> 2.77s
45 #10. changed file format to avoid file/fn name repetition 2.40s
46 # (not sure why higher; maybe due to new '.' entries?)
47 #11. changed file format to drop unnecessary end-line "."s 2.36s
48 # (shrunk file by about 37%)
49 #12. switched from hash CCs to array CCs 1.61s
50 #13. only adding b[i] to a[i] if b[i] defined (was doing it if
51 # either a[i] or b[i] was defined, but if b[i] was undefined
52 # it just added 0) 1.48s
53 #14. Stopped converting "." entries to undef and then back 1.16s
54 #15. Using foreach $i (x..y) instead of for ($i = 0...) in
55 # add_array_a_to_b() 1.11s
57 # Auto-annotating primes:
58 #16. Finding count lengths by int((length-1)/3), not by
59 # commifying (halves the number of commify calls) 1.68s --> 1.47s
64 #----------------------------------------------------------------------------
65 # Overview: the running example in the comments is for:
69 #----------------------------------------------------------------------------
71 #----------------------------------------------------------------------------
72 # Global variables, main data structures
73 #----------------------------------------------------------------------------
74 # CCs are arrays, the counts corresponding to @events, with 'undef'
75 # representing '.'. This makes things fast (faster than using hashes for CCs)
76 # but we have to use @sort_order and @show_order below to handle the --sort and
77 # --show options, which is a bit tricky.
78 #----------------------------------------------------------------------------
80 # Total counts for summary (an array reference).
83 my $summary_calculated = 0;
85 # Totals for each function, for overall summary.
86 # hash(filename:fn_name => CC array)
89 # Individual CCs, organised by filename and line_num for easy annotation.
90 # hash(filename => hash(line_num => CC array))
93 # Files chosen for annotation on the command line.
94 # key = basename (trimmed of any directory), value = full filename
97 # Generic description string.
100 # Command line of profiled program.
103 # Info on the profiled process.
109 # Positions used for cost lines; default: line numbers
113 # Events in input file, eg. (A,B,C,D)
117 # Events to show, from command line, eg. (C,A,D)
120 # Map from @show_events indices to @events indices, eg. (2,0,3). Gives the
121 # order in which we must traverse @events in order to show the @show_events,
122 # eg. (@events[$show_order[1]], @events[$show_order[2]]...) = @show_events.
123 # (Might help to think of it like a hash (0 => 2, 1 => 0, 2 => 3).)
126 # Print out the function totals sorted by these events, eg. (D,C).
129 # Map from @sort_events indices to @events indices, eg. (3,2). Same idea as
133 # Thresholds, one for each sort event (or default to 1 if no sort events
134 # specified). We print out functions and do auto-annotations until we've
135 # handled this proportion of all the events thresholded.
138 my $default_threshold = 99;
140 my $single_threshold = $default_threshold;
142 # If on, show a percentage for each non-zero count.
145 # If on, automatically annotates all files that are involved in getting over
146 # all the threshold counts.
147 my $auto_annotate = 1;
149 # Number of lines to show around each annotated line.
152 # Directories in which to look for annotation files.
153 my @include_dirs = ("");
158 # Inclusive statistics (with subroutine events)
161 # Inclusive totals for each function, for overall summary.
162 # hash(filename:fn_name => CC array)
165 # hash( file:func => [ called file:func ])
168 # hash( file:func => [ calling file:func ])
171 # hash( file:func,line => [called file:func ])
172 my $called_from_line;
174 # hash( file:func,line => file:func
177 # hash (file:func => object name)
180 # Print out the callers of a function
183 # Print out the called functions
184 my $tree_calling = 0;
186 # hash( file:func,cfile:cfunc => call CC[])
189 # hash( file:func,cfile:cfunc => call counter)
192 # hash(context, index) => realname for compressed traces
195 # Input file name, will be set in process_cmd_line
199 my $version = "@VERSION@";
203 usage: callgrind_annotate [options] [callgrind-out-file [source-files...]]
205 options for the user, with defaults in [ ], are:
206 -h --help show this message
207 --version show version
208 --show=A,B,C only show figures for events A,B,C [all]
209 --threshold=<0--100> percentage of counts (of primary sort event) we
210 are interested in [$default_threshold%]
211 --sort=A,B,C sort columns by events A,B,C [event column order]
212 Each event can optionally be followed by a :
213 and a threshold percentage. If some event specific
214 threshold are given, --threshold value is ignored.
215 --show-percs=yes|no show a percentage for each non-zero count [yes]
216 --auto=yes|no annotate all source files containing functions
217 that helped reach the event count threshold [yes]
218 --context=N print N lines of context before and after
220 --inclusive=yes|no add subroutine costs to functions calls [no]
221 --tree=none|caller| print for each function their callers,
222 calling|both the called functions or both [none]
223 -I --include=<dir> add <dir> to list of directories to search for
229 # Used in various places of output.
230 my $fancy = '-' x
80 . "\n";
235 return ($y == 0 ?
0 : $x / $y);
238 #-----------------------------------------------------------------------------
239 # Argument and option handling
240 #-----------------------------------------------------------------------------
241 sub process_cmd_line
()
243 for my $arg (@ARGV) {
249 if ($arg =~ /^--version$/) {
250 die("callgrind_annotate-$version\n");
253 } elsif ($arg =~ /^--show=(.*)$/) {
254 @show_events = split(/,/, $1);
257 } elsif ($arg =~ /^--sort=(.*)$/) {
258 @sort_events = split(/,/, $1);
259 my $th_specified = 0;
260 foreach my $i (0 .. scalar @sort_events - 1) {
261 if ($sort_events[$i] =~ /.*:([\d\.]+)%?$/) {
263 ($th >= 0 && $th <= 100) or die($usage);
264 $sort_events[$i] =~ s/:.*//;
265 $thresholds[$i] = $th;
271 if (not $th_specified) {
275 # --threshold=X (tolerates a trailing '%')
276 } elsif ($arg =~ /^--threshold=([\d\.]+)%?$/) {
277 $single_threshold = $1;
278 ($1 >= 0 && $1 <= 100) or die($usage);
280 # --show-percs=yes|no
281 } elsif ($arg =~ /^--show-percs=yes$/) {
283 } elsif ($arg =~ /^--show-percs=no$/) {
287 } elsif ($arg =~ /^--auto=(yes|no)$/) {
288 $auto_annotate = 1 if ($1 eq "yes");
289 $auto_annotate = 0 if ($1 eq "no");
292 } elsif ($arg =~ /^--context=([\d\.]+)$/) {
299 } elsif ($arg =~ /^--inclusive=(yes|no)$/) {
300 $inclusive = 1 if ($1 eq "yes");
301 $inclusive = 0 if ($1 eq "no");
303 # --tree=none|caller|calling|both
304 } elsif ($arg =~ /^--tree=(none|caller|calling|both)$/) {
305 $tree_caller = 1 if ($1 eq "caller" || $1 eq "both");
306 $tree_calling = 1 if ($1 eq "calling" || $1 eq "both");
309 } elsif ($arg =~ /^(-I|--include)=(.*)$/) {
311 $inc =~ s
|/$||; # trim trailing '/'
312 push(@include_dirs, "$inc/");
314 } else { # -h and --help fall under this case
318 # Argument handling -- annotation file checking and selection.
319 # Stick filenames into a hash for quick 'n easy lookup throughout
321 if ($input_file eq "") {
326 foreach my $include_dir (@include_dirs) {
327 if (-r
$include_dir . $arg) {
331 $readable or die("File $arg not found in any of: @include_dirs\n");
332 $user_ann_files{$arg} = 1;
337 if ($input_file eq "") {
338 $input_file = (<callgrind
.out
*>)[0];
339 if (!defined $input_file) {
340 $input_file = (<cachegrind
.out
*>)[0];
343 (defined $input_file) or die($usage);
344 print "Reading data from '$input_file'...\n";
348 #-----------------------------------------------------------------------------
349 # Reading of input file
350 #-----------------------------------------------------------------------------
354 return ($x > $y ?
$x : $y);
357 # Add the two arrays; any '.' entries are ignored. Two tricky things:
358 # 1. If $a2->[$i] is undefined, it defaults to 0 which is what we want; we turn
359 # off warnings to allow this. This makes things about 10% faster than
360 # checking for definedness ourselves.
361 # 2. We don't add an undefined count or a ".", even though it's value is 0,
362 # because we don't want to make an $a2->[$i] that is undef become 0
364 sub add_array_a_to_b
($$)
368 my $n = max
(scalar @
$a1, scalar @
$a2);
370 foreach my $i (0 .. $n-1) {
371 $a2->[$i] += $a1->[$i] if (defined $a1->[$i] && "." ne $a1->[$i]);
376 # Is this a line with all events zero?
381 foreach my $i (0 .. (scalar @
$CC)-1) {
382 $isZero = 0 if ($CC->[$i] >0);
387 # Add each event count to the CC array. '.' counts become undef, as do
388 # missing entries (implicitly).
391 my @CC = (split /\s+/, $_[0]);
392 (@CC <= @events) or die("Line $.: too many event counts\n");
396 sub uncompressed_name
($$)
398 my ($context, $name) = @_;
400 if ($name =~ /^\((\d+)\)\s*(.*)$/) {
404 if ($realname eq "") {
405 $realname = $compressed{$context,$index};
408 $compressed{$context,$index} = $realname;
415 sub read_input_file
()
417 open(INPUTFILE
, "< $input_file") || die "File $input_file not opened\n";
424 # Skip comments and empty lines.
425 if (/^\s*$/ || /^\#/) { ; }
427 elsif (/^version:\s*(\d+)/) {
428 # Can't read format with major version > 1
429 ($1<2) or die("Can't read format with major version $1.\n");
432 elsif (/^pid:\s+(.*)$/) { $pid = $1; }
433 elsif (/^thread:\s+(.*)$/) { $thread = $1; }
434 elsif (/^part:\s+(.*)$/) { $part = $1; }
435 elsif (/^desc:\s+(.*)$/) {
437 # suppress profile options in description output
438 if ($dline =~ /^Option:/) {;}
439 else { $desc .= "$dline\n"; }
441 elsif (/^cmd:\s+(.*)$/) { $cmd = $1; }
442 elsif (/^creator:\s+(.*)$/) { $creator = $1; }
443 elsif (/^positions:\s+(.*)$/) {
445 $has_line = ($positions =~ /line/);
446 $has_addr = ($positions =~ /(addr|instr)/);
448 elsif (/^event:\s+.*$/) {
449 # ignore lines giving a long name to an event
451 elsif (/^events:\s+(.*)$/) {
454 # events line is last in header
458 warn("WARNING: header line $. malformed, ignoring\n");
459 if ($verbose) { chomp; warn(" line: '$_'\n"); }
463 # Read "events:" line. We make a temporary hash in which the Nth event's
464 # value is N, which is useful for handling --show/--sort options below.
465 ($events ne "") or die("Line $.: missing events line\n");
466 @events = split(/\s+/, $events);
469 foreach my $event (@events) {
470 $events{$event} = $n;
474 # If no --show arg give, default to showing all events in the file.
475 # If --show option is used, check all specified events appeared in the
476 # "events:" line. Then initialise @show_order.
478 foreach my $show_event (@show_events) {
479 (defined $events{$show_event}) or
480 die("--show event `$show_event' did not appear in input\n");
483 @show_events = @events;
485 foreach my $show_event (@show_events) {
486 push(@show_order, $events{$show_event});
489 # Do as for --show, but if no --sort arg given, default to sorting by
490 # column order (ie. first column event is primary sort key, 2nd column is
493 foreach my $sort_event (@sort_events) {
494 (defined $events{$sort_event}) or
495 die("--sort event `$sort_event' did not appear in input\n");
498 @sort_events = @events;
500 foreach my $sort_event (@sort_events) {
501 push(@sort_order, $events{$sort_event});
504 # If multiple threshold args weren't given via --sort, stick in the single
505 # threshold (either from --threshold if used, or the default otherwise) for
506 # the primary sort event, and 0% for the rest.
507 if (not @thresholds) {
508 foreach my $e (@sort_order) {
509 push(@thresholds, 0);
511 $thresholds[0] = $single_threshold;
513 # setting $single_threshold to 0 to ensure the 'per event'
514 # threshold logic is used.
515 $single_threshold = 0;
518 # Current directory, used to strip from file names if absolute
527 my $curr_line_num = 0;
528 my $prev_line_num = 0;
534 my $curr_call_counter = 0;
535 my $curr_cfn_CC = [];
538 my $curr_file_ind_CCs = {}; # hash(line_num => CC)
540 # Read body of input file.
541 while (<INPUTFILE
>) {
542 # Skip comments and empty lines.
543 next if /^\s*$/ || /^\#/;
545 $prev_line_num = $curr_line_num;
547 s/^\+(\d+)/$prev_line_num+$1/e;
548 s/^\-(\d+)/$prev_line_num-$1/e;
549 s/^\*/$prev_line_num/e;
550 if (s/^(-?\d+|0x\w+)\s+//) {
554 s/^\+(\d+)/$prev_line_num+$1/e;
555 s/^\-(\d+)/$prev_line_num-$1/e;
556 s/^\*/$prev_line_num/e;
558 if (s/^(\d+)\s+//) { $curr_line_num = $1; }
560 else { $curr_line_num = 0; }
562 my $CC = line_to_CC
($_);
564 if ($curr_call_counter>0) {
565 # print "Read ($curr_name => $curr_cname) $curr_call_counter\n";
567 if (!defined $call_CCs{$curr_name,$curr_cname}) {
568 $call_CCs{$curr_name,$curr_cname} = [];
569 $call_counter{$curr_name,$curr_cname} = 0;
571 add_array_a_to_b
($CC, $call_CCs{$curr_name,$curr_cname});
572 $call_counter{$curr_name,$curr_cname} += $curr_call_counter;
574 my $tmp = $called_from_line->{$curr_file,$curr_line_num};
576 $func_of_line{$curr_file,$curr_line_num} = $curr_name;
578 $tmp = {} unless defined $tmp;
579 $$tmp{$curr_cname} = 1;
580 $called_from_line->{$curr_file,$curr_line_num} = $tmp;
581 if (!defined $call_CCs{$curr_name,$curr_cname,$curr_line_num}) {
582 $call_CCs{$curr_name,$curr_cname,$curr_line_num} = [];
583 $call_counter{$curr_name,$curr_cname,$curr_line_num} = 0;
585 add_array_a_to_b
($CC, $call_CCs{$curr_name,$curr_cname,$curr_line_num});
586 $call_counter{$curr_name,$curr_cname,$curr_line_num} += $curr_call_counter;
588 $curr_call_counter = 0;
591 $curr_cfn_CC = $cfn_totals{$curr_cname};
592 $curr_cfn_CC = [] unless (defined $curr_cfn_CC);
593 add_array_a_to_b
($CC, $curr_cfn_CC);
594 $cfn_totals{$curr_cname} = $curr_cfn_CC;
597 add_array_a_to_b
($CC, $curr_fn_CC);
602 add_array_a_to_b
($CC, $curr_fn_CC);
604 # If curr_file is selected, add CC to curr_file list. We look for
605 # full filename matches; or, if auto-annotating, we have to
606 # remember everything -- we won't know until the end what's needed.
607 if ($auto_annotate || defined $user_ann_files{$curr_file}) {
608 my $tmp = $curr_file_ind_CCs->{$curr_line_num};
609 $tmp = [] unless defined $tmp;
610 add_array_a_to_b
($CC, $tmp);
611 $curr_file_ind_CCs->{$curr_line_num} = $tmp;
614 } elsif (s/^fn=(.*)$//) {
615 # Commit result from previous function
616 $fn_totals{$curr_name} = $curr_fn_CC if (defined $curr_name);
619 $curr_fn = uncompressed_name
("fn",$1);
620 $curr_name = "$curr_file:$curr_fn";
621 $obj_name{$curr_name} = $curr_obj;
622 $curr_fn_CC = $fn_totals{$curr_name};
623 $curr_fn_CC = [] unless (defined $curr_fn_CC);
625 } elsif (s/^ob=(.*)$//) {
626 $curr_obj = uncompressed_name
("ob",$1);
628 } elsif (s/^fl=(.*)$//) {
629 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs
630 if (defined $curr_file);
632 $curr_file = uncompressed_name
("fl",$1);
633 $curr_file =~ s/^\Q$pwd\E//;
634 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
635 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
637 } elsif (s/^(fi|fe)=(.*)$//) {
638 (defined $curr_name) or die("Line $.: Unexpected fi/fe line\n");
639 $fn_totals{$curr_name} = $curr_fn_CC;
640 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs;
642 $curr_file = uncompressed_name
("fl",$2);
643 $curr_file =~ s/^\Q$pwd\E//;
644 $curr_name = "$curr_file:$curr_fn";
645 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
646 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
647 $curr_fn_CC = $fn_totals{$curr_name};
648 $curr_fn_CC = [] unless (defined $curr_fn_CC);
650 } elsif (s/^cob=(.*)$//) {
651 $curr_cobj = uncompressed_name
("ob",$1);
653 } elsif (s/^cf[il]=(.*)$//) {
654 $curr_cfile = uncompressed_name
("fl",$1);
656 } elsif (s/^cfn=(.*)$//) {
657 $curr_cfunc = uncompressed_name
("fn",$1);
658 if ($curr_cfile eq "") {
659 $curr_cname = "$curr_file:$curr_cfunc";
662 $curr_cname = "$curr_cfile:$curr_cfunc";
666 my $tmp = $calling_funcs->{$curr_cname};
667 $tmp = {} unless defined $tmp;
668 $$tmp{$curr_name} = 1;
669 $calling_funcs->{$curr_cname} = $tmp;
671 my $tmp2 = $called_funcs->{$curr_name};
672 $tmp2 = {} unless defined $tmp2;
673 $$tmp2{$curr_cname} = 1;
674 $called_funcs->{$curr_name} = $tmp2;
676 } elsif (s/^calls=(\d+)//) {
677 $curr_call_counter = $1;
679 } elsif (s/^(jump|jcnd)=//) {
680 #ignore jump information
682 } elsif (s/^jfi=(.*)$//) {
683 # side effect needed: possibly add compression mapping
684 uncompressed_name
("fl",$1);
685 # ignore jump information
687 } elsif (s/^jfn=(.*)$//) {
688 # side effect needed: possibly add compression mapping
689 uncompressed_name
("fn",$1);
690 # ignore jump information
692 } elsif (s/^totals:\s+//) {
693 $totals_CC = line_to_CC
($_);
695 } elsif (s/^summary:\s+//) {
696 $summary_CC = line_to_CC
($_);
699 warn("WARNING: line $. malformed, ignoring\n");
700 if ($verbose) { chomp; warn(" line: '$_'\n"); }
704 # Finish up handling final filename/fn_name counts
705 $fn_totals{"$curr_file:$curr_fn"} = $curr_fn_CC
706 if (defined $curr_file && defined $curr_fn);
707 $all_ind_CCs{$curr_file} =
708 $curr_file_ind_CCs if (defined $curr_file);
710 # Correct inclusive totals
712 foreach my $name (keys %cfn_totals) {
713 $fn_totals{$name} = $cfn_totals{$name};
719 if ((not defined $summary_CC) || is_zero
($summary_CC)) {
720 $summary_CC = $totals_CC;
722 # if neither 'summary:' nor 'totals:' line is given,
723 # calculate summary from fn_totals hash
724 if ((not defined $summary_CC) || is_zero
($summary_CC)) {
725 $summary_calculated = 1;
727 foreach my $name (keys %fn_totals) {
728 add_array_a_to_b
($fn_totals{$name}, $summary_CC);
734 #-----------------------------------------------------------------------------
736 #-----------------------------------------------------------------------------
740 print "Profile data file '$input_file'";
741 if ($creator ne "") { print " (creator: $creator)"; }
747 if ($target eq "") { $target = "(unknown)"; }
749 $target .= " (PID $pid";
750 if ($part ne "") { $target .= ", part $part"; }
751 if ($thread ne "") { $target .= ", thread $thread"; }
754 print("Profiled target: $target\n");
755 print("Events recorded: @events\n");
756 print("Events shown: @show_events\n");
757 print("Event sort order: @sort_events\n");
758 print("Thresholds: @thresholds\n");
760 my @include_dirs2 = @include_dirs; # copy @include_dirs
761 shift(@include_dirs2); # remove "" entry, which is always the first
762 unshift(@include_dirs2, "") if (0 == @include_dirs2);
763 my $include_dir = shift(@include_dirs2);
764 print("Include dirs: $include_dir\n");
765 foreach my $include_dir (@include_dirs2) {
766 print(" $include_dir\n");
769 my @user_ann_files = keys %user_ann_files;
770 unshift(@user_ann_files, "") if (0 == @user_ann_files);
771 my $user_ann_file = shift(@user_ann_files);
772 print("User annotated: $user_ann_file\n");
773 foreach $user_ann_file (@user_ann_files) {
774 print(" $user_ann_file\n");
777 my $is_on = ($auto_annotate ?
"on" : "off");
778 print("Auto-annotation: $is_on\n");
782 #-----------------------------------------------------------------------------
783 # Print summary and sorted function totals
784 #-----------------------------------------------------------------------------
789 # Iterate through sort events (eg. 3,2); return result if two are different
790 foreach my $i (@sort_order) {
794 $x = -1 unless defined $x;
795 $y = -1 unless defined $y;
797 my $cmp = $y <=> $x; # reverse sort
802 # Exhausted events, equal
808 1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
812 # Because the counts can get very big, and we don't want to waste screen space
813 # and make lines too long, we compute exactly how wide each column needs to be
814 # by finding the widest entry for each one.
815 sub compute_CC_col_widths
(@
)
818 my $CC_col_widths = [];
820 # Initialise with minimum widths (from event names)
821 foreach my $event (@events) {
822 push(@
$CC_col_widths, length($event));
825 # Find maximum width count for each column. @CC_col_width positions
826 # correspond to @CC positions.
827 foreach my $CC (@CCs) {
828 foreach my $i (0 .. scalar(@
$CC)-1) {
829 if (defined $CC->[$i]) {
830 # Find length, accounting for commas that will be added, and
831 # possibly a percentage.
832 my $length = length $CC->[$i];
833 my $width = $length + int(($length - 1) / 3);
835 $width += 9; # e.g. " (12.34%)" is 9 chars
837 $CC_col_widths->[$i] = max
($CC_col_widths->[$i], $width);
841 return $CC_col_widths;
844 # Print the CC with each column's size dictated by $CC_col_widths.
847 my ($CC, $CC_col_widths) = @_;
849 foreach my $i (@show_order) {
850 my $count = (defined $CC->[$i] ? commify
($CC->[$i]) : ".");
854 if (defined $CC->[$i] && $CC->[$i] != 0) {
855 # Try our best to keep the number fitting into 5 chars. This
856 # requires dropping a digit after the decimal place if it's
857 # sufficiently negative (e.g. "-10.0") or positive (e.g.
858 # "100.0"). Thanks to diffs it's possible to have even more
859 # extreme values, like "-100.0" or "1000.0"; those rare case
860 # will end up with slightly wrong indenting, oh well.
861 $perc = safe_div
($CC->[$i] * 100, $summary_CC->[$i]);
862 $perc = (-9.995 < $perc && $perc < 99.995)
863 ?
sprintf(" (%5.2f%%)", $perc)
864 : sprintf(" (%5.1f%%)", $perc);
866 # Don't show percentages for "." and "0" entries.
871 # $reps will be negative for the extreme values mentioned above. The
872 # use of max() avoids a possible warning about a negative repeat count.
873 my $text = $count . $perc;
874 my $len = length($text);
875 my $reps = $CC_col_widths->[$i] - length($text);
876 my $space = ' ' x max
($reps, 0);
877 print("$space$text ");
883 my ($CC_col_widths) = @_;
885 foreach my $i (@show_order) {
886 my $event = $events[$i];
887 my $event_width = length($event);
888 my $col_width = $CC_col_widths->[$i];
889 my $space = ' ' x
($col_width - $event_width);
890 print("$event$space ");
894 # Prints summary and function totals (with separate column widths, so that
895 # function names aren't pushed over unnecessarily by huge summary figures).
896 # Also returns a hash containing all the files that are involved in getting the
897 # events count above the thresholds (ie. all the interesting ones).
898 sub print_summary_and_fn_totals
()
900 my @fn_fullnames = keys %fn_totals;
902 # Work out the size of each column for printing (summary and functions
904 my $summary_CC_col_widths = compute_CC_col_widths
($summary_CC);
905 my $fn_CC_col_widths = compute_CC_col_widths
(values %fn_totals);
907 # Header and counts for summary
909 print_events
($summary_CC_col_widths);
912 print_CC
($summary_CC, $summary_CC_col_widths);
913 print(" PROGRAM TOTALS");
914 if ($summary_calculated) {
915 print(" (calculated)");
919 # Header for functions
921 print_events
($fn_CC_col_widths);
922 print(" file:function\n");
925 # Sort function names into order dictated by --sort option.
926 @fn_fullnames = sort {
927 mycmp
($fn_totals{$a}, $fn_totals{$b}) || $a cmp $b
932 (scalar @sort_order == scalar @thresholds) or
933 die("sort_order length != thresholds length:\n",
934 " @sort_order\n @thresholds\n");
936 my $threshold_files = {};
937 # @curr_totals has the same shape as @sort_order and @thresholds
938 my @curr_totals = ();
939 foreach my $e (@thresholds) {
940 push(@curr_totals, 0);
943 # Print functions, stopping when the threshold has been reached.
944 foreach my $fn_name (@fn_fullnames) {
945 # if $single_threshold is 100 the user want to see everything,
946 # so do not enter the filtering logic, as truncation can cause
947 # some functions to not be shown.
948 if ($single_threshold < 100) {
949 # Stop when we've reached all the thresholds
950 my $reached_all_thresholds = 1;
951 foreach my $i (0 .. scalar @thresholds - 1) {
952 my $prop = $curr_totals[$i] * 100;
953 if (defined $summary_CC->[$sort_order[$i]] &&
954 $summary_CC->[$sort_order[$i]] >0) {
955 $prop = $prop / $summary_CC->[$sort_order[$i]];
957 $reached_all_thresholds &&= ($prop >= $thresholds[$i]);
959 last if $reached_all_thresholds;
962 if ($tree_caller || $tree_calling) { print "\n"; }
964 if ($tree_caller && ($fn_name ne "???:???")) {
965 # Print function callers
966 my $tmp1 = $calling_funcs->{$fn_name};
968 # Sort calling functions into order dictated by --sort option.
969 my @callings = sort {
970 mycmp
($call_CCs{$a,$fn_name}, $call_CCs{$b,$fn_name})
972 foreach my $calling (@callings) {
973 if (defined $call_counter{$calling,$fn_name}) {
974 print_CC
($call_CCs{$calling,$fn_name}, $fn_CC_col_widths);
975 print" < $calling (";
976 print commify
($call_counter{$calling,$fn_name}) . "x)";
977 if (defined $obj_name{$calling}) {
978 print " [$obj_name{$calling}]";
986 # Print function results
987 my $fn_CC = $fn_totals{$fn_name};
988 print_CC
($fn_CC, $fn_CC_col_widths);
989 if ($tree_caller || $tree_calling) { print " * "; }
991 if ((defined $obj_name{$fn_name}) &&
992 ($obj_name{$fn_name} ne "")) {
993 print " [$obj_name{$fn_name}]";
997 if ($tree_calling && ($fn_name ne "???:???")) {
998 # Print called functions
999 my $tmp2 = $called_funcs->{$fn_name};
1000 if (defined $tmp2) {
1001 # Sort called functions into order dictated by --sort option.
1002 my @calleds = sort {
1003 mycmp
($call_CCs{$fn_name,$a}, $call_CCs{$fn_name,$b})
1005 foreach my $called (@calleds) {
1006 if (defined $call_counter{$fn_name,$called}) {
1007 print_CC
($call_CCs{$fn_name,$called}, $fn_CC_col_widths);
1008 print" > $called (";
1009 print commify
($call_counter{$fn_name,$called}) . "x)";
1010 if (defined $obj_name{$called}) {
1011 print " [$obj_name{$called}]";
1019 # Update the threshold counts
1020 my $filename = $fn_name;
1021 $filename =~ s/:.+$//; # remove function name
1022 $threshold_files->{$filename} = 1;
1023 foreach my $i (0 .. scalar @sort_order - 1) {
1025 $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
1026 $fn_CC->[$sort_order[$i]]
1027 if (defined $fn_CC->[$sort_order[$i]]);
1029 $curr_totals[$i] += $fn_CC->[$sort_order[$i]]
1030 if (defined $fn_CC->[$sort_order[$i]]);
1036 return $threshold_files;
1039 #-----------------------------------------------------------------------------
1040 # Annotate selected files
1041 #-----------------------------------------------------------------------------
1043 # Issue a warning that the source file is more recent than the input file.
1044 sub warning_on_src_more_recent_than_inputfile
($)
1046 my $src_file = $_[0];
1049 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1050 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1051 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1052 @ Source file '$src_file' is more recent than input file '$input_file'.
1053 @ Annotations may not be correct.
1054 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1061 # If there is information about lines not in the file, issue a warning
1062 # explaining possible causes.
1063 sub warning_on_nonexistent_lines
($$$)
1065 my ($src_more_recent_than_inputfile, $src_file, $excess_line_nums) = @_;
1066 my $cause_and_solution;
1068 if ($src_more_recent_than_inputfile) {
1069 $cause_and_solution = <<END
1070 @@ cause: '$src_file' has changed since information was gathered.
1071 @@ If so, a warning will have already been issued about this.
1072 @@ solution: Recompile program and rerun under "valgrind --cachesim=yes" to
1073 @@ gather new information.
1075 # We suppress warnings about .h files
1076 } elsif ($src_file =~ /\.h$/) {
1077 $cause_and_solution = <<END
1078 @@ cause: bug in the Valgrind's debug info reader that screws up with .h
1080 @@ solution: none, sorry
1083 $cause_and_solution = <<END
1084 @@ cause: not sure, sorry
1089 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1090 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1091 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1093 @@ Information recorded about lines past the end of '$src_file'.
1095 @@ Probable cause and solution:
1096 $cause_and_solution@@
1097 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1103 sub annotate_ann_files
($)
1105 my ($threshold_files) = @_;
1108 my @unfound_auto_annotate_files;
1109 my $printed_totals_CC = [];
1111 # If auto-annotating, add interesting files (but not "???")
1112 if ($auto_annotate) {
1113 delete $threshold_files->{"???"};
1114 %all_ann_files = (%user_ann_files, %$threshold_files)
1116 %all_ann_files = %user_ann_files;
1119 # Track if we did any annotations.
1120 my $did_annotations = 0;
1123 foreach my $src_file (keys %all_ann_files) {
1125 my $opened_file = "";
1126 my $full_file_name = "";
1127 foreach my $include_dir (@include_dirs) {
1128 my $try_name = $include_dir . $src_file;
1129 if (open(INPUTFILE
, "< $try_name")) {
1130 $opened_file = $try_name;
1131 $full_file_name = ($include_dir eq ""
1133 : "$include_dir + $src_file");
1138 if (not $opened_file) {
1139 # Failed to open the file. If chosen on the command line, die.
1140 # If arose from auto-annotation, print a little message.
1141 if (defined $user_ann_files{$src_file}) {
1142 die("File $src_file not opened in any of: @include_dirs\n");
1145 push(@unfound_auto_annotate_files, $src_file);
1149 # File header (distinguish between user- and auto-selected files).
1152 (defined $user_ann_files{$src_file} ?
"User" : "Auto");
1153 print("-- $ann_type-annotated source: $full_file_name\n");
1157 my $src_file_CCs = $all_ind_CCs{$src_file};
1158 if (!defined $src_file_CCs) {
1159 print(" No information has been collected for $src_file\n\n");
1163 $did_annotations = 1;
1165 # Numeric, not lexicographic sort!
1166 my @line_nums = sort {$a <=> $b} keys %$src_file_CCs;
1168 # If $src_file more recent than cachegrind.out, issue warning
1169 my $src_more_recent_than_inputfile = 0;
1170 if ((stat $opened_file)[9] > (stat $input_file)[9]) {
1171 $src_more_recent_than_inputfile = 1;
1172 warning_on_src_more_recent_than_inputfile
($src_file);
1175 # Work out the size of each column for printing
1176 my $CC_col_widths = compute_CC_col_widths
(values %$src_file_CCs);
1179 print_events
($CC_col_widths);
1182 # Shift out 0 if it's in the line numbers (from unknown entries,
1183 # likely due to bugs in Valgrind's stabs debug info reader)
1184 shift(@line_nums) if (0 == $line_nums[0]);
1186 # Finds interesting line ranges -- all lines with a CC, and all
1187 # lines within $context lines of a line with a CC.
1190 for (my $i = 0; $i < $n; $i++) {
1191 push(@pairs, $line_nums[$i] - $context); # lower marker
1193 $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1196 push(@pairs, $line_nums[$i] + $context); # upper marker
1199 # Annotate chosen lines, tracking total counts of lines printed
1200 $pairs[0] = 1 if ($pairs[0] < 1);
1202 my $low = shift @pairs;
1203 my $high = shift @pairs;
1204 while ($. < $low-1) {
1205 my $tmp = <INPUTFILE
>;
1206 last unless (defined $tmp); # hack to detect EOF
1209 # Print line number, unless start of file
1210 print("-- line $low " . '-' x
40 . "\n") if ($low != 1);
1211 while (($. < $high) && ($src_line = <INPUTFILE
>)) {
1212 if (defined $line_nums[0] && $. == $line_nums[0]) {
1213 print_CC
($src_file_CCs->{$.}, $CC_col_widths);
1214 add_array_a_to_b
($src_file_CCs->{$.},
1215 $printed_totals_CC);
1219 print_CC
([], $CC_col_widths);
1222 print(" $src_line");
1224 my $tmp = $called_from_line->{$src_file,$.};
1225 my $func = $func_of_line{$src_file,$.};
1227 # Sort called functions into order dictated by --sort option.
1228 my @calleds = sort {
1229 mycmp
($call_CCs{$func,$a}, $call_CCs{$func,$b})
1231 foreach my $called (@calleds) {
1232 if (defined $call_CCs{$func,$called,$.}) {
1233 print_CC
($call_CCs{$func,$called,$.}, $CC_col_widths);
1234 print " => $called (";
1235 print commify
($call_counter{$func,$called,$.}) . "x)\n";
1240 # Print line number, unless EOF
1242 print("-- line $high " . '-' x
40 . "\n");
1248 # If there was info on lines past the end of the file...
1250 foreach my $line_num (@line_nums) {
1251 print_CC
($src_file_CCs->{$line_num}, $CC_col_widths);
1252 print(" <bogus line $line_num>\n");
1255 warning_on_nonexistent_lines
($src_more_recent_than_inputfile,
1256 $src_file, \
@line_nums);
1260 # Print summary of counts attributed to file but not to any
1261 # particular line (due to incomplete debug info).
1262 if ($src_file_CCs->{0}) {
1263 print_CC
($src_file_CCs->{0}, $CC_col_widths);
1264 print(" <counts for unidentified lines in $src_file>\n\n");
1271 # Print list of unfound auto-annotate selected files.
1272 if (@unfound_auto_annotate_files) {
1274 print("The following files chosen for auto-annotation could not be found:\n");
1276 foreach my $f (sort @unfound_auto_annotate_files) {
1282 # If we did any annotating, show how many events were covered by annotated
1284 if ($did_annotations) {
1285 foreach (my $i = 0; $i < @
$summary_CC; $i++) {
1286 # Some files (in particular the files produced by --xtree-memory)
1287 # have non additive self costs, so have a special case for these
1288 # to print all functions and also to avoid a division by 0.
1289 if ($summary_CC->[$i] == 0
1290 || $printed_totals_CC->[$i] > $summary_CC->[$i]) {
1291 # Set the summary_CC value equal to the printed_totals_CC value
1292 # so that the percentage printed by the print_CC call below is
1293 # 100%. This is ok because the summary_CC value is not used
1295 $summary_CC->[$i] = $printed_totals_CC->[$i];
1298 my $CC_col_widths = compute_CC_col_widths
($printed_totals_CC);
1300 print_events
($CC_col_widths);
1303 print_CC
($printed_totals_CC, $CC_col_widths);
1304 print(" events annotated\n\n");
1308 #----------------------------------------------------------------------------
1310 #----------------------------------------------------------------------------
1314 my $threshold_files = print_summary_and_fn_totals
();
1315 annotate_ann_files
($threshold_files);
1317 ##--------------------------------------------------------------------##
1318 ##--- end vg_annotate.in ---##
1319 ##--------------------------------------------------------------------##