Mega rename to Devel::Memory commit
[p5sagit/Devel-Size.git] / bin / dmemtree.pl
CommitLineData
5aa3ad8e 1#!/usr/bin/env perl
2c631ee0 2
d3b8a135 3# Read the raw memory data from Devel::Memory and process the tree
4# (as a stack, propagating data such as totals, up the tree).
5# Output completed nodes in the request formats.
6# Needs to be generalized to support pluggable output formats.
7# Making nodes into (lightweight fast) objects would be smart.
8# Tests would be even smarter!
9#
10# When working on this code it's important to have a sense of the flow.
11# Specifically the way that depth drives the completion of nodes.
12# It's a depth-first stream processing machine, which only ever holds
13# a single stack of the currently incomplete nodes, which is always the same as
14# the current depth. I.e., when a node of depth N arrives, all nodes >N are
15# popped off the stack and 'completed', each rippling data up to its parent.
16
2c631ee0 17use strict;
18use warnings;
5aa3ad8e 19use autodie;
2c631ee0 20
e8f4c506 21use DBI qw(looks_like_number);
b2fc39a5 22use DBD::SQLite;
f60f09e5 23use JSON::XS;
de73b186 24use Devel::Dwarn;
d3b8a135 25use HTML::Entities qw(encode_entities);;
b2fc39a5 26
fc6614ee 27use Getopt::Long;
28
de73b186 29# XXX import these from the XS code
30use constant NPtype_NAME => 0x01;
31use constant NPtype_LINK => 0x02;
32use constant NPtype_SV => 0x03;
33use constant NPtype_MAGIC => 0x04;
34use constant NPtype_OP => 0x05;
35
36use constant NPattr_LEAFSIZE => 0x00;
37use constant NPattr_NAME => 0x01;
38use constant NPattr_PADFAKE => 0x02;
39use constant NPattr_PADNAME => 0x03;
40use constant NPattr_PADTMP => 0x04;
41use constant NPattr_NOTE => 0x05;
68cafb30 42use constant NPattr_PRE_ATTR => 0x06;
de73b186 43
44
fc6614ee 45GetOptions(
5aa3ad8e 46 'text!' => \my $opt_text,
47 'dot=s' => \my $opt_dot,
b2fc39a5 48 'db=s' => \my $opt_db,
e8f4c506 49 'verbose|v!' => \my $opt_verbose,
50 'debug|d!' => \my $opt_debug,
98128850 51 'showid!' => \my $opt_showid,
fc6614ee 52) or exit 1;
94fab3d1 53
f60f09e5 54my $j = JSON::XS->new->ascii->pretty(0);
55
1915946b 56my ($dbh, $node_ins_sth);
57if ($opt_db) {
58 $dbh = DBI->connect("dbi:SQLite:dbname=$opt_db","","", {
59 RaiseError => 1, PrintError => 0, AutoCommit => 0
60 });
61 $dbh->do("PRAGMA synchronous = OFF");
62 $dbh->do("DROP TABLE IF EXISTS node");
63 $dbh->do(q{
64 CREATE TABLE node (
65 id integer primary key,
66 name text,
67 title text,
98128850 68 type integer,
1915946b 69 depth integer,
70 parent_id integer,
71
72 self_size integer,
73 kids_size integer,
74 kids_node_count integer,
75 child_ids text,
76 attr_json text,
77 leaves_json text
78 )
79 });
80 $node_ins_sth = $dbh->prepare(q{
98128850 81 INSERT INTO node VALUES (?,?,?,?,?,?, ?,?,?,?,?,?)
1915946b 82 });
83}
b2fc39a5 84
2c631ee0 85my @stack;
86my %seqn2node;
87
7020702a 88my $dotnode = sub {
89 my $name = encode_entities(shift);
90 $name =~ s/"/\\"/g;
7020702a 91 return '"'.$name.'"';
92};
ee2793c1 93
ee2793c1 94
5aa3ad8e 95my $dot_fh;
ee2793c1 96if ($opt_dot) {
5aa3ad8e 97 open $dot_fh, ">$opt_dot";
98 print $dot_fh "digraph {\n"; # }
99 print $dot_fh "graph [overlap=false]\n"; # target="???", URL="???"
ee2793c1 100}
101
0741448c 102sub fmt_size {
103 my $size = shift;
104 my $kb = $size / 1024;
105 return $size if $kb < 5;
106 return sprintf "%.1fKb", $kb if $kb < 1000;
107 return sprintf "%.1fMb", $kb/1024;
108}
109
ee2793c1 110
94fab3d1 111sub enter_node {
112 my $x = shift;
de73b186 113
114 my $parent = $stack[-1];
115 if ($parent) {
116
37836f2a 117 if ($x->{name} eq 'AVelem' and $parent->{name} eq 'SV(PVAV)') {
68cafb30 118 my $index = $x->{attr}{index};
119 # If node is an AVelem of a CvPADLIST propagate pad name to AVelem
120 if (@stack >= 4 and (my $cvpl = $stack[-4])->{name} eq 'CvPADLIST') {
68cafb30 121 my $padnames = $cvpl->{_cached}{padnames} ||= do {
122 my @names = @{ $cvpl->{attr}{+NPattr_PADNAME} || []};
123 $_ = "my(".($_||'').")" for @names;
124 $names[0] = '@_';
125 \@names;
126 };
68cafb30 127 $x->{name} = $padnames->[$index] || "?";
128 $x->{name} =~ s/my\(SVs_PADTMP\)/PADTMP/; # XXX hack for neatness
129 }
130 else {
131 $x->{name} = "[$index]";
de73b186 132 }
133 }
ee2793c1 134 }
de73b186 135
136 return $x;
94fab3d1 137}
138
de73b186 139
94fab3d1 140sub leave_node {
141 my $x = shift;
b2fc39a5 142 delete $seqn2node{$x->{id}};
ee2793c1 143
d3b8a135 144 my $self_size = 0; $self_size += $_ for values %{$x->{leaves}};
94fab3d1 145 $x->{self_size} = $self_size;
ee2793c1 146
147 my $parent = $stack[-1];
148 if ($parent) {
2c631ee0 149 # link to parent
5a78486c 150 $x->{parent_id} = $parent->{id};
2c631ee0 151 # accumulate into parent
152 $parent->{kids_node_count} += 1 + ($x->{kids_node_count}||0);
94fab3d1 153 $parent->{kids_size} += $self_size + $x->{kids_size};
5a78486c 154 push @{$parent->{child_id}}, $x->{id};
2c631ee0 155 }
de73b186 156
2c631ee0 157 # output
158 # ...
ee2793c1 159 if ($opt_dot) {
1915946b 160 printf "// n%d parent=%s(type=%s)\n", $x->{id},
0741448c 161 $parent ? $parent->{id} : "",
162 $parent ? $parent->{type} : ""
163 if 0;
de73b186 164 if ($x->{type} != NPtype_LINK) {
0741448c 165 my $name = $x->{title} ? "\"$x->{title}\" $x->{name}" : $x->{name};
166
167 if ($x->{kids_size}) {
168 $name .= sprintf " %s+%s=%s", fmt_size($x->{self_size}), fmt_size($x->{kids_size}), fmt_size($x->{self_size}+$x->{kids_size});
169 }
170 else {
171 $name .= sprintf " +%s", fmt_size($x->{self_size});
172 }
98128850 173 $name .= " $x->{id}" if $opt_showid;
0741448c 174
175 my @node_attr = (
176 sprintf("label=%s", $dotnode->($name)),
177 "id=$x->{id}",
178 );
179 my @link_attr;
180 #if ($x->{name} eq 'hek') { push @node_attr, "shape=point"; push @node_attr, "labelfontsize=6"; }
1915946b 181 if ($parent) { # probably a link
1915946b 182 my $parent_id = $parent->{id};
0741448c 183 my @link_attr = ("id=$parent_id");
de73b186 184 if ($parent->{type} == NPtype_LINK) { # link
1915946b 185 (my $link_name = $parent->{name}) =~ s/->$//;
186 push @link_attr, (sprintf "label=%s", $dotnode->($link_name));
187 $parent_id = ($stack[-2]||die "panic")->{id};
188 }
5aa3ad8e 189 printf $dot_fh qq{n%d -> n%d [%s];\n},
1915946b 190 $parent_id, $x->{id}, join(",", @link_attr);
191 }
5aa3ad8e 192 printf $dot_fh qq{n%d [ %s ];\n}, $x->{id}, join(",", @node_attr);
1915946b 193 }
194
ee2793c1 195 }
b2fc39a5 196 if ($dbh) {
f60f09e5 197 my $attr_json = $j->encode($x->{attr});
e78b28ca 198 my $leaves_json = $j->encode($x->{leaves});
b2fc39a5 199 $node_ins_sth->execute(
98128850 200 $x->{id}, $x->{name}, $x->{title}, $x->{type}, $x->{depth}, $x->{parent_id},
b2fc39a5 201 $x->{self_size}, $x->{kids_size}, $x->{kids_node_count},
f60f09e5 202 $x->{child_id} ? join(",", @{$x->{child_id}}) : undef,
e78b28ca 203 $attr_json, $leaves_json,
b2fc39a5 204 );
205 # XXX attribs
206 }
d3b8a135 207
208 return $x;
2c631ee0 209}
210
5aa3ad8e 211my $indent = ": ";
d3b8a135 212my @attr_type_name = (qw(size NAME PADFAKE my PADTMP NOTE)); # XXX get from XS in some way
68cafb30 213my $pending_pre_attr = {};
94fab3d1 214
2c631ee0 215while (<>) {
216 chomp;
de73b186 217
b2fc39a5 218 my ($type, $id, $val, $name, $extra) = split / /, $_, 5;
de73b186 219
ee2793c1 220 if ($type =~ s/^-//) { # Node type ($val is depth)
d3b8a135 221
65b2cf7d 222 printf "%s%s%s %s [#%d @%d]\n", $indent x $val, $name,
223 ($type == NPtype_LINK) ? "->" : "",
224 $extra||'', $id, $val
5aa3ad8e 225 if $opt_text;
d3b8a135 226
227 # this is the core driving logic
2c631ee0 228 while ($val < @stack) {
d3b8a135 229 my $x = leave_node(pop @stack);
e8f4c506 230 warn "N $id d$val ends $x->{id} d$x->{depth}: size $x->{self_size}+$x->{kids_size}\n"
231 if $opt_verbose;
2c631ee0 232 }
c5078bcb 233 die "panic: stack already has item at depth $val"
234 if $stack[$val];
de73b186 235 my $node = enter_node({
236 id => $id, type => $type, name => $name, extra => $extra,
68cafb30 237 attr => { %$pending_pre_attr },
238 leaves => {}, depth => $val, self_size=>0, kids_size=>0
de73b186 239 });
68cafb30 240 %$pending_pre_attr = ();
de73b186 241 $stack[$val] = $node;
b2fc39a5 242 $seqn2node{$id} = $node;
2c631ee0 243 }
d3b8a135 244
de73b186 245 # --- Leaf name and memory size
246 elsif ($type eq "L") {
b2fc39a5 247 my $node = $seqn2node{$id} || die;
2c631ee0 248 $node->{leaves}{$name} += $val;
5aa3ad8e 249 printf "%s+%d %s\n", $indent x ($node->{depth}+1), $val, $name
250 if $opt_text;
2c631ee0 251 }
d3b8a135 252
253 # --- Attribute type, name and value (all rather hackish)
de73b186 254 elsif (looks_like_number($type)) {
b2fc39a5 255 my $node = $seqn2node{$id} || die;
e8f4c506 256 my $attr = $node->{attr} || die;
de73b186 257
68cafb30 258 # attributes to queue up and apply to the next node
259 if (NPattr_PRE_ATTR == $type) {
260 $pending_pre_attr->{$name} = $val;
261 }
262 # attributes where the string is a key (or always empty and the type is the key)
263 elsif ($type == NPattr_NAME or $type == NPattr_NOTE) {
de73b186 264 printf "%s~%s(%s) %d [t%d]\n", $indent x ($node->{depth}+1), $attr_type_name[$type], $name, $val, $type
265 if $opt_text;
e8f4c506 266 warn "Node $id already has attribute $type:$name (value $attr->{$type}{$name})\n"
267 if exists $attr->{$type}{$name};
268 $attr->{$type}{$name} = $val || $id;
e8f4c506 269 $node->{title} = $name if $type == 1 and !$val;
270 }
68cafb30 271 # attributes where the number is a key (or always zero)
de73b186 272 elsif (NPattr_PADFAKE==$type or NPattr_PADTMP==$type or NPattr_PADNAME==$type) {
273 printf "%s~%s('%s') %d [t%d]\n", $indent x ($node->{depth}+1), $attr_type_name[$type], $name, $val, $type
274 if $opt_text;
e8f4c506 275 warn "Node $id already has attribute $type:$name (value $attr->{$type}[$val])\n"
276 if defined $attr->{$type}[$val];
de73b186 277 $attr->{+NPattr_PADNAME}[$val] = $name; # store all as NPattr_PADNAME
e8f4c506 278 }
279 else {
de73b186 280 printf "%s~%s %d [t%d]\n", $indent x ($node->{depth}+1), $name, $val, $type
281 if $opt_text;
e8f4c506 282 warn "Invalid attribute type '$type' on line $. ($_)";
283 }
2c631ee0 284 }
285 else {
286 warn "Invalid type '$type' on line $. ($_)";
e8f4c506 287 next;
2c631ee0 288 }
d3b8a135 289
b2fc39a5 290 $dbh->commit if $dbh and $id % 10_000 == 0;
2c631ee0 291}
c5078bcb 292my $top = $stack[0]; # grab top node before we pop all the nodes
293leave_node(pop @stack) while @stack;
d3b8a135 294
295if ($opt_verbose) {
296 warn "EOF ends $top->{id} d$top->{depth}: size $top->{self_size}+$top->{kids_size}\n";
297 warn Dumper($top);
298}
5aa3ad8e 299
300if ($dot_fh) {
301 print $dot_fh "}\n";
302 close $dot_fh;
303 system("open -a Graphviz $opt_dot");
2c631ee0 304}
94fab3d1 305
b2fc39a5 306$dbh->commit if $dbh;
307
2c631ee0 308use Data::Dumper;
5aa3ad8e 309warn Dumper(\%seqn2node) if %seqn2node; # should be empty
2c631ee0 310
d3b8a135 311=for This is out of date but gives you an idea of the data and stream
312
2c631ee0 313SV(PVAV) fill=1/1 [#1 @0]
314: +64 sv =64
315: +16 av_max =80
316: AVelem-> [#2 @1]
317: : SV(RV) [#3 @2]
318: : : +24 sv =104
319: : : RV-> [#4 @3]
320: : : : SV(PVAV) fill=-1/-1 [#5 @4]
321: : : : : +64 sv =168
322: AVelem-> [#6 @1]
323: : SV(IV) [#7 @2]
324: : : +24 sv =192
325192 at -e line 1.
326=cut
327__DATA__
328N 1 0 SV(PVAV) fill=1/1
329L 1 64 sv
330L 1 16 av_max
331N 2 1 AVelem->
332N 3 2 SV(RV)
333L 3 24 sv
334N 4 3 RV->
335N 5 4 SV(PVAV) fill=-1/-1
336L 5 64 sv
337N 6 1 AVelem->
338N 7 2 SV(IV)
339L 7 24 sv