1 package DBICTest::Util::LeakTracer;
8 use Scalar::Util qw(isweak weaken blessed reftype);
9 use DBIx::Class::_Util qw(refcount hrefaddr refdesc);
10 use DBIx::Class::Optional::Dependencies;
11 use DBICTest::RunMode;
12 use Data::Dumper::Concise;
13 use DBICTest::Util qw( stacktrace visit_namespaces );
15 CV_TRACING => !DBICTest::RunMode->is_plain && DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
19 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
25 sub populate_weakregistry {
26 my ($weak_registry, $target, $note) = @_;
28 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
29 croak 'Target is not a reference' unless length ref $target;
31 my $refaddr = hrefaddr $target;
33 # a registry could be fed to itself or another registry via recursive sweeps
34 return $target if $reg_of_regs{$refaddr};
36 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
37 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
39 # an explicit "garbage collection" pass every time we store a ref
40 # if we do not do this the registry will keep growing appearing
41 # as if the traced program is continuously slowly leaking memory
42 for my $reg (values %reg_of_regs) {
43 (defined $reg->{$_}{weakref}) or delete $reg->{$_}
47 if (! defined $weak_registry->{$refaddr}{weakref}) {
48 $weak_registry->{$refaddr} = {
49 stacktrace => stacktrace(1),
53 # on perl < 5.8.3 sometimes a weaken can throw (can't find RT)
54 # so guard against that unlikely event
56 eval { weaken( $weak_registry->{$refaddr}{weakref} ); $refs_traced++ }
57 or delete $weak_registry->{$refaddr};
60 my $desc = refdesc $target;
61 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
63 $note =~ s/\s*\Q$desc\E\s*//g;
64 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
70 # Regenerate the slots names on a thread spawn
72 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
75 for my $reg (@individual_regs) {
76 my @live_slots = grep { defined $_->{weakref} } values %$reg
79 $reg = {}; # get a fresh hashref in the new thread ctx
80 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
82 for my $slot_info (@live_slots) {
83 my $new_addr = hrefaddr $slot_info->{weakref};
85 # replace all slot names
86 $slot_info->{slot_names} = { map {
88 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
90 } keys %{$slot_info->{slot_names}} };
92 $reg->{$new_addr} = $slot_info;
96 # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
97 # collected before leaving this scope. Depending on the code above, this
98 # may very well be just a preventive measure guarding future modifications
103 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
105 $args->{seen_refs} ||= {};
107 my $visited_cnt = '0E0';
108 for my $i (0 .. $#{$args->{refs}} ) {
110 next unless length ref $args->{refs}[$i]; # not-a-ref
112 my $addr = hrefaddr $args->{refs}[$i];
114 # no diving into weakregistries
115 next if $reg_of_regs{$addr};
117 next if $args->{seen_refs}{$addr}++;
120 my $r = $args->{refs}[$i];
122 $args->{action}->($r) or next;
124 # This may end up being necessarry some day, but do not slow things
126 #if ( defined( my $t = tied($r) ) ) {
127 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
130 my $type = reftype $r;
134 if ($type eq 'HASH') {
135 $visited_cnt += visit_refs({ %$args, refs => [ map {
136 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
139 elsif ($type eq 'ARRAY') {
140 $visited_cnt += visit_refs({ %$args, refs => [ map {
141 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
144 elsif ($type eq 'REF' and !isweak($$r)) {
145 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
147 elsif (CV_TRACING and $type eq 'CODE') {
148 $visited_cnt += visit_refs({ %$args, refs => [ map {
149 ( !isweak($_) ) ? $_ : ()
150 } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
153 } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
158 # compiles a list of addresses stored as globals (possibly even catching
159 # class data in the form of method closures), so we can skip them further on
160 sub symtable_referenced_addresses {
172 # the unless regex at the end skips some dangerous namespaces outright
173 # (but does not prevent descent)
174 $refs_per_pkg->{$pkg} += visit_refs (
175 seen_refs => $seen_refs,
179 refs => [ map { my $sym = $_;
180 # *{"${pkg}::$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
181 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}::$sym") : () ),
183 ( defined *{"${pkg}::$sym"}{SCALAR} and length ref ${"${pkg}::$sym"} and ! isweak( ${"${pkg}::$sym"} ) )
184 ? ${"${pkg}::$sym"} : ()
188 ( defined *{"${pkg}::$sym"}{$_} and ! isweak(defined *{"${pkg}::$sym"}{$_}) )
189 ? *{"${pkg}::$sym"}{$_}
191 } qw(HASH ARRAY IO GLOB) ),
193 } keys %{"${pkg}::"} ],
194 ) unless $pkg =~ /^ (?:
195 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
202 # { { $_ => $refs_per_pkg->{$_} } }
204 # {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
205 # keys %$refs_per_pkg
211 sub assert_empty_weakregistry {
212 my ($weak_registry, $quiet) = @_;
214 # in case we hooked bless any extra object creation will wreak
215 # havoc during the assert phase
216 local *CORE::GLOBAL::bless;
217 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : CORE::caller() ) };
219 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
221 defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
222 for keys %$weak_registry;
224 return unless keys %$weak_registry;
226 my $tb = eval { Test::Builder->new }
227 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
229 for my $addr (keys %$weak_registry) {
230 $weak_registry->{$addr}{display_name} = join ' | ', (
232 { length $a <=> length $b or $a cmp $b }
233 keys %{$weak_registry->{$addr}{slot_names}}
236 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
237 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
240 # the symtable walk is very expensive
241 # if we are $quiet (running in an END block) we do not really need to be
242 # that thorough - can get by with only %Sub::Quote::QUOTED
243 delete $weak_registry->{$_} for $quiet
247 # only look at the closed over stuffs
248 refs => [ grep { length ref $_ } map { values %{$_->[2]} } grep { ref $_ eq 'ARRAY' } values %Sub::Quote::QUOTED ],
255 # full sumtable walk, starting from ::
256 keys %{ symtable_referenced_addresses() }
260 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
262 next if ! defined $weak_registry->{$addr}{weakref};
264 $leaks_found++ unless $tb->in_todo;
265 $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
268 local $Data::Dumper::Maxdepth = 1;
269 sprintf "\n%s (refcnt %d) => %s\n",
270 $weak_registry->{$addr}{display_name},
271 refcount($weak_registry->{$addr}{weakref}),
273 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
275 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
276 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
280 # FIXME - need to add a circular reference seeker based on the visitor
281 # (will need a bunch of modifications, punting with just a stub for now)
283 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
284 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
288 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
289 $diag .= " Reference first seen$stack";
294 # if ($leaks_found == 1) {
295 # # using the fh dumper due to intermittent buffering issues
296 # # in case we decide to exit soon after (possibly via _exit)
297 # require Devel::MAT::Dumper;
298 # local $Devel::MAT::Dumper::MAX_STRING = -1;
299 # open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
300 # Devel::MAT::Dumper::dumpfh( $fh );
301 # close ($fh) or die $!;
308 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
309 $tb->ok(1, sprintf "No leaks found at %s line %d", (CORE::caller())[1,2] );
315 $INC{'Test/Builder.pm'}
319 my $t = eval { Test::Builder->new }
320 or warn "Test::Builder->new failed:\n$@\n";
324 # we check for test passage - a leak may be a part of a TODO
325 if ($leaks_found and !$tb->is_passing) {
328 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
329 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
330 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
331 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
335 $tb->note("Auto checked $refs_traced references for leaks - none detected");
338 # also while we are here and not in plain runmode: make sure we never
339 # loaded any of the strictures XS bullshit (it's a leak in a sense)
341 $ENV{MOO_FATAL_WARNINGS}
343 # FIXME - SQLT loads strictures explicitly, /facedesk
344 # remove this INC check when 0fb58589 and 45287c815 are rectified
345 $INC{'SQL/Translator.pm'}
347 DBICTest::RunMode->is_plain
349 for (qw(indirect multidimensional bareword::filehandles)) {
350 exists $INC{ Module::Runtime::module_notional_filename($_) }
352 $tb->ok(0, "$_ load should not have been attempted!!!" )