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