Debian Codegraph @

share/analysis-scripts/flamegraph.pl

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