More prereqs
[p5sagit/Devel-Size.git] / bin / dmemtree.pl
1 #!/usr/bin/env perl
2
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
17 use strict;
18 use warnings;
19 use autodie;
20
21 use DBI qw(looks_like_number);
22 use DBD::SQLite;
23 use JSON::XS;
24 use Devel::Dwarn;
25 use HTML::Entities qw(encode_entities);;
26
27 use Getopt::Long;
28
29 # XXX import these from the XS code
30 use constant NPtype_NAME     => 0x01;
31 use constant NPtype_LINK     => 0x02;
32 use constant NPtype_SV       => 0x03;
33 use constant NPtype_MAGIC    => 0x04;
34 use constant NPtype_OP       => 0x05;
35
36 use constant NPattr_LEAFSIZE => 0x00;
37 use constant NPattr_NAME     => 0x01;
38 use constant NPattr_PADFAKE  => 0x02;
39 use constant NPattr_PADNAME  => 0x03;
40 use constant NPattr_PADTMP   => 0x04;
41 use constant NPattr_NOTE     => 0x05;
42 use constant NPattr_PRE_ATTR => 0x06;
43
44
45 GetOptions(
46     'text!' => \my $opt_text,
47     'dot=s' => \my $opt_dot,
48     'db=s'  => \my $opt_db,
49     'verbose|v!' => \my $opt_verbose,
50     'debug|d!' => \my $opt_debug,
51     'showid!' => \my $opt_showid,
52 ) or exit 1;
53
54 my $j = JSON::XS->new->ascii->pretty(0);
55
56 my ($dbh, $node_ins_sth);
57 if ($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,
68             type integer,
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{
81         INSERT INTO node VALUES (?,?,?,?,?,?,  ?,?,?,?,?,?)
82     });
83 }
84
85 my @stack;
86 my %seqn2node;
87
88 my $dotnode = sub {
89     my $name = encode_entities(shift);
90     $name =~ s/"/\\"/g;
91     return '"'.$name.'"';
92 };
93
94
95 my $dot_fh;
96 if ($opt_dot) {
97     open $dot_fh, ">$opt_dot";
98     print $dot_fh "digraph {\n"; # }
99     print $dot_fh "graph [overlap=false]\n"; # target="???", URL="???"
100 }
101
102 sub 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
110
111 sub enter_node {
112     my $x = shift;
113
114     my $parent = $stack[-1];
115     if ($parent) {
116
117         if ($x->{name} eq 'AVelem' and $parent->{name} eq 'SV(PVAV)') {
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') {
121                 my $padnames = $cvpl->{_cached}{padnames} ||= do {
122                     my @names = @{ $cvpl->{attr}{+NPattr_PADNAME} || []};
123                     $_ = "my(".($_||'').")" for @names;
124                     $names[0] = '@_';
125                     \@names;
126                 };
127                 $x->{name} = $padnames->[$index] || "?";
128                 $x->{name} =~ s/my\(SVs_PADTMP\)/PADTMP/; # XXX hack for neatness
129             }
130             else {
131                 $x->{name} = "[$index]";
132             }
133         }
134     }
135
136     return $x;
137 }
138
139
140 sub leave_node {
141     my $x = shift;
142     delete $seqn2node{$x->{id}};
143
144     my $self_size = 0; $self_size += $_ for values %{$x->{leaves}};
145     $x->{self_size} = $self_size;
146
147     my $parent = $stack[-1];
148     if ($parent) {
149         # link to parent
150         $x->{parent_id} = $parent->{id};
151         # accumulate into parent
152         $parent->{kids_node_count} += 1 + ($x->{kids_node_count}||0);
153         $parent->{kids_size} += $self_size + $x->{kids_size};
154         push @{$parent->{child_id}}, $x->{id};
155     }
156
157     # output
158     # ...
159     if ($opt_dot) {
160         printf "// n%d parent=%s(type=%s)\n", $x->{id},
161                 $parent ? $parent->{id} : "",
162                 $parent ? $parent->{type} : ""
163             if 0;
164         if ($x->{type} != NPtype_LINK) {
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             }
173             $name .= " $x->{id}" if $opt_showid;
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"; }
181             if ($parent) { # probably a link
182                 my $parent_id = $parent->{id};
183                 my @link_attr = ("id=$parent_id");
184                 if ($parent->{type} == NPtype_LINK) { # link
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                 }
189                 printf $dot_fh qq{n%d -> n%d [%s];\n},
190                     $parent_id, $x->{id}, join(",", @link_attr);
191             }
192             printf $dot_fh qq{n%d [ %s ];\n}, $x->{id}, join(",", @node_attr);
193         }
194
195     }
196     if ($dbh) {
197         my $attr_json = $j->encode($x->{attr});
198         my $leaves_json = $j->encode($x->{leaves});
199         $node_ins_sth->execute(
200             $x->{id}, $x->{name}, $x->{title}, $x->{type}, $x->{depth}, $x->{parent_id},
201             $x->{self_size}, $x->{kids_size}, $x->{kids_node_count},
202             $x->{child_id} ? join(",", @{$x->{child_id}}) : undef,
203             $attr_json, $leaves_json,
204         );
205         # XXX attribs
206     }
207
208     return $x;
209 }
210
211 my $indent = ":   ";
212 my @attr_type_name = (qw(size NAME PADFAKE my PADTMP NOTE)); # XXX get from XS in some way
213 my $pending_pre_attr = {};
214
215 while (<>) {
216     chomp;
217
218     my ($type, $id, $val, $name, $extra) = split / /, $_, 5;
219
220     if ($type =~ s/^-//) {     # Node type ($val is depth)
221
222         printf "%s%s%s %s [#%d @%d]\n", $indent x $val, $name,
223                 ($type == NPtype_LINK) ? "->" : "",
224                 $extra||'', $id, $val
225             if $opt_text;
226
227         # this is the core driving logic
228         while ($val < @stack) {
229             my $x = leave_node(pop @stack);
230             warn "N $id d$val ends $x->{id} d$x->{depth}: size $x->{self_size}+$x->{kids_size}\n"
231                 if $opt_verbose;
232         }
233         die "panic: stack already has item at depth $val"
234             if $stack[$val];
235         my $node = enter_node({
236             id => $id, type => $type, name => $name, extra => $extra,
237             attr => { %$pending_pre_attr },
238             leaves => {}, depth => $val, self_size=>0, kids_size=>0
239         });
240         %$pending_pre_attr = ();
241         $stack[$val] = $node;
242         $seqn2node{$id} = $node;
243     }
244
245     # --- Leaf name and memory size
246     elsif ($type eq "L") {
247         my $node = $seqn2node{$id} || die;
248         $node->{leaves}{$name} += $val;
249         printf "%s+%d %s\n", $indent x ($node->{depth}+1), $val, $name
250             if $opt_text;
251     }
252
253     # --- Attribute type, name and value (all rather hackish)
254     elsif (looks_like_number($type)) {
255         my $node = $seqn2node{$id} || die;
256         my $attr = $node->{attr} || die;
257
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) {
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;
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;
269             $node->{title} = $name if $type == 1 and !$val;
270         }
271         # attributes where the number is a key (or always zero)
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;
275             warn "Node $id already has attribute $type:$name (value $attr->{$type}[$val])\n"
276                 if defined $attr->{$type}[$val];
277             $attr->{+NPattr_PADNAME}[$val] = $name; # store all as NPattr_PADNAME
278         }
279         else {
280             printf "%s~%s %d [t%d]\n", $indent x ($node->{depth}+1), $name, $val, $type
281                 if $opt_text;
282             warn "Invalid attribute type '$type' on line $. ($_)";
283         }
284     }
285     else {
286         warn "Invalid type '$type' on line $. ($_)";
287         next;
288     }
289
290     $dbh->commit if $dbh and $id % 10_000 == 0;
291 }
292 my $top = $stack[0]; # grab top node before we pop all the nodes
293 leave_node(pop @stack) while @stack;
294
295 if ($opt_verbose) {
296     warn "EOF ends $top->{id} d$top->{depth}: size $top->{self_size}+$top->{kids_size}\n";
297     warn Dumper($top);
298 }
299
300 if ($dot_fh) {
301     print $dot_fh "}\n";
302     close $dot_fh;
303     system("open -a Graphviz $opt_dot") if $^O eq 'darwin'; # OSX
304 }
305
306 $dbh->commit if $dbh;
307
308 use Data::Dumper;
309 warn Dumper(\%seqn2node) if %seqn2node; # should be empty
310
311 =for This is out of date but gives you an idea of the data and stream
312
313 SV(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 
325 192 at -e line 1.
326 =cut
327 __DATA__
328 N 1 0 SV(PVAV) fill=1/1
329 L 1 64 sv
330 L 1 16 av_max
331 N 2 1 AVelem->
332 N 3 2 SV(RV)
333 L 3 24 sv
334 N 4 3 RV->
335 N 5 4 SV(PVAV) fill=-1/-1
336 L 5 64 sv
337 N 6 1 AVelem->
338 N 7 2 SV(IV)
339 L 7 24 sv