blob: 617354d194582860e0192dd924d19a55423c4d8e [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;
486
487 my $curr_cobj = "";
488 my $curr_cfile = "";
489 my $curr_cfunc = "";
490 my $curr_cname;
491 my $curr_call_counter = 0;
492 my $curr_cfn_CC = [];
493
494 my $curr_fn_CC = [];
495 my $curr_file_ind_CCs = {}; # hash(line_num => CC)
496
497 # Read body of input file.
498 while (<INPUTFILE>) {
499 s/#.*$//; # remove comments
500 s/^\+(\d+)/$curr_line_num+$1/e;
501 s/^\-(\d+)/$curr_line_num-$1/e;
502 s/^\*/$curr_line_num/e;
503 if (s/^(\d+|0x\w+)\s+//) {
504 $curr_line_num = $1;
505 if ($has_addr) {
506 if ($has_line) {
507 s/^\+(\d+)/$curr_line_num+$1/e;
508 s/^\-(\d+)/$curr_line_num-$1/e;
509 s/^\*/$curr_line_num/e;
510
511 if (s/^(\d+)\s+//) { $curr_line_num = $1; }
512 }
513 else { $curr_line_num = 0; }
514 }
515 my $CC = line_to_CC($_);
516
517 if ($curr_call_counter>0) {
518# print "Read ($curr_name => $curr_cname) $curr_call_counter\n";
519
520 if (defined $call_CCs{$curr_name,$curr_cname}) {
521 add_array_a_to_b($CC, $call_CCs{$curr_name,$curr_cname});
522 $call_counter{$curr_name,$curr_cname} += $curr_call_counter;
523 }
524 else {
525 $call_CCs{$curr_name,$curr_cname} = $CC;
526 $call_counter{$curr_name,$curr_cname} = $curr_call_counter;
527 }
528
529 my $tmp = $called_from_line->{$curr_file,$curr_line_num};
530 if (!defined $tmp) {
531 $func_of_line{$curr_file,$curr_line_num} = $curr_name;
532 }
533 $tmp = {} unless defined $tmp;
534 $$tmp{$curr_cname} = 1;
535 $called_from_line->{$curr_file,$curr_line_num} = $tmp;
536 $call_CCs{$curr_name,$curr_cname,$curr_line_num} = $CC;
537 $call_counter{$curr_name,$curr_cname,$curr_line_num} = $curr_call_counter;
538
539 $curr_call_counter = 0;
540
541 # inclusive costs
542 $curr_cfn_CC = $cfn_totals{$curr_cname};
543 $curr_cfn_CC = [] unless (defined $curr_cfn_CC);
544 add_array_a_to_b($CC, $curr_cfn_CC);
545 $cfn_totals{$curr_cname} = $curr_cfn_CC;
546
547 if ($inclusive) {
548 add_array_a_to_b($CC, $curr_fn_CC);
549 }
550 next;
551 }
552
553 add_array_a_to_b($CC, $curr_fn_CC);
554
555 # If curr_file is selected, add CC to curr_file list. We look for
556 # full filename matches; or, if auto-annotating, we have to
557 # remember everything -- we won't know until the end what's needed.
558 if ($auto_annotate || defined $user_ann_files{$curr_file}) {
559 my $tmp = $curr_file_ind_CCs->{$curr_line_num};
560 $tmp = [] unless defined $tmp;
561 add_array_a_to_b($CC, $tmp);
562 $curr_file_ind_CCs->{$curr_line_num} = $tmp;
563 }
564
565 } elsif (s/^fn=(.*)$//) {
566 # Commit result from previous function
567 $fn_totals{$curr_name} = $curr_fn_CC if (defined $curr_name);
568
569 # Setup new one
570 $curr_fn = uncompressed_name("fn",$1);
571 $curr_name = "$curr_file:$curr_fn";
572 $obj_name{$curr_name} = $curr_obj;
573 $curr_fn_CC = $fn_totals{$curr_name};
574 $curr_fn_CC = [] unless (defined $curr_fn_CC);
575
576 } elsif (s/^ob=(.*)$//) {
577 $curr_obj = uncompressed_name("ob",$1);
578
579 } elsif (s/^fl=(.*)$//) {
580 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs
581 if (defined $curr_file);
582
583 $curr_file = uncompressed_name("fl",$1);
584 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
585 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
586
587 } elsif (s/^(fi|fe)=(.*)$//) {
588 (defined $curr_name) or die("Line $.: Unexpected fi/fe line\n");
589 $fn_totals{$curr_name} = $curr_fn_CC;
590 $all_ind_CCs{$curr_file} = $curr_file_ind_CCs;
591
592 $curr_file = uncompressed_name("fl",$2);
593 $curr_name = "$curr_file:$curr_fn";
594 $curr_file_ind_CCs = $all_ind_CCs{$curr_file};
595 $curr_file_ind_CCs = {} unless (defined $curr_file_ind_CCs);
596 $curr_fn_CC = $fn_totals{$curr_name};
597 $curr_fn_CC = [] unless (defined $curr_fn_CC);
598
599 } elsif (s/^\s*$//) {
600 # blank, do nothing
601
602 } elsif (s/^cob=(.*)$//) {
603 $curr_cobj = uncompressed_name("ob",$1);
604
605 } elsif (s/^cfi=(.*)$//) {
606 $curr_cfile = uncompressed_name("fl",$1);
607
608 } elsif (s/^cfn=(.*)$//) {
609 $curr_cfunc = uncompressed_name("fn",$1);
610 if ($curr_cfile eq "") {
611 $curr_cname = "$curr_file:$curr_cfunc";
612 }
613 else {
614 $curr_cname = "$curr_cfile:$curr_cfunc";
615 $curr_cfile = "";
616 }
617
618 my $tmp = $calling_funcs->{$curr_cname};
619 $tmp = {} unless defined $tmp;
620 $$tmp{$curr_name} = 1;
621 $calling_funcs->{$curr_cname} = $tmp;
622
623 my $tmp2 = $called_funcs->{$curr_name};
624 $tmp2 = {} unless defined $tmp2;
625 $$tmp2{$curr_cname} = 1;
626 $called_funcs->{$curr_name} = $tmp2;
627
628 } elsif (s/^calls=(\d+)//) {
629 $curr_call_counter = $1;
630
631 } elsif (s/^(jump|jcnd)=//) {
632 #ignore jump information
633
634 } elsif (s/^totals:\s+//) {
635 #ignore
636
637 } elsif (s/^summary:\s+//) {
638 $summary_CC = line_to_CC($_);
639
640 } else {
641 warn("WARNING: line $. malformed, ignoring\n");
642 if ($verbose) { chomp; warn(" line: '$_'\n"); }
643 }
644 }
645
646 # Check if summary line was present
647 if (not defined $summary_CC) {
648 warn("WARNING: missing final summary line, no summary will be printed\n");
649 }
650 else {
651 # Finish up handling final filename/fn_name counts
652 $fn_totals{"$curr_file:$curr_fn"} = $curr_fn_CC
653 if (defined $curr_file && defined $curr_fn);
654 $all_ind_CCs{$curr_file} =
655 $curr_file_ind_CCs if (defined $curr_file);
656
657 (scalar(@$summary_CC) == @events)
658 or die("Line $.: summary event and total event mismatch\n");
659 }
660
661 # Correct inclusive totals
662 if ($inclusive) {
663 foreach my $name (keys %cfn_totals) {
664 $fn_totals{$name} = $cfn_totals{$name};
665 }
666 }
667
668 close(INPUTFILE);
669}
670
671#-----------------------------------------------------------------------------
672# Print options used
673#-----------------------------------------------------------------------------
674sub print_options ()
675{
676 print($fancy);
weidendo9e2b7b82006-08-31 19:29:13 +0000677 print "Profile data file '$input_file'";
678 if ($creator ne "") { print " (creator: $creator)"; }
679 print "\n";
680
681 print($fancy);
weidendoa17f2a32006-03-20 10:27:30 +0000682 print($desc);
683 my $target = $cmd;
684 if ($pid ne "") {
685 $target .= " (PID $pid";
686 if ($part ne "") { $target .= ", part $part"; }
687 if ($thread ne "") { $target .= ", thread $thread"; }
688 $target .= ")";
689 }
690 print("Profiled target: $target\n");
691 print("Events recorded: @events\n");
692 print("Events shown: @show_events\n");
693 print("Event sort order: @sort_events\n");
694 print("Thresholds: @thresholds\n");
695
696 my @include_dirs2 = @include_dirs; # copy @include_dirs
697 shift(@include_dirs2); # remove "" entry, which is always the first
698 unshift(@include_dirs2, "") if (0 == @include_dirs2);
699 my $include_dir = shift(@include_dirs2);
700 print("Include dirs: $include_dir\n");
701 foreach my $include_dir (@include_dirs2) {
702 print(" $include_dir\n");
703 }
704
705 my @user_ann_files = keys %user_ann_files;
706 unshift(@user_ann_files, "") if (0 == @user_ann_files);
707 my $user_ann_file = shift(@user_ann_files);
708 print("User annotated: $user_ann_file\n");
709 foreach $user_ann_file (@user_ann_files) {
710 print(" $user_ann_file\n");
711 }
712
713 my $is_on = ($auto_annotate ? "on" : "off");
714 print("Auto-annotation: $is_on\n");
715 print("\n");
716}
717
718#-----------------------------------------------------------------------------
719# Print summary and sorted function totals
720#-----------------------------------------------------------------------------
721sub mycmp ($$)
722{
723 my ($c, $d) = @_;
724
725 # Iterate through sort events (eg. 3,2); return result if two are different
726 foreach my $i (@sort_order) {
727 my ($x, $y);
728 $x = $c->[$i];
729 $y = $d->[$i];
730 $x = -1 unless defined $x;
731 $y = -1 unless defined $y;
732
733 my $cmp = $y <=> $x; # reverse sort
734 if (0 != $cmp) {
735 return $cmp;
736 }
737 }
738 # Exhausted events, equal
739 return 0;
740}
741
742sub commify ($) {
743 my ($val) = @_;
744 1 while ($val =~ s/^(\d+)(\d{3})/$1,$2/);
745 return $val;
746}
747
748# Because the counts can get very big, and we don't want to waste screen space
749# and make lines too long, we compute exactly how wide each column needs to be
750# by finding the widest entry for each one.
751sub compute_CC_col_widths (@)
752{
753 my @CCs = @_;
754 my $CC_col_widths = [];
755
756 # Initialise with minimum widths (from event names)
757 foreach my $event (@events) {
758 push(@$CC_col_widths, length($event));
759 }
760
761 # Find maximum width count for each column. @CC_col_width positions
762 # correspond to @CC positions.
763 foreach my $CC (@CCs) {
764 foreach my $i (0 .. scalar(@$CC)-1) {
765 if (defined $CC->[$i]) {
766 # Find length, accounting for commas that will be added
767 my $length = length $CC->[$i];
768 my $clength = $length + int(($length - 1) / 3);
769 $CC_col_widths->[$i] = max($CC_col_widths->[$i], $clength);
770 }
771 }
772 }
773 return $CC_col_widths;
774}
775
776# Print the CC with each column's size dictated by $CC_col_widths.
777sub print_CC ($$)
778{
779 my ($CC, $CC_col_widths) = @_;
780
781 foreach my $i (@show_order) {
782 my $count = (defined $CC->[$i] ? commify($CC->[$i]) : ".");
783 my $space = ' ' x ($CC_col_widths->[$i] - length($count));
784 print("$space$count ");
785 }
786}
787
788sub print_events ($)
789{
790 my ($CC_col_widths) = @_;
791
792 foreach my $i (@show_order) {
793 my $event = $events[$i];
794 my $event_width = length($event);
795 my $col_width = $CC_col_widths->[$i];
796 my $space = ' ' x ($col_width - $event_width);
797 print("$space$event ");
798 }
799}
800
801# Prints summary and function totals (with separate column widths, so that
802# function names aren't pushed over unnecessarily by huge summary figures).
803# Also returns a hash containing all the files that are involved in getting the
804# events count above the thresholds (ie. all the interesting ones).
805sub print_summary_and_fn_totals ()
806{
807 my @fn_fullnames = keys %fn_totals;
808
809 # Work out the size of each column for printing (summary and functions
810 # separately).
811 my $summary_CC_col_widths = compute_CC_col_widths($summary_CC);
812 my $fn_CC_col_widths = compute_CC_col_widths(values %fn_totals);
813
814 # Header and counts for summary
815 print($fancy);
816 print_events($summary_CC_col_widths);
817 print("\n");
818 print($fancy);
819 print_CC($summary_CC, $summary_CC_col_widths);
820 print(" PROGRAM TOTALS\n");
821 print("\n");
822
823 # Header for functions
824 print($fancy);
825 print_events($fn_CC_col_widths);
826 print(" file:function\n");
827 print($fancy);
828
829 # Sort function names into order dictated by --sort option.
830 @fn_fullnames = sort {
831 mycmp($fn_totals{$a}, $fn_totals{$b})
832 } @fn_fullnames;
833
834
835 # Assertion
836 (scalar @sort_order == scalar @thresholds) or
837 die("sort_order length != thresholds length:\n",
838 " @sort_order\n @thresholds\n");
839
840 my $threshold_files = {};
841 # @curr_totals has the same shape as @sort_order and @thresholds
842 my @curr_totals = ();
843 foreach my $e (@thresholds) {
844 push(@curr_totals, 0);
845 }
846
847 # Print functions, stopping when the threshold has been reached.
848 foreach my $fn_name (@fn_fullnames) {
849
850 # Stop when we've reached all the thresholds
851 my $reached_all_thresholds = 1;
852 foreach my $i (0 .. scalar @thresholds - 1) {
853 my $prop = $curr_totals[$i] * 100;
854 if ($summary_CC->[$sort_order[$i]] >0) {
855 $prop = $prop / $summary_CC->[$sort_order[$i]];
856 }
857 $reached_all_thresholds &= ($prop >= $thresholds[$i]);
858 }
859 last if $reached_all_thresholds;
860
861 if ($tree_caller || $tree_calling) { print "\n"; }
862
863 if ($tree_caller && ($fn_name ne "???:???")) {
864 # Print function callers
865 my $tmp1 = $calling_funcs->{$fn_name};
866 if (defined $tmp1) {
867 foreach my $calling (keys %$tmp1) {
868 if (defined $call_counter{$calling,$fn_name}) {
869 print_CC($call_CCs{$calling,$fn_name}, $fn_CC_col_widths);
870 print" < $calling (";
871 print $call_counter{$calling,$fn_name} . "x)";
872 if (defined $obj_name{$calling}) {
873 print " [$obj_name{$calling}]";
874 }
875 print "\n";
876 }
877 }
878 }
879 }
880
881 # Print function results
882 my $fn_CC = $fn_totals{$fn_name};
883 print_CC($fn_CC, $fn_CC_col_widths);
884 if ($tree_caller || $tree_calling) { print " * "; }
885 print(" $fn_name");
886 if (defined $obj_name{$fn_name}) {
887 print " [$obj_name{$fn_name}]";
888 }
889 print "\n";
890
891 if ($tree_calling && ($fn_name ne "???:???")) {
892 # Print called functions
893 my $tmp2 = $called_funcs->{$fn_name};
894 if (defined $tmp2) {
895 foreach my $called (keys %$tmp2) {
896 if (defined $call_counter{$fn_name,$called}) {
897 print_CC($call_CCs{$fn_name,$called}, $fn_CC_col_widths);
898 print" > $called (";
899 print $call_counter{$fn_name,$called} . "x)";
900 if (defined $obj_name{$called}) {
901 print " [$obj_name{$called}]";
902 }
903 print "\n";
904 }
905 }
906 }
907 }
908
909 # Update the threshold counts
910 my $filename = $fn_name;
911 $filename =~ s/:.+$//; # remove function name
912 $threshold_files->{$filename} = 1;
913 foreach my $i (0 .. scalar @sort_order - 1) {
914 if ($inclusive) {
915 $curr_totals[$i] = $summary_CC->[$sort_order[$i]] -
916 $fn_CC->[$sort_order[$i]]
917 if (defined $fn_CC->[$sort_order[$i]]);
918 } else {
919 $curr_totals[$i] += $fn_CC->[$sort_order[$i]]
920 if (defined $fn_CC->[$sort_order[$i]]);
921 }
922 }
923 }
924 print("\n");
925
926 return $threshold_files;
927}
928
929#-----------------------------------------------------------------------------
930# Annotate selected files
931#-----------------------------------------------------------------------------
932
933# Issue a warning that the source file is more recent than the input file.
934sub warning_on_src_more_recent_than_inputfile ($)
935{
936 my $src_file = $_[0];
937
938 my $warning = <<END
939@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
940@@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
941@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
942@ Source file '$src_file' is more recent than input file '$input_file'.
943@ Annotations may not be correct.
944@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
945
946END
947;
948 print($warning);
949}
950
951# If there is information about lines not in the file, issue a warning
952# explaining possible causes.
953sub warning_on_nonexistent_lines ($$$)
954{
955 my ($src_more_recent_than_inputfile, $src_file, $excess_line_nums) = @_;
956 my $cause_and_solution;
957
958 if ($src_more_recent_than_inputfile) {
959 $cause_and_solution = <<END
960@@ cause: '$src_file' has changed since information was gathered.
961@@ If so, a warning will have already been issued about this.
962@@ solution: Recompile program and rerun under "valgrind --cachesim=yes" to
963@@ gather new information.
964END
965 # We suppress warnings about .h files
966 } elsif ($src_file =~ /\.h$/) {
967 $cause_and_solution = <<END
968@@ cause: bug in the Valgrind's debug info reader that screws up with .h
969@@ files sometimes
970@@ solution: none, sorry
971END
972 } else {
973 $cause_and_solution = <<END
974@@ cause: not sure, sorry
975END
976 }
977
978 my $warning = <<END
979@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
980@@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@ WARNING @@
981@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
982@@
983@@ Information recorded about lines past the end of '$src_file'.
984@@
985@@ Probable cause and solution:
986$cause_and_solution@@
987@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
988END
989;
990 print($warning);
991}
992
993sub annotate_ann_files($)
994{
995 my ($threshold_files) = @_;
996
997 my %all_ann_files;
998 my @unfound_auto_annotate_files;
999 my $printed_totals_CC = [];
1000
1001 # If auto-annotating, add interesting files (but not "???")
1002 if ($auto_annotate) {
1003 delete $threshold_files->{"???"};
1004 %all_ann_files = (%user_ann_files, %$threshold_files)
1005 } else {
1006 %all_ann_files = %user_ann_files;
1007 }
1008
1009 # Track if we did any annotations.
1010 my $did_annotations = 0;
1011
1012 LOOP:
1013 foreach my $src_file (keys %all_ann_files) {
1014
1015 my $opened_file = "";
1016 my $full_file_name = "";
1017 foreach my $include_dir (@include_dirs) {
1018 my $try_name = $include_dir . $src_file;
1019 if (open(INPUTFILE, "< $try_name")) {
1020 $opened_file = $try_name;
1021 $full_file_name = ($include_dir eq ""
1022 ? $src_file
1023 : "$include_dir + $src_file");
1024 last;
1025 }
1026 }
1027
1028 if (not $opened_file) {
1029 # Failed to open the file. If chosen on the command line, die.
1030 # If arose from auto-annotation, print a little message.
1031 if (defined $user_ann_files{$src_file}) {
1032 die("File $src_file not opened in any of: @include_dirs\n");
1033
1034 } else {
1035 push(@unfound_auto_annotate_files, $src_file);
1036 }
1037
1038 } else {
1039 # File header (distinguish between user- and auto-selected files).
1040 print("$fancy");
1041 my $ann_type =
1042 (defined $user_ann_files{$src_file} ? "User" : "Auto");
1043 print("-- $ann_type-annotated source: $full_file_name\n");
1044 print("$fancy");
1045
1046 # Get file's CCs
1047 my $src_file_CCs = $all_ind_CCs{$src_file};
1048 if (!defined $src_file_CCs) {
1049 print(" No information has been collected for $src_file\n\n");
1050 next LOOP;
1051 }
1052
1053 $did_annotations = 1;
1054
1055 # Numeric, not lexicographic sort!
1056 my @line_nums = sort {$a <=> $b} keys %$src_file_CCs;
1057
1058 # If $src_file more recent than cachegrind.out, issue warning
1059 my $src_more_recent_than_inputfile = 0;
1060 if ((stat $opened_file)[9] > (stat $input_file)[9]) {
1061 $src_more_recent_than_inputfile = 1;
1062 warning_on_src_more_recent_than_inputfile($src_file);
1063 }
1064
1065 # Work out the size of each column for printing
1066 my $CC_col_widths = compute_CC_col_widths(values %$src_file_CCs);
1067
1068 # Events header
1069 print_events($CC_col_widths);
1070 print("\n\n");
1071
1072 # Shift out 0 if it's in the line numbers (from unknown entries,
1073 # likely due to bugs in Valgrind's stabs debug info reader)
1074 shift(@line_nums) if (0 == $line_nums[0]);
1075
1076 # Finds interesting line ranges -- all lines with a CC, and all
1077 # lines within $context lines of a line with a CC.
1078 my $n = @line_nums;
1079 my @pairs;
1080 for (my $i = 0; $i < $n; $i++) {
1081 push(@pairs, $line_nums[$i] - $context); # lower marker
1082 while ($i < $n-1 &&
1083 $line_nums[$i] + 2*$context >= $line_nums[$i+1]) {
1084 $i++;
1085 }
1086 push(@pairs, $line_nums[$i] + $context); # upper marker
1087 }
1088
1089 # Annotate chosen lines, tracking total counts of lines printed
1090 $pairs[0] = 1 if ($pairs[0] < 1);
1091 while (@pairs) {
1092 my $low = shift @pairs;
1093 my $high = shift @pairs;
1094 while ($. < $low-1) {
1095 my $tmp = <INPUTFILE>;
1096 last unless (defined $tmp); # hack to detect EOF
1097 }
1098 my $src_line;
1099 # Print line number, unless start of file
1100 print("-- line $low " . '-' x 40 . "\n") if ($low != 1);
1101 while (($. < $high) && ($src_line = <INPUTFILE>)) {
1102 if (defined $line_nums[0] && $. == $line_nums[0]) {
1103 print_CC($src_file_CCs->{$.}, $CC_col_widths);
1104 add_array_a_to_b($src_file_CCs->{$.},
1105 $printed_totals_CC);
1106 shift(@line_nums);
1107
1108 } else {
1109 print_CC( [], $CC_col_widths);
1110 }
1111
1112 print(" $src_line");
1113
1114 my $tmp = $called_from_line->{$src_file,$.};
1115 my $func = $func_of_line{$src_file,$.};
1116 if (defined $tmp) {
1117 foreach my $called (keys %$tmp) {
1118 if (defined $call_CCs{$func,$called,$.}) {
1119 print_CC($call_CCs{$func,$called,$.}, $CC_col_widths);
1120 print " => $called (";
1121 print $call_counter{$func,$called,$.} . "x)\n";
1122 }
1123 }
1124 }
1125 }
1126 # Print line number, unless EOF
1127 if ($src_line) {
1128 print("-- line $high " . '-' x 40 . "\n");
1129 } else {
1130 last;
1131 }
1132 }
1133
1134 # If there was info on lines past the end of the file...
1135 if (@line_nums) {
1136 foreach my $line_num (@line_nums) {
1137 print_CC($src_file_CCs->{$line_num}, $CC_col_widths);
1138 print(" <bogus line $line_num>\n");
1139 }
1140 print("\n");
1141 warning_on_nonexistent_lines($src_more_recent_than_inputfile,
1142 $src_file, \@line_nums);
1143 }
1144 print("\n");
1145
1146 # Print summary of counts attributed to file but not to any
1147 # particular line (due to incomplete debug info).
1148 if ($src_file_CCs->{0}) {
1149 print_CC($src_file_CCs->{0}, $CC_col_widths);
1150 print(" <counts for unidentified lines in $src_file>\n\n");
1151 }
1152
1153 close(INPUTFILE);
1154 }
1155 }
1156
1157 # Print list of unfound auto-annotate selected files.
1158 if (@unfound_auto_annotate_files) {
1159 print("$fancy");
1160 print("The following files chosen for auto-annotation could not be found:\n");
1161 print($fancy);
1162 foreach my $f (@unfound_auto_annotate_files) {
1163 print(" $f\n");
1164 }
1165 print("\n");
1166 }
1167
1168 # If we did any annotating, print what proportion of events were covered by
1169 # annotated lines above.
1170 if ($did_annotations) {
1171 my $percent_printed_CC;
1172 foreach (my $i = 0; $i < @$summary_CC; $i++) {
1173 $percent_printed_CC->[$i] =
1174 sprintf("%.0f",
1175 $printed_totals_CC->[$i] / $summary_CC->[$i] * 100);
1176 }
1177 my $pp_CC_col_widths = compute_CC_col_widths($percent_printed_CC);
1178 print($fancy);
1179 print_events($pp_CC_col_widths);
1180 print("\n");
1181 print($fancy);
1182 print_CC($percent_printed_CC, $pp_CC_col_widths);
1183 print(" percentage of events annotated\n\n");
1184 }
1185}
1186
1187#----------------------------------------------------------------------------
1188# "main()"
1189#----------------------------------------------------------------------------
1190process_cmd_line();
1191read_input_file();
1192print_options();
1193my $threshold_files = print_summary_and_fn_totals();
1194annotate_ann_files($threshold_files);
1195
1196##--------------------------------------------------------------------##
1197##--- end vg_annotate.in ---##
1198##--------------------------------------------------------------------##
1199
1200