blib/script/flamegraph.pl untested

filter: Statementstmt 0.0% 0 / 383 Branchbran 0.0% 0 / 148 Conditioncond 0.0% 0 / 76 MC/DCmcdc 0.0% 0 / 48 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 17 totaltotal 0.0% 0 / 691 CC 42 SCAR 50.4
CC
42
Cov
0%
color
420.0
group_start
56.0
flow
42.0
CRAP 154.1
1 #!/usr/local/bin/perl -w
2 #
3 # flamegraph.pl flame stack grapher.
4 #
5 # This takes stack samples and renders a call graph, allowing hot functions
6 # and codepaths to be quickly identified. Stack samples can be generated using
7 # tools such as DTrace, perf, SystemTap, and Instruments.
8 #
9 # USAGE: ./flamegraph.pl [options] input.txt > graph.svg
10 #
11 # grep funcA input.txt | ./flamegraph.pl [options] > graph.svg
12 #
13 # Options are listed in the usage message (--help).
14 #
15 # The input is stack frames and sample counts formatted as single lines. Each
16 # frame in the stack is semicolon separated, with a space and count at the end
17 # of the line. These can be generated using DTrace with stackcollapse.pl,
18 # and other tools using the stackcollapse variants.
19 #
20 # An optional extra column of counts can be provided to generate a differential
21 # flame graph of the counts, colored red for more, and blue for less. This
22 # can be useful when using flame graphs for non-regression testing.
23 # See the header comment in the difffolded.pl program for instructions.
24 #
25 # The output graph shows relative presence of functions in stack samples. The
26 # ordering on the x-axis has no meaning; since the data is samples, time order
27 # of events is not known. The order used sorts function names alphabetically.
28 #
29 # While intended to process stack samples, this can also process stack traces.
30 # For example, tracing stacks for memory allocation, or resource usage. You
31 # can use --title to set the title to reflect the content, and --countname
32 # to change "samples" to "bytes" etc.
33 #
34 # There are a few different palettes, selectable using --color. By default,
35 # the colors are selected at random (except for differentials). Functions
36 # called "-" will be printed gray, which can be used for stack separators (eg,
37 # between user and kernel stacks).
38 #
39 # HISTORY
40 #
41 # This was inspired by Neelakanth Nadgir's excellent function_call_graph.rb
42 # program, which visualized function entry and return trace events. As Neel
43 # wrote: "The output displayed is inspired by Roch's CallStackAnalyzer which
44 # was in turn inspired by the work on vftrace by Jan Boerhout". See:
45 # https://blogs.oracle.com/realneel/entry/visualizing_callstacks_via_dtrace_and
46 #
47 # Copyright 2011 Joyent, Inc. All rights reserved.
48 # Copyright 2011 Brendan Gregg. All rights reserved.
49 #
50 # CDDL HEADER START
51 #
52 # The contents of this file are subject to the terms of the
53 # Common Development and Distribution License (the "License").
54 # You may not use this file except in compliance with the License.
55 #
56 # You can obtain a copy of the license at docs/cddl1.txt or
57 # http://opensource.org/licenses/CDDL-1.0.
58 # See the License for the specific language governing permissions
59 # and limitations under the License.
60 #
61 # When distributing Covered Code, include this CDDL HEADER in each
62 # file and include the License file at docs/cddl1.txt.
63 # If applicable, add the following below this CDDL HEADER, with the
64 # fields enclosed by brackets "[]" replaced with your own identifying
65 # information: Portions Copyright [yyyy] [name of copyright owner]
66 #
67 # CDDL HEADER END
68 #
69 # 11-Oct-2014 Adrien Mahieux Added zoom.
70 # 21-Nov-2013 Shawn Sterling Added consistent palette file option
71 # 17-Mar-2013 Tim Bunce Added options and more tunables.
72 # 15-Dec-2011 Dave Pacheco Support for frames with whitespace.
73 # 10-Sep-2011 Brendan Gregg Created this.
74  
75 use strict;
76  
77 use Getopt::Long;
78  
79 # tunables
80 my $encoding;
81 my $fonttype = "Verdana";
82 my $imagewidth = 1200; # max width, pixels
83 my $frameheight = 16; # max height is dynamic
84 my $fontsize = 12; # base text size
85 my $fontwidth = 0.59; # avg width relative to fontsize
86 my $minwidth = 0.1; # min function width, pixels
87 my $nametype = "Function:"; # what are the names in the data?
88 my $countname = "samples"; # what are the counts in the data?
89 my $colors = "hot"; # color theme
90 my $bgcolor1 = "#eeeeee"; # background color gradient start
91 my $bgcolor2 = "#eeeeb0"; # background color gradient stop
92 my $nameattrfile; # file holding function attributes
93 my $timemax; # (override the) sum of the counts
94 my $factor = 1; # factor to scale counts by
95 my $hash = 0; # color by function name
96 my $palette = 0; # if we use consistent palettes (default off)
97 my %palette_map; # palette map hash
98 my $pal_file = "palette.map"; # palette map file name
99 my $stackreverse = 0; # reverse stack order, switching merge end
100 my $inverted = 0; # icicle graph
101 my $negate = 0; # switch differential hues
102 my $titletext = ""; # centered heading
103 my $titledefault = "Flame Graph"; # overwritten by --title
104 my $titleinverted = "Icicle Graph"; # " "
105 my $searchcolor = "rgb(230,0,230)"; # color for search highlighting
106 my $help = 0;
107  
108 sub usage {
109 die <<USAGE_END;
110 USAGE: $0 [options] infile > outfile.svg\n
111 --title # change title text
112 --width # width of image (default 1200)
113 --height # height of each frame (default 16)
114 --minwidth # omit smaller functions (default 0.1 pixels)
115 --fonttype # font type (default "Verdana")
116 --fontsize # font size (default 12)
117 --countname # count type label (default "samples")
118 --nametype # name type label (default "Function:")
119 --colors # set color palette. choices are: hot (default), mem, io,
120 # java, js, red, green, blue, yellow, purple, orange
121 --hash # colors are keyed by function name hash
122 --cp # use consistent palette (palette.map)
123 --reverse # generate stack-reversed flame graph
124 --inverted # icicle graph
125 --negate # switch differential hues (blue<->red)
126 --help # this message
127  
128 eg,
129 $0 --title="Flame Graph: malloc()" trace.txt > graph.svg
130 USAGE_END
131 }
132  
133 GetOptions(
134 'fonttype=s' => \$fonttype,
135 'width=i' => \$imagewidth,
136 'height=i' => \$frameheight,
137 'encoding=s' => \$encoding,
138 'fontsize=f' => \$fontsize,
139 'fontwidth=f' => \$fontwidth,
140 'minwidth=f' => \$minwidth,
141 'title=s' => \$titletext,
142 'nametype=s' => \$nametype,
143 'countname=s' => \$countname,
144 'nameattr=s' => \$nameattrfile,
145 'total=s' => \$timemax,
146 'factor=f' => \$factor,
147 'colors=s' => \$colors,
148 'hash' => \$hash,
149 'cp' => \$palette,
150 'reverse' => \$stackreverse,
151 'inverted' => \$inverted,
152 'negate' => \$negate,
153 'help' => \$help,
154 ) or usage();
155 $help && usage();
156  
157 # internals
158 my $ypad1 = $fontsize * 4; # pad top, include title
159 my $ypad2 = $fontsize * 2 + 10; # pad bottom, include labels
160 my $xpad = 10; # pad lefm and right
161 my $framepad = 1; # vertical padding for frames
162 my $depthmax = 0;
163 my %Events;
164 my %nameattr;
165  
166 if ($titletext eq "") {
167 unless ($inverted) {
168 $titletext = $titledefault;
169 } else {
170 $titletext = $titleinverted;
171 }
172 }
173  
174 if ($nameattrfile) {
175 # The name-attribute file format is a function name followed by a tab then
176 # a sequence of tab separated name=value pairs.
177 open my $attrfh, $nameattrfile or die "Can't read $nameattrfile: $!\n";
178 while (<$attrfh>) {
179 chomp;
180 my ($funcname, $attrstr) = split /\t/, $_, 2;
181 die "Invalid format in $nameattrfile" unless defined $attrstr;
182 $nameattr{$funcname} = { map { split /=/, $_, 2 } split /\t/, $attrstr };
183 }
184 }
185  
186 if ($colors eq "mem") { $bgcolor1 = "#eeeeee"; $bgcolor2 = "#e0e0ff"; }
187 if ($colors eq "io") { $bgcolor1 = "#f8f8f8"; $bgcolor2 = "#e8e8e8"; }
188  
189 # SVG functions
190 { package SVG;
191 sub new {
192 my $class = shift;
193 my $self = {};
194 bless ($self, $class);
195 return $self;
196 }
197  
198 sub header {
199 my ($self, $w, $h) = @_;
200 my $enc_attr = '';
201 if (defined $encoding) {
202 $enc_attr = qq{ encoding="$encoding"};
203 }
204 $self->{svg} .= <<SVG;
205 <?xml version="1.0"$enc_attr standalone="no"?>
206 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
207 <svg version="1.1" width="$w" height="$h" onload="init(evt)" viewBox="0 0 $w $h" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
208 <!-- Flame graph stack visualization. See https://github.com/brendangregg/FlameGraph for latest version, and http://www.brendangregg.com/flamegraphs.html for examples. -->
209 SVG
210 }
211  
212 sub include {
213 my ($self, $content) = @_;
214 $self->{svg} .= $content;
215 }
216  
217 sub colorAllocate {
218 my ($self, $r, $g, $b) = @_;
219 return "rgb($r,$g,$b)";
220 }
221  
222 sub group_start {
223 my ($self, $attr) = @_;
224  
225 my @g_attr = map {
226 exists $attr->{$_} ? sprintf(qq/$_="%s"/, $attr->{$_}) : ()
227 } qw(class style onmouseover onmouseout onclick);
228 push @g_attr, $attr->{g_extra} if $attr->{g_extra};
229 $self->{svg} .= sprintf qq/<g %s>\n/, join(' ', @g_attr);
230  
231 $self->{svg} .= sprintf qq/<title>%s<\/title>/, $attr->{title}
232 if $attr->{title}; # should be first element within g container
233  
234 if ($attr->{href}) {
235 my @a_attr;
236 push @a_attr, sprintf qq/xlink:href="%s"/, $attr->{href} if $attr->{href};
237 # default target=_top else links will open within SVG <object>
238 push @a_attr, sprintf qq/target="%s"/, $attr->{target} || "_top";
239 push @a_attr, $attr->{a_extra} if $attr->{a_extra};
240 $self->{svg} .= sprintf qq/<a %s>/, join(' ', @a_attr);
241 }
242 }
243  
244 sub group_end {
245 my ($self, $attr) = @_;
246 $self->{svg} .= qq/<\/a>\n/ if $attr->{href};
247 $self->{svg} .= qq/<\/g>\n/;
248 }
249  
250 sub filledRectangle {
251 my ($self, $x1, $y1, $x2, $y2, $fill, $extra) = @_;
252 $x1 = sprintf "%0.1f", $x1;
253 $x2 = sprintf "%0.1f", $x2;
254 my $w = sprintf "%0.1f", $x2 - $x1;
255 my $h = sprintf "%0.1f", $y2 - $y1;
256 $extra = defined $extra ? $extra : "";
257 $self->{svg} .= qq/<rect x="$x1" y="$y1" width="$w" height="$h" fill="$fill" $extra \/>\n/;
258 }
259  
260 sub stringTTF {
261 my ($self, $color, $font, $size, $angle, $x, $y, $str, $loc, $extra) = @_;
262 $x = sprintf "%0.2f", $x;
263 $loc = defined $loc ? $loc : "left";
264 $extra = defined $extra ? $extra : "";
265 $self->{svg} .= qq/<text text-anchor="$loc" x="$x" y="$y" font-size="$size" font-family="$font" fill="$color" $extra >$str<\/text>\n/;
266 }
267  
268 sub svg {
269 my $self = shift;
270 return "$self->{svg}</svg>\n";
271 }
272 1;
273 }
274  
275 sub namehash {
276 # Generate a vector hash for the name string, weighting early over
277 # later characters. We want to pick the same colors for function
278 # names across different flame graphs.
279 my $name = shift;
280 my $vector = 0;
281 my $weight = 1;
282 my $max = 1;
283 my $mod = 10;
284 # if module name present, trunc to 1st char
285 $name =~ s/.(.*?)`//;
286 foreach my $c (split //, $name) {
287 my $i = (ord $c) % $mod;
288 $vector += ($i / ($mod++ - 1)) * $weight;
289 $max += 1 * $weight;
290 $weight *= 0.70;
291 last if $mod > 12;
292 }
293 return (1 - $vector / $max)
294 }
295  
296 sub color {
297 my ($type, $hash, $name) = @_;
298 my ($v1, $v2, $v3);
299  
300 if ($hash) {
301 $v1 = namehash($name);
302 $v2 = $v3 = namehash(scalar reverse $name);
303 } else {
304 $v1 = rand(1);
305 $v2 = rand(1);
306 $v3 = rand(1);
307 }
308  
309 # theme palettes
310 if (defined $type and $type eq "hot") {
311 my $r = 205 + int(50 * $v3);
312 my $g = 0 + int(230 * $v1);
313 my $b = 0 + int(55 * $v2);
314 return "rgb($r,$g,$b)";
315 }
316 if (defined $type and $type eq "mem") {
317 my $r = 0;
318 my $g = 190 + int(50 * $v2);
319 my $b = 0 + int(210 * $v1);
320 return "rgb($r,$g,$b)";
321 }
322 if (defined $type and $type eq "io") {
323 my $r = 80 + int(60 * $v1);
324 my $g = $r;
325 my $b = 190 + int(55 * $v2);
326 return "rgb($r,$g,$b)";
327 }
328  
329 # multi palettes
330 if (defined $type and $type eq "java") {
331 if ($name =~ /::/) { # C++
332 $type = "yellow";
333 } elsif ($name =~ m:/:) { # Java (match "/" in path)
334 $type = "green"
335 } else { # system
336 $type = "red";
337 }
338 # fall-through to color palettes
339 }
340 if (defined $type and $type eq "js") {
341 if ($name =~ /::/) { # C++
342 $type = "yellow";
343 } elsif ($name =~ m:/:) { # JavaScript (match "/" in path)
344 $type = "green"
345 } elsif ($name =~ m/:/) { # JavaScript (match ":" in builtin)
346 $type = "aqua"
347 } elsif ($name =~ m/^ $/) { # Missing symbol
348 $type = "green"
349 } else { # system
350 $type = "red";
351 }
352 # fall-through to color palettes
353 }
354  
355 # color palettes
356 if (defined $type and $type eq "red") {
357 my $r = 200 + int(55 * $v1);
358 my $x = 50 + int(80 * $v1);
359 return "rgb($r,$x,$x)";
360 }
361 if (defined $type and $type eq "green") {
362 my $g = 200 + int(55 * $v1);
363 my $x = 50 + int(60 * $v1);
364 return "rgb($x,$g,$x)";
365 }
366 if (defined $type and $type eq "blue") {
367 my $b = 205 + int(50 * $v1);
368 my $x = 80 + int(60 * $v1);
369 return "rgb($x,$x,$b)";
370 }
371 if (defined $type and $type eq "yellow") {
372 my $x = 175 + int(55 * $v1);
373 my $b = 50 + int(20 * $v1);
374 return "rgb($x,$x,$b)";
375 }
376 if (defined $type and $type eq "purple") {
377 my $x = 190 + int(65 * $v1);
378 my $g = 80 + int(60 * $v1);
379 return "rgb($x,$g,$x)";
380 }
381 if (defined $type and $type eq "aqua") {
382 my $r = 50 + int(60 * $v1);
383 my $g = 165 + int(55 * $v1);
384 my $b = 165 + int(55 * $v1);
385 return "rgb($r,$g,$b)";
386 }
387 if (defined $type and $type eq "orange") {
388 my $r = 190 + int(65 * $v1);
389 my $g = 90 + int(65 * $v1);
390 return "rgb($r,$g,0)";
391 }
392  
393 return "rgb(0,0,0)";
394 }
395  
396 sub color_scale {
397 my ($value, $max) = @_;
398 my ($r, $g, $b) = (255, 255, 255);
399 $value = -$value if $negate;
400 if ($value > 0) {
401 $g = $b = int(210 * ($max - $value) / $max);
402 } elsif ($value < 0) {
403 $r = $g = int(210 * ($max + $value) / $max);
404 }
405 return "rgb($r,$g,$b)";
406 }
407  
408 sub color_map {
409 my ($colors, $func) = @_;
410 if (exists $palette_map{$func}) {
411 return $palette_map{$func};
412 } else {
413 $palette_map{$func} = color($colors);
414 return $palette_map{$func};
415 }
416 }
417  
418 sub write_palette {
419 open(FILE, ">$pal_file");
420 foreach my $key (sort keys %palette_map) {
421 print FILE $key."->".$palette_map{$key}."\n";
422 }
423 close(FILE);
424 }
425  
426 sub read_palette {
427 if (-e $pal_file) {
428 open(FILE, $pal_file) or die "can't open file $pal_file: $!";
429 while ( my $line = <FILE>) {
430 chomp($line);
431 (my $key, my $value) = split("->",$line);
432 $palette_map{$key}=$value;
433 }
434 close(FILE)
435 }
436 }
437  
438 my %Node; # Hash of merged frame data
439 my %Tmp;
440  
441 # flow() merges two stacks, storing the merged frames and value data in %Node.
442 sub flow {
443 my ($last, $this, $v, $d) = @_;
444  
445 my $len_a = @$last - 1;
446 my $len_b = @$this - 1;
447  
448 my $i = 0;
449 my $len_same;
450 for (; $i <= $len_a; $i++) {
451 last if $i > $len_b;
452 last if $last->[$i] ne $this->[$i];
453 }
454 $len_same = $i;
455  
456 for ($i = $len_a; $i >= $len_same; $i--) {
457 my $k = "$last->[$i];$i";
458 # a unique ID is constructed from "func;depth;etime";
459 # func-depth isn't unique, it may be repeated later.
460 $Node{"$k;$v"}->{stime} = delete $Tmp{$k}->{stime};
461 if (defined $Tmp{$k}->{delta}) {
462 $Node{"$k;$v"}->{delta} = delete $Tmp{$k}->{delta};
463 }
464 delete $Tmp{$k};
465 }
466  
467 for ($i = $len_same; $i <= $len_b; $i++) {
468 my $k = "$this->[$i];$i";
469 $Tmp{$k}->{stime} = $v;
470 if (defined $d) {
471 $Tmp{$k}->{delta} += $i == $len_b ? $d : 0;
472 }
473 }
474  
475 return $this;
476 }
477  
478 # parse input
479 my @Data;
480 my $last = [];
481 my $time = 0;
482 my $delta = undef;
483 my $ignored = 0;
484 my $line;
485 my $maxdelta = 1;
486  
487 # reverse if needed
488 foreach (<>) {
489 chomp;
490 $line = $_;
491 if ($stackreverse) {
492 # there may be an extra samples column for differentials
493 # XXX todo: redo these REs as one. It's repeated below.
494 my ($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
495 my $samples2 = undef;
496 if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
497 $samples2 = $samples;
498 ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
499 unshift @Data, join(";", reverse split(";", $stack)) . " $samples $samples2";
500 } else {
501 unshift @Data, join(";", reverse split(";", $stack)) . " $samples";
502 }
503 } else {
504 unshift @Data, $line;
505 }
506 }
507  
508 # process and merge frames
509 foreach (sort @Data) {
510 chomp;
511 # process: folded_stack count
512 # eg: func_a;func_b;func_c 31
513 my ($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
514 unless (defined $samples and defined $stack) {
515 ++$ignored;
516 next;
517 }
518  
519 # there may be an extra samples column for differentials:
520 my $samples2 = undef;
521 if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
522 $samples2 = $samples;
523 ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
524 }
525 $delta = undef;
526 if (defined $samples2) {
527 $delta = $samples2 - $samples;
528 $maxdelta = abs($delta) if abs($delta) > $maxdelta;
529 }
530  
531 $stack =~ tr/<>/()/;
532  
533 # merge frames and populate %Node:
534 $last = flow($last, [ '', split ";", $stack ], $time, $delta);
535  
536 if (defined $samples2) {
537 $time += $samples2;
538 } else {
539 $time += $samples;
540 }
541 }
542 flow($last, [], $time, $delta);
543  
544 warn "Ignored $ignored lines with invalid format\n" if $ignored;
545 unless ($time) {
546 warn "ERROR: No stack counts found\n";
547 my $im = SVG->new();
548 # emit an error message SVG, for tools automating flamegraph use
549 my $imageheight = $fontsize * 5;
550 $im->header($imagewidth, $imageheight);
551 $im->stringTTF($im->colorAllocate(0, 0, 0), $fonttype, $fontsize + 2,
552 0.0, int($imagewidth / 2), $fontsize * 2,
553 "ERROR: No valid input provided to flamegraph.pl.", "middle");
554 print $im->svg;
555 exit 2;
556 }
557 if ($timemax and $timemax < $time) {
558 warn "Specified --total $timemax is less than actual total $time, so ignored\n"
559 if $timemax/$time > 0.02; # only warn is significant (e.g., not rounding etc)
560 undef $timemax;
561 }
562 $timemax ||= $time;
563  
564 my $widthpertime = ($imagewidth - 2 * $xpad) / $timemax;
565 my $minwidth_time = $minwidth / $widthpertime;
566  
567 # prune blocks that are too narrow and determine max depth
568 while (my ($id, $node) = each %Node) {
569 my ($func, $depth, $etime) = split ";", $id;
570 my $stime = $node->{stime};
571 die "missing start for $id" if not defined $stime;
572  
573 if (($etime-$stime) < $minwidth_time) {
574 delete $Node{$id};
575 next;
576 }
577 $depthmax = $depth if $depth > $depthmax;
578 }
579  
580 # draw canvas, and embed interactive JavaScript program
581 my $imageheight = ($depthmax * $frameheight) + $ypad1 + $ypad2;
582 my $im = SVG->new();
583 $im->header($imagewidth, $imageheight);
584 my $inc = <<INC;
585 <defs >
586 <linearGradient id="background" y1="0" y2="1" x1="0" x2="0" >
587 <stop stop-color="$bgcolor1" offset="5%" />
588 <stop stop-color="$bgcolor2" offset="95%" />
589 </linearGradient>
590 </defs>
591 <style type="text/css">
592 .func_g:hover { stroke:black; stroke-width:0.5; cursor:pointer; }
593 </style>
594 <script type="text/ecmascript">
595 <![CDATA[
596 var details, svg;
597 function init(evt) {
598 details = document.getElementById("details").firstChild;
599 svg = document.getElementsByTagName("svg")[0];
600 searching = 0;
601 }
602  
603 // mouse-over for info
604 function s(info) { details.nodeValue = "$nametype " + info; }
605 function c() { details.nodeValue = ' '; }
606  
607 // functions
608 function find_child(parent, name, attr) {
609 var children = parent.childNodes;
610 for (var i=0; i<children.length;i++) {
611 if (children[i].tagName == name)
612 return (attr != undefined) ? children[i].attributes[attr].value : children[i];
613 }
614 return;
615 }
616 function orig_save(e, attr, val) {
617 if (e.attributes["_orig_"+attr] != undefined) return;
618 if (e.attributes[attr] == undefined) return;
619 if (val == undefined) val = e.attributes[attr].value;
620 e.setAttribute("_orig_"+attr, val);
621 }
622 function orig_load(e, attr) {
623 if (e.attributes["_orig_"+attr] == undefined) return;
624 e.attributes[attr].value = e.attributes["_orig_"+attr].value;
625 e.removeAttribute("_orig_"+attr);
626 }
627 function update_text(e) {
628 var r = find_child(e, "rect");
629 var t = find_child(e, "text");
630 var w = parseFloat(r.attributes["width"].value) -3;
631 var txt = find_child(e, "title").textContent.replace(/\\([^(]*\\)/,"");
632 t.attributes["x"].value = parseFloat(r.attributes["x"].value) +3;
633
634 // Smaller than this size won't fit anything
635 if (w < 2*$fontsize*$fontwidth) {
636 t.textContent = "";
637 return;
638 }
639
640 t.textContent = txt;
641 // Fit in full text width
642 if (/^ *\$/.test(txt) || t.getSubStringLength(0, txt.length) < w)
643 return;
644
645 for (var x=txt.length-2; x>0; x--) {
646 if (t.getSubStringLength(0, x+2) <= w) {
647 t.textContent = txt.substring(0,x) + "..";
648 return;
649 }
650 }
651 t.textContent = "";
652 }
653  
654 // zoom
655 function zoom_reset(e) {
656 if (e.attributes != undefined) {
657 orig_load(e, "x");
658 orig_load(e, "width");
659 }
660 if (e.childNodes == undefined) return;
661 for(var i=0, c=e.childNodes; i<c.length; i++) {
662 zoom_reset(c[i]);
663 }
664 }
665 function zoom_child(e, x, ratio) {
666 if (e.attributes != undefined) {
667 if (e.attributes["x"] != undefined) {
668 orig_save(e, "x");
669 e.attributes["x"].value = (parseFloat(e.attributes["x"].value) - x - $xpad) * ratio + $xpad;
670 if(e.tagName == "text") e.attributes["x"].value = find_child(e.parentNode, "rect", "x") + 3;
671 }
672 if (e.attributes["width"] != undefined) {
673 orig_save(e, "width");
674 e.attributes["width"].value = parseFloat(e.attributes["width"].value) * ratio;
675 }
676 }
677
678 if (e.childNodes == undefined) return;
679 for(var i=0, c=e.childNodes; i<c.length; i++) {
680 zoom_child(c[i], x-$xpad, ratio);
681 }
682 }
683 function zoom_parent(e) {
684 if (e.attributes) {
685 if (e.attributes["x"] != undefined) {
686 orig_save(e, "x");
687 e.attributes["x"].value = $xpad;
688 }
689 if (e.attributes["width"] != undefined) {
690 orig_save(e, "width");
691 e.attributes["width"].value = parseInt(svg.width.baseVal.value) - ($xpad*2);
692 }
693 }
694 if (e.childNodes == undefined) return;
695 for(var i=0, c=e.childNodes; i<c.length; i++) {
696 zoom_parent(c[i]);
697 }
698 }
699 function zoom(node) {
700 var attr = find_child(node, "rect").attributes;
701 var width = parseFloat(attr["width"].value);
702 var xmin = parseFloat(attr["x"].value);
703 var xmax = parseFloat(xmin + width);
704 var ymin = parseFloat(attr["y"].value);
705 var ratio = (svg.width.baseVal.value - 2*$xpad) / width;
706
707 // XXX: Workaround for JavaScript float issues (fix me)
708 var fudge = 0.0001;
709
710 var unzoombtn = document.getElementById("unzoom");
711 unzoombtn.style["opacity"] = "1.0";
712
713 var el = document.getElementsByTagName("g");
714 for(var i=0;i<el.length;i++){
715 var e = el[i];
716 var a = find_child(e, "rect").attributes;
717 var ex = parseFloat(a["x"].value);
718 var ew = parseFloat(a["width"].value);
719 // Is it an ancestor
720 if ($inverted == 0) {
721 var upstack = parseFloat(a["y"].value) > ymin;
722 } else {
723 var upstack = parseFloat(a["y"].value) < ymin;
724 }
725 if (upstack) {
726 // Direct ancestor
727 if (ex <= xmin && (ex+ew+fudge) >= xmax) {
728 e.style["opacity"] = "0.5";
729 zoom_parent(e);
730 e.onclick = function(e){unzoom(); zoom(this);};
731 update_text(e);
732 }
733 // not in current path
734 else
735 e.style["display"] = "none";
736 }
737 // Children maybe
738 else {
739 // no common path
740 if (ex < xmin || ex + fudge >= xmax) {
741 e.style["display"] = "none";
742 }
743 else {
744 zoom_child(e, xmin, ratio);
745 e.onclick = function(e){zoom(this);};
746 update_text(e);
747 }
748 }
749 }
750 }
751 function unzoom() {
752 var unzoombtn = document.getElementById("unzoom");
753 unzoombtn.style["opacity"] = "0.0";
754
755 var el = document.getElementsByTagName("g");
756 for(i=0;i<el.length;i++) {
757 el[i].style["display"] = "block";
758 el[i].style["opacity"] = "1";
759 zoom_reset(el[i]);
760 update_text(el[i]);
761 }
762 }
763  
764 // search
765 function reset_search() {
766 var el = document.getElementsByTagName("rect");
767 for (var i=0; i < el.length; i++){
768 orig_load(el[i], "fill")
769 }
770 }
771 function search_prompt() {
772 if (!searching) {
773 var term = prompt("Enter a search term (regexp " +
774 "allowed, eg: ^ext4_)", "");
775 if (term != null) {
776 search(term)
777 }
778 } else {
779 reset_search();
780 searching = 0;
781 var searchbtn = document.getElementById("search");
782 searchbtn.style["opacity"] = "0.1";
783 searchbtn.firstChild.nodeValue = "Search"
784 }
785 }
786 function search(term) {
787 var re = new RegExp(term);
788 var el = document.getElementsByTagName("g");
789 for (var i=0; i < el.length; i++){
790 var e = el[i];
791 if (e.attributes["class"].value == "func_g") {
792 // Scrape the function name from the onmouseover
793 // callback text. This is a little dirty.
794 var func = e.attributes["onmouseover"].value;
795 if (func != null) {
796 func = func.substr(3);
797 func = func.replace(/ .*/, "");
798 var r = find_child(e, "rect");
799 if (r == null) {
800 // the rect might be wrapped in an anchor
801 // if nameattr href is being used
802 if (r = find_child(e, "a")) {
803 r = find_child(r, "rect");
804 }
805 }
806 }
807 if (func != null && r != null &&
808 func.match(re)) {
809 orig_save(r, "fill");
810 r.attributes["fill"].value =
811 "$searchcolor";
812 searching = 1;
813 }
814 }
815 }
816 if (searching) {
817 var searchbtn = document.getElementById("search");
818 searchbtn.style["opacity"] = "1.0";
819 searchbtn.firstChild.nodeValue = "Reset Search"
820 }
821 }
822 function searchover(e) {
823 var searchbtn = document.getElementById("search");
824 searchbtn.style["opacity"] = "1.0";
825 }
826 function searchout(e) {
827 var searchbtn = document.getElementById("search");
828 if (searching) {
829 searchbtn.style["opacity"] = "1.0";
830 } else {
831 searchbtn.style["opacity"] = "0.1";
832 }
833 }
834 ]]>
835 </script>
836 INC
837 $im->include($inc);
838 $im->filledRectangle(0, 0, $imagewidth, $imageheight, 'url(#background)');
839 my ($white, $black, $vvdgrey, $vdgrey) = (
840 $im->colorAllocate(255, 255, 255),
841 $im->colorAllocate(0, 0, 0),
842 $im->colorAllocate(40, 40, 40),
843 $im->colorAllocate(160, 160, 160),
844 );
845 $im->stringTTF($black, $fonttype, $fontsize + 5, 0.0, int($imagewidth / 2), $fontsize * 2, $titletext, "middle");
846 $im->stringTTF($black, $fonttype, $fontsize, 0.0, $xpad, $imageheight - ($ypad2 / 2), " ", "", 'id="details"');
847 $im->stringTTF($black, $fonttype, $fontsize, 0.0, $xpad, $fontsize * 2,
848 "Reset Zoom", "", 'id="unzoom" onclick="unzoom()" style="opacity:0.0;cursor:pointer"');
849 $im->stringTTF($black, $fonttype, $fontsize, 0.0, $imagewidth - $xpad - 100,
850 $fontsize * 2, "Search", "", 'id="search" onmouseover="searchover()" onmouseout="searchout()" onclick="search_prompt()" style="opacity:0.1;cursor:pointer"');
851  
852 if ($palette) {
853 read_palette();
854 }
855  
856 # draw frames
857 while (my ($id, $node) = each %Node) {
858 my ($func, $depth, $etime) = split ";", $id;
859 my $stime = $node->{stime};
860 my $delta = $node->{delta};
861  
862 $etime = $timemax if $func eq "" and $depth == 0;
863  
864 my $x1 = $xpad + $stime * $widthpertime;
865 my $x2 = $xpad + $etime * $widthpertime;
866 my ($y1, $y2);
867 unless ($inverted) {
868 $y1 = $imageheight - $ypad2 - ($depth + 1) * $frameheight + $framepad;
869 $y2 = $imageheight - $ypad2 - $depth * $frameheight;
870 } else {
871 $y1 = $ypad1 + $depth * $frameheight;
872 $y2 = $ypad1 + ($depth + 1) * $frameheight - $framepad;
873 }
874  
875 my $samples = sprintf "%.0f", ($etime - $stime) * $factor;
876 (my $samples_txt = $samples) # add commas per perlfaq5
877 =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
878  
879 my $info;
880 if ($func eq "" and $depth == 0) {
881 $info = "all ($samples_txt $countname, 100%)";
882 } else {
883 my $pct = sprintf "%.2f", ((100 * $samples) / ($timemax * $factor));
884 my $escaped_func = $func;
885 $escaped_func =~ s/&/&amp;/g;
886 $escaped_func =~ s/</&lt;/g;
887 $escaped_func =~ s/>/&gt;/g;
888 $escaped_func =~ s/"/&quot;/g;
889 unless (defined $delta) {
890 $info = "$escaped_func ($samples_txt $countname, $pct%)";
891 } else {
892 my $d = $negate ? -$delta : $delta;
893 my $deltapct = sprintf "%.2f", ((100 * $d) / ($timemax * $factor));
894 $deltapct = $d > 0 ? "+$deltapct" : $deltapct;
895 $info = "$escaped_func ($samples_txt $countname, $pct%; $deltapct%)";
896 }
897 }
898  
899 my $nameattr = { %{ $nameattr{$func}||{} } }; # shallow clone
900 my $jsinfo = $info;
901 $jsinfo =~ s/'/\\'/g;
902 $nameattr->{class} ||= "func_g";
903 $nameattr->{onmouseover} ||= "s('".$jsinfo."')";
904 $nameattr->{onmouseout} ||= "c()";
905 $nameattr->{onclick} ||= "zoom(this)";
906 $nameattr->{title} ||= $info;
907 $im->group_start($nameattr);
908  
909 my $color;
910 if ($func eq "-") {
911 $color = $vdgrey;
912 } elsif (defined $delta) {
913 $color = color_scale($delta, $maxdelta);
914 } elsif ($palette) {
915 $color = color_map($colors, $func);
916 } else {
917 $color = color($colors, $hash, $func);
918 }
919 $im->filledRectangle($x1, $y1, $x2, $y2, $color, 'rx="2" ry="2"');
920  
921 my $chars = int( ($x2 - $x1) / ($fontsize * $fontwidth));
922 my $text = "";
923 if ($chars >= 3) { # room for one char plus two dots
924 $text = substr $func, 0, $chars;
925 substr($text, -2, 2) = ".." if $chars < length $func;
926 $text =~ s/&/&amp;/g;
927 $text =~ s/</&lt;/g;
928 $text =~ s/>/&gt;/g;
929 }
930 $im->stringTTF($black, $fonttype, $fontsize, 0.0, $x1 + 3, 3 + ($y1 + $y2) / 2, $text, "");
931  
932 $im->group_end($nameattr);
933 }
934  
935 print $im->svg;
936  
937 if ($palette) {
938 write_palette();
939 }
940  
941 # vim: ts=8 sts=8 sw=8 noexpandtab