blob: 859d51a96b10a07638d6bca8e760f76bf34b8041 [file] [log] [blame]
weidendoa17f2a32006-03-20 10:27:30 +00001#! /usr/bin/perl -w
2##--------------------------------------------------------------------##
3##--- The cache simulation framework: instrumentation, recording ---##
4##--- and results printing. ---##
5##--- callgrind_annotate ---##
6##--------------------------------------------------------------------##
7
8# This file is part of Callgrind, a cache-simulator and call graph
9# tracer built on Valgrind.
10#
11# Copyright (C) 2003 Josef Weidendorfer
12# Josef.Weidendorfer@gmx.de
13#
14# This file is based heavily on vg_annotate, part of Valgrind.
15# Copyright (C) 2002 Nicholas Nethercote
16# njn25@cam.ac.uk
17#
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.
22#
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.
27#
28# You should have received a copy of the GNU General Public License
29# along with this program; if not, write to the Free Software
30# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
31# 02111-1307, USA.
32#
33# The GNU General Public License is contained in the file COPYING.
34
35#----------------------------------------------------------------------------
36# Annotator for cachegrind/callgrind.
37#
38# File format is described in /docs/techdocs.html.
39#
40# Performance improvements record, using cachegrind.out for cacheprof, doing no
41# source annotation (irrelevant ones removed):
42# user time
43# 1. turned off warnings in add_hash_a_to_b() 3.81 --> 3.48s
44# [now add_array_a_to_b()]
45# 6. make line_to_CC() return a ref instead of a hash 3.01 --> 2.77s
46#
47#10. changed file format to avoid file/fn name repetition 2.40s
48# (not sure why higher; maybe due to new '.' entries?)
49#11. changed file format to drop unnecessary end-line "."s 2.36s
50# (shrunk file by about 37%)
51#12. switched from hash CCs to array CCs 1.61s
52#13. only adding b[i] to a[i] if b[i] defined (was doing it if
53# either a[i] or b[i] was defined, but if b[i] was undefined
54# it just added 0) 1.48s
55#14. Stopped converting "." entries to undef and then back 1.16s
56#15. Using foreach $i (x..y) instead of for ($i = 0...) in
57# add_array_a_to_b() 1.11s
58#
59# Auto-annotating primes:
60#16. Finding count lengths by int((length-1)/3), not by
61# commifying (halves the number of commify calls) 1.68s --> 1.47s
62
63use strict;
64
65#----------------------------------------------------------------------------
66# Overview: the running example in the comments is for:
67# - events = A,B,C,D
68# - --show=C,A,D
69# - --sort=D,C
70#----------------------------------------------------------------------------
71
72#----------------------------------------------------------------------------
73# Global variables, main data structures
74#----------------------------------------------------------------------------
75# CCs are arrays, the counts corresponding to @events, with 'undef'
76# representing '.'. This makes things fast (faster than using hashes for CCs)
77# but we have to use @sort_order and @show_order below to handle the --sort and
78# --show options, which is a bit tricky.
79#----------------------------------------------------------------------------
80
81# Total counts for summary (an array reference).
82my $summary_CC;
83
84# Totals for each function, for overall summary.
85# hash(filename:fn_name => CC array)
86my %fn_totals;
87
88# Individual CCs, organised by filename and line_num for easy annotation.
89# hash(filename => hash(line_num => CC array))
90my %all_ind_CCs;
91
92# Files chosen for annotation on the command line.
93# key = basename (trimmed of any directory), value = full filename
94my %user_ann_files;
95
96# Generic description string.
97my $desc = "";
98
99# Command line of profiled program.
100my $cmd = "";
101
102# Info on the profiled process.
weidendo9e2b7b82006-08-31 19:29:13 +0000103my $creator = "";
weidendoa17f2a32006-03-20 10:27:30 +0000104my $pid = "";
105my $part = "";
106my $thread = "";
107
108# Positions used for cost lines; default: line numbers
109my $has_line = 1;
110my $has_addr = 0;
111
112# Events in input file, eg. (A,B,C,D)
113my @events;
114my $events;
115
116# Events to show, from command line, eg. (C,A,D)
117my @show_events;
118
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).)
123my @show_order;
124
125# Print out the function totals sorted by these events, eg. (D,C).
126my @sort_events;
127
128# Map from @sort_events indices to @events indices, eg. (3,2). Same idea as
129# for @show_order.
130my @sort_order;
131
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.
135my @thresholds;
136
137my $default_threshold = 99;
138
139my $single_threshold = $default_threshold;
140
141# If on, automatically annotates all files that are involved in getting over
142# all the threshold counts.
143my $auto_annotate = 0;
144
145# Number of lines to show around each annotated line.
146my $context = 8;
147
148# Directories in which to look for annotation files.
149my @include_dirs = ("");
150
151# Verbose mode
152my $verbose = "1";
153
154# Inclusive statistics (with subroutine events)
155my $inclusive = 0;
156
157# Inclusive totals for each function, for overall summary.
158# hash(filename:fn_name => CC array)
159my %cfn_totals;
160
161# hash( file:func => [ called file:func ])
162my $called_funcs;
163
164# hash( file:func => [ calling file:func ])
165my $calling_funcs;
166
167# hash( file:func,line => [called file:func ])
168my $called_from_line;
169
170# hash( file:func,line => file:func
171my %func_of_line;
172
173# hash (file:func => object name)
174my %obj_name;
175
176# Print out the callers of a function
177my $tree_caller = 0;
178
179# Print out the called functions
180my $tree_calling = 0;
181
182# hash( file:func,cfile:cfunc => call CC[])
183my %call_CCs;
184
185# hash( file:func,cfile:cfunc => call counter)
186my %call_counter;
187
188# hash(context, index) => realname for compressed traces
189my %compressed;
190
191# Input file name, will be set in process_cmd_line
192my $input_file = "";
193
194# Version number
195my $version = "@VERSION@";
196
197# Usage message.
198my $usage = <<END
199usage: callgrind_annotate [options] [data-file [source-files]]
200
201 options for the user, with defaults in [ ], are:
202 -h --help show this message
203 -v --version show version
204 --show=A,B,C only show figures for events A,B,C [all]
205 --sort=A,B,C sort columns by events A,B,C [event column order]
206 --threshold=<0--100> percentage of counts (of primary sort event) we
207 are interested in [$default_threshold%]
208 --auto=yes|no annotate all source files containing functions
209 that helped reach the event count threshold [no]
210 --context=N print N lines of context before and after
211 annotated lines [8]
212 --inclusive=yes|no add subroutine costs to functions calls [no]
213 --tree=none|caller| print for each function their callers,
214 calling|both the called functions or both [none]
215 -I --include=<dir> add <dir> to list of directories to search for
216 source files
217
218END
219;
220
221# Used in various places of output.
222my $fancy = '-' x 80 . "\n";
223
224#-----------------------------------------------------------------------------
225# Argument and option handling
226#-----------------------------------------------------------------------------
227sub process_cmd_line()
228{
229 for my $arg (@ARGV) {
230
231 # Option handling
232 if ($arg =~ /^-/) {
233
234 # --version
235 if ($arg =~ /^-v$|^--version$/) {
236 die("callgrind_annotate-$version\n");
237
238 # --show=A,B,C
239 } elsif ($arg =~ /^--show=(.*)$/) {
240 @show_events = split(/,/, $1);
241
242 # --sort=A,B,C
243 } elsif ($arg =~ /^--sort=(.*)$/) {
244 @sort_events = split(/,/, $1);
245 foreach my $i (0 .. scalar @sort_events - 1) {
246 if ($sort_events[$i] =~#/.*:(\d+)$/) {
247 /.*:([\d\.]+)%?$/) {
248 my $th = $1;
249 ($th >= 0 && $th <= 100) or die($usage);
250 $sort_events[$i] =~ s/:.*//;
251 $thresholds[$i] = $th;
252 } else {
253 $thresholds[$i] = 0;
254 }
255 }
256
257 # --threshold=X (tolerates a trailing '%')
258 } elsif ($arg =~ /^--threshold=([\d\.]+)%?$/) {
259 $single_threshold = $1;
260 ($1 >= 0 && $1 <= 100) or die($usage);
261
262 # --auto=yes|no
263 } elsif ($arg =~ /^--auto=(yes|no)$/) {
264 $auto_annotate = 1 if ($1 eq "yes");
265 $auto_annotate = 0 if ($1 eq "no");
266
267 # --context=N
268 } elsif ($arg =~ /^--context=([\d\.]+)$/) {
269 $context = $1;
270 if ($context < 0) {
271 die($usage);
272 }
273
274 # --inclusive=yes|no
275 } elsif ($arg =~ /^--inclusive=(yes|no)$/) {
276 $inclusive = 1 if ($1 eq "yes");
277 $inclusive = 0 if ($1 eq "no");
278
279 # --tree=none|caller|calling|both
280 } elsif ($arg =~ /^--tree=(none|caller|calling|both)$/) {
281 $tree_caller = 1 if ($1 eq "caller" || $1 eq "both");
282 $tree_calling = 1 if ($1 eq "calling" || $1 eq "both");
283
284 # --include=A,B,C
285 } elsif ($arg =~ /^(-I|--include)=(.*)$/) {
286 my $inc = $2;
287 $inc =~ s|/$||; # trim trailing '/'
288 push(@include_dirs, "$inc/");
289
290 } else { # -h and --help fall under this case
291 die($usage);
292 }
293
294 # Argument handling -- annotation file checking and selection.
295 # Stick filenames into a hash for quick 'n easy lookup throughout
296 } else {
297 if ($input_file eq "") {
298 $input_file = $arg;
299 }
300 else {
301 my $readable = 0;
302 foreach my $include_dir (@include_dirs) {
303 if (-r $include_dir . $arg) {
304 $readable = 1;
305 }
306 }
307 $readable or die("File $arg not found in any of: @include_dirs\n");
308 $user_ann_files{$arg} = 1;
309 }
310 }
311 }
312
313 if ($input_file eq "") {
weidendo9e2b7b82006-08-31 19:29:13 +0000314 $input_file = (<callgrind.out*>)[0];
weidendoa17f2a32006-03-20 10:27:30 +0000315 if (!defined $input_file) {
weidendo9e2b7b82006-08-31 19:29:13 +0000316 $input_file = (<cachegrind.out*>)[0];
weidendoa17f2a32006-03-20 10:27:30 +0000317 }
weidendo9e2b7b82006-08-31 19:29:13 +0000318
319 (defined $input_file) or die($usage);
weidendoa17f2a32006-03-20 10:27:30 +0000320 print "Reading data from '$input_file'...\n";
321 }
322}
323
324#-----------------------------------------------------------------------------
325# Reading of input file
326#-----------------------------------------------------------------------------
327sub max ($$)
328{
329 my ($x, $y) = @_;
330 return ($x > $y ? $x : $y);
331}
332
333# Add the two arrays; any '.' entries are ignored. Two tricky things:
334# 1. If $a2->[$i] is undefined, it defaults to 0 which is what we want; we turn
335# off warnings to allow this. This makes things about 10% faster than
336# checking for definedness ourselves.
337# 2. We don't add an undefined count or a ".", even though it's value is 0,
338# because we don't want to make an $a2->[$i] that is undef become 0
339# unnecessarily.
340sub add_array_a_to_b ($$)
341{
342 my ($a1, $a2) = @_;
343
344 my $n = max(scalar @$a1, scalar @$a2);
345 $^W = 0;
346 foreach my $i (0 .. $n-1) {
347 $a2->[$i] += $a1->[$i] if (defined $a1->[$i] && "." ne $a1->[$i]);
348 }
349 $^W = 1;
350}
351
352# Add each event count to the CC array. '.' counts become undef, as do
353# missing entries (implicitly).
354sub line_to_CC ($)
355{
356 my @CC = (split /\s+/, $_[0]);
357 (@CC <= @events) or die("Line $.: too many event counts\n");
358 return \@CC;
359}
360
361sub uncompressed_name($$)
362{
363 my ($context, $name) = @_;
364
365 if ($name =~ /^\((\d+)\)\s*(.*)$/) {
366 my $index = $1;
367 my $realname = $2;
368
369 if ($realname eq "") {
370 $realname = $compressed{$context,$index};
371 }
372 else {
373 $compressed{$context,$index} = $realname;
374 }
375 return $realname;
376 }
377 return $name;
378}
379
380sub read_input_file()
381{
382 open(INPUTFILE, "< $input_file") || die "File $input_file not opened\n";
383
384 my $line;
385
386 # Read header
387 while(<INPUTFILE>) {
388
389 # remove comments
390 s/#.*$//;
391
392 if (/^$/) { ; }
393
394 elsif (/^version:\s*(\d+)/) {
395 # Can't read format with major version > 1
396 ($1<2) or die("Can't read format with major version $1.\n");
397 }
398
399 elsif (/^pid:\s+(.*)$/) { $pid = $1; }
400 elsif (/^thread:\s+(.*)$/) { $thread = $1; }
401 elsif (/^part:\s+(.*)$/) { $part = $1; }
402 elsif (/^desc:\s+(.*)$/) {
403 my $dline = $1;
404 # suppress profile options in description output
405 if ($dline =~ /^Option:/) {;}
406 else { $desc .= "$dline\n"; }
407 }
408 elsif (/^cmd:\s+(.*)$/) { $cmd = $1; }
weidendo9e2b7b82006-08-31 19:29:13 +0000409 elsif (/^creator:\s+(.*)$/) { $creator = $1; }
weidendoa17f2a32006-03-20 10:27:30 +0000410 elsif (/^positions:\s+(.*)$/) {
411 my $positions = $1;
412 $has_line = ($positions =~ /line/);
413 $has_addr = ($positions =~ /(addr|instr)/);
414 }
415 elsif (/^events:\s+(.*)$/) {
416 $events = $1;
417
418 # events line is last in header
419 last;
420 }
421 else {
422 warn("WARNING: header line $. malformed, ignoring\n");
423 if ($verbose) { chomp; warn(" line: '$_'\n"); }
424 }
425 }
426
427 # Check for needed header entries
428 ($cmd ne "") or die("Line $.: missing command line\n");
429
430 # Read "events:" line. We make a temporary hash in which the Nth event's
431 # value is N, which is useful for handling --show/--sort options below.
432 ($events ne "") or die("Line $.: missing events line\n");
433 @events = split(/\s+/, $events);
434 my %events;
435 my $n = 0;
436 foreach my $event (@events) {
437 $events{$event} = $n;
438 $n++
439 }
440
441 # If no --show arg give, default to showing all events in the file.
442 # If --show option is used, check all specified events appeared in the
443 # "events:" line. Then initialise @show_order.
444 if (@show_events) {
445 foreach my $show_event (@show_events) {
446 (defined $events{$show_event}) or
447 die("--show event `$show_event' did not appear in input\n");
448 }
449 } else {
450 @show_events = @events;
451 }
452 foreach my $show_event (@show_events) {
453 push(@show_order, $events{$show_event});
454 }
455
456 # Do as for --show, but if no --sort arg given, default to sorting by
457 # column order (ie. first column event is primary sort key, 2nd column is
458 # 2ndary key, etc).
459 if (@sort_events) {
460 foreach my $sort_event (@sort_events) {
461 (defined $events{$sort_event}) or
462 die("--sort event `$sort_event' did not appear in input\n");
463 }
464 } else {
465 @sort_events = @events;
466 }
467 foreach my $sort_event (@sort_events) {
468 push(@sort_order, $events{$sort_event});
469 }
470
471 # If multiple threshold args weren't given via --sort, stick in the single
472 # threshold (either from --threshold if used, or the default otherwise) for
473 # the primary sort event, and 0% for the rest.
474 if (not @thresholds) {
475 foreach my $e (@sort_order) {
476 push(@thresholds, 0);
477 }
478 $thresholds[0] = $single_threshold;
479 }
480
481 my $curr_obj = "";
482 my $curr_file;
483 my $curr_fn;
484 my $curr_name;
485 my $curr_line_num = 0;
weidendo7b43dde2006-08-31 22:54:36 +0000486 my $prev_line_num = 0;
weidendoa17f2a32006-03-20 10:27:30 +0000487
488 my $curr_cobj = "";
489 my $curr_cfile = "";
490 my $curr_cfunc = "";
491 my $curr_cname;
492 my $curr_call_counter = 0;
493 my $curr_cfn_CC = [];
494
495 my $curr_fn_CC = [];
496 my $curr_file_ind_CCs = {}; # hash(line_num => CC)
497
498 # Read body of input file.
499 while (<INPUTFILE>) {
weidendo7b43dde2006-08-31 22:54:36 +0000500 $prev_line_num = $curr_line_num;
501
weidendoa17f2a32006-03-20 10:27:30 +0000502 s/#.*$//; # remove comments
weidendo7b43dde2006-08-31 22:54:36 +0000503 s/^\+(\d+)/$prev_line_num+$1/e;
504 s/^\-(\d+)/$prev_line_num-$1/e;
505 s/^\*/$prev_line_num/e;
506 if (s/^(-?\d+|0x\w+)\s+//) {
weidendoa17f2a32006-03-20 10:27:30 +0000507 $curr_line_num = $1;
508 if ($has_addr) {
509 if ($has_line) {
weidendo7b43dde2006-08-31 22:54:36 +0000510 s/^\+(\d+)/$prev_line_num+$1/e;
511 s/^\-(\d+)/$prev_line_num-$1/e;
512 s/^\*/$prev_line_num/e;
weidendoa17f2a32006-03-20 10:27:30 +0000513
514 if (s/^(\d+)\s+//) { $curr_line_num = $1; }
515 }
516 else { $curr_line_num = 0; }
517 }
518 my $CC = line_to_CC($_);
519
520 if ($curr_call_counter>0) {
521# print "Read ($curr_name => $curr_cname) $curr_call_counter\n";
522
523 if (defined $call_CCs{$curr_name,$curr_cname}) {
524 add_array_a_to_b($CC, $call_CCs{$curr_name,$curr_cname});
525 $call_counter{$curr_name,$curr_cname} += $curr_call_counter;
526 }
527 else {
528 $call_CCs{$curr_name,$curr_cname} = $CC;
529 $call_counter{$curr_name,$curr_cname} = $curr_call_counter;
530 }
531
532 my $tmp = $called_from_line->{$curr_file,$curr_line_num};
533 if (!defined $tmp) {
534 $func_of_line{$curr_file,$curr_line_num} = $curr_name;
535 }
536 $tmp = {} unless defined $tmp;
537 $$tmp{$curr_cname} = 1;
538 $called_from_line->{$curr_file,$curr_line_num} = $tmp;
539 $call_CCs{$curr_name,$curr_cname,$curr_line_num} = $CC;
540 $call_counter{$curr_name,$curr_cname,$curr_line_num} = $curr_call_counter;
541
542 $curr_call_counter = 0;
543
544 # inclusive costs
545 $curr_cfn_CC = $cfn_totals{$curr_cname};
546 $curr_cfn_CC = [] unless (defined $curr_cfn_CC);
547 add_array_a_to_b($CC, $curr_cfn_CC);
548 $cfn_totals{$curr_cname} = $curr_cfn_CC;
549
550 if ($inclusive) {
551 add_array_a_to_b($CC, $curr_fn_CC);
552 }
553 next;
554 }
555
556 add_array_a_to_b($CC, $curr_fn_CC);
557
558 # If curr_file is selected, add CC to curr_file list. We look for
559 # full filename matches; or, if auto-annotating, we have to
560 # remember everything -- we won't know until the end what's needed.
561 if ($auto_annotate || defined $user_ann_files{$curr_file}) {
562 my $tmp = $curr_file_ind_CCs->{$curr_line_num};
563 $tmp = [] unless defined $tmp;
564 add_array_a_to_b($CC, $tmp);
565 $curr_file_ind_CCs->{$curr_line_num} = $tmp;
566 }
567
568 } elsif (s/^fn=(.*)$//) {
569 # Commit result from previous function
570 $fn_totals{$curr_name} = $curr_fn_CC if (defined $curr_name);
571
572 # Setup new one
573 $curr_fn = uncompressed_name("fn",$1);
574 $curr_name = "$curr_file:$curr_fn";
575 $obj_name{$curr_name} = $curr_obj;
576 $curr_fn_CC = $fn_totals{$curr_name};
577 $curr_fn_CC = [] unless (defined $curr_fn_CC);
578
579 } elsif (s/^ob=(.*)$//) {
580 $curr_obj = uncompressed_name("ob",$1);
581
582 } elsif (s/^fl=(.*)$//) {
583 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs
584 if (defined $curr_file);
585
586 $curr_file = uncompressed_name("fl",$1);
587 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
588 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
589
590 } elsif (s/^(fi|fe)=(.*)$//) {
591 (defined $curr_name) or die("Line $.: Unexpected fi/fe line\n");
592 $fn_totals{$curr_name} = $curr_fn_CC;
593 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs;
594
595 $curr_file = uncompressed_name("fl",$2);
596 $curr_name = "$curr_file:$curr_fn";
597 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
598 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
599 $curr_fn_CC = $fn_totals{$curr_name};
600 $curr_fn_CC = [] unless (defined $curr_fn_CC);
601
602 } elsif (s/^\s*$//) {
603 # blank, do nothing
604
605 } elsif (s/^cob=(.*)$//) {
606 $curr_cobj = uncompressed_name("ob",$1);
607
608 } elsif (s/^cfi=(.*)$//) {
609 $curr_cfile = uncompressed_name("fl",$1);
610
611 } elsif (s/^cfn=(.*)$//) {
612 $curr_cfunc = uncompressed_name("fn",$1);
613 if ($curr_cfile eq "") {
614 $curr_cname = "$curr_file:$curr_cfunc";
615 }
616 else {
617 $curr_cname = "$curr_cfile:$curr_cfunc";
618 $curr_cfile = "";
619 }
620
621 my $tmp = $calling_funcs->{$curr_cname};
622 $tmp = {} unless defined $tmp;
623 $$tmp{$curr_name} = 1;
624 $calling_funcs->{$curr_cname} = $tmp;
625
626 my $tmp2 = $called_funcs->{$curr_name};
627 $tmp2 = {} unless defined $tmp2;
628 $$tmp2{$curr_cname} = 1;
629 $called_funcs->{$curr_name} = $tmp2;
630
631 } elsif (s/^calls=(\d+)//) {
632 $curr_call_counter = $1;
633
634 } elsif (s/^(jump|jcnd)=//) {
635 #ignore jump information
636
637 } elsif (s/^totals:\s+//) {
638 #ignore
639
640 } elsif (s/^summary:\s+//) {
641 $summary_CC = line_to_CC($_);
642
643 } else {
644 warn("WARNING: line $. malformed, ignoring\n");
645 if ($verbose) { chomp; warn(" line: '$_'\n"); }
646 }
647 }
648
649 # Check if summary line was present
650 if (not defined $summary_CC) {
651 warn("WARNING: missing final summary line, no summary will be printed\n");
652 }
653 else {
654 # Finish up handling final filename/fn_name counts
655 $fn_totals{"$curr_file:$curr_fn"} = $curr_fn_CC
656 if (defined $curr_file && defined $curr_fn);
657 $all_ind_CCs{$curr_file} =
658 $curr_file_ind_CCs if (defined $curr_file);
659
660 (scalar(@$summary_CC) == @events)
661 or die("Line $.: summary event and total event mismatch\n");
662 }
663
664 # Correct inclusive totals
665 if ($inclusive) {
666 foreach my $name (keys %cfn_totals) {
667 $fn_totals{$name} = $cfn_totals{$name};
668 }
669 }
670
671 close(INPUTFILE);
672}
673
674#-----------------------------------------------------------------------------
675# Print options used
676#-----------------------------------------------------------------------------
677sub print_options ()
678{
679 print($fancy);
weidendo9e2b7b82006-08-31 19:29:13 +0000680 print "Profile data file '$input_file'";
681 if ($creator ne "") { print " (creator: $creator)"; }
682 print "\n";
683
684 print($fancy);
weidendoa17f2a32006-03-20 10:27:30 +0000685 print($desc);
686 my $target = $cmd;
687 if ($pid ne "") {
688 $target .= " (PID $pid";
689 if ($part ne "") { $target .= ", part $part"; }
690 if ($thread ne "") { $target .= ", thread $thread"; }
691 $target .= ")";
692 }
693 print("Profiled target: $target\n");
694 print("Events recorded: @events\n");
695 print("Events shown: @show_events\n");
696 print("Event sort order: @sort_events\n");
697 print("Thresholds: @thresholds\n");
698
699 my @include_dirs2 = @include_dirs; # copy @include_dirs
700 shift(@include_dirs2); # remove "" entry, which is always the first
701 unshift(@include_dirs2, "") if (0 == @include_dirs2);
702 my $include_dir = shift(@include_dirs2);
703 print("Include dirs: $include_dir\n");
704 foreach my $include_dir (@include_dirs2) {
705 print(" $include_dir\n");
706 }
707
708 my @user_ann_files = keys %user_ann_files;
709 unshift(@user_ann_files, "") if (0 == @user_ann_files);
710 my $user_ann_file = shift(@user_ann_files);
711 print("User annotated: $user_ann_file\n");
712 foreach $user_ann_file (@user_ann_files) {
713 print(" $user_ann_file\n");
714 }
715
716 my $is_on = ($auto_annotate ? "on" : "off");
717 print("Auto-annotation: $is_on\n");
718 print("\n");
719}
720
721#-----------------------------------------------------------------------------
722# Print summary and sorted function totals
723#-----------------------------------------------------------------------------
724sub mycmp ($$)
725{
726 my ($c, $d) = @_;
727
728 # Iterate through sort events (eg. 3,2); return result if two are different
729 foreach my $i (@sort_order) {
730 my ($x, $y);
731 $x = $c->[$i];
732 $y = $d->[$i];
733 $x = -1 unless defined $x;
734 $y = -1 unless defined $y;
735
736 my $cmp = $y <=> $x; # reverse sort
737 if (0 != $cmp) {
738 return $cmp;
739 }
740 }
741 # Exhausted events, equal
742 return 0;
743}
744
745sub commify ($) {
746 my ($val) = @_;
747 1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
748 return $val;
749}
750
751# Because the counts can get very big, and we don't want to waste screen space
752# and make lines too long, we compute exactly how wide each column needs to be
753# by finding the widest entry for each one.
754sub compute_CC_col_widths (@)
755{
756 my @CCs = @_;
757 my $CC_col_widths = [];
758
759 # Initialise with minimum widths (from event names)
760 foreach my $event (@events) {
761 push(@$CC_col_widths, length($event));
762 }
763
764 # Find maximum width count for each column. @CC_col_width positions
765 # correspond to @CC positions.
766 foreach my $CC (@CCs) {
767 foreach my $i (0 .. scalar(@$CC)-1) {
768 if (defined $CC->[$i]) {
769 # Find length, accounting for commas that will be added
770 my $length = length $CC->[$i];
771 my $clength = $length + int(($length - 1) / 3);
772 $CC_col_widths->[$i] = max($CC_col_widths->[$i], $clength);
773 }
774 }
775 }
776 return $CC_col_widths;
777}
778
779# Print the CC with each column's size dictated by $CC_col_widths.
780sub print_CC ($$)
781{
782 my ($CC, $CC_col_widths) = @_;
783
784 foreach my $i (@show_order) {
785 my $count = (defined $CC->[$i] ? commify($CC->[$i]) : ".");
786 my $space = ' ' x ($CC_col_widths->[$i] - length($count));
787 print("$space$count ");
788 }
789}
790
791sub print_events ($)
792{
793 my ($CC_col_widths) = @_;
794
795 foreach my $i (@show_order) {
796 my $event = $events[$i];
797 my $event_width = length($event);
798 my $col_width = $CC_col_widths->[$i];
799 my $space = ' ' x ($col_width - $event_width);
800 print("$space$event ");
801 }
802}
803
804# Prints summary and function totals (with separate column widths, so that
805# function names aren't pushed over unnecessarily by huge summary figures).
806# Also returns a hash containing all the files that are involved in getting the
807# events count above the thresholds (ie. all the interesting ones).
808sub print_summary_and_fn_totals ()
809{
810 my @fn_fullnames = keys %fn_totals;
811
812 # Work out the size of each column for printing (summary and functions
813 # separately).
814 my $summary_CC_col_widths = compute_CC_col_widths($summary_CC);
815 my $fn_CC_col_widths = compute_CC_col_widths(values %fn_totals);
816
817 # Header and counts for summary
818 print($fancy);
819 print_events($summary_CC_col_widths);
820 print("\n");
821 print($fancy);
822 print_CC($summary_CC, $summary_CC_col_widths);
823 print(" PROGRAM TOTALS\n");
824 print("\n");
825
826 # Header for functions
827 print($fancy);
828 print_events($fn_CC_col_widths);
829 print(" file:function\n");
830 print($fancy);
831
832 # Sort function names into order dictated by --sort option.
833 @fn_fullnames = sort {
834 mycmp($fn_totals{$a}, $fn_totals{$b})
835 } @fn_fullnames;
836
837
838 # Assertion
839 (scalar @sort_order == scalar @thresholds) or
840 die("sort_order length != thresholds length:\n",
841 " @sort_order\n @thresholds\n");
842
843 my $threshold_files = {};
844 # @curr_totals has the same shape as @sort_order and @thresholds
845 my @curr_totals = ();
846 foreach my $e (@thresholds) {
847 push(@curr_totals, 0);
848 }
849
850 # Print functions, stopping when the threshold has been reached.
851 foreach my $fn_name (@fn_fullnames) {
852
853 # Stop when we've reached all the thresholds
854 my $reached_all_thresholds = 1;
855 foreach my $i (0 .. scalar @thresholds - 1) {
856 my $prop = $curr_totals[$i] * 100;
857 if ($summary_CC->[$sort_order[$i]] >0) {
858 $prop = $prop / $summary_CC->[$sort_order[$i]];
859 }
860 $reached_all_thresholds &= ($prop >= $thresholds[$i]);
861 }
862 last if $reached_all_thresholds;
863
864 if ($tree_caller || $tree_calling) { print "\n"; }
865
866 if ($tree_caller && ($fn_name ne "???:???")) {
867 # Print function callers
868 my $tmp1 = $calling_funcs->{$fn_name};
869 if (defined $tmp1) {
870 foreach my $calling (keys %$tmp1) {
871 if (defined $call_counter{$calling,$fn_name}) {
872 print_CC($call_CCs{$calling,$fn_name}, $fn_CC_col_widths);
873 print" < $calling (";
874 print $call_counter{$calling,$fn_name} . "x)";
875 if (defined $obj_name{$calling}) {
876 print " [$obj_name{$calling}]";
877 }
878 print "\n";
879 }
880 }
881 }
882 }
883
884 # Print function results
885 my $fn_CC = $fn_totals{$fn_name};
886 print_CC($fn_CC, $fn_CC_col_widths);
887 if ($tree_caller || $tree_calling) { print " * "; }
888 print(" $fn_name");
889 if (defined $obj_name{$fn_name}) {
890 print " [$obj_name{$fn_name}]";
891 }
892 print "\n";
893
894 if ($tree_calling && ($fn_name ne "???:???")) {
895 # Print called functions
896 my $tmp2 = $called_funcs->{$fn_name};
897 if (defined $tmp2) {
898 foreach my $called (keys %$tmp2) {
899 if (defined $call_counter{$fn_name,$called}) {
900 print_CC($call_CCs{$fn_name,$called}, $fn_CC_col_widths);
901 print" > $called (";
902 print $call_counter{$fn_name,$called} . "x)";
903 if (defined $obj_name{$called}) {
904 print " [$obj_name{$called}]";
905 }
906 print "\n";
907 }
908 }
909 }
910 }
911
912 # Update the threshold counts
913 my $filename = $fn_name;
914 $filename =~ s/:.+$//; # remove function name
915 $threshold_files->{$filename} = 1;
916 foreach my $i (0 .. scalar @sort_order - 1) {
917 if ($inclusive) {
918 $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
919 $fn_CC->[$sort_order[$i]]
920 if (defined $fn_CC->[$sort_order[$i]]);
921 } else {
922 $curr_totals[$i] += $fn_CC->[$sort_order[$i]]
923 if (defined $fn_CC->[$sort_order[$i]]);
924 }
925 }
926 }
927 print("\n");
928
929 return $threshold_files;
930}
931
932#-----------------------------------------------------------------------------
933# Annotate selected files
934#-----------------------------------------------------------------------------
935
936# Issue a warning that the source file is more recent than the input file.
937sub warning_on_src_more_recent_than_inputfile ($)
938{
939 my $src_file = $_[0];
940
941 my $warning = <<END
942@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
943@@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
944@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
945@ Source file '$src_file' is more recent than input file '$input_file'.
946@ Annotations may not be correct.
947@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
948
949END
950;
951 print($warning);
952}
953
954# If there is information about lines not in the file, issue a warning
955# explaining possible causes.
956sub warning_on_nonexistent_lines ($$$)
957{
958 my ($src_more_recent_than_inputfile, $src_file, $excess_line_nums) = @_;
959 my $cause_and_solution;
960
961 if ($src_more_recent_than_inputfile) {
962 $cause_and_solution = <<END
963@@ cause: '$src_file' has changed since information was gathered.
964@@ If so, a warning will have already been issued about this.
965@@ solution: Recompile program and rerun under "valgrind --cachesim=yes" to
966@@ gather new information.
967END
968 # We suppress warnings about .h files
969 } elsif ($src_file =~ /\.h$/) {
970 $cause_and_solution = <<END
971@@ cause: bug in the Valgrind's debug info reader that screws up with .h
972@@ files sometimes
973@@ solution: none, sorry
974END
975 } else {
976 $cause_and_solution = <<END
977@@ cause: not sure, sorry
978END
979 }
980
981 my $warning = <<END
982@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
983@@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
984@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
985@@
986@@ Information recorded about lines past the end of '$src_file'.
987@@
988@@ Probable cause and solution:
989$cause_and_solution@@
990@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
991END
992;
993 print($warning);
994}
995
996sub annotate_ann_files($)
997{
998 my ($threshold_files) = @_;
999
1000 my %all_ann_files;
1001 my @unfound_auto_annotate_files;
1002 my $printed_totals_CC = [];
1003
1004 # If auto-annotating, add interesting files (but not "???")
1005 if ($auto_annotate) {
1006 delete $threshold_files->{"???"};
1007 %all_ann_files = (%user_ann_files, %$threshold_files)
1008 } else {
1009 %all_ann_files = %user_ann_files;
1010 }
1011
1012 # Track if we did any annotations.
1013 my $did_annotations = 0;
1014
1015 LOOP:
1016 foreach my $src_file (keys %all_ann_files) {
1017
1018 my $opened_file = "";
1019 my $full_file_name = "";
1020 foreach my $include_dir (@include_dirs) {
1021 my $try_name = $include_dir . $src_file;
1022 if (open(INPUTFILE, "< $try_name")) {
1023 $opened_file = $try_name;
1024 $full_file_name = ($include_dir eq ""
1025 ? $src_file
1026 : "$include_dir + $src_file");
1027 last;
1028 }
1029 }
1030
1031 if (not $opened_file) {
1032 # Failed to open the file. If chosen on the command line, die.
1033 # If arose from auto-annotation, print a little message.
1034 if (defined $user_ann_files{$src_file}) {
1035 die("File $src_file not opened in any of: @include_dirs\n");
1036
1037 } else {
1038 push(@unfound_auto_annotate_files, $src_file);
1039 }
1040
1041 } else {
1042 # File header (distinguish between user- and auto-selected files).
1043 print("$fancy");
1044 my $ann_type =
1045 (defined $user_ann_files{$src_file} ? "User" : "Auto");
1046 print("-- $ann_type-annotated source: $full_file_name\n");
1047 print("$fancy");
1048
1049 # Get file's CCs
1050 my $src_file_CCs = $all_ind_CCs{$src_file};
1051 if (!defined $src_file_CCs) {
1052 print(" No information has been collected for $src_file\n\n");
1053 next LOOP;
1054 }
1055
1056 $did_annotations = 1;
1057
1058 # Numeric, not lexicographic sort!
1059 my @line_nums = sort {$a <=> $b} keys %$src_file_CCs;
1060
1061 # If $src_file more recent than cachegrind.out, issue warning
1062 my $src_more_recent_than_inputfile = 0;
1063 if ((stat $opened_file)[9] > (stat $input_file)[9]) {
1064 $src_more_recent_than_inputfile = 1;
1065 warning_on_src_more_recent_than_inputfile($src_file);
1066 }
1067
1068 # Work out the size of each column for printing
1069 my $CC_col_widths = compute_CC_col_widths(values %$src_file_CCs);
1070
1071 # Events header
1072 print_events($CC_col_widths);
1073 print("\n\n");
1074
1075 # Shift out 0 if it's in the line numbers (from unknown entries,
1076 # likely due to bugs in Valgrind's stabs debug info reader)
1077 shift(@line_nums) if (0 == $line_nums[0]);
1078
1079 # Finds interesting line ranges -- all lines with a CC, and all
1080 # lines within $context lines of a line with a CC.
1081 my $n = @line_nums;
1082 my @pairs;
1083 for (my $i = 0; $i < $n; $i++) {
1084 push(@pairs, $line_nums[$i] - $context); # lower marker
1085 while ($i < $n-1 &&
1086 $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1087 $i++;
1088 }
1089 push(@pairs, $line_nums[$i] + $context); # upper marker
1090 }
1091
1092 # Annotate chosen lines, tracking total counts of lines printed
1093 $pairs[0] = 1 if ($pairs[0] < 1);
1094 while (@pairs) {
1095 my $low = shift @pairs;
1096 my $high = shift @pairs;
1097 while ($. < $low-1) {
1098 my $tmp = <INPUTFILE>;
1099 last unless (defined $tmp); # hack to detect EOF
1100 }
1101 my $src_line;
1102 # Print line number, unless start of file
1103 print("-- line $low " . '-' x 40 . "\n") if ($low != 1);
1104 while (($. < $high) && ($src_line = <INPUTFILE>)) {
1105 if (defined $line_nums[0] && $. == $line_nums[0]) {
1106 print_CC($src_file_CCs->{$.}, $CC_col_widths);
1107 add_array_a_to_b($src_file_CCs->{$.},
1108 $printed_totals_CC);
1109 shift(@line_nums);
1110
1111 } else {
1112 print_CC( [], $CC_col_widths);
1113 }
1114
1115 print(" $src_line");
1116
1117 my $tmp = $called_from_line->{$src_file,$.};
1118 my $func = $func_of_line{$src_file,$.};
1119 if (defined $tmp) {
1120 foreach my $called (keys %$tmp) {
1121 if (defined $call_CCs{$func,$called,$.}) {
1122 print_CC($call_CCs{$func,$called,$.}, $CC_col_widths);
1123 print " => $called (";
1124 print $call_counter{$func,$called,$.} . "x)\n";
1125 }
1126 }
1127 }
1128 }
1129 # Print line number, unless EOF
1130 if ($src_line) {
1131 print("-- line $high " . '-' x 40 . "\n");
1132 } else {
1133 last;
1134 }
1135 }
1136
1137 # If there was info on lines past the end of the file...
1138 if (@line_nums) {
1139 foreach my $line_num (@line_nums) {
1140 print_CC($src_file_CCs->{$line_num}, $CC_col_widths);
1141 print(" <bogus line $line_num>\n");
1142 }
1143 print("\n");
1144 warning_on_nonexistent_lines($src_more_recent_than_inputfile,
1145 $src_file, \@line_nums);
1146 }
1147 print("\n");
1148
1149 # Print summary of counts attributed to file but not to any
1150 # particular line (due to incomplete debug info).
1151 if ($src_file_CCs->{0}) {
1152 print_CC($src_file_CCs->{0}, $CC_col_widths);
1153 print(" <counts for unidentified lines in $src_file>\n\n");
1154 }
1155
1156 close(INPUTFILE);
1157 }
1158 }
1159
1160 # Print list of unfound auto-annotate selected files.
1161 if (@unfound_auto_annotate_files) {
1162 print("$fancy");
1163 print("The following files chosen for auto-annotation could not be found:\n");
1164 print($fancy);
1165 foreach my $f (@unfound_auto_annotate_files) {
1166 print(" $f\n");
1167 }
1168 print("\n");
1169 }
1170
1171 # If we did any annotating, print what proportion of events were covered by
1172 # annotated lines above.
1173 if ($did_annotations) {
1174 my $percent_printed_CC;
1175 foreach (my $i = 0; $i < @$summary_CC; $i++) {
1176 $percent_printed_CC->[$i] =
1177 sprintf("%.0f",
1178 $printed_totals_CC->[$i] / $summary_CC->[$i] * 100);
1179 }
1180 my $pp_CC_col_widths = compute_CC_col_widths($percent_printed_CC);
1181 print($fancy);
1182 print_events($pp_CC_col_widths);
1183 print("\n");
1184 print($fancy);
1185 print_CC($percent_printed_CC, $pp_CC_col_widths);
1186 print(" percentage of events annotated\n\n");
1187 }
1188}
1189
1190#----------------------------------------------------------------------------
1191# "main()"
1192#----------------------------------------------------------------------------
1193process_cmd_line();
1194read_input_file();
1195print_options();
1196my $threshold_files = print_summary_and_fn_totals();
1197annotate_ann_files($threshold_files);
1198
1199##--------------------------------------------------------------------##
1200##--- end vg_annotate.in ---##
1201##--------------------------------------------------------------------##
1202
1203