valgrind-monitor.py regular expressions should use raw strings
[valgrind.git] / callgrind / callgrind_annotate.in
blob976fe9b5fb97dad30cc07990c0762f3a0854da4b
1 #! /usr/bin/env perl
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
16 # njn@valgrind.org
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):
40 # user time
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
61 use strict;
62 use warnings;
64 #----------------------------------------------------------------------------
65 # Overview: the running example in the comments is for:
66 # - events = A,B,C,D
67 # - --show=C,A,D
68 # - --sort=D,C
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).
81 my $summary_CC;
82 my $totals_CC;
83 my $summary_calculated = 0;
85 # Totals for each function, for overall summary.
86 # hash(filename:fn_name => CC array)
87 my %fn_totals;
89 # Individual CCs, organised by filename and line_num for easy annotation.
90 # hash(filename => hash(line_num => CC array))
91 my %all_ind_CCs;
93 # Files chosen for annotation on the command line.
94 # key = basename (trimmed of any directory), value = full filename
95 my %user_ann_files;
97 # Generic description string.
98 my $desc = "";
100 # Command line of profiled program.
101 my $cmd = "";
103 # Info on the profiled process.
104 my $creator = "";
105 my $pid = "";
106 my $part = "";
107 my $thread = "";
109 # Positions used for cost lines; default: line numbers
110 my $has_line = 1;
111 my $has_addr = 0;
113 # Events in input file, eg. (A,B,C,D)
114 my @events;
115 my $events;
117 # Events to show, from command line, eg. (C,A,D)
118 my @show_events;
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).)
124 my @show_order;
126 # Print out the function totals sorted by these events, eg. (D,C).
127 my @sort_events;
129 # Map from @sort_events indices to @events indices, eg. (3,2). Same idea as
130 # for @show_order.
131 my @sort_order;
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.
136 my @thresholds;
138 my $default_threshold = 99;
140 my $single_threshold = $default_threshold;
142 # If on, show a percentage for each non-zero count.
143 my $show_percs = 1;
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.
150 my $context = 8;
152 # Directories in which to look for annotation files.
153 my @include_dirs = ("");
155 # Verbose mode
156 my $verbose = "1";
158 # Inclusive statistics (with subroutine events)
159 my $inclusive = 0;
161 # Inclusive totals for each function, for overall summary.
162 # hash(filename:fn_name => CC array)
163 my %cfn_totals;
165 # hash( file:func => [ called file:func ])
166 my $called_funcs;
168 # hash( file:func => [ calling file:func ])
169 my $calling_funcs;
171 # hash( file:func,line => [called file:func ])
172 my $called_from_line;
174 # hash( file:func,line => file:func
175 my %func_of_line;
177 # hash (file:func => object name)
178 my %obj_name;
180 # Print out the callers of a function
181 my $tree_caller = 0;
183 # Print out the called functions
184 my $tree_calling = 0;
186 # hash( file:func,cfile:cfunc => call CC[])
187 my %call_CCs;
189 # hash( file:func,cfile:cfunc => call counter)
190 my %call_counter;
192 # hash(context, index) => realname for compressed traces
193 my %compressed;
195 # Input file name, will be set in process_cmd_line
196 my $input_file = "";
198 # Version number
199 my $version = "@VERSION@";
201 # Usage message.
202 my $usage = <<END
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
219 annotated lines [8]
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
224 source files
229 # Used in various places of output.
230 my $fancy = '-' x 80 . "\n";
232 sub safe_div($$)
234 my ($x, $y) = @_;
235 return ($y == 0 ? 0 : $x / $y);
238 #-----------------------------------------------------------------------------
239 # Argument and option handling
240 #-----------------------------------------------------------------------------
241 sub process_cmd_line()
243 for my $arg (@ARGV) {
245 # Option handling
246 if ($arg =~ /^-/) {
248 # --version
249 if ($arg =~ /^--version$/) {
250 die("callgrind_annotate-$version\n");
252 # --show=A,B,C
253 } elsif ($arg =~ /^--show=(.*)$/) {
254 @show_events = split(/,/, $1);
256 # --sort=A,B,C
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\.]+)%?$/) {
262 my $th = $1;
263 ($th >= 0 && $th <= 100) or die($usage);
264 $sort_events[$i] =~ s/:.*//;
265 $thresholds[$i] = $th;
266 $th_specified = 1;
267 } else {
268 $thresholds[$i] = 0;
271 if (not $th_specified) {
272 @thresholds = ();
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$/) {
282 $show_percs = 1;
283 } elsif ($arg =~ /^--show-percs=no$/) {
284 $show_percs = 0;
286 # --auto=yes|no
287 } elsif ($arg =~ /^--auto=(yes|no)$/) {
288 $auto_annotate = 1 if ($1 eq "yes");
289 $auto_annotate = 0 if ($1 eq "no");
291 # --context=N
292 } elsif ($arg =~ /^--context=([\d\.]+)$/) {
293 $context = $1;
294 if ($context < 0) {
295 die($usage);
298 # --inclusive=yes|no
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");
308 # --include=A,B,C
309 } elsif ($arg =~ /^(-I|--include)=(.*)$/) {
310 my $inc = $2;
311 $inc =~ s|/$||; # trim trailing '/'
312 push(@include_dirs, "$inc/");
314 } else { # -h and --help fall under this case
315 die($usage);
318 # Argument handling -- annotation file checking and selection.
319 # Stick filenames into a hash for quick 'n easy lookup throughout
320 } else {
321 if ($input_file eq "") {
322 $input_file = $arg;
324 else {
325 my $readable = 0;
326 foreach my $include_dir (@include_dirs) {
327 if (-r $include_dir . $arg) {
328 $readable = 1;
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 #-----------------------------------------------------------------------------
351 sub max ($$)
353 my ($x, $y) = @_;
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
363 # unnecessarily.
364 sub add_array_a_to_b ($$)
366 my ($a1, $a2) = @_;
368 my $n = max(scalar @$a1, scalar @$a2);
369 $^W = 0;
370 foreach my $i (0 .. $n-1) {
371 $a2->[$i] += $a1->[$i] if (defined $a1->[$i] && "." ne $a1->[$i]);
373 $^W = 1;
376 # Is this a line with all events zero?
377 sub is_zero ($)
379 my ($CC) = @_;
380 my $isZero = 1;
381 foreach my $i (0 .. (scalar @$CC)-1) {
382 $isZero = 0 if ($CC->[$i] >0);
384 return $isZero;
387 # Add each event count to the CC array. '.' counts become undef, as do
388 # missing entries (implicitly).
389 sub line_to_CC ($)
391 my @CC = (split /\s+/, $_[0]);
392 (@CC <= @events) or die("Line $.: too many event counts\n");
393 return \@CC;
396 sub uncompressed_name($$)
398 my ($context, $name) = @_;
400 if ($name =~ /^\((\d+)\)\s*(.*)$/) {
401 my $index = $1;
402 my $realname = $2;
404 if ($realname eq "") {
405 $realname = $compressed{$context,$index};
407 else {
408 $compressed{$context,$index} = $realname;
410 return $realname;
412 return $name;
415 sub read_input_file()
417 open(INPUTFILE, "< $input_file") || die "File $input_file not opened\n";
419 my $line;
421 # Read header
422 while(<INPUTFILE>) {
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+(.*)$/) {
436 my $dline = $1;
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+(.*)$/) {
444 my $positions = $1;
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+(.*)$/) {
452 $events = $1;
454 # events line is last in header
455 last;
457 else {
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);
467 my %events;
468 my $n = 0;
469 foreach my $event (@events) {
470 $events{$event} = $n;
471 $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.
477 if (@show_events) {
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");
482 } else {
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
491 # 2ndary key, etc).
492 if (@sort_events) {
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");
497 } else {
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;
512 } else {
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
519 my $pwd = `pwd`;
520 chomp $pwd;
521 $pwd .= '/';
523 my $curr_obj = "";
524 my $curr_file;
525 my $curr_fn;
526 my $curr_name;
527 my $curr_line_num = 0;
528 my $prev_line_num = 0;
530 my $curr_cobj = "";
531 my $curr_cfile = "";
532 my $curr_cfunc = "";
533 my $curr_cname;
534 my $curr_call_counter = 0;
535 my $curr_cfn_CC = [];
537 my $curr_fn_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+//) {
551 $curr_line_num = $1;
552 if ($has_addr) {
553 if ($has_line) {
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};
575 if (!defined $tmp) {
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;
590 # inclusive costs
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;
596 if ($inclusive) {
597 add_array_a_to_b($CC, $curr_fn_CC);
599 next;
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);
618 # Setup new one
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";
661 else {
662 $curr_cname = "$curr_cfile:$curr_cfunc";
663 $curr_cfile = "";
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($_);
698 } else {
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
711 if ($inclusive) {
712 foreach my $name (keys %cfn_totals) {
713 $fn_totals{$name} = $cfn_totals{$name};
717 close(INPUTFILE);
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;
726 $summary_CC = [];
727 foreach my $name (keys %fn_totals) {
728 add_array_a_to_b($fn_totals{$name}, $summary_CC);
734 #-----------------------------------------------------------------------------
735 # Print options used
736 #-----------------------------------------------------------------------------
737 sub print_options ()
739 print($fancy);
740 print "Profile data file '$input_file'";
741 if ($creator ne "") { print " (creator: $creator)"; }
742 print "\n";
744 print($fancy);
745 print($desc);
746 my $target = $cmd;
747 if ($target eq "") { $target = "(unknown)"; }
748 if ($pid ne "") {
749 $target .= " (PID $pid";
750 if ($part ne "") { $target .= ", part $part"; }
751 if ($thread ne "") { $target .= ", thread $thread"; }
752 $target .= ")";
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");
779 print("\n");
782 #-----------------------------------------------------------------------------
783 # Print summary and sorted function totals
784 #-----------------------------------------------------------------------------
785 sub mycmp ($$)
787 my ($c, $d) = @_;
789 # Iterate through sort events (eg. 3,2); return result if two are different
790 foreach my $i (@sort_order) {
791 my ($x, $y);
792 $x = $c->[$i];
793 $y = $d->[$i];
794 $x = -1 unless defined $x;
795 $y = -1 unless defined $y;
797 my $cmp = $y <=> $x; # reverse sort
798 if (0 != $cmp) {
799 return $cmp;
802 # Exhausted events, equal
803 return 0;
806 sub commify ($) {
807 my ($val) = @_;
808 1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
809 return $val;
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 (@)
817 my @CCs = @_;
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);
834 if ($show_percs) {
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.
845 sub print_CC ($$)
847 my ($CC, $CC_col_widths) = @_;
849 foreach my $i (@show_order) {
850 my $count = (defined $CC->[$i] ? commify($CC->[$i]) : ".");
852 my $perc = "";
853 if ($show_percs) {
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);
865 } else {
866 # Don't show percentages for "." and "0" entries.
867 $perc = " ";
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 ");
881 sub print_events ($)
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
903 # separately).
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
908 print($fancy);
909 print_events($summary_CC_col_widths);
910 print("\n");
911 print($fancy);
912 print_CC($summary_CC, $summary_CC_col_widths);
913 print(" PROGRAM TOTALS");
914 if ($summary_calculated) {
915 print(" (calculated)");
917 print("\n\n");
919 # Header for functions
920 print($fancy);
921 print_events($fn_CC_col_widths);
922 print(" file:function\n");
923 print($fancy);
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
928 } @fn_fullnames;
931 # Assertion
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};
967 if (defined $tmp1) {
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})
971 } keys %$tmp1;
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}]";
980 print "\n";
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 " * "; }
990 print(" $fn_name");
991 if ((defined $obj_name{$fn_name}) &&
992 ($obj_name{$fn_name} ne "")) {
993 print " [$obj_name{$fn_name}]";
995 print "\n";
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})
1004 } keys %$tmp2;
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}]";
1013 print "\n";
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) {
1024 if ($inclusive) {
1025 $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
1026 $fn_CC->[$sort_order[$i]]
1027 if (defined $fn_CC->[$sort_order[$i]]);
1028 } else {
1029 $curr_totals[$i] += $fn_CC->[$sort_order[$i]]
1030 if (defined $fn_CC->[$sort_order[$i]]);
1034 print("\n");
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];
1048 my $warning = <<END
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 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1058 print($warning);
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
1079 @@ files sometimes
1080 @@ solution: none, sorry
1082 } else {
1083 $cause_and_solution = <<END
1084 @@ cause: not sure, sorry
1088 my $warning = <<END
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 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1100 print($warning);
1103 sub annotate_ann_files($)
1105 my ($threshold_files) = @_;
1107 my %all_ann_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)
1115 } else {
1116 %all_ann_files = %user_ann_files;
1119 # Track if we did any annotations.
1120 my $did_annotations = 0;
1122 LOOP:
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 ""
1132 ? $src_file
1133 : "$include_dir + $src_file");
1134 last;
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");
1144 } else {
1145 push(@unfound_auto_annotate_files, $src_file);
1148 } else {
1149 # File header (distinguish between user- and auto-selected files).
1150 print("$fancy");
1151 my $ann_type =
1152 (defined $user_ann_files{$src_file} ? "User" : "Auto");
1153 print("-- $ann_type-annotated source: $full_file_name\n");
1154 print("$fancy");
1156 # Get file's CCs
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");
1160 next LOOP;
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);
1178 # Events header
1179 print_events($CC_col_widths);
1180 print("\n\n");
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.
1188 my $n = @line_nums;
1189 my @pairs;
1190 for (my $i = 0; $i < $n; $i++) {
1191 push(@pairs, $line_nums[$i] - $context); # lower marker
1192 while ($i < $n-1 &&
1193 $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1194 $i++;
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);
1201 while (@pairs) {
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
1208 my $src_line;
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);
1216 shift(@line_nums);
1218 } else {
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,$.};
1226 if (defined $tmp) {
1227 # Sort called functions into order dictated by --sort option.
1228 my @calleds = sort {
1229 mycmp($call_CCs{$func,$a}, $call_CCs{$func,$b})
1230 } keys %$tmp;
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
1241 if ($src_line) {
1242 print("-- line $high " . '-' x 40 . "\n");
1243 } else {
1244 last;
1248 # If there was info on lines past the end of the file...
1249 if (@line_nums) {
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");
1254 print("\n");
1255 warning_on_nonexistent_lines($src_more_recent_than_inputfile,
1256 $src_file, \@line_nums);
1258 print("\n");
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");
1267 close(INPUTFILE);
1271 # Print list of unfound auto-annotate selected files.
1272 if (@unfound_auto_annotate_files) {
1273 print("$fancy");
1274 print("The following files chosen for auto-annotation could not be found:\n");
1275 print($fancy);
1276 foreach my $f (sort @unfound_auto_annotate_files) {
1277 print(" $f\n");
1279 print("\n");
1282 # If we did any annotating, show how many events were covered by annotated
1283 # lines above.
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
1294 # again afterward.
1295 $summary_CC->[$i] = $printed_totals_CC->[$i];
1298 my $CC_col_widths = compute_CC_col_widths($printed_totals_CC);
1299 print($fancy);
1300 print_events($CC_col_widths);
1301 print("\n");
1302 print($fancy);
1303 print_CC($printed_totals_CC, $CC_col_widths);
1304 print(" events annotated\n\n");
1308 #----------------------------------------------------------------------------
1309 # "main()"
1310 #----------------------------------------------------------------------------
1311 process_cmd_line();
1312 read_input_file();
1313 print_options();
1314 my $threshold_files = print_summary_and_fn_totals();
1315 annotate_ann_files($threshold_files);
1317 ##--------------------------------------------------------------------##
1318 ##--- end vg_annotate.in ---##
1319 ##--------------------------------------------------------------------##