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