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