]> gitweb.factorcode.org Git - factor.git/blob - extra/flamegraph/flamegraph.pl
flamegraph: adding a flamegraph tool
[factor.git] / extra / flamegraph / flamegraph.pl
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 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:
23 #
24 #  swapper;start_kernel;rest_init;cpu_idle;default_idle;native_safe_halt 1
25 #
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.
30 #
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]):
33 #       _[k] for kernel
34 #       _[i] for inlined
35 #       _[j] for jit
36 #       _[w] for waker
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.
40 #
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
44 # alphabetically.
45 #
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.
50 #
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).
55 #
56 # HISTORY
57 #
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
63 #
64 # Copyright 2016 Netflix, Inc.
65 # Copyright 2011 Joyent, Inc.  All rights reserved.
66 # Copyright 2011 Brendan Gregg.  All rights reserved.
67 #
68 # CDDL HEADER START
69 #
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.
73 #
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.
78 #
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]
84 #
85 # CDDL HEADER END
86 #
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.
92
93 use strict;
94
95 use Getopt::Long;
96
97 use open qw(:std :utf8);
98
99 # tunables
100 my $encoding;
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)
129 my $help = 0;
130
131 sub usage {
132         die <<USAGE_END;
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
158
159         eg,
160         $0 --title="Flame Graph: malloc()" trace.txt > graph.svg
161 USAGE_END
162 }
163
164 GetOptions(
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,
181         'hash'        => \$hash,
182         'random'      => \$rand,
183         'cp'          => \$palette,
184         'reverse'     => \$stackreverse,
185         'inverted'    => \$inverted,
186         'flamechart'  => \$flamechart,
187         'negate'      => \$negate,
188         'notes=s'     => \$notestext,
189         'help'        => \$help,
190 ) or usage();
191 $help && usage();
192
193 # internals
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
199 my $depthmax = 0;
200 my %Events;
201 my %nameattr;
202
203 if ($flamechart && $titletext eq "") {
204         $titletext = "Flame Chart";
205 }
206
207 if ($titletext eq "") {
208         unless ($inverted) {
209                 $titletext = $titledefault;
210         } else {
211                 $titletext = $titleinverted;
212         }
213 }
214
215 if ($nameattrfile) {
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";
219         while (<$attrfh>) {
220                 chomp;
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 };
224         }
225 }
226
227 if ($notestext =~ /[<>]/) {
228         die "Notes string can't contain < or >"
229 }
230
231 # Ensure minwidth is a valid floating-point number,
232 # print usage string if not
233 my $minwidth_f;
234 if ($minwidth =~ /^([0-9.]+)%?$/) {
235         $minwidth_f = $1;
236 } else {
237         warn "Value '$minwidth' is invalid for minwidth, expected a float.\n";
238         usage();
239 }
240
241 # background colors:
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 "") {
247         # choose a default
248         if ($colors eq "mem") {
249                 $bgcolors = "green";
250         } elsif ($colors =~ /^(io|wakeup|chain)$/) {
251                 $bgcolors = "blue";
252         } elsif ($colors =~ /^(red|green|blue|aqua|yellow|purple|orange)$/) {
253                 $bgcolors = "grey";
254         } else {
255                 $bgcolors = "yellow";
256         }
257 }
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;
270 } else {
271         die "Unrecognized bgcolor option \"$bgcolors\""
272 }
273
274 # SVG functions
275 { package SVG;
276         sub new {
277                 my $class = shift;
278                 my $self = {};
279                 bless ($self, $class);
280                 return $self;
281         }
282
283         sub header {
284                 my ($self, $w, $h) = @_;
285                 my $enc_attr = '';
286                 if (defined $encoding) {
287                         $enc_attr = qq{ encoding="$encoding"};
288                 }
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 -->
295 SVG
296         }
297
298         sub include {
299                 my ($self, $content) = @_;
300                 $self->{svg} .= $content;
301         }
302
303         sub colorAllocate {
304                 my ($self, $r, $g, $b) = @_;
305                 return "rgb($r,$g,$b)";
306         }
307
308         sub group_start {
309                 my ($self, $attr) = @_;
310
311                 my @g_attr = map {
312                         exists $attr->{$_} ? sprintf(qq/$_="%s"/, $attr->{$_}) : ()
313                 } qw(id class);
314                 push @g_attr, $attr->{g_extra} if $attr->{g_extra};
315                 if ($attr->{href}) {
316                         my @a_attr;
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));
322                 } else {
323                         $self->{svg} .= sprintf qq/<g %s>\n/, join(' ', @g_attr);
324                 }
325
326                 $self->{svg} .= sprintf qq/<title>%s<\/title>/, $attr->{title}
327                         if $attr->{title}; # should be first element within g container
328         }
329
330         sub group_end {
331                 my ($self, $attr) = @_;
332                 $self->{svg} .= $attr->{href} ? qq/<\/a>\n/ : qq/<\/g>\n/;
333         }
334
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/;
343         }
344
345         sub stringTTF {
346                 my ($self, $id, $x, $y, $str, $extra) = @_;
347                 $x = sprintf "%0.2f", $x;
348                 $id =  defined $id ? qq/id="$id"/ : "";
349                 $extra ||= "";
350                 $self->{svg} .= qq/<text $id x="$x" y="$y" $extra>$str<\/text>\n/;
351         }
352
353         sub svg {
354                 my $self = shift;
355                 return "$self->{svg}</svg>\n";
356         }
357         1;
358 }
359
360 sub namehash {
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.
364         my $name = shift;
365         my $vector = 0;
366         my $weight = 1;
367         my $max = 1;
368         my $mod = 10;
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;
374                 $max += 1 * $weight;
375                 $weight *= 0.70;
376                 last if $mod > 12;
377         }
378         return (1 - $vector / $max)
379 }
380
381 sub sum_namehash {
382   my $name = shift;
383   return unpack("%32W*", $name);
384 }
385
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.
392         my $name = shift;
393         my $hash = sum_namehash($name);
394         srand($hash);
395         return rand(1)
396 }
397
398 sub color {
399         my ($type, $hash, $name) = @_;
400         my ($v1, $v2, $v3);
401
402         if ($hash) {
403                 $v1 = namehash($name);
404                 $v2 = $v3 = namehash(scalar reverse $name);
405         } elsif ($rand) {
406                 $v1 = rand(1);
407                 $v2 = rand(1);
408                 $v3 = rand(1);
409         } else {
410                 $v1 = random_namehash($name);
411                 $v2 = random_namehash($name);
412                 $v3 = random_namehash($name);
413         }
414
415         # theme palettes
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)";
421         }
422         if (defined $type and $type eq "mem") {
423                 my $r = 0;
424                 my $g = 190 + int(50 * $v2);
425                 my $b = 0 + int(210 * $v1);
426                 return "rgb($r,$g,$b)";
427         }
428         if (defined $type and $type eq "io") {
429                 my $r = 80 + int(60 * $v1);
430                 my $g = $r;
431                 my $b = 190 + int(55 * $v2);
432                 return "rgb($r,$g,$b)";
433         }
434
435         # multi palettes
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
442                         $type = "green";
443                 } elsif ($name =~ m:_\[i\]$:) { # inline annotation
444                         $type = "aqua";
445                 } elsif ($name =~ m:^L?(java|javax|jdk|net|org|com|io|sun)/:) { # Java
446                         $type = "green";
447                 } elsif ($name =~ /:::/) {      # Java, typical perf-map-agent method separator
448                         $type = "green";
449                 } elsif ($name =~ /::/) {       # C++
450                         $type = "yellow";
451                 } elsif ($name =~ m:_\[k\]$:) { # kernel annotation
452                         $type = "orange";
453                 } elsif ($name =~ /::/) {       # C++
454                         $type = "yellow";
455                 } else {                        # system
456                         $type = "red";
457                 }
458                 # fall-through to color palettes
459         }
460         if (defined $type and $type eq "perl") {
461                 if ($name =~ /::/) {            # C++
462                         $type = "yellow";
463                 } elsif ($name =~ m:Perl: or $name =~ m:\.pl:) {        # Perl
464                         $type = "green";
465                 } elsif ($name =~ m:_\[k\]$:) { # kernel
466                         $type = "orange";
467                 } else {                        # system
468                         $type = "red";
469                 }
470                 # fall-through to color palettes
471         }
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
478                         if ($name =~ m:/:) {
479                                 $type = "green";        # source
480                         } else {
481                                 $type = "aqua";         # builtin
482                         }
483                 } elsif ($name =~ /::/) {       # C++
484                         $type = "yellow";
485                 } elsif ($name =~ m:/.*\.js:) { # JavaScript (match "/" in path)
486                         $type = "green";
487                 } elsif ($name =~ m/:/) {       # JavaScript (match ":" in builtin)
488                         $type = "aqua";
489                 } elsif ($name =~ m/^ $/) {     # Missing symbol
490                         $type = "green";
491                 } elsif ($name =~ m:_\[k\]:) {  # kernel
492                         $type = "orange";
493                 } else {                        # system
494                         $type = "red";
495                 }
496                 # fall-through to color palettes
497         }
498         if (defined $type and $type eq "wakeup") {
499                 $type = "aqua";
500                 # fall-through to color palettes
501         }
502         if (defined $type and $type eq "chain") {
503                 if ($name =~ m:_\[w\]:) {       # waker
504                         $type = "aqua"
505                 } else {                        # off-CPU
506                         $type = "blue";
507                 }
508                 # fall-through to color palettes
509         }
510
511         # 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)";
516         }
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)";
521         }
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)";
526         }
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)";
531         }
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)";
536         }
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)";
542         }
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)";
547         }
548
549         return "rgb(0,0,0)";
550 }
551
552 sub color_scale {
553         my ($value, $max) = @_;
554         my ($r, $g, $b) = (255, 255, 255);
555         $value = -$value if $negate;
556         if ($value > 0) {
557                 $g = $b = int(210 * ($max - $value) / $max);
558         } elsif ($value < 0) {
559                 $r = $g = int(210 * ($max + $value) / $max);
560         }
561         return "rgb($r,$g,$b)";
562 }
563
564 sub color_map {
565         my ($colors, $func) = @_;
566         if (exists $palette_map{$func}) {
567                 return $palette_map{$func};
568         } else {
569                 $palette_map{$func} = color($colors, $hash, $func);
570                 return $palette_map{$func};
571         }
572 }
573
574 sub write_palette {
575         open(FILE, ">$pal_file");
576         foreach my $key (sort keys %palette_map) {
577                 print FILE $key."->".$palette_map{$key}."\n";
578         }
579         close(FILE);
580 }
581
582 sub read_palette {
583         if (-e $pal_file) {
584         open(FILE, $pal_file) or die "can't open file $pal_file: $!";
585         while ( my $line = <FILE>) {
586                 chomp($line);
587                 (my $key, my $value) = split("->",$line);
588                 $palette_map{$key}=$value;
589         }
590         close(FILE)
591         }
592 }
593
594 my %Node;       # Hash of merged frame data
595 my %Tmp;
596
597 # flow() merges two stacks, storing the merged frames and value data in %Node.
598 sub flow {
599         my ($last, $this, $v, $d) = @_;
600
601         my $len_a = @$last - 1;
602         my $len_b = @$this - 1;
603
604         my $i = 0;
605         my $len_same;
606         for (; $i <= $len_a; $i++) {
607                 last if $i > $len_b;
608                 last if $last->[$i] ne $this->[$i];
609         }
610         $len_same = $i;
611
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};
619                 }
620                 delete $Tmp{$k};
621         }
622
623         for ($i = $len_same; $i <= $len_b; $i++) {
624                 my $k = "$this->[$i];$i";
625                 $Tmp{$k}->{stime} = $v;
626                 if (defined $d) {
627                         $Tmp{$k}->{delta} += $i == $len_b ? $d : 0;
628                 }
629         }
630
631         return $this;
632 }
633
634 # parse input
635 my @Data;
636 my @SortedData;
637 my $last = [];
638 my $time = 0;
639 my $delta = undef;
640 my $ignored = 0;
641 my $line;
642 my $maxdelta = 1;
643
644 # reverse if needed
645 foreach (<>) {
646         chomp;
647         $line = $_;
648         if ($stackreverse) {
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";
657                 } else {
658                         unshift @Data, join(";", reverse split(";", $stack)) . " $samples";
659                 }
660         } else {
661                 unshift @Data, $line;
662         }
663 }
664
665 if ($flamechart) {
666         # In flame chart mode, just reverse the data so time moves from left to right.
667         @SortedData = reverse @Data;
668 } else {
669         @SortedData = sort @Data;
670 }
671
672 # process and merge frames
673 foreach (@SortedData) {
674         chomp;
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) {
679                 ++$ignored;
680                 next;
681         }
682
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*)?)$/);
688         }
689         $delta = undef;
690         if (defined $samples2) {
691                 $delta = $samples2 - $samples;
692                 $maxdelta = abs($delta) if abs($delta) > $maxdelta;
693         }
694
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;
699                 my @newparts = ();
700                 $stack = shift @parts;
701                 $stack .= ";--;";
702                 foreach my $part (@parts) {
703                         $part =~ s/;/_[w];/g;
704                         $part .= "_[w]";
705                         push @newparts, $part;
706                 }
707                 $stack .= join ";--;", @parts;
708         }
709
710         # merge frames and populate %Node:
711         $last = flow($last, [ '', split ";", $stack ], $time, $delta);
712
713         if (defined $samples2) {
714                 $time += $samples2;
715         } else {
716                 $time += $samples;
717         }
718 }
719 flow($last, [], $time, $delta);
720
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;
725 }
726
727 warn "Ignored $ignored lines with invalid format\n" if $ignored;
728 unless ($time) {
729         warn "ERROR: No stack counts found\n";
730         my $im = SVG->new();
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.");
736         print $im->svg;
737         exit 2;
738 }
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)
742         undef $timemax;
743 }
744 $timemax ||= $time;
745
746 my $widthpertime = ($imagewidth - 2 * $xpad) / $timemax;
747
748 # Treat as a percentage of time if the string ends in a "%".
749 my $minwidth_time;
750 if ($minwidth =~ /%$/) {
751         $minwidth_time = $timemax * $minwidth_f / 100;
752 } else {
753         $minwidth_time = $minwidth_f / $widthpertime;
754 }
755
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;
761
762         if (($etime-$stime) < $minwidth_time) {
763                 delete $Node{$id};
764                 next;
765         }
766         $depthmax = $depth if $depth > $depthmax;
767 }
768
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;
773 my $im = SVG->new();
774 my ($black, $vdgrey, $dgrey) = (
775         $im->colorAllocate(0, 0, 0),
776         $im->colorAllocate(160, 160, 160),
777         $im->colorAllocate(200, 200, 200),
778     );
779 $im->header($imagewidth, $imageheight);
780 my $inc = <<INC;
781 <defs>
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%" />
785         </linearGradient>
786 </defs>
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; }
797 </style>
798 <script type="text/ecmascript">
799 <![CDATA[
800         "use strict";
801         var details, searchbtn, unzoombtn, matchedtxt, svg, searching, currentSearchTerm, ignorecase, ignorecaseBtn;
802         function init(evt) {
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];
809                 searching = 0;
810                 currentSearchTerm = null;
811
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);
817         }
818
819         // event listeners
820         window.addEventListener("click", function(e) {
821                 var target = find_group(e.target);
822                 if (target) {
823                         if (target.nodeName == "a") {
824                                 if (e.ctrlKey === false) return;
825                                 e.preventDefault();
826                         }
827                         if (target.classList.contains("parent")) unzoom(true);
828                         zoom(target);
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");
836                                 return;
837                         }
838
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));
846                         }
847                 }
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();
851         }, false)
852
853         // mouse-over for info
854         // show
855         window.addEventListener("mouseover", function(e) {
856                 var target = find_group(e.target);
857                 if (target) details.nodeValue = "$nametype " + g_to_text(target);
858         }, false)
859
860         // clear
861         window.addEventListener("mouseout", function(e) {
862                 var target = find_group(e.target);
863                 if (target) details.nodeValue = ' ';
864         }, false)
865
866         // ctrl-F for search
867         // ctrl-I to toggle case-sensitive search
868         window.addEventListener("keydown",function (e) {
869                 if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
870                         e.preventDefault();
871                         search_prompt();
872                 }
873                 else if (e.ctrlKey && e.keyCode === 73) {
874                         e.preventDefault();
875                         toggle_ignorecase();
876                 }
877         }, false)
878
879         // functions
880         function get_params() {
881                 var 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]);
887                 }
888                 return params;
889         }
890         function parse_params(params) {
891                 var uri = "?";
892                 for (var key in params) {
893                         uri += key + '=' + encodeURIComponent(params[key]) + '&';
894                 }
895                 if (uri.slice(-1) == "&")
896                         uri = uri.substring(0, uri.length - 1);
897                 if (uri == '?')
898                         uri = window.location.href.split('?')[0];
899                 return uri;
900         }
901         function find_child(node, selector) {
902                 var children = node.querySelectorAll(selector);
903                 if (children.length) return children[0];
904         }
905         function find_group(node) {
906                 var parent = node.parentElement;
907                 if (!parent) return;
908                 if (parent.id == "frames") return node;
909                 return find_group(parent);
910         }
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);
916         }
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);
921         }
922         function g_to_text(e) {
923                 var text = find_child(e, "title").firstChild.nodeValue;
924                 return (text)
925         }
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.
930                 return (func);
931         }
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;
938
939                 // Smaller than this size won't fit anything
940                 if (w < 2 * $fontsize * $fontwidth) {
941                         t.textContent = "";
942                         return;
943                 }
944
945                 t.textContent = txt;
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)
949                         return;
950
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) + "..";
957                                 return;
958                         }
959                 }
960                 t.textContent = "";
961         }
962
963         // zoom
964         function zoom_reset(e) {
965                 if (e.attributes != undefined) {
966                         orig_load(e, "x");
967                         orig_load(e, "width");
968                 }
969                 if (e.childNodes == undefined) return;
970                 for (var i = 0, c = e.childNodes; i < c.length; i++) {
971                         zoom_reset(c[i]);
972                 }
973         }
974         function zoom_child(e, x, ratio) {
975                 if (e.attributes != undefined) {
976                         if (e.attributes.x != undefined) {
977                                 orig_save(e, "x");
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;
981                         }
982                         if (e.attributes.width != undefined) {
983                                 orig_save(e, "width");
984                                 e.attributes.width.value = parseFloat(e.attributes.width.value) * ratio;
985                         }
986                 }
987
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);
991                 }
992         }
993         function zoom_parent(e) {
994                 if (e.attributes) {
995                         if (e.attributes.x != undefined) {
996                                 orig_save(e, "x");
997                                 e.attributes.x.value = $xpad;
998                         }
999                         if (e.attributes.width != undefined) {
1000                                 orig_save(e, "width");
1001                                 e.attributes.width.value = parseInt(svg.width.baseVal.value) - ($xpad * 2);
1002                         }
1003                 }
1004                 if (e.childNodes == undefined) return;
1005                 for (var i = 0, c = e.childNodes; i < c.length; i++) {
1006                         zoom_parent(c[i]);
1007                 }
1008         }
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;
1016
1017                 // XXX: Workaround for JavaScript float issues (fix me)
1018                 var fudge = 0.0001;
1019
1020                 unzoombtn.classList.remove("hide");
1021
1022                 var el = document.getElementById("frames").children;
1023                 for (var i = 0; i < el.length; i++) {
1024                         var e = el[i];
1025                         var a = find_child(e, "rect").attributes;
1026                         var ex = parseFloat(a.x.value);
1027                         var ew = parseFloat(a.width.value);
1028                         var upstack;
1029                         // Is it an ancestor
1030                         if ($inverted == 0) {
1031                                 upstack = parseFloat(a.y.value) > ymin;
1032                         } else {
1033                                 upstack = parseFloat(a.y.value) < ymin;
1034                         }
1035                         if (upstack) {
1036                                 // Direct ancestor
1037                                 if (ex <= xmin && (ex+ew+fudge) >= xmax) {
1038                                         e.classList.add("parent");
1039                                         zoom_parent(e);
1040                                         update_text(e);
1041                                 }
1042                                 // not in current path
1043                                 else
1044                                         e.classList.add("hide");
1045                         }
1046                         // Children maybe
1047                         else {
1048                                 // no common path
1049                                 if (ex < xmin || ex + fudge >= xmax) {
1050                                         e.classList.add("hide");
1051                                 }
1052                                 else {
1053                                         zoom_child(e, xmin, ratio);
1054                                         update_text(e);
1055                                 }
1056                         }
1057                 }
1058                 search();
1059         }
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");
1066                         zoom_reset(el[i]);
1067                         if(!dont_update_text) update_text(el[i]);
1068                 }
1069                 search();
1070         }
1071         function clearzoom() {
1072                 unzoom();
1073
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));
1079         }
1080
1081         // search
1082         function toggle_ignorecase() {
1083                 ignorecase = !ignorecase;
1084                 if (ignorecase) {
1085                         ignorecaseBtn.classList.add("show");
1086                 } else {
1087                         ignorecaseBtn.classList.remove("show");
1088                 }
1089                 reset_search();
1090                 search();
1091         }
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")
1096                 }
1097                 var params = get_params();
1098                 delete params.s;
1099                 history.replaceState(null, null, parse_params(params));
1100         }
1101         function search_prompt() {
1102                 if (!searching) {
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);
1108                 } else {
1109                         reset_search();
1110                         searching = 0;
1111                         currentSearchTerm = null;
1112                         searchbtn.classList.remove("show");
1113                         searchbtn.firstChild.nodeValue = "Search"
1114                         matchedtxt.classList.add("hide");
1115                         matchedtxt.firstChild.nodeValue = ""
1116                 }
1117         }
1118         function search(term) {
1119                 if (term) currentSearchTerm = term;
1120
1121                 var re = new RegExp(currentSearchTerm, ignorecase ? 'i' : '');
1122                 var el = document.getElementById("frames").children;
1123                 var matches = new Object();
1124                 var maxwidth = 0;
1125                 for (var i = 0; i < el.length; i++) {
1126                         var e = el[i];
1127                         var func = g_to_func(e);
1128                         var rect = find_child(e, "rect");
1129                         if (func == null || rect == null)
1130                                 continue;
1131
1132                         // Save max width. Only works as we have a root frame
1133                         var w = parseFloat(rect.attributes.width.value);
1134                         if (w > maxwidth)
1135                                 maxwidth = w;
1136
1137                         if (func.match(re)) {
1138                                 // highlight
1139                                 var x = parseFloat(rect.attributes.x.value);
1140                                 orig_save(rect, "fill");
1141                                 rect.attributes.fill.value = "$searchcolor";
1142
1143                                 // remember matches
1144                                 if (matches[x] == undefined) {
1145                                         matches[x] = w;
1146                                 } else {
1147                                         if (w > matches[x]) {
1148                                                 // overwrite with parent
1149                                                 matches[x] = w;
1150                                         }
1151                                 }
1152                                 searching = 1;
1153                         }
1154                 }
1155                 if (!searching)
1156                         return;
1157                 var params = get_params();
1158                 params.s = currentSearchTerm;
1159                 history.replaceState(null, null, parse_params(params));
1160
1161                 searchbtn.classList.add("show");
1162                 searchbtn.firstChild.nodeValue = "Reset Search";
1163
1164                 // calculate percent matched, excluding vertical overlap
1165                 var count = 0;
1166                 var lastx = -1;
1167                 var lastw = 0;
1168                 var keys = Array();
1169                 for (k in matches) {
1170                         if (matches.hasOwnProperty(k))
1171                                 keys.push(k);
1172                 }
1173                 // sort the matched frames by their x location
1174                 // ascending, then width descending
1175                 keys.sort(function(a, b){
1176                         return a - b;
1177                 });
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) {
1186                                 count += w;
1187                                 lastx = x;
1188                                 lastw = w;
1189                         }
1190                 }
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 + "%";
1196         }
1197 ]]>
1198 </script>
1199 INC
1200 $im->include($inc);
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), " ");
1209
1210 if ($palette) {
1211         read_palette();
1212 }
1213
1214 # draw frames
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};
1220
1221         $etime = $timemax if $func eq "" and $depth == 0;
1222
1223         my $x1 = $xpad + $stime * $widthpertime;
1224         my $x2 = $xpad + $etime * $widthpertime;
1225         my ($y1, $y2);
1226         unless ($inverted) {
1227                 $y1 = $imageheight - $ypad2 - ($depth + 1) * $frameheight + $framepad;
1228                 $y2 = $imageheight - $ypad2 - $depth * $frameheight;
1229         } else {
1230                 $y1 = $ypad1 + $depth * $frameheight;
1231                 $y2 = $ypad1 + ($depth + 1) * $frameheight - $framepad;
1232         }
1233
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;
1239
1240         my $info;
1241         if ($func eq "" and $depth == 0) {
1242                 $info = "all ($samples_txt $countname, 100%)";
1243         } else {
1244                 my $pct = sprintf "%.2f", ((100 * $samples) / ($timemax * $factor));
1245                 my $escaped_func = $func;
1246                 # clean up SVG breaking characters:
1247                 $escaped_func =~ s/&/&amp;/g;
1248                 $escaped_func =~ s/</&lt;/g;
1249                 $escaped_func =~ s/>/&gt;/g;
1250                 $escaped_func =~ s/"/&quot;/g;
1251                 $escaped_func =~ s/_\[[kwij]\]$//;      # strip any annotation
1252                 unless (defined $delta) {
1253                         $info = "$escaped_func ($samples_txt $countname, $pct%)";
1254                 } else {
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%)";
1259                 }
1260         }
1261
1262         my $nameattr = { %{ $nameattr{$func}||{} } }; # shallow clone
1263         $nameattr->{title}       ||= $info;
1264         $im->group_start($nameattr);
1265
1266         my $color;
1267         if ($func eq "--") {
1268                 $color = $vdgrey;
1269         } elsif ($func eq "-") {
1270                 $color = $dgrey;
1271         } elsif (defined $delta) {
1272                 $color = color_scale($delta, $maxdelta);
1273         } elsif ($palette) {
1274                 $color = color_map($colors, $func);
1275         } else {
1276                 $color = color($colors, $hash, $func);
1277         }
1278         $im->filledRectangle($x1, $y1, $x2, $y2, $color, 'rx="2" ry="2"');
1279
1280         my $chars = int( ($x2 - $x1) / ($fontsize * $fontwidth));
1281         my $text = "";
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/&/&amp;/g;
1287                 $text =~ s/</&lt;/g;
1288                 $text =~ s/>/&gt;/g;
1289         }
1290         $im->stringTTF(undef, $x1 + 3, 3 + ($y1 + $y2) / 2, $text);
1291
1292         $im->group_end($nameattr);
1293 }
1294 $im->group_end();
1295
1296 print $im->svg;
1297
1298 if ($palette) {
1299         write_palette();
1300 }
1301
1302 # vim: ts=8 sts=8 sw=8 noexpandtab