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