blib/lib/auto/share/dist/Devel-StatProfiler/flamegraph.pl untested

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