Add bug 467036 Add time cost statistics for Regtest to NEWS
[valgrind.git] / callgrind / callgrind_annotate.in
blobc0715e06493ac32a78fc00510ea5bffad87405f6
1 #! /usr/bin/env -S perl -w
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;
63 #----------------------------------------------------------------------------
64 # Overview: the running example in the comments is for:
65 #   - events = A,B,C,D
66 #   - --show=C,A,D
67 #   - --sort=D,C
68 #----------------------------------------------------------------------------
70 #----------------------------------------------------------------------------
71 # Global variables, main data structures
72 #----------------------------------------------------------------------------
73 # CCs are arrays, the counts corresponding to @events, with 'undef'
74 # representing '.'.  This makes things fast (faster than using hashes for CCs)
75 # but we have to use @sort_order and @show_order below to handle the --sort and
76 # --show options, which is a bit tricky.
77 #----------------------------------------------------------------------------
79 # Total counts for summary (an array reference).
80 my $summary_CC;
81 my $totals_CC;
82 my $summary_calculated = 0;
84 # Totals for each function, for overall summary.
85 # hash(filename:fn_name => CC array)
86 my %fn_totals;
88 # Individual CCs, organised by filename and line_num for easy annotation.
89 # hash(filename => hash(line_num => CC array))
90 my %all_ind_CCs;
92 # Files chosen for annotation on the command line.  
93 # key = basename (trimmed of any directory), value = full filename
94 my %user_ann_files;
96 # Generic description string.
97 my $desc = "";
99 # Command line of profiled program.
100 my $cmd = "";
102 # Info on the profiled process.
103 my $creator = "";
104 my $pid = "";
105 my $part = "";
106 my $thread = "";
108 # Positions used for cost lines; default: line numbers
109 my $has_line = 1;
110 my $has_addr = 0;
112 # Events in input file, eg. (A,B,C,D)
113 my @events;
114 my $events;
116 # Events to show, from command line, eg. (C,A,D)
117 my @show_events;
119 # Map from @show_events indices to @events indices, eg. (2,0,3).  Gives the
120 # order in which we must traverse @events in order to show the @show_events, 
121 # eg. (@events[$show_order[1]], @events[$show_order[2]]...) = @show_events.
122 # (Might help to think of it like a hash (0 => 2, 1 => 0, 2 => 3).)
123 my @show_order;
125 # Print out the function totals sorted by these events, eg. (D,C).
126 my @sort_events;
128 # Map from @sort_events indices to @events indices, eg. (3,2).  Same idea as
129 # for @show_order.
130 my @sort_order;
132 # Thresholds, one for each sort event (or default to 1 if no sort events
133 # specified).  We print out functions and do auto-annotations until we've
134 # handled this proportion of all the events thresholded.
135 my @thresholds;
137 my $default_threshold = 99;
139 my $single_threshold  = $default_threshold;
141 # If on, show a percentage for each non-zero count.
142 my $show_percs = 1;
144 # If on, automatically annotates all files that are involved in getting over
145 # all the threshold counts.
146 my $auto_annotate = 1;
148 # Number of lines to show around each annotated line.
149 my $context = 8;
151 # Directories in which to look for annotation files.
152 my @include_dirs = ("");
154 # Verbose mode
155 my $verbose = "1";
157 # Inclusive statistics (with subroutine events)
158 my $inclusive = 0;
160 # Inclusive totals for each function, for overall summary.
161 # hash(filename:fn_name => CC array)
162 my %cfn_totals;
164 # hash( file:func => [ called file:func ])
165 my $called_funcs;
167 # hash( file:func => [ calling file:func ])
168 my $calling_funcs;
170 # hash( file:func,line => [called file:func ])
171 my $called_from_line;
173 # hash( file:func,line => file:func
174 my %func_of_line;
176 # hash (file:func => object name)
177 my %obj_name;
179 # Print out the callers of a function
180 my $tree_caller = 0;
182 # Print out the called functions
183 my $tree_calling = 0;
185 # hash( file:func,cfile:cfunc => call CC[])
186 my %call_CCs;
188 # hash( file:func,cfile:cfunc => call counter)
189 my %call_counter;
191 # hash(context, index) => realname for compressed traces
192 my %compressed;
194 # Input file name, will be set in process_cmd_line
195 my $input_file = "";
197 # Version number
198 my $version = "@VERSION@";
200 # Usage message.
201 my $usage = <<END
202 usage: callgrind_annotate [options] [callgrind-out-file [source-files...]]
204   options for the user, with defaults in [ ], are:
205     -h --help             show this message
206     --version             show version
207     --show=A,B,C          only show figures for events A,B,C [all]
208     --threshold=<0--100>  percentage of counts (of primary sort event) we
209                           are interested in [$default_threshold%]
210     --sort=A,B,C          sort columns by events A,B,C [event column order]
211                           Each event can optionally be followed by a :
212                           and a threshold percentage. If some event specific
213                           threshold are given, --threshold value is ignored.
214     --show-percs=yes|no   show a percentage for each non-zero count [yes]
215     --auto=yes|no         annotate all source files containing functions
216                           that helped reach the event count threshold [yes]
217     --context=N           print N lines of context before and after
218                           annotated lines [8]
219     --inclusive=yes|no    add subroutine costs to functions calls [no]
220     --tree=none|caller|   print for each function their callers,
221            calling|both   the called functions or both [none]
222     -I --include=<dir>    add <dir> to list of directories to search for 
223                           source files
228 # Used in various places of output.
229 my $fancy = '-' x 80 . "\n";
231 sub safe_div($$)
233     my ($x, $y) = @_;
234     return ($y == 0 ? 0 : $x / $y);
237 #-----------------------------------------------------------------------------
238 # Argument and option handling
239 #-----------------------------------------------------------------------------
240 sub process_cmd_line() 
242     for my $arg (@ARGV) { 
244         # Option handling
245         if ($arg =~ /^-/) {
247             # --version
248             if ($arg =~ /^--version$/) {
249                 die("callgrind_annotate-$version\n");
251             # --show=A,B,C
252             } elsif ($arg =~ /^--show=(.*)$/) {
253                 @show_events = split(/,/, $1);
255             # --sort=A,B,C
256             } elsif ($arg =~ /^--sort=(.*)$/) {
257                 @sort_events = split(/,/, $1);
258                 my $th_specified = 0;
259                 foreach my $i (0 .. scalar @sort_events - 1) {
260                     if ($sort_events[$i] =~ /.*:([\d\.]+)%?$/) {
261                         my $th = $1;
262                         ($th >= 0 && $th <= 100) or die($usage);
263                         $sort_events[$i] =~ s/:.*//;
264                         $thresholds[$i] = $th;
265                         $th_specified = 1;
266                     } else {
267                         $thresholds[$i] = 0;
268                     }
269                 }
270                 if (not $th_specified) {
271                     @thresholds = ();
272                 }
274             # --threshold=X (tolerates a trailing '%')
275             } elsif ($arg =~ /^--threshold=([\d\.]+)%?$/) {
276                 $single_threshold = $1;
277                 ($1 >= 0 && $1 <= 100) or die($usage);
279             # --show-percs=yes|no
280             } elsif ($arg =~ /^--show-percs=yes$/) {
281                 $show_percs = 1;
282             } elsif ($arg =~ /^--show-percs=no$/) {
283                 $show_percs = 0;
285             # --auto=yes|no
286             } elsif ($arg =~ /^--auto=(yes|no)$/) {
287                 $auto_annotate = 1 if ($1 eq "yes");
288                 $auto_annotate = 0 if ($1 eq "no");
290             # --context=N
291             } elsif ($arg =~ /^--context=([\d\.]+)$/) {
292                 $context = $1;
293                 if ($context < 0) {
294                     die($usage);
295                 }
297             # --inclusive=yes|no
298             } elsif ($arg =~ /^--inclusive=(yes|no)$/) {
299                 $inclusive = 1 if ($1 eq "yes");
300                 $inclusive = 0 if ($1 eq "no");
302             # --tree=none|caller|calling|both
303             } elsif ($arg =~ /^--tree=(none|caller|calling|both)$/) {
304                 $tree_caller  = 1 if ($1 eq "caller" || $1 eq "both");
305                 $tree_calling = 1 if ($1 eq "calling" || $1 eq "both");
307             # --include=A,B,C
308             } elsif ($arg =~ /^(-I|--include)=(.*)$/) {
309                 my $inc = $2;
310                 $inc =~ s|/$||;         # trim trailing '/'
311                 push(@include_dirs, "$inc/");
313             } else {            # -h and --help fall under this case
314                 die($usage);
315             }
317         # Argument handling -- annotation file checking and selection.
318         # Stick filenames into a hash for quick 'n easy lookup throughout
319         } else {
320           if ($input_file eq "") {
321             $input_file = $arg;
322           }
323           else {
324             my $readable = 0;
325             foreach my $include_dir (@include_dirs) {
326                 if (-r $include_dir . $arg) {
327                     $readable = 1;
328                 }
329             }
330             $readable or die("File $arg not found in any of: @include_dirs\n");
331             $user_ann_files{$arg} = 1;
332         } 
333     }
334     }
336     if ($input_file eq "") {
337       $input_file = (<callgrind.out*>)[0];
338       if (!defined $input_file) {
339           $input_file = (<cachegrind.out*>)[0];
340       }
342       (defined $input_file) or die($usage);
343       print "Reading data from '$input_file'...\n";
344     }
347 #-----------------------------------------------------------------------------
348 # Reading of input file
349 #-----------------------------------------------------------------------------
350 sub max ($$) 
352     my ($x, $y) = @_;
353     return ($x > $y ? $x : $y);
356 # Add the two arrays;  any '.' entries are ignored.  Two tricky things:
357 # 1. If $a2->[$i] is undefined, it defaults to 0 which is what we want; we turn
358 #    off warnings to allow this.  This makes things about 10% faster than
359 #    checking for definedness ourselves.
360 # 2. We don't add an undefined count or a ".", even though it's value is 0,
361 #    because we don't want to make an $a2->[$i] that is undef become 0
362 #    unnecessarily.
363 sub add_array_a_to_b ($$) 
365     my ($a1, $a2) = @_;
367     my $n = max(scalar @$a1, scalar @$a2);
368     $^W = 0;
369     foreach my $i (0 .. $n-1) {
370         $a2->[$i] += $a1->[$i] if (defined $a1->[$i] && "." ne $a1->[$i]);
371     }
372     $^W = 1;
375 # Is this a line with all events zero?
376 sub is_zero ($)
378     my ($CC) = @_;
379     my $isZero = 1;
380     foreach my $i (0 .. (scalar @$CC)-1) {
381         $isZero = 0 if ($CC->[$i] >0);
382     }
383     return $isZero;
386 # Add each event count to the CC array.  '.' counts become undef, as do
387 # missing entries (implicitly).
388 sub line_to_CC ($)
390     my @CC = (split /\s+/, $_[0]);
391     (@CC <= @events) or die("Line $.: too many event counts\n");
392     return \@CC;
395 sub uncompressed_name($$)
397    my ($context, $name) = @_;
399    if ($name =~ /^\((\d+)\)\s*(.*)$/) {
400      my $index = $1;
401      my $realname = $2;
403      if ($realname eq "") {
404        $realname = $compressed{$context,$index};
405      }
406      else {
407        $compressed{$context,$index} = $realname;
408      }
409      return $realname;
410    }
411    return $name;
414 sub read_input_file() 
416     open(INPUTFILE, "< $input_file") || die "File $input_file not opened\n";
418     my $line;
420     # Read header
421     while(<INPUTFILE>) {
423       # Skip comments and empty lines.
424       if (/^\s*$/ || /^\#/) { ; }
426       elsif (/^version:\s*(\d+)/) {
427         # Can't read format with major version > 1
428         ($1<2) or die("Can't read format with major version $1.\n");
429       }
431       elsif (/^pid:\s+(.*)$/) { $pid = $1;  }
432       elsif (/^thread:\s+(.*)$/) { $thread = $1;  }
433       elsif (/^part:\s+(.*)$/) { $part = $1;  }
434       elsif (/^desc:\s+(.*)$/) {
435         my $dline = $1;
436         # suppress profile options in description output
437         if ($dline =~ /^Option:/) {;}
438         else { $desc .= "$dline\n"; }
439       }
440       elsif (/^cmd:\s+(.*)$/)  { $cmd = $1; }
441       elsif (/^creator:\s+(.*)$/)  { $creator = $1; }
442       elsif (/^positions:\s+(.*)$/) {
443         my $positions = $1;
444         $has_line = ($positions =~ /line/);
445         $has_addr = ($positions =~ /(addr|instr)/);
446       }
447       elsif (/^event:\s+.*$/) { 
448         # ignore lines giving a long name to an event
449       }
450       elsif (/^events:\s+(.*)$/) {
451         $events = $1;
452         
453         # events line is last in header
454         last;
455       }
456       else {
457         warn("WARNING: header line $. malformed, ignoring\n");
458         if ($verbose) { chomp; warn("    line: '$_'\n"); }
459       }
460     }
462     # Read "events:" line.  We make a temporary hash in which the Nth event's
463     # value is N, which is useful for handling --show/--sort options below.
464     ($events ne "") or die("Line $.: missing events line\n");
465     @events = split(/\s+/, $events);
466     my %events;
467     my $n = 0;
468     foreach my $event (@events) {
469         $events{$event} = $n;
470         $n++
471     }
473     # If no --show arg give, default to showing all events in the file.
474     # If --show option is used, check all specified events appeared in the
475     # "events:" line.  Then initialise @show_order.
476     if (@show_events) {
477         foreach my $show_event (@show_events) {
478             (defined $events{$show_event}) or 
479                 die("--show event `$show_event' did not appear in input\n");
480         }
481     } else {
482         @show_events = @events;
483     }
484     foreach my $show_event (@show_events) {
485         push(@show_order, $events{$show_event});
486     }
488     # Do as for --show, but if no --sort arg given, default to sorting by
489     # column order (ie. first column event is primary sort key, 2nd column is
490     # 2ndary key, etc).
491     if (@sort_events) {
492         foreach my $sort_event (@sort_events) {
493             (defined $events{$sort_event}) or 
494                 die("--sort event `$sort_event' did not appear in input\n");
495         }
496     } else {
497         @sort_events = @events;
498     }
499     foreach my $sort_event (@sort_events) {
500         push(@sort_order, $events{$sort_event});
501     }
503     # If multiple threshold args weren't given via --sort, stick in the single
504     # threshold (either from --threshold if used, or the default otherwise) for
505     # the primary sort event, and 0% for the rest.
506     if (not @thresholds) {
507         foreach my $e (@sort_order) {
508             push(@thresholds, 0);
509         }
510         $thresholds[0] = $single_threshold;
511     } else {
512         # setting $single_threshold to 0 to ensure the 'per event'
513         # threshold logic is used.
514         $single_threshold = 0;
515     }
517     # Current directory, used to strip from file names if absolute
518     my $pwd = `pwd`;
519     chomp $pwd;
520     $pwd .= '/';
522     my $curr_obj = "";
523     my $curr_file;
524     my $curr_fn;
525     my $curr_name;
526     my $curr_line_num = 0;
527     my $prev_line_num = 0;
529     my $curr_cobj = "";
530     my $curr_cfile = "";
531     my $curr_cfunc = "";
532     my $curr_cname;
533     my $curr_call_counter = 0;
534     my $curr_cfn_CC = [];
536     my $curr_fn_CC = [];
537     my $curr_file_ind_CCs = {};     # hash(line_num => CC)
539     # Read body of input file.
540     while (<INPUTFILE>) {
541         # Skip comments and empty lines.
542         next if /^\s*$/ || /^\#/;
544         $prev_line_num = $curr_line_num;
546         s/^\+(\d+)/$prev_line_num+$1/e;
547         s/^\-(\d+)/$prev_line_num-$1/e;
548         s/^\*/$prev_line_num/e;
549         if (s/^(-?\d+|0x\w+)\s+//) {
550             $curr_line_num = $1;
551             if ($has_addr) {
552               if ($has_line) {
553                 s/^\+(\d+)/$prev_line_num+$1/e;
554                 s/^\-(\d+)/$prev_line_num-$1/e;
555                 s/^\*/$prev_line_num/e;
557                 if (s/^(\d+)\s+//) { $curr_line_num = $1; }
558               }
559               else { $curr_line_num = 0; }
560             }
561             my $CC = line_to_CC($_);
563             if ($curr_call_counter>0) {
564 #             print "Read ($curr_name => $curr_cname) $curr_call_counter\n";
566               if (!defined $call_CCs{$curr_name,$curr_cname}) {
567                 $call_CCs{$curr_name,$curr_cname} = [];
568                 $call_counter{$curr_name,$curr_cname} = 0;
569               }
570               add_array_a_to_b($CC, $call_CCs{$curr_name,$curr_cname});
571               $call_counter{$curr_name,$curr_cname} += $curr_call_counter;
573               my $tmp = $called_from_line->{$curr_file,$curr_line_num};
574               if (!defined $tmp) {
575                 $func_of_line{$curr_file,$curr_line_num} = $curr_name;
576               }
577               $tmp = {} unless defined $tmp;
578               $$tmp{$curr_cname} = 1;
579               $called_from_line->{$curr_file,$curr_line_num} = $tmp;
580               if (!defined $call_CCs{$curr_name,$curr_cname,$curr_line_num}) {
581                 $call_CCs{$curr_name,$curr_cname,$curr_line_num} = [];
582                 $call_counter{$curr_name,$curr_cname,$curr_line_num} = 0;
583               }
584               add_array_a_to_b($CC, $call_CCs{$curr_name,$curr_cname,$curr_line_num});
585               $call_counter{$curr_name,$curr_cname,$curr_line_num} += $curr_call_counter;
587               $curr_call_counter = 0;
589               # inclusive costs
590               $curr_cfn_CC = $cfn_totals{$curr_cname};
591               $curr_cfn_CC = [] unless (defined $curr_cfn_CC);
592               add_array_a_to_b($CC, $curr_cfn_CC);
593               $cfn_totals{$curr_cname} = $curr_cfn_CC;
595               if ($inclusive) {
596                 add_array_a_to_b($CC, $curr_fn_CC);
597               }
598               next;
599             }
601             add_array_a_to_b($CC, $curr_fn_CC);
603             # If curr_file is selected, add CC to curr_file list.  We look for
604             # full filename matches;  or, if auto-annotating, we have to
605             # remember everything -- we won't know until the end what's needed.
606             if ($auto_annotate || defined $user_ann_files{$curr_file}) {
607                 my $tmp = $curr_file_ind_CCs->{$curr_line_num};
608                 $tmp = [] unless defined $tmp;
609                 add_array_a_to_b($CC, $tmp);
610                 $curr_file_ind_CCs->{$curr_line_num} = $tmp;
611             }
613         } elsif (s/^fn=(.*)$//) {
614             # Commit result from previous function
615             $fn_totals{$curr_name} = $curr_fn_CC if (defined $curr_name);
617             # Setup new one
618             $curr_fn = uncompressed_name("fn",$1);
619             $curr_name = "$curr_file:$curr_fn";
620             $obj_name{$curr_name} = $curr_obj;
621             $curr_fn_CC = $fn_totals{$curr_name};
622             $curr_fn_CC = [] unless (defined $curr_fn_CC);
624         } elsif (s/^ob=(.*)$//) {
625             $curr_obj = uncompressed_name("ob",$1);
627         } elsif (s/^fl=(.*)$//) {
628             $all_ind_CCs{$curr_file} = $curr_file_ind_CCs 
629                 if (defined $curr_file);
631             $curr_file = uncompressed_name("fl",$1);
632             $curr_file =~ s/^\Q$pwd\E//;
633             $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
634             $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
636         } elsif (s/^(fi|fe)=(.*)$//) {
637             (defined $curr_name) or die("Line $.: Unexpected fi/fe line\n");
638             $fn_totals{$curr_name} = $curr_fn_CC;
639             $all_ind_CCs{$curr_file} = $curr_file_ind_CCs;
641             $curr_file = uncompressed_name("fl",$2);
642             $curr_file =~ s/^\Q$pwd\E//;
643             $curr_name = "$curr_file:$curr_fn";
644             $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
645             $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
646             $curr_fn_CC = $fn_totals{$curr_name};
647             $curr_fn_CC = [] unless (defined $curr_fn_CC);
649         } elsif (s/^cob=(.*)$//) {
650           $curr_cobj = uncompressed_name("ob",$1);
652         } elsif (s/^cf[il]=(.*)$//) {
653           $curr_cfile = uncompressed_name("fl",$1);
655         } elsif (s/^cfn=(.*)$//) {
656           $curr_cfunc = uncompressed_name("fn",$1);
657           if ($curr_cfile eq "") {
658             $curr_cname = "$curr_file:$curr_cfunc";
659           }
660           else {
661             $curr_cname = "$curr_cfile:$curr_cfunc";
662             $curr_cfile = "";
663           }
665           my $tmp = $calling_funcs->{$curr_cname};
666           $tmp = {} unless defined $tmp;
667           $$tmp{$curr_name} = 1;
668           $calling_funcs->{$curr_cname} = $tmp;
669                 
670           my $tmp2 = $called_funcs->{$curr_name};
671           $tmp2 = {} unless defined $tmp2;
672           $$tmp2{$curr_cname} = 1;
673           $called_funcs->{$curr_name} = $tmp2;
675         } elsif (s/^calls=(\d+)//) {
676           $curr_call_counter = $1;
678         } elsif (s/^(jump|jcnd)=//) {
679           #ignore jump information
681         } elsif (s/^jfi=(.*)$//) {
682           # side effect needed: possibly add compression mapping 
683           uncompressed_name("fl",$1);
684           # ignore jump information     
686         } elsif (s/^jfn=(.*)$//) {
687           # side effect needed: possibly add compression mapping
688           uncompressed_name("fn",$1);
689           # ignore jump information
691         } elsif (s/^totals:\s+//) {
692             $totals_CC = line_to_CC($_);
694         } elsif (s/^summary:\s+//) {
695             $summary_CC = line_to_CC($_);
697         } else {
698             warn("WARNING: line $. malformed, ignoring\n");
699             if ($verbose) { chomp; warn("    line: '$_'\n"); }
700         }
701     }
703     # Finish up handling final filename/fn_name counts
704     $fn_totals{"$curr_file:$curr_fn"} = $curr_fn_CC
705         if (defined $curr_file && defined $curr_fn);
706     $all_ind_CCs{$curr_file} =
707         $curr_file_ind_CCs if (defined $curr_file);
709     # Correct inclusive totals
710     if ($inclusive) {
711       foreach my $name (keys %cfn_totals) {
712         $fn_totals{$name} = $cfn_totals{$name};
713       }
714     }
716     close(INPUTFILE);
718     if ((not defined $summary_CC) || is_zero($summary_CC)) {
719         $summary_CC = $totals_CC;
721         # if neither 'summary:' nor 'totals:' line is given,
722         # calculate summary from fn_totals hash
723         if ((not defined $summary_CC) || is_zero($summary_CC)) {
724             $summary_calculated = 1;
725             $summary_CC = [];
726             foreach my $name (keys %fn_totals) {
727                 add_array_a_to_b($fn_totals{$name}, $summary_CC);
728             }
729         }
730     }
733 #-----------------------------------------------------------------------------
734 # Print options used
735 #-----------------------------------------------------------------------------
736 sub print_options ()
738     print($fancy);
739     print "Profile data file '$input_file'";
740     if ($creator ne "") { print " (creator: $creator)"; }
741     print "\n";
743     print($fancy);
744     print($desc);
745     my $target = $cmd;
746     if ($target eq "") { $target = "(unknown)"; }
747     if ($pid ne "") {
748       $target .= " (PID $pid";
749       if ($part ne "") { $target .= ", part $part"; }
750       if ($thread ne "") { $target .= ", thread $thread"; }
751       $target .= ")";
752     }
753     print("Profiled target:  $target\n");
754     print("Events recorded:  @events\n");
755     print("Events shown:     @show_events\n");
756     print("Event sort order: @sort_events\n");
757     print("Thresholds:       @thresholds\n");
759     my @include_dirs2 = @include_dirs;  # copy @include_dirs
760     shift(@include_dirs2);       # remove "" entry, which is always the first
761     unshift(@include_dirs2, "") if (0 == @include_dirs2); 
762     my $include_dir = shift(@include_dirs2);
763     print("Include dirs:     $include_dir\n");
764     foreach my $include_dir (@include_dirs2) {
765         print("                  $include_dir\n");
766     }
768     my @user_ann_files = keys %user_ann_files;
769     unshift(@user_ann_files, "") if (0 == @user_ann_files); 
770     my $user_ann_file = shift(@user_ann_files);
771     print("User annotated:   $user_ann_file\n");
772     foreach $user_ann_file (@user_ann_files) {
773         print("                  $user_ann_file\n");
774     }
776     my $is_on = ($auto_annotate ? "on" : "off");
777     print("Auto-annotation:  $is_on\n");
778     print("\n");
781 #-----------------------------------------------------------------------------
782 # Print summary and sorted function totals
783 #-----------------------------------------------------------------------------
784 sub mycmp ($$) 
786     my ($c, $d) = @_;
788     # Iterate through sort events (eg. 3,2); return result if two are different
789     foreach my $i (@sort_order) {
790         my ($x, $y);
791         $x = $c->[$i];
792         $y = $d->[$i];
793         $x = -1 unless defined $x;
794         $y = -1 unless defined $y;
796         my $cmp = $y <=> $x;        # reverse sort
797         if (0 != $cmp) {
798             return $cmp;
799         }
800     }
801     # Exhausted events, equal
802     return 0;
805 sub commify ($) {
806     my ($val) = @_;
807     1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
808     return $val;
811 # Because the counts can get very big, and we don't want to waste screen space
812 # and make lines too long, we compute exactly how wide each column needs to be
813 # by finding the widest entry for each one.
814 sub compute_CC_col_widths (@) 
816     my @CCs = @_;
817     my $CC_col_widths = [];
819     # Initialise with minimum widths (from event names)
820     foreach my $event (@events) {
821         push(@$CC_col_widths, length($event));
822     }
823     
824     # Find maximum width count for each column.  @CC_col_width positions
825     # correspond to @CC positions.
826     foreach my $CC (@CCs) {
827         foreach my $i (0 .. scalar(@$CC)-1) {
828             if (defined $CC->[$i]) {
829                 # Find length, accounting for commas that will be added, and
830                 # possibly a percentage.
831                 my $length = length $CC->[$i];
832                 my $width = $length + int(($length - 1) / 3);
833                 if ($show_percs) {
834                     $width += 9;    # e.g. " (12.34%)" is 9 chars
835                 }
836                 $CC_col_widths->[$i] = max($CC_col_widths->[$i], $width); 
837             }
838         }
839     }
840     return $CC_col_widths;
843 # Print the CC with each column's size dictated by $CC_col_widths.
844 sub print_CC ($$) 
846     my ($CC, $CC_col_widths) = @_;
848     foreach my $i (@show_order) {
849         my $count = (defined $CC->[$i] ? commify($CC->[$i]) : ".");
851         my $perc = "";
852         if ($show_percs) {
853             if (defined $CC->[$i] && $CC->[$i] != 0) {
854                 # Try our best to keep the number fitting into 5 chars. This
855                 # requires dropping a digit after the decimal place if it's
856                 # sufficiently negative (e.g. "-10.0") or positive (e.g.
857                 # "100.0"). Thanks to diffs it's possible to have even more
858                 # extreme values, like "-100.0" or "1000.0"; those rare case
859                 # will end up with slightly wrong indenting, oh well.
860                 $perc = safe_div($CC->[$i] * 100, $summary_CC->[$i]);
861                 $perc = (-9.995 < $perc && $perc < 99.995)
862                       ? sprintf(" (%5.2f%%)", $perc)
863                       : sprintf(" (%5.1f%%)", $perc);
864             } else {
865                 # Don't show percentages for "." and "0" entries.
866                 $perc = "         ";
867             }
868         }
870         # $reps will be negative for the extreme values mentioned above. The
871         # use of max() avoids a possible warning about a negative repeat count.
872         my $text = $count . $perc;
873         my $len = length($text);
874         my $reps = $CC_col_widths->[$i] - length($text);
875         my $space = ' ' x max($reps, 0);
876         print("$space$text ");
877     }
880 sub print_events ($)
882     my ($CC_col_widths) = @_;
884     foreach my $i (@show_order) { 
885         my $event       = $events[$i];
886         my $event_width = length($event);
887         my $col_width   = $CC_col_widths->[$i];
888         my $space       = ' ' x ($col_width - $event_width);
889         print("$event$space ");
890     }
893 # Prints summary and function totals (with separate column widths, so that
894 # function names aren't pushed over unnecessarily by huge summary figures).
895 # Also returns a hash containing all the files that are involved in getting the
896 # events count above the thresholds (ie. all the interesting ones).
897 sub print_summary_and_fn_totals ()
899     my @fn_fullnames = keys   %fn_totals;
901     # Work out the size of each column for printing (summary and functions
902     # separately).
903     my $summary_CC_col_widths = compute_CC_col_widths($summary_CC);
904     my      $fn_CC_col_widths = compute_CC_col_widths(values %fn_totals);
906     # Header and counts for summary
907     print($fancy);
908     print_events($summary_CC_col_widths);
909     print("\n");
910     print($fancy);
911     print_CC($summary_CC, $summary_CC_col_widths);
912     print(" PROGRAM TOTALS");
913     if ($summary_calculated) {
914         print(" (calculated)");
915     }
916     print("\n\n");
918     # Header for functions
919     print($fancy);
920     print_events($fn_CC_col_widths);
921     print(" file:function\n");
922     print($fancy);
924     # Sort function names into order dictated by --sort option.
925     @fn_fullnames = sort {
926         mycmp($fn_totals{$a}, $fn_totals{$b}) || $a cmp $b
927     } @fn_fullnames;
930     # Assertion
931     (scalar @sort_order == scalar @thresholds) or 
932         die("sort_order length != thresholds length:\n",
933             "  @sort_order\n  @thresholds\n");
935     my $threshold_files       = {};
936     # @curr_totals has the same shape as @sort_order and @thresholds
937     my @curr_totals = ();
938     foreach my $e (@thresholds) {
939         push(@curr_totals, 0);
940     }
942     # Print functions, stopping when the threshold has been reached.
943     foreach my $fn_name (@fn_fullnames) {
944         # if $single_threshold is 100 the user want to see everything,
945         # so do not enter the filtering logic, as truncation can cause
946         # some functions to not be shown.
947         if ($single_threshold < 100) {
948             # Stop when we've reached all the thresholds
949             my $reached_all_thresholds = 1;
950             foreach my $i (0 .. scalar @thresholds - 1) {
951                 my $prop = $curr_totals[$i] * 100;
952                 if (defined $summary_CC->[$sort_order[$i]] &&
953                     $summary_CC->[$sort_order[$i]] >0) {
954                     $prop = $prop / $summary_CC->[$sort_order[$i]];
955                 }
956                 $reached_all_thresholds &&= ($prop >= $thresholds[$i]);
957             }
958             last if $reached_all_thresholds;
959         }
961         if ($tree_caller || $tree_calling) { print "\n"; }
963         if ($tree_caller && ($fn_name ne "???:???")) {
964           # Print function callers
965           my $tmp1 = $calling_funcs->{$fn_name};
966           if (defined $tmp1) {
967             # Sort calling functions into order dictated by --sort option.
968             my @callings = sort {
969               mycmp($call_CCs{$a,$fn_name}, $call_CCs{$b,$fn_name})
970             } keys %$tmp1;
971             foreach my $calling (@callings) {
972               if (defined $call_counter{$calling,$fn_name}) {
973                 print_CC($call_CCs{$calling,$fn_name}, $fn_CC_col_widths);
974                 print" < $calling (";
975                 print commify($call_counter{$calling,$fn_name}) . "x)";
976                 if (defined $obj_name{$calling}) {
977                   print " [$obj_name{$calling}]";
978                 }
979                 print "\n";
980               }
981             }
982           }
983         }
985         # Print function results
986         my $fn_CC = $fn_totals{$fn_name};
987         print_CC($fn_CC, $fn_CC_col_widths);
988         if ($tree_caller || $tree_calling) { print " * "; }
989         print(" $fn_name");
990         if ((defined $obj_name{$fn_name}) &&
991             ($obj_name{$fn_name} ne "")) {
992           print " [$obj_name{$fn_name}]";
993         }
994         print "\n";
996         if ($tree_calling && ($fn_name ne "???:???")) {
997           # Print called functions
998           my $tmp2 = $called_funcs->{$fn_name};
999           if (defined $tmp2) {
1000             # Sort called functions into order dictated by --sort option.
1001             my @calleds = sort {
1002               mycmp($call_CCs{$fn_name,$a}, $call_CCs{$fn_name,$b})
1003             } keys %$tmp2;
1004             foreach my $called (@calleds) {
1005               if (defined $call_counter{$fn_name,$called}) {
1006                 print_CC($call_CCs{$fn_name,$called}, $fn_CC_col_widths);
1007                 print" >   $called (";
1008                 print commify($call_counter{$fn_name,$called}) . "x)";
1009                 if (defined $obj_name{$called}) {
1010                   print " [$obj_name{$called}]";
1011                 }
1012                 print "\n";
1013               }
1014             }
1015           }
1016         }
1018         # Update the threshold counts
1019         my $filename = $fn_name;
1020         $filename =~ s/:.+$//;    # remove function name
1021         $threshold_files->{$filename} = 1;
1022         foreach my $i (0 .. scalar @sort_order - 1) {
1023           if ($inclusive) {
1024             $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
1025                                $fn_CC->[$sort_order[$i]]
1026               if (defined $fn_CC->[$sort_order[$i]]);
1027           } else {
1028             $curr_totals[$i] += $fn_CC->[$sort_order[$i]] 
1029                 if (defined $fn_CC->[$sort_order[$i]]);
1030         }
1031     }
1032     }
1033     print("\n");
1035     return $threshold_files;
1038 #-----------------------------------------------------------------------------
1039 # Annotate selected files
1040 #-----------------------------------------------------------------------------
1042 # Issue a warning that the source file is more recent than the input file. 
1043 sub warning_on_src_more_recent_than_inputfile ($)
1045     my $src_file = $_[0];
1047     my $warning = <<END
1048 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1049 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1050 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1051 @ Source file '$src_file' is more recent than input file '$input_file'.
1052 @ Annotations may not be correct.
1053 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1057     print($warning);
1060 # If there is information about lines not in the file, issue a warning
1061 # explaining possible causes.
1062 sub warning_on_nonexistent_lines ($$$)
1064     my ($src_more_recent_than_inputfile, $src_file, $excess_line_nums) = @_;
1065     my $cause_and_solution;
1067     if ($src_more_recent_than_inputfile) {
1068         $cause_and_solution = <<END
1069 @@ cause:    '$src_file' has changed since information was gathered.
1070 @@           If so, a warning will have already been issued about this.
1071 @@ solution: Recompile program and rerun under "valgrind --cachesim=yes" to 
1072 @@           gather new information.
1074     # We suppress warnings about .h files
1075     } elsif ($src_file =~ /\.h$/) {
1076         $cause_and_solution = <<END
1077 @@ cause:    bug in the Valgrind's debug info reader that screws up with .h
1078 @@           files sometimes
1079 @@ solution: none, sorry
1081     } else {
1082         $cause_and_solution = <<END
1083 @@ cause:    not sure, sorry
1085     }
1087     my $warning = <<END
1088 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1089 @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
1090 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1092 @@ Information recorded about lines past the end of '$src_file'.
1094 @@ Probable cause and solution:
1095 $cause_and_solution@@
1096 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
1099     print($warning);
1102 sub annotate_ann_files($)
1104     my ($threshold_files) = @_; 
1106     my %all_ann_files;
1107     my @unfound_auto_annotate_files;
1108     my $printed_totals_CC = [];
1110     # If auto-annotating, add interesting files (but not "???")
1111     if ($auto_annotate) {
1112         delete $threshold_files->{"???"};
1113         %all_ann_files = (%user_ann_files, %$threshold_files) 
1114     } else {
1115         %all_ann_files = %user_ann_files;
1116     }
1118     # Track if we did any annotations.
1119     my $did_annotations = 0;
1121     LOOP:
1122     foreach my $src_file (keys %all_ann_files) {
1124         my $opened_file = "";
1125         my $full_file_name = "";
1126         foreach my $include_dir (@include_dirs) {
1127             my $try_name = $include_dir . $src_file;
1128             if (open(INPUTFILE, "< $try_name")) {
1129                 $opened_file    = $try_name;
1130                 $full_file_name = ($include_dir eq "" 
1131                                   ? $src_file 
1132                                   : "$include_dir + $src_file"); 
1133                 last;
1134             }
1135         }
1136         
1137         if (not $opened_file) {
1138             # Failed to open the file.  If chosen on the command line, die.
1139             # If arose from auto-annotation, print a little message.
1140             if (defined $user_ann_files{$src_file}) {
1141                 die("File $src_file not opened in any of: @include_dirs\n");
1143             } else {
1144                 push(@unfound_auto_annotate_files, $src_file);
1145             }
1147         } else {
1148             # File header (distinguish between user- and auto-selected files).
1149             print("$fancy");
1150             my $ann_type = 
1151                 (defined $user_ann_files{$src_file} ? "User" : "Auto");
1152             print("-- $ann_type-annotated source: $full_file_name\n");
1153             print("$fancy");
1155             # Get file's CCs
1156             my $src_file_CCs = $all_ind_CCs{$src_file};
1157             if (!defined $src_file_CCs) {
1158                 print("  No information has been collected for $src_file\n\n");
1159                 next LOOP;
1160             }
1161         
1162             $did_annotations = 1;
1163             
1164             # Numeric, not lexicographic sort!
1165             my @line_nums = sort {$a <=> $b} keys %$src_file_CCs;  
1167             # If $src_file more recent than cachegrind.out, issue warning
1168             my $src_more_recent_than_inputfile = 0;
1169             if ((stat $opened_file)[9] > (stat $input_file)[9]) {
1170                 $src_more_recent_than_inputfile = 1;
1171                 warning_on_src_more_recent_than_inputfile($src_file);
1172             }
1174             # Work out the size of each column for printing
1175             my $CC_col_widths = compute_CC_col_widths(values %$src_file_CCs);
1177             # Events header
1178             print_events($CC_col_widths);
1179             print("\n\n");
1181             # Shift out 0 if it's in the line numbers (from unknown entries,
1182             # likely due to bugs in Valgrind's stabs debug info reader)
1183             shift(@line_nums) if (0 == $line_nums[0]);
1185             # Finds interesting line ranges -- all lines with a CC, and all
1186             # lines within $context lines of a line with a CC.
1187             my $n = @line_nums;
1188             my @pairs;
1189             for (my $i = 0; $i < $n; $i++) {
1190                 push(@pairs, $line_nums[$i] - $context);   # lower marker
1191                 while ($i < $n-1 && 
1192                        $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1193                     $i++;
1194                 }
1195                 push(@pairs, $line_nums[$i] + $context);   # upper marker
1196             }
1198             # Annotate chosen lines, tracking total counts of lines printed
1199             $pairs[0] = 1 if ($pairs[0] < 1);
1200             while (@pairs) {
1201                 my $low  = shift @pairs;
1202                 my $high = shift @pairs;
1203                 while ($. < $low-1) {
1204                     my $tmp = <INPUTFILE>;
1205                     last unless (defined $tmp);     # hack to detect EOF
1206                 }
1207                 my $src_line;
1208                 # Print line number, unless start of file
1209                 print("-- line $low " . '-' x 40 . "\n") if ($low != 1);
1210                 while (($. < $high) && ($src_line = <INPUTFILE>)) {
1211                     if (defined $line_nums[0] && $. == $line_nums[0]) {
1212                         print_CC($src_file_CCs->{$.}, $CC_col_widths);
1213                         add_array_a_to_b($src_file_CCs->{$.}, 
1214                                          $printed_totals_CC);
1215                         shift(@line_nums);
1217                     } else {
1218                         print_CC([], $CC_col_widths);
1219                     }
1221                     print(" $src_line");
1223                     my $tmp  = $called_from_line->{$src_file,$.};
1224                     my $func = $func_of_line{$src_file,$.};
1225                     if (defined $tmp) {
1226                       # Sort called functions into order dictated by --sort option.
1227                       my @calleds = sort {
1228                         mycmp($call_CCs{$func,$a}, $call_CCs{$func,$b})
1229                       } keys %$tmp;
1230                       foreach my $called (@calleds) {
1231                         if (defined $call_CCs{$func,$called,$.}) {
1232                           print_CC($call_CCs{$func,$called,$.}, $CC_col_widths);
1233                           print " => $called (";
1234                           print commify($call_counter{$func,$called,$.}) . "x)\n";
1235                         }
1236                       }
1237                     }
1238                 }
1239                 # Print line number, unless EOF
1240                 if ($src_line) {
1241                     print("-- line $high " . '-' x 40 . "\n");
1242                 } else {
1243                     last;
1244                 }
1245             }
1247             # If there was info on lines past the end of the file...
1248             if (@line_nums) {
1249                 foreach my $line_num (@line_nums) {
1250                     print_CC($src_file_CCs->{$line_num}, $CC_col_widths);
1251                     print(" <bogus line $line_num>\n");
1252                 }
1253                 print("\n");
1254                 warning_on_nonexistent_lines($src_more_recent_than_inputfile,
1255                                              $src_file, \@line_nums);
1256             }
1257             print("\n");
1259             # Print summary of counts attributed to file but not to any
1260             # particular line (due to incomplete debug info).
1261             if ($src_file_CCs->{0}) {
1262                 print_CC($src_file_CCs->{0}, $CC_col_widths);
1263                 print(" <counts for unidentified lines in $src_file>\n\n");
1264             }
1265             
1266             close(INPUTFILE);
1267         }
1268     }
1270     # Print list of unfound auto-annotate selected files.
1271     if (@unfound_auto_annotate_files) {
1272         print("$fancy");
1273         print("The following files chosen for auto-annotation could not be found:\n");
1274         print($fancy);
1275         foreach my $f (sort @unfound_auto_annotate_files) {
1276             print("  $f\n");
1277         }
1278         print("\n");
1279     }
1281     # If we did any annotating, show how many events were covered by annotated
1282     # lines above.
1283     if ($did_annotations) {
1284         foreach (my $i = 0; $i < @$summary_CC; $i++) {
1285             # Some files (in particular the files produced by --xtree-memory)
1286             # have non additive self costs, so have a special case for these
1287             # to print all functions and also to avoid a division by 0.
1288             if ($summary_CC->[$i] == 0
1289                 || $printed_totals_CC->[$i] > $summary_CC->[$i]) {
1290                 # Set the summary_CC value equal to the printed_totals_CC value
1291                 # so that the percentage printed by the print_CC call below is
1292                 # 100%. This is ok because the summary_CC value is not used
1293                 # again afterward.
1294                 $summary_CC->[$i] = $printed_totals_CC->[$i];
1295             }
1296         }
1297         my $CC_col_widths = compute_CC_col_widths($printed_totals_CC);
1298         print($fancy);
1299         print_events($CC_col_widths);
1300         print("\n");
1301         print($fancy);
1302         print_CC($printed_totals_CC, $CC_col_widths);
1303         print(" events annotated\n\n");
1304     }
1307 #----------------------------------------------------------------------------
1308 # "main()"
1309 #----------------------------------------------------------------------------
1310 process_cmd_line();
1311 read_input_file();
1312 print_options();
1313 my $threshold_files = print_summary_and_fn_totals();
1314 annotate_ann_files($threshold_files);
1316 ##--------------------------------------------------------------------##
1317 ##--- end                                           vg_annotate.in ---##
1318 ##--------------------------------------------------------------------##