flamegraph.pl (28125B)
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" 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 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 INC 799 $im->include($inc); 800 $im->filledRectangle(0, 0, $imagewidth, $imageheight, 'url(#background)'); 801 $im->stringTTF("title", int($imagewidth / 2), $fontsize * 2, $titletext); 802 $im->stringTTF("subtitle", int($imagewidth / 2), $fontsize * 4, $subtitletext) if $subtitletext ne ""; 803 $im->stringTTF("details", $xpad, $imageheight - ($ypad2 / 2), " "); 804 $im->stringTTF("unzoom", $xpad, $fontsize * 2, "Reset Zoom", 'class="hide"'); 805 $im->stringTTF("search", $imagewidth - $xpad - 100, $fontsize * 2, "Search"); 806 $im->stringTTF("ignorecase", $imagewidth - $xpad - 16, $fontsize * 2, "ic"); 807 $im->stringTTF("matched", $imagewidth - $xpad - 100, $imageheight - ($ypad2 / 2), " "); 808 809 if ($palette) { 810 read_palette(); 811 } 812 813 # draw frames 814 $im->group_start({id => "frames"}); 815 while (my ($id, $node) = each %Node) { 816 my ($func, $depth, $etime) = split ";", $id; 817 my $stime = $node->{stime}; 818 my $delta = $node->{delta}; 819 820 $etime = $timemax if $func eq "" and $depth == 0; 821 822 my $x1 = $xpad + $stime * $widthpertime; 823 my $x2 = $xpad + $etime * $widthpertime; 824 my ($y1, $y2); 825 unless ($inverted) { 826 $y1 = $imageheight - $ypad2 - ($depth + 1) * $frameheight + $framepad; 827 $y2 = $imageheight - $ypad2 - $depth * $frameheight; 828 } else { 829 $y1 = $ypad1 + $depth * $frameheight; 830 $y2 = $ypad1 + ($depth + 1) * $frameheight - $framepad; 831 } 832 833 # Add commas per perlfaq5: 834 # https://perldoc.perl.org/perlfaq5#How-can-I-output-my-numbers-with-commas-added? 835 my $samples = sprintf "%.0f", ($etime - $stime) * $factor; 836 (my $samples_txt = $samples) 837 =~ s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g; 838 839 my $info; 840 if ($func eq "" and $depth == 0) { 841 $info = "all ($samples_txt $countname, 100%)"; 842 } else { 843 my $pct = sprintf "%.2f", ((100 * $samples) / ($timemax * $factor)); 844 my $escaped_func = $func; 845 # clean up SVG breaking characters: 846 $escaped_func =~ s/&/&/g; 847 $escaped_func =~ s/</</g; 848 $escaped_func =~ s/>/>/g; 849 $escaped_func =~ s/"/"/g; 850 $escaped_func =~ s/_\[[kwij]\]$//; # strip any annotation 851 unless (defined $delta) { 852 $info = "$escaped_func ($samples_txt $countname, $pct%)"; 853 } else { 854 my $d = $negate ? -$delta : $delta; 855 my $deltapct = sprintf "%.2f", ((100 * $d) / ($timemax * $factor)); 856 $deltapct = $d > 0 ? "+$deltapct" : $deltapct; 857 $info = "$escaped_func ($samples_txt $countname, $pct%; $deltapct%)"; 858 } 859 } 860 861 my $nameattr = { %{ $nameattr{$func}||{} } }; # shallow clone 862 $nameattr->{title} ||= $info; 863 $im->group_start($nameattr); 864 865 my $color; 866 if ($func eq "--") { 867 $color = $vdgrey; 868 } elsif ($func eq "-") { 869 $color = $dgrey; 870 } elsif (defined $delta) { 871 $color = color_scale($delta, $maxdelta); 872 } elsif ($palette) { 873 $color = color_map($colors, $func); 874 } else { 875 $color = color($colors, $hash, $func); 876 } 877 $im->filledRectangle($x1, $y1, $x2, $y2, $color, 'rx="2" ry="2"'); 878 879 my $chars = int( ($x2 - $x1) / ($fontsize * $fontwidth)); 880 my $text = ""; 881 if ($chars >= 3) { # room for one char plus two dots 882 $func =~ s/_\[[kwij]\]$//; # strip any annotation 883 $text = substr $func, 0, $chars; 884 substr($text, -2, 2) = ".." if $chars < length $func; 885 $text =~ s/&/&/g; 886 $text =~ s/</</g; 887 $text =~ s/>/>/g; 888 } 889 $im->stringTTF(undef, $x1 + 3, 3 + ($y1 + $y2) / 2, $text); 890 891 $im->group_end($nameattr); 892 } 893 $im->group_end(); 894 895 print $im->svg; 896 897 if ($palette) { 898 write_palette(); 899 } 900 901 # vim: ts=8 sts=8 sw=8 noexpandtab