Keep T::B IO open in t/52leaks.t END - other ENDs pending (esp. since 961d79db)
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / Util / LeakTracer.pm
CommitLineData
218b7c12 1package DBICTest::Util::LeakTracer;
2
3use warnings;
4use strict;
5
6use Carp;
96577657 7use Scalar::Util qw(isweak weaken blessed reftype);
8433421f 8use DBIx::Class::_Util qw(refcount hrefaddr refdesc);
556c4fe6 9use DBIx::Class::Optional::Dependencies;
96577657 10use Data::Dumper::Concise;
218b7c12 11use DBICTest::Util 'stacktrace';
556c4fe6 12use constant {
13 CV_TRACING => DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
10635a06 14 SKIP_SCALAR_REFS => ( $] > 5.017 ) ? 1 : 0,
556c4fe6 15};
218b7c12 16
17use base 'Exporter';
bf302897 18our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
218b7c12 19
20my $refs_traced = 0;
96577657 21my $leaks_found = 0;
218b7c12 22my %reg_of_regs;
23
24sub populate_weakregistry {
96577657 25 my ($weak_registry, $target, $note) = @_;
218b7c12 26
27 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
28 croak 'Target is not a reference' unless length ref $target;
29
96577657 30 my $refaddr = hrefaddr $target;
8fa57d17 31
96577657 32 # a registry could be fed to itself or another registry via recursive sweeps
33 return $target if $reg_of_regs{$refaddr};
218b7c12 34
85ad63df 35 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
36 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
37
38 # an explicit "garbage collection" pass every time we store a ref
39 # if we do not do this the registry will keep growing appearing
40 # as if the traced program is continuously slowly leaking memory
41 for my $reg (values %reg_of_regs) {
42 (defined $reg->{$_}{weakref}) or delete $reg->{$_}
43 for keys %$reg;
44 }
45
10635a06 46 # FIXME/INVESTIGATE - something fishy is going on with refs to plain
47 # strings, perhaps something to do with the CoW work etc...
48 return $target if SKIP_SCALAR_REFS and reftype($target) eq 'SCALAR';
49
96577657 50 if (! defined $weak_registry->{$refaddr}{weakref}) {
51 $weak_registry->{$refaddr} = {
8fa57d17 52 stacktrace => stacktrace(1),
96577657 53 weakref => $target,
8fa57d17 54 };
4841171c 55
56 # on perl < 5.8.3 sometimes a weaken can throw (can't find RT)
57 # so guard against that unlikely event
58 local $@;
59 eval { weaken( $weak_registry->{$refaddr}{weakref} ); $refs_traced++ }
60 or delete $weak_registry->{$refaddr};
218b7c12 61 }
62
8433421f 63 my $desc = refdesc $target;
96577657 64 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
65 if ($note) {
66 $note =~ s/\s*\Q$desc\E\s*//g;
67 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
68 }
69
218b7c12 70 $target;
71}
72
96577657 73# Regenerate the slots names on a thread spawn
218b7c12 74sub CLONE {
75 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
76 %reg_of_regs = ();
77
78 for my $reg (@individual_regs) {
96577657 79 my @live_slots = grep { defined $_->{weakref} } values %$reg
218b7c12 80 or next;
cf8fa286 81
cf8fa286 82 $reg = {}; # get a fresh hashref in the new thread ctx
96577657 83 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
218b7c12 84
96577657 85 for my $slot_info (@live_slots) {
86 my $new_addr = hrefaddr $slot_info->{weakref};
8fa57d17 87
96577657 88 # replace all slot names
89 $slot_info->{slot_names} = { map {
90 my $name = $_;
91 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
92 ($name => 1);
93 } keys %{$slot_info->{slot_names}} };
218b7c12 94
96577657 95 $reg->{$new_addr} = $slot_info;
218b7c12 96 }
97 }
98}
99
556c4fe6 100sub visit_refs {
101 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
102
103 $args->{seen_refs} ||= {};
104
105 my $visited_cnt = '0E0';
106 for my $i (0 .. $#{$args->{refs}} ) {
556c4fe6 107
a42634cd 108 next unless length ref $args->{refs}[$i]; # not-a-ref
556c4fe6 109
a42634cd 110 my $addr = hrefaddr $args->{refs}[$i];
556c4fe6 111
6ae62c5c 112 # no diving into weakregistries
a42634cd 113 next if $reg_of_regs{$addr};
556c4fe6 114
a42634cd 115 next if $args->{seen_refs}{$addr}++;
556c4fe6 116 $visited_cnt++;
a42634cd 117
118 my $r = $args->{refs}[$i];
119
556c4fe6 120 $args->{action}->($r) or next;
121
6ae62c5c 122 # This may end up being necessarry some day, but do not slow things
123 # down for now
124 #if ( defined( my $t = tied($r) ) ) {
125 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
126 #}
127
a42634cd 128 my $type = reftype $r;
129
7664b1a0 130 local $@;
131 eval {
7664b1a0 132 if ($type eq 'HASH') {
133 $visited_cnt += visit_refs({ %$args, refs => [ map {
134 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
135 } keys %$r ] });
136 }
137 elsif ($type eq 'ARRAY') {
138 $visited_cnt += visit_refs({ %$args, refs => [ map {
139 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
140 } 0..$#$r ] });
141 }
142 elsif ($type eq 'REF' and !isweak($$r)) {
143 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
144 }
145 elsif (CV_TRACING and $type eq 'CODE') {
146 $visited_cnt += visit_refs({ %$args, refs => [ map {
147 ( !isweak($_) ) ? $_ : ()
148 } scalar PadWalker::closed_over($r) ] }); # scalar due to RT#92269
149 }
150 1;
8433421f 151 } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
556c4fe6 152 }
153 $visited_cnt;
154}
155
a42634cd 156sub visit_namespaces {
157 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
556c4fe6 158
a42634cd 159 my $visited = 1;
218b7c12 160
a42634cd 161 $args->{package} ||= '::';
162 $args->{package} = '::' if $args->{package} eq 'main';
de4705b7 163
a42634cd 164 if ( $args->{action}->($args->{package}) ) {
218b7c12 165
a42634cd 166 my $base = $args->{package};
167 $base = '' if $base eq '::';
218b7c12 168
218b7c12 169
a42634cd 170 $visited += visit_namespaces({ %$args, package => $_ }) for map
8d73fcd4 171 { $_ =~ /(.+?)::$/ ? "${base}::$1" : () }
a42634cd 172 grep
173 { $_ =~ /(?<!^main)::$/ }
174 do { no strict 'refs'; keys %{ $base . '::'} }
96577657 175 }
218b7c12 176
a42634cd 177 return $visited;
178}
179
180# compiles a list of addresses stored as globals (possibly even catching
181# class data in the form of method closures), so we can skip them further on
182sub symtable_referenced_addresses {
183
184 my $refs_per_pkg;
185
186 my $dummy_addresslist;
187
188 my $seen_refs = {};
189 visit_namespaces(
190 action => sub {
556c4fe6 191
556c4fe6 192 no strict 'refs';
556c4fe6 193
a42634cd 194 my $pkg = shift;
195 $pkg = '' if $pkg eq '::';
196 $pkg .= '::';
197
556c4fe6 198 # the unless regex at the end skips some dangerous namespaces outright
199 # (but does not prevent descent)
a42634cd 200 $refs_per_pkg->{$pkg} += visit_refs (
556c4fe6 201 seen_refs => $seen_refs,
a42634cd 202
203 # FIXME FIXME FIXME
204 # This is so damn odd - if we feed a constsub {1} (or in fact almost
205 # anything other than the actionsub below, any scalarref will show
206 # up as a leak, trapped by... something...
207 # Ideally we should be able to const this to sub{1} and just return
208 # $seen_refs (in fact it is identical to the dummy list at the end of
209 # a run here). Alas this doesn't seem to work, so punt for now...
210 action => sub { ++$dummy_addresslist->{ hrefaddr $_[0] } },
211
556c4fe6 212 refs => [ map { my $sym = $_;
213 # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
214 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
215
216 ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
217 ? ${"$pkg$sym"} : ()
218 ,
a42634cd 219
556c4fe6 220 ( map {
221 ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
222 ? *{"$pkg$sym"}{$_}
223 : ()
224 } qw(HASH ARRAY IO GLOB) ),
a42634cd 225
556c4fe6 226 } keys %$pkg ],
227 ) unless $pkg =~ /^ :: (?:
228 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
229 ) :: $/x;
a42634cd 230 }
231 );
556c4fe6 232
a42634cd 233# use Devel::Dwarn;
234# Ddie [ map
235# { { $_ => $refs_per_pkg->{$_} } }
236# sort
237# {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
238# keys %$refs_per_pkg
239# ];
240
241 $seen_refs;
242}
243
244sub assert_empty_weakregistry {
245 my ($weak_registry, $quiet) = @_;
246
8d73fcd4 247 Sub::Defer::undefer_all();
248
a42634cd 249 # in case we hooked bless any extra object creation will wreak
250 # havoc during the assert phase
251 local *CORE::GLOBAL::bless;
252 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
253
254 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
255
256 defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
257 for keys %$weak_registry;
258
259 return unless keys %$weak_registry;
8fa57d17 260
a42634cd 261 my $tb = eval { Test::Builder->new }
262 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
8fa57d17 263
a42634cd 264 for my $addr (keys %$weak_registry) {
265 $weak_registry->{$addr}{display_name} = join ' | ', (
266 sort
267 { length $a <=> length $b or $a cmp $b }
268 keys %{$weak_registry->{$addr}{slot_names}}
269 );
270
271 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
272 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
273 }
274
8d73fcd4 275 # the symtable walk is very expensive
276 # if we are $quiet (running in an END block) we do not really need to be
277 # that thorough - can get by with only %Sub::Quote::QUOTED
278 delete $weak_registry->{$_} for $quiet
279 ? do {
280 my $refs = {};
281 visit_refs (
282 # only look at the closed over stuffs
283 refs => [ grep { length ref $_ } map { values %{$_->[2]} } grep { ref $_ eq 'ARRAY' } values %Sub::Quote::QUOTED ],
284 seen_refs => $refs,
285 action => sub { 1 },
286 );
287 keys %$refs;
288 }
289 : (
290 # full sumtable walk, starting from ::
291 keys %{ symtable_referenced_addresses() }
292 )
293 ;
556c4fe6 294
96577657 295 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
296
1a44a267 297 next if ! defined $weak_registry->{$addr}{weakref};
298
5dc4301c 299 $leaks_found++ unless $tb->in_todo;
ee20ecfc 300 $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
1a44a267 301
302 my $diag = do {
303 local $Data::Dumper::Maxdepth = 1;
304 sprintf "\n%s (refcnt %d) => %s\n",
305 $weak_registry->{$addr}{display_name},
306 refcount($weak_registry->{$addr}{weakref}),
307 (
308 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
309 and
310 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
311 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
312 ;
218b7c12 313 };
1a44a267 314
5dc4301c 315 # FIXME - need to add a circular reference seeker based on the visitor
316 # (will need a bunch of modifications, punting with just a stub for now)
317
556c4fe6 318 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
1a44a267 319 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
320
321 $diag =~ s/^/ /mg;
322
323 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
324 $diag .= " Reference first seen$stack";
325 }
326
327 $tb->diag($diag);
6ae62c5c 328
329# if ($leaks_found == 1) {
330# # using the fh dumper due to intermittent buffering issues
331# # in case we decide to exit soon after (possibly via _exit)
332# require Devel::MAT::Dumper;
333# local $Devel::MAT::Dumper::MAX_STRING = -1;
334# open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
335# Devel::MAT::Dumper::dumpfh( $fh );
336# close ($fh) or die $!;
337#
338# use POSIX;
339# POSIX::_exit(1);
340# }
1a44a267 341 }
342
5dc4301c 343 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
1a44a267 344 $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
218b7c12 345 }
346}
347
348END {
b77a61d8 349 if (
350 $INC{'Test/Builder.pm'}
351 and
352 my $tb = do {
353 local $@;
354 my $t = eval { Test::Builder->new }
355 or warn "Test::Builder->new failed:\n$@\n";
356 $t;
357 }
358 ) {
218b7c12 359 # we check for test passage - a leak may be a part of a TODO
360 if ($leaks_found and !$tb->is_passing) {
361
362 $tb->diag(sprintf
363 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
364 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
365 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
366 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
367
368 }
369 else {
370 $tb->note("Auto checked $refs_traced references for leaks - none detected");
371 }
cbd7f87a 372
373# Disable this until better times - SQLT and probably other things
374# still load strictures. Let's just wait until Moo2.0 and go from there
375=begin for tears
376 # also while we are here and not in plain runmode: make sure we never
377 # loaded any of the strictures XS bullshit (it's a leak in a sense)
378 unless (DBICTest::RunMode->is_plain) {
379 for (qw(indirect multidimensional bareword::filehandles)) {
380 exists $INC{ Module::Runtime::module_notional_filename($_) }
381 and
ee20ecfc 382 $tb->ok(0, "$_ load should not have been attempted!!!" )
cbd7f87a 383 }
384 }
385=cut
386
218b7c12 387 }
388}
389
3901;