3 # flamegraph.pl flame stack grapher.
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.
9 # USAGE: ./flamegraph.pl [options] input.txt > graph.svg
11 # grep funcA input.txt | ./flamegraph.pl [options] > graph.svg
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.
16 # Options are listed in the usage message (--help).
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 for Linux perf script output using
21 # stackcollapse-perf.pl, for DTrace using stackcollapse.pl, and for other tools
22 # using the other stackcollapse programs. Example input:
24 # swapper;start_kernel;rest_init;cpu_idle;default_idle;native_safe_halt 1
26 # An optional extra column of counts can be provided to generate a differential
27 # flame graph of the counts, colored red for more, and blue for less. This
28 # can be useful when using flame graphs for non-regression testing.
29 # See the header comment in the difffolded.pl program for instructions.
31 # The input functions can optionally have annotations at the end of each
32 # function name, following a precedent by some tools (Linux perf's _[k]):
37 # Some of the stackcollapse programs support adding these annotations, eg,
38 # stackcollapse-perf.pl --kernel --jit. They are used merely for colors by
39 # some palettes, eg, flamegraph.pl --color=java.
41 # The output flame graph shows relative presence of functions in stack samples.
42 # The ordering on the x-axis has no meaning; since the data is samples, time
43 # order of events is not known. The order used sorts function names
46 # While intended to process stack samples, this can also process stack traces.
47 # For example, tracing stacks for memory allocation, or resource usage. You
48 # can use --title to set the title to reflect the content, and --countname
49 # to change "samples" to "bytes" etc.
51 # There are a few different palettes, selectable using --color. By default,
52 # the colors are selected at random (except for differentials). Functions
53 # called "-" will be printed gray, which can be used for stack separators (eg,
54 # between user and kernel stacks).
58 # This was inspired by Neelakanth Nadgir's excellent function_call_graph.rb
59 # program, which visualized function entry and return trace events. As Neel
60 # wrote: "The output displayed is inspired by Roch's CallStackAnalyzer which
61 # was in turn inspired by the work on vftrace by Jan Boerhout". See:
62 # https://blogs.oracle.com/realneel/entry/visualizing_callstacks_via_dtrace_and
64 # Copyright 2016 Netflix, Inc.
65 # Copyright 2011 Joyent, Inc. All rights reserved.
66 # Copyright 2011 Brendan Gregg. All rights reserved.
70 # The contents of this file are subject to the terms of the
71 # Common Development and Distribution License (the "License").
72 # You may not use this file except in compliance with the License.
74 # You can obtain a copy of the license at docs/cddl1.txt or
75 # http://opensource.org/licenses/CDDL-1.0.
76 # See the License for the specific language governing permissions
77 # and limitations under the License.
79 # When distributing Covered Code, include this CDDL HEADER in each
80 # file and include the License file at docs/cddl1.txt.
81 # If applicable, add the following below this CDDL HEADER, with the
82 # fields enclosed by brackets "[]" replaced with your own identifying
83 # information: Portions Copyright [yyyy] [name of copyright owner]
87 # 11-Oct-2014 Adrien Mahieux Added zoom.
88 # 21-Nov-2013 Shawn Sterling Added consistent palette file option
89 # 17-Mar-2013 Tim Bunce Added options and more tunables.
90 # 15-Dec-2011 Dave Pacheco Support for frames with whitespace.
91 # 10-Sep-2011 Brendan Gregg Created this.
97 use open qw(:std :utf8);
101 my $fonttype = "Verdana";
102 my $imagewidth = 1200; # max width, pixels
103 my $frameheight = 16; # max height is dynamic
104 my $fontsize = 12; # base text size
105 my $fontwidth = 0.59; # avg width relative to fontsize
106 my $minwidth = 0.1; # min function width, pixels or percentage of time
107 my $nametype = "Function:"; # what are the names in the data?
108 my $countname = "samples"; # what are the counts in the data?
109 my $colors = "hot"; # color theme
110 my $bgcolors = ""; # background color theme
111 my $nameattrfile; # file holding function attributes
112 my $timemax; # (override the) sum of the counts
113 my $factor = 1; # factor to scale counts by
114 my $hash = 0; # color by function name
115 my $rand = 0; # color randomly
116 my $palette = 0; # if we use consistent palettes (default off)
117 my %palette_map; # palette map hash
118 my $pal_file = "palette.map"; # palette map file name
119 my $stackreverse = 0; # reverse stack order, switching merge end
120 my $inverted = 0; # icicle graph
121 my $flamechart = 0; # produce a flame chart (sort by time, do not merge stacks)
122 my $negate = 0; # switch differential hues
123 my $titletext = ""; # centered heading
124 my $titledefault = "Flame Graph"; # overwritten by --title
125 my $titleinverted = "Icicle Graph"; # " "
126 my $searchcolor = "rgb(230,0,230)"; # color for search highlighting
127 my $notestext = ""; # embedded notes in SVG
128 my $subtitletext = ""; # second level title (optional)
133 USAGE: $0 [options] infile > outfile.svg\n
134 --title TEXT # change title text
135 --subtitle TEXT # second level title (optional)
136 --width NUM # width of image (default 1200)
137 --height NUM # height of each frame (default 16)
138 --minwidth NUM # omit smaller functions. In pixels or use "%" for
139 # percentage of time (default 0.1 pixels)
140 --fonttype FONT # font type (default "Verdana")
141 --fontsize NUM # font size (default 12)
142 --countname TEXT # count type label (default "samples")
143 --nametype TEXT # name type label (default "Function:")
144 --colors PALETTE # set color palette. choices are: hot (default), mem,
145 # io, wakeup, chain, java, js, perl, red, green, blue,
146 # aqua, yellow, purple, orange
147 --bgcolors COLOR # set background colors. gradient choices are yellow
148 # (default), blue, green, grey; flat colors use "#rrggbb"
149 --hash # colors are keyed by function name hash
150 --random # colors are randomly generated
151 --cp # use consistent palette (palette.map)
152 --reverse # generate stack-reversed flame graph
153 --inverted # icicle graph
154 --flamechart # produce a flame chart (sort by time, do not merge stacks)
155 --negate # switch differential hues (blue<->red)
156 --notes TEXT # add notes comment in SVG (for debugging)
157 --help # this message
160 $0 --title="Flame Graph: malloc()" trace.txt > graph.svg
165 'fonttype=s' => \$fonttype,
166 'width=i' => \$imagewidth,
167 'height=i' => \$frameheight,
168 'encoding=s' => \$encoding,
169 'fontsize=f' => \$fontsize,
170 'fontwidth=f' => \$fontwidth,
171 'minwidth=s' => \$minwidth,
172 'title=s' => \$titletext,
173 'subtitle=s' => \$subtitletext,
174 'nametype=s' => \$nametype,
175 'countname=s' => \$countname,
176 'nameattr=s' => \$nameattrfile,
177 'total=s' => \$timemax,
178 'factor=f' => \$factor,
179 'colors=s' => \$colors,
180 'bgcolors=s' => \$bgcolors,
184 'reverse' => \$stackreverse,
185 'inverted' => \$inverted,
186 'flamechart' => \$flamechart,
187 'negate' => \$negate,
188 'notes=s' => \$notestext,
194 my $ypad1 = $fontsize * 3; # pad top, include title
195 my $ypad2 = $fontsize * 2 + 10; # pad bottom, include labels
196 my $ypad3 = $fontsize * 2; # pad top, include subtitle (optional)
197 my $xpad = 10; # pad lefm and right
198 my $framepad = 1; # vertical padding for frames
203 if ($flamechart && $titletext eq "") {
204 $titletext = "Flame Chart";
207 if ($titletext eq "") {
209 $titletext = $titledefault;
211 $titletext = $titleinverted;
216 # The name-attribute file format is a function name followed by a tab then
217 # a sequence of tab separated name=value pairs.
218 open my $attrfh, $nameattrfile or die "Can't read $nameattrfile: $!\n";
221 my ($funcname, $attrstr) = split /\t/, $_, 2;
222 die "Invalid format in $nameattrfile" unless defined $attrstr;
223 $nameattr{$funcname} = { map { split /=/, $_, 2 } split /\t/, $attrstr };
227 if ($notestext =~ /[<>]/) {
228 die "Notes string can't contain < or >"
231 # Ensure minwidth is a valid floating-point number,
232 # print usage string if not
234 if ($minwidth =~ /^([0-9.]+)%?$/) {
237 warn "Value '$minwidth' is invalid for minwidth, expected a float.\n";
242 # - yellow gradient: default (hot, java, js, perl)
243 # - green gradient: mem
244 # - blue gradient: io, wakeup, chain
245 # - gray gradient: flat colors (red, green, blue, ...)
246 if ($bgcolors eq "") {
248 if ($colors eq "mem") {
250 } elsif ($colors =~ /^(io|wakeup|chain)$/) {
252 } elsif ($colors =~ /^(red|green|blue|aqua|yellow|purple|orange)$/) {
255 $bgcolors = "yellow";
258 my ($bgcolor1, $bgcolor2);
259 if ($bgcolors eq "yellow") {
260 $bgcolor1 = "#eeeeee"; # background color gradient start
261 $bgcolor2 = "#eeeeb0"; # background color gradient stop
262 } elsif ($bgcolors eq "blue") {
263 $bgcolor1 = "#eeeeee"; $bgcolor2 = "#e0e0ff";
264 } elsif ($bgcolors eq "green") {
265 $bgcolor1 = "#eef2ee"; $bgcolor2 = "#e0ffe0";
266 } elsif ($bgcolors eq "grey") {
267 $bgcolor1 = "#f8f8f8"; $bgcolor2 = "#e8e8e8";
268 } elsif ($bgcolors =~ /^#......$/) {
269 $bgcolor1 = $bgcolor2 = $bgcolors;
271 die "Unrecognized bgcolor option \"$bgcolors\""
279 bless ($self, $class);
284 my ($self, $w, $h) = @_;
286 if (defined $encoding) {
287 $enc_attr = qq{ encoding="$encoding"};
289 $self->{svg} .= <<SVG;
290 <?xml version="1.0"$enc_attr standalone="no"?>
291 <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
292 <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">
293 <!-- Flame graph stack visualization. See https://github.com/brendangregg/FlameGraph for latest version, and http://www.brendangregg.com/flamegraphs.html for examples. -->
294 <!-- NOTES: $notestext -->
299 my ($self, $content) = @_;
300 $self->{svg} .= $content;
304 my ($self, $r, $g, $b) = @_;
305 return "rgb($r,$g,$b)";
309 my ($self, $attr) = @_;
312 exists $attr->{$_} ? sprintf(qq/$_="%s"/, $attr->{$_}) : ()
314 push @g_attr, $attr->{g_extra} if $attr->{g_extra};
317 push @a_attr, sprintf qq/xlink:href="%s"/, $attr->{href} if $attr->{href};
318 # default target=_top else links will open within SVG <object>
319 push @a_attr, sprintf qq/target="%s"/, $attr->{target} || "_top";
320 push @a_attr, $attr->{a_extra} if $attr->{a_extra};
321 $self->{svg} .= sprintf qq/<a %s>\n/, join(' ', (@a_attr, @g_attr));
323 $self->{svg} .= sprintf qq/<g %s>\n/, join(' ', @g_attr);
326 $self->{svg} .= sprintf qq/<title>%s<\/title>/, $attr->{title}
327 if $attr->{title}; # should be first element within g container
331 my ($self, $attr) = @_;
332 $self->{svg} .= $attr->{href} ? qq/<\/a>\n/ : qq/<\/g>\n/;
335 sub filledRectangle {
336 my ($self, $x1, $y1, $x2, $y2, $fill, $extra) = @_;
337 $x1 = sprintf "%0.1f", $x1;
338 $x2 = sprintf "%0.1f", $x2;
339 my $w = sprintf "%0.1f", $x2 - $x1;
340 my $h = sprintf "%0.1f", $y2 - $y1;
341 $extra = defined $extra ? $extra : "";
342 $self->{svg} .= qq/<rect x="$x1" y="$y1" width="$w" height="$h" fill="$fill" $extra \/>\n/;
346 my ($self, $id, $x, $y, $str, $extra) = @_;
347 $x = sprintf "%0.2f", $x;
348 $id = defined $id ? qq/id="$id"/ : "";
350 $self->{svg} .= qq/<text $id x="$x" y="$y" $extra>$str<\/text>\n/;
355 return "$self->{svg}</svg>\n";
361 # Generate a vector hash for the name string, weighting early over
362 # later characters. We want to pick the same colors for function
363 # names across different flame graphs.
369 # if module name present, trunc to 1st char
370 $name =~ s/.(.*?)`//;
371 foreach my $c (split //, $name) {
372 my $i = (ord $c) % $mod;
373 $vector += ($i / ($mod++ - 1)) * $weight;
378 return (1 - $vector / $max)
383 return unpack("%32W*", $name);
386 sub random_namehash {
387 # Generate a random hash for the name string.
388 # This ensures that functions with the same name have the same color,
389 # both within a flamegraph and across multiple flamegraphs without
390 # needing to set a palette and while preserving the original flamegraph
391 # optic, unlike what happens with --hash.
393 my $hash = sum_namehash($name);
399 my ($type, $hash, $name) = @_;
403 $v1 = namehash($name);
404 $v2 = $v3 = namehash(scalar reverse $name);
410 $v1 = random_namehash($name);
411 $v2 = random_namehash($name);
412 $v3 = random_namehash($name);
416 if (defined $type and $type eq "hot") {
417 my $r = 205 + int(50 * $v3);
418 my $g = 0 + int(230 * $v1);
419 my $b = 0 + int(55 * $v2);
420 return "rgb($r,$g,$b)";
422 if (defined $type and $type eq "mem") {
424 my $g = 190 + int(50 * $v2);
425 my $b = 0 + int(210 * $v1);
426 return "rgb($r,$g,$b)";
428 if (defined $type and $type eq "io") {
429 my $r = 80 + int(60 * $v1);
431 my $b = 190 + int(55 * $v2);
432 return "rgb($r,$g,$b)";
436 if (defined $type and $type eq "java") {
437 # Handle both annotations (_[j], _[i], ...; which are
438 # accurate), as well as input that lacks any annotations, as
439 # best as possible. Without annotations, we get a little hacky
440 # and match on java|org|com, etc.
441 if ($name =~ m:_\[j\]$:) { # jit annotation
443 } elsif ($name =~ m:_\[i\]$:) { # inline annotation
445 } elsif ($name =~ m:^L?(java|javax|jdk|net|org|com|io|sun)/:) { # Java
447 } elsif ($name =~ /:::/) { # Java, typical perf-map-agent method separator
449 } elsif ($name =~ /::/) { # C++
451 } elsif ($name =~ m:_\[k\]$:) { # kernel annotation
453 } elsif ($name =~ /::/) { # C++
458 # fall-through to color palettes
460 if (defined $type and $type eq "perl") {
461 if ($name =~ /::/) { # C++
463 } elsif ($name =~ m:Perl: or $name =~ m:\.pl:) { # Perl
465 } elsif ($name =~ m:_\[k\]$:) { # kernel
470 # fall-through to color palettes
472 if (defined $type and $type eq "js") {
473 # Handle both annotations (_[j], _[i], ...; which are
474 # accurate), as well as input that lacks any annotations, as
475 # best as possible. Without annotations, we get a little hacky,
476 # and match on a "/" with a ".js", etc.
477 if ($name =~ m:_\[j\]$:) { # jit annotation
479 $type = "green"; # source
481 $type = "aqua"; # builtin
483 } elsif ($name =~ /::/) { # C++
485 } elsif ($name =~ m:/.*\.js:) { # JavaScript (match "/" in path)
487 } elsif ($name =~ m/:/) { # JavaScript (match ":" in builtin)
489 } elsif ($name =~ m/^ $/) { # Missing symbol
491 } elsif ($name =~ m:_\[k\]:) { # kernel
496 # fall-through to color palettes
498 if (defined $type and $type eq "wakeup") {
500 # fall-through to color palettes
502 if (defined $type and $type eq "chain") {
503 if ($name =~ m:_\[w\]:) { # waker
508 # fall-through to color palettes
512 if (defined $type and $type eq "red") {
513 my $r = 200 + int(55 * $v1);
514 my $x = 50 + int(80 * $v1);
515 return "rgb($r,$x,$x)";
517 if (defined $type and $type eq "green") {
518 my $g = 200 + int(55 * $v1);
519 my $x = 50 + int(60 * $v1);
520 return "rgb($x,$g,$x)";
522 if (defined $type and $type eq "blue") {
523 my $b = 205 + int(50 * $v1);
524 my $x = 80 + int(60 * $v1);
525 return "rgb($x,$x,$b)";
527 if (defined $type and $type eq "yellow") {
528 my $x = 175 + int(55 * $v1);
529 my $b = 50 + int(20 * $v1);
530 return "rgb($x,$x,$b)";
532 if (defined $type and $type eq "purple") {
533 my $x = 190 + int(65 * $v1);
534 my $g = 80 + int(60 * $v1);
535 return "rgb($x,$g,$x)";
537 if (defined $type and $type eq "aqua") {
538 my $r = 50 + int(60 * $v1);
539 my $g = 165 + int(55 * $v1);
540 my $b = 165 + int(55 * $v1);
541 return "rgb($r,$g,$b)";
543 if (defined $type and $type eq "orange") {
544 my $r = 190 + int(65 * $v1);
545 my $g = 90 + int(65 * $v1);
546 return "rgb($r,$g,0)";
553 my ($value, $max) = @_;
554 my ($r, $g, $b) = (255, 255, 255);
555 $value = -$value if $negate;
557 $g = $b = int(210 * ($max - $value) / $max);
558 } elsif ($value < 0) {
559 $r = $g = int(210 * ($max + $value) / $max);
561 return "rgb($r,$g,$b)";
565 my ($colors, $func) = @_;
566 if (exists $palette_map{$func}) {
567 return $palette_map{$func};
569 $palette_map{$func} = color($colors, $hash, $func);
570 return $palette_map{$func};
575 open(FILE, ">$pal_file");
576 foreach my $key (sort keys %palette_map) {
577 print FILE $key."->".$palette_map{$key}."\n";
584 open(FILE, $pal_file) or die "can't open file $pal_file: $!";
585 while ( my $line = <FILE>) {
587 (my $key, my $value) = split("->",$line);
588 $palette_map{$key}=$value;
594 my %Node; # Hash of merged frame data
597 # flow() merges two stacks, storing the merged frames and value data in %Node.
599 my ($last, $this, $v, $d) = @_;
601 my $len_a = @$last - 1;
602 my $len_b = @$this - 1;
606 for (; $i <= $len_a; $i++) {
608 last if $last->[$i] ne $this->[$i];
612 for ($i = $len_a; $i >= $len_same; $i--) {
613 my $k = "$last->[$i];$i";
614 # a unique ID is constructed from "func;depth;etime";
615 # func-depth isn't unique, it may be repeated later.
616 $Node{"$k;$v"}->{stime} = delete $Tmp{$k}->{stime};
617 if (defined $Tmp{$k}->{delta}) {
618 $Node{"$k;$v"}->{delta} = delete $Tmp{$k}->{delta};
623 for ($i = $len_same; $i <= $len_b; $i++) {
624 my $k = "$this->[$i];$i";
625 $Tmp{$k}->{stime} = $v;
627 $Tmp{$k}->{delta} += $i == $len_b ? $d : 0;
649 # there may be an extra samples column for differentials
650 # XXX todo: redo these REs as one. It's repeated below.
651 my($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
652 my $samples2 = undef;
653 if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
654 $samples2 = $samples;
655 ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
656 unshift @Data, join(";", reverse split(";", $stack)) . " $samples $samples2";
658 unshift @Data, join(";", reverse split(";", $stack)) . " $samples";
661 unshift @Data, $line;
666 # In flame chart mode, just reverse the data so time moves from left to right.
667 @SortedData = reverse @Data;
669 @SortedData = sort @Data;
672 # process and merge frames
673 foreach (@SortedData) {
675 # process: folded_stack count
676 # eg: func_a;func_b;func_c 31
677 my ($stack, $samples) = (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
678 unless (defined $samples and defined $stack) {
683 # there may be an extra samples column for differentials:
684 my $samples2 = undef;
685 if ($stack =~ /^(.*)\s+?(\d+(?:\.\d*)?)$/) {
686 $samples2 = $samples;
687 ($stack, $samples) = $stack =~ (/^(.*)\s+?(\d+(?:\.\d*)?)$/);
690 if (defined $samples2) {
691 $delta = $samples2 - $samples;
692 $maxdelta = abs($delta) if abs($delta) > $maxdelta;
695 # for chain graphs, annotate waker frames with "_[w]", for later
696 # coloring. This is a hack, but has a precedent ("_[k]" from perf).
697 if ($colors eq "chain") {
698 my @parts = split ";--;", $stack;
700 $stack = shift @parts;
702 foreach my $part (@parts) {
703 $part =~ s/;/_[w];/g;
705 push @newparts, $part;
707 $stack .= join ";--;", @parts;
710 # merge frames and populate %Node:
711 $last = flow($last, [ '', split ";", $stack ], $time, $delta);
713 if (defined $samples2) {
719 flow($last, [], $time, $delta);
721 if ($countname eq "samples") {
722 # If $countname is used, it's likely that we're not measuring in stack samples
723 # (e.g. time could be the unit), so don't warn.
724 warn "Stack count is low ($time). Did something go wrong?\n" if $time < 100;
727 warn "Ignored $ignored lines with invalid format\n" if $ignored;
729 warn "ERROR: No stack counts found\n";
731 # emit an error message SVG, for tools automating flamegraph use
732 my $imageheight = $fontsize * 5;
733 $im->header($imagewidth, $imageheight);
734 $im->stringTTF(undef, int($imagewidth / 2), $fontsize * 2,
735 "ERROR: No valid input provided to flamegraph.pl.");
739 if ($timemax and $timemax < $time) {
740 warn "Specified --total $timemax is less than actual total $time, so ignored\n"
741 if $timemax/$time > 0.02; # only warn is significant (e.g., not rounding etc)
746 my $widthpertime = ($imagewidth - 2 * $xpad) / $timemax;
748 # Treat as a percentage of time if the string ends in a "%".
750 if ($minwidth =~ /%$/) {
751 $minwidth_time = $timemax * $minwidth_f / 100;
753 $minwidth_time = $minwidth_f / $widthpertime;
756 # prune blocks that are too narrow and determine max depth
757 while (my ($id, $node) = each %Node) {
758 my ($func, $depth, $etime) = split ";", $id;
759 my $stime = $node->{stime};
760 die "missing start for $id" if not defined $stime;
762 if (($etime-$stime) < $minwidth_time) {
766 $depthmax = $depth if $depth > $depthmax;
769 # draw canvas, and embed interactive JavaScript program
770 my $imageheight = (($depthmax + 1) * $frameheight) + $ypad1 + $ypad2;
771 $imageheight += $ypad3 if $subtitletext ne "";
772 my $titlesize = $fontsize + 5;
774 my ($black, $vdgrey, $dgrey) = (
775 $im->colorAllocate(0, 0, 0),
776 $im->colorAllocate(160, 160, 160),
777 $im->colorAllocate(200, 200, 200),
779 $im->header($imagewidth, $imageheight);
782 <linearGradient id="background" y1="0" y2="1" x1="0" x2="0" >
783 <stop stop-color="$bgcolor1" offset="5%" />
784 <stop stop-color="$bgcolor2" offset="95%" />
787 <style type="text/css">
788 text { font-family:$fonttype; font-size:${fontsize}px; fill:$black; }
789 #search, #ignorecase { opacity:0.1; cursor:pointer; }
790 #search:hover, #search.show, #ignorecase:hover, #ignorecase.show { opacity:1; }
791 #subtitle { text-anchor:middle; font-color:$vdgrey; }
792 #title { text-anchor:middle; font-size:${titlesize}px}
793 #unzoom { cursor:pointer; }
794 #frames > *:hover { stroke:black; stroke-width:0.5; cursor:pointer; }
795 .hide { display:none; }
796 .parent { opacity:0.5; }
798 <script type="text/ecmascript">
801 var details, searchbtn, unzoombtn, matchedtxt, svg, searching, currentSearchTerm, ignorecase, ignorecaseBtn;
803 details = document.getElementById("details").firstChild;
804 searchbtn = document.getElementById("search");
805 ignorecaseBtn = document.getElementById("ignorecase");
806 unzoombtn = document.getElementById("unzoom");
807 matchedtxt = document.getElementById("matched");
808 svg = document.getElementsByTagName("svg")[0];
810 currentSearchTerm = null;
812 // use GET parameters to restore a flamegraphs state.
813 var params = get_params();
814 if (params.x && params.y)
815 zoom(find_group(document.querySelector('[x="' + params.x + '"][y="' + params.y + '"]')));
816 if (params.s) search(params.s);
820 window.addEventListener("click", function(e) {
821 var target = find_group(e.target);
823 if (target.nodeName == "a") {
824 if (e.ctrlKey === false) return;
827 if (target.classList.contains("parent")) unzoom(true);
829 if (!document.querySelector('.parent')) {
830 // we have basically done a clearzoom so clear the url
831 var params = get_params();
832 if (params.x) delete params.x;
833 if (params.y) delete params.y;
834 history.replaceState(null, null, parse_params(params));
835 unzoombtn.classList.add("hide");
839 // set parameters for zoom state
840 var el = target.querySelector("rect");
841 if (el && el.attributes && el.attributes.y && el.attributes._orig_x) {
842 var params = get_params()
843 params.x = el.attributes._orig_x.value;
844 params.y = el.attributes.y.value;
845 history.replaceState(null, null, parse_params(params));
848 else if (e.target.id == "unzoom") clearzoom();
849 else if (e.target.id == "search") search_prompt();
850 else if (e.target.id == "ignorecase") toggle_ignorecase();
853 // mouse-over for info
855 window.addEventListener("mouseover", function(e) {
856 var target = find_group(e.target);
857 if (target) details.nodeValue = "$nametype " + g_to_text(target);
861 window.addEventListener("mouseout", function(e) {
862 var target = find_group(e.target);
863 if (target) details.nodeValue = ' ';
867 // ctrl-I to toggle case-sensitive search
868 window.addEventListener("keydown",function (e) {
869 if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
873 else if (e.ctrlKey && e.keyCode === 73) {
880 function get_params() {
882 var paramsarr = window.location.search.substr(1).split('&');
883 for (var i = 0; i < paramsarr.length; ++i) {
884 var tmp = paramsarr[i].split("=");
885 if (!tmp[0] || !tmp[1]) continue;
886 params[tmp[0]] = decodeURIComponent(tmp[1]);
890 function parse_params(params) {
892 for (var key in params) {
893 uri += key + '=' + encodeURIComponent(params[key]) + '&';
895 if (uri.slice(-1) == "&")
896 uri = uri.substring(0, uri.length - 1);
898 uri = window.location.href.split('?')[0];
901 function find_child(node, selector) {
902 var children = node.querySelectorAll(selector);
903 if (children.length) return children[0];
905 function find_group(node) {
906 var parent = node.parentElement;
908 if (parent.id == "frames") return node;
909 return find_group(parent);
911 function orig_save(e, attr, val) {
912 if (e.attributes["_orig_" + attr] != undefined) return;
913 if (e.attributes[attr] == undefined) return;
914 if (val == undefined) val = e.attributes[attr].value;
915 e.setAttribute("_orig_" + attr, val);
917 function orig_load(e, attr) {
918 if (e.attributes["_orig_"+attr] == undefined) return;
919 e.attributes[attr].value = e.attributes["_orig_" + attr].value;
920 e.removeAttribute("_orig_"+attr);
922 function g_to_text(e) {
923 var text = find_child(e, "title").firstChild.nodeValue;
926 function g_to_func(e) {
927 var func = g_to_text(e);
928 // if there's any manipulation we want to do to the function
929 // name before it's searched, do it here before returning.
932 function update_text(e) {
933 var r = find_child(e, "rect");
934 var t = find_child(e, "text");
935 var w = parseFloat(r.attributes.width.value) -3;
936 var txt = find_child(e, "title").textContent.replace(/\\([^(]*\\)\$/,"");
937 t.attributes.x.value = parseFloat(r.attributes.x.value) + 3;
939 // Smaller than this size won't fit anything
940 if (w < 2 * $fontsize * $fontwidth) {
946 var sl = t.getSubStringLength(0, txt.length);
947 // check if only whitespace or if we can fit the entire string into width w
948 if (/^ *\$/.test(txt) || sl < w)
951 // this isn't perfect, but gives a good starting point
952 // and avoids calling getSubStringLength too often
953 var start = Math.floor((w/sl) * txt.length);
954 for (var x = start; x > 0; x = x-2) {
955 if (t.getSubStringLength(0, x + 2) <= w) {
956 t.textContent = txt.substring(0, x) + "..";
964 function zoom_reset(e) {
965 if (e.attributes != undefined) {
967 orig_load(e, "width");
969 if (e.childNodes == undefined) return;
970 for (var i = 0, c = e.childNodes; i < c.length; i++) {
974 function zoom_child(e, x, ratio) {
975 if (e.attributes != undefined) {
976 if (e.attributes.x != undefined) {
978 e.attributes.x.value = (parseFloat(e.attributes.x.value) - x - $xpad) * ratio + $xpad;
979 if (e.tagName == "text")
980 e.attributes.x.value = find_child(e.parentNode, "rect[x]").attributes.x.value + 3;
982 if (e.attributes.width != undefined) {
983 orig_save(e, "width");
984 e.attributes.width.value = parseFloat(e.attributes.width.value) * ratio;
988 if (e.childNodes == undefined) return;
989 for (var i = 0, c = e.childNodes; i < c.length; i++) {
990 zoom_child(c[i], x - $xpad, ratio);
993 function zoom_parent(e) {
995 if (e.attributes.x != undefined) {
997 e.attributes.x.value = $xpad;
999 if (e.attributes.width != undefined) {
1000 orig_save(e, "width");
1001 e.attributes.width.value = parseInt(svg.width.baseVal.value) - ($xpad * 2);
1004 if (e.childNodes == undefined) return;
1005 for (var i = 0, c = e.childNodes; i < c.length; i++) {
1009 function zoom(node) {
1010 var attr = find_child(node, "rect").attributes;
1011 var width = parseFloat(attr.width.value);
1012 var xmin = parseFloat(attr.x.value);
1013 var xmax = parseFloat(xmin + width);
1014 var ymin = parseFloat(attr.y.value);
1015 var ratio = (svg.width.baseVal.value - 2 * $xpad) / width;
1017 // XXX: Workaround for JavaScript float issues (fix me)
1020 unzoombtn.classList.remove("hide");
1022 var el = document.getElementById("frames").children;
1023 for (var i = 0; i < el.length; i++) {
1025 var a = find_child(e, "rect").attributes;
1026 var ex = parseFloat(a.x.value);
1027 var ew = parseFloat(a.width.value);
1029 // Is it an ancestor
1030 if ($inverted == 0) {
1031 upstack = parseFloat(a.y.value) > ymin;
1033 upstack = parseFloat(a.y.value) < ymin;
1037 if (ex <= xmin && (ex+ew+fudge) >= xmax) {
1038 e.classList.add("parent");
1042 // not in current path
1044 e.classList.add("hide");
1049 if (ex < xmin || ex + fudge >= xmax) {
1050 e.classList.add("hide");
1053 zoom_child(e, xmin, ratio);
1060 function unzoom(dont_update_text) {
1061 unzoombtn.classList.add("hide");
1062 var el = document.getElementById("frames").children;
1063 for(var i = 0; i < el.length; i++) {
1064 el[i].classList.remove("parent");
1065 el[i].classList.remove("hide");
1067 if(!dont_update_text) update_text(el[i]);
1071 function clearzoom() {
1074 // remove zoom state
1075 var params = get_params();
1076 if (params.x) delete params.x;
1077 if (params.y) delete params.y;
1078 history.replaceState(null, null, parse_params(params));
1082 function toggle_ignorecase() {
1083 ignorecase = !ignorecase;
1085 ignorecaseBtn.classList.add("show");
1087 ignorecaseBtn.classList.remove("show");
1092 function reset_search() {
1093 var el = document.querySelectorAll("#frames rect");
1094 for (var i = 0; i < el.length; i++) {
1095 orig_load(el[i], "fill")
1097 var params = get_params();
1099 history.replaceState(null, null, parse_params(params));
1101 function search_prompt() {
1103 var term = prompt("Enter a search term (regexp " +
1104 "allowed, eg: ^ext4_)"
1105 + (ignorecase ? ", ignoring case" : "")
1106 + "\\nPress Ctrl-i to toggle case sensitivity", "");
1107 if (term != null) search(term);
1111 currentSearchTerm = null;
1112 searchbtn.classList.remove("show");
1113 searchbtn.firstChild.nodeValue = "Search"
1114 matchedtxt.classList.add("hide");
1115 matchedtxt.firstChild.nodeValue = ""
1118 function search(term) {
1119 if (term) currentSearchTerm = term;
1121 var re = new RegExp(currentSearchTerm, ignorecase ? 'i' : '');
1122 var el = document.getElementById("frames").children;
1123 var matches = new Object();
1125 for (var i = 0; i < el.length; i++) {
1127 var func = g_to_func(e);
1128 var rect = find_child(e, "rect");
1129 if (func == null || rect == null)
1132 // Save max width. Only works as we have a root frame
1133 var w = parseFloat(rect.attributes.width.value);
1137 if (func.match(re)) {
1139 var x = parseFloat(rect.attributes.x.value);
1140 orig_save(rect, "fill");
1141 rect.attributes.fill.value = "$searchcolor";
1144 if (matches[x] == undefined) {
1147 if (w > matches[x]) {
1148 // overwrite with parent
1157 var params = get_params();
1158 params.s = currentSearchTerm;
1159 history.replaceState(null, null, parse_params(params));
1161 searchbtn.classList.add("show");
1162 searchbtn.firstChild.nodeValue = "Reset Search";
1164 // calculate percent matched, excluding vertical overlap
1169 for (k in matches) {
1170 if (matches.hasOwnProperty(k))
1173 // sort the matched frames by their x location
1174 // ascending, then width descending
1175 keys.sort(function(a, b){
1178 // Step through frames saving only the biggest bottom-up frames
1179 // thanks to the sort order. This relies on the tree property
1180 // where children are always smaller than their parents.
1181 var fudge = 0.0001; // JavaScript floating point
1182 for (var k in keys) {
1183 var x = parseFloat(keys[k]);
1184 var w = matches[keys[k]];
1185 if (x >= lastx + lastw - fudge) {
1191 // display matched percent
1192 matchedtxt.classList.remove("hide");
1193 var pct = 100 * count / maxwidth;
1194 if (pct != 100) pct = pct.toFixed(1)
1195 matchedtxt.firstChild.nodeValue = "Matched: " + pct + "%";
1201 $im->filledRectangle(0, 0, $imagewidth, $imageheight, 'url(#background)');
1202 $im->stringTTF("title", int($imagewidth / 2), $fontsize * 2, $titletext);
1203 $im->stringTTF("subtitle", int($imagewidth / 2), $fontsize * 4, $subtitletext) if $subtitletext ne "";
1204 $im->stringTTF("details", $xpad, $imageheight - ($ypad2 / 2), " ");
1205 $im->stringTTF("unzoom", $xpad, $fontsize * 2, "Reset Zoom", 'class="hide"');
1206 $im->stringTTF("search", $imagewidth - $xpad - 100, $fontsize * 2, "Search");
1207 $im->stringTTF("ignorecase", $imagewidth - $xpad - 16, $fontsize * 2, "ic");
1208 $im->stringTTF("matched", $imagewidth - $xpad - 100, $imageheight - ($ypad2 / 2), " ");
1215 $im->group_start({id => "frames"});
1216 while (my ($id, $node) = each %Node) {
1217 my ($func, $depth, $etime) = split ";", $id;
1218 my $stime = $node->{stime};
1219 my $delta = $node->{delta};
1221 $etime = $timemax if $func eq "" and $depth == 0;
1223 my $x1 = $xpad + $stime * $widthpertime;
1224 my $x2 = $xpad + $etime * $widthpertime;
1226 unless ($inverted) {
1227 $y1 = $imageheight - $ypad2 - ($depth + 1) * $frameheight + $framepad;
1228 $y2 = $imageheight - $ypad2 - $depth * $frameheight;
1230 $y1 = $ypad1 + $depth * $frameheight;
1231 $y2 = $ypad1 + ($depth + 1) * $frameheight - $framepad;
1234 # Add commas per perlfaq5:
1235 # https://perldoc.perl.org/perlfaq5#How-can-I-output-my-numbers-with-commas-added?
1236 my $samples = sprintf "%.0f", ($etime - $stime) * $factor;
1237 (my $samples_txt = $samples)
1238 =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;
1241 if ($func eq "" and $depth == 0) {
1242 $info = "all ($samples_txt $countname, 100%)";
1244 my $pct = sprintf "%.2f", ((100 * $samples) / ($timemax * $factor));
1245 my $escaped_func = $func;
1246 # clean up SVG breaking characters:
1247 $escaped_func =~ s/&/&/g;
1248 $escaped_func =~ s/</</g;
1249 $escaped_func =~ s/>/>/g;
1250 $escaped_func =~ s/"/"/g;
1251 $escaped_func =~ s/_\[[kwij]\]$//; # strip any annotation
1252 unless (defined $delta) {
1253 $info = "$escaped_func ($samples_txt $countname, $pct%)";
1255 my $d = $negate ? -$delta : $delta;
1256 my $deltapct = sprintf "%.2f", ((100 * $d) / ($timemax * $factor));
1257 $deltapct = $d > 0 ? "+$deltapct" : $deltapct;
1258 $info = "$escaped_func ($samples_txt $countname, $pct%; $deltapct%)";
1262 my $nameattr = { %{ $nameattr{$func}||{} } }; # shallow clone
1263 $nameattr->{title} ||= $info;
1264 $im->group_start($nameattr);
1267 if ($func eq "--") {
1269 } elsif ($func eq "-") {
1271 } elsif (defined $delta) {
1272 $color = color_scale($delta, $maxdelta);
1273 } elsif ($palette) {
1274 $color = color_map($colors, $func);
1276 $color = color($colors, $hash, $func);
1278 $im->filledRectangle($x1, $y1, $x2, $y2, $color, 'rx="2" ry="2"');
1280 my $chars = int( ($x2 - $x1) / ($fontsize * $fontwidth));
1282 if ($chars >= 3) { # room for one char plus two dots
1283 $func =~ s/_\[[kwij]\]$//; # strip any annotation
1284 $text = substr $func, 0, $chars;
1285 substr($text, -2, 2) = ".." if $chars < length $func;
1286 $text =~ s/&/&/g;
1287 $text =~ s/</</g;
1288 $text =~ s/>/>/g;
1290 $im->stringTTF(undef, $x1 + 3, 3 + ($y1 + $y2) / 2, $text);
1292 $im->group_end($nameattr);
1302 # vim: ts=8 sts=8 sw=8 noexpandtab