flamegraph.pl 35 KB

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