1 package DBICTest::Util::LeakTracer;
7 use Scalar::Util qw(isweak weaken blessed reftype);
8 use DBIx::Class::_Util qw(refcount hrefaddr refdesc);
9 use DBIx::Class::Optional::Dependencies;
10 use Data::Dumper::Concise;
11 use DBICTest::Util 'stacktrace';
13 CV_TRACING => DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
14 SKIP_SCALAR_REFS => ( $] > 5.017 ) ? 1 : 0,
18 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
24 sub populate_weakregistry {
25 my ($weak_registry, $target, $note) = @_;
27 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
28 croak 'Target is not a reference' unless length ref $target;
30 my $refaddr = hrefaddr $target;
32 # a registry could be fed to itself or another registry via recursive sweeps
33 return $target if $reg_of_regs{$refaddr};
35 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
36 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
38 # an explicit "garbage collection" pass every time we store a ref
39 # if we do not do this the registry will keep growing appearing
40 # as if the traced program is continuously slowly leaking memory
41 for my $reg (values %reg_of_regs) {
42 (defined $reg->{$_}{weakref}) or delete $reg->{$_}
46 # FIXME/INVESTIGATE - something fishy is going on with refs to plain
47 # strings, perhaps something to do with the CoW work etc...
48 return $target if SKIP_SCALAR_REFS and reftype($target) eq 'SCALAR';
50 if (! defined $weak_registry->{$refaddr}{weakref}) {
51 $weak_registry->{$refaddr} = {
52 stacktrace => stacktrace(1),
55 weaken( $weak_registry->{$refaddr}{weakref} );
59 my $desc = refdesc $target;
60 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
62 $note =~ s/\s*\Q$desc\E\s*//g;
63 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
69 # Regenerate the slots names on a thread spawn
71 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
74 for my $reg (@individual_regs) {
75 my @live_slots = grep { defined $_->{weakref} } values %$reg
78 $reg = {}; # get a fresh hashref in the new thread ctx
79 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
81 for my $slot_info (@live_slots) {
82 my $new_addr = hrefaddr $slot_info->{weakref};
84 # replace all slot names
85 $slot_info->{slot_names} = { map {
87 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
89 } keys %{$slot_info->{slot_names}} };
91 $reg->{$new_addr} = $slot_info;
97 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
99 $args->{seen_refs} ||= {};
101 my $visited_cnt = '0E0';
102 for my $i (0 .. $#{$args->{refs}} ) {
104 next unless length ref $args->{refs}[$i]; # not-a-ref
106 my $addr = hrefaddr $args->{refs}[$i];
108 # no diving into weakregistries
109 next if $reg_of_regs{$addr};
111 next if $args->{seen_refs}{$addr}++;
114 my $r = $args->{refs}[$i];
116 $args->{action}->($r) or next;
118 # This may end up being necessarry some day, but do not slow things
120 #if ( defined( my $t = tied($r) ) ) {
121 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
124 my $type = reftype $r;
128 if ($type eq 'HASH') {
129 $visited_cnt += visit_refs({ %$args, refs => [ map {
130 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
133 elsif ($type eq 'ARRAY') {
134 $visited_cnt += visit_refs({ %$args, refs => [ map {
135 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
138 elsif ($type eq 'REF' and !isweak($$r)) {
139 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
141 elsif (CV_TRACING and $type eq 'CODE') {
142 $visited_cnt += visit_refs({ %$args, refs => [ map {
143 ( !isweak($_) ) ? $_ : ()
144 } scalar PadWalker::closed_over($r) ] }); # scalar due to RT#92269
147 } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
152 sub visit_namespaces {
153 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
157 $args->{package} ||= '::';
158 $args->{package} = '::' if $args->{package} eq 'main';
160 if ( $args->{action}->($args->{package}) ) {
162 my $base = $args->{package};
163 $base = '' if $base eq '::';
166 $visited += visit_namespaces({ %$args, package => $_ }) for map
167 { $_ =~ /(.+?)::$/ && "${base}::$1" }
169 { $_ =~ /(?<!^main)::$/ }
170 do { no strict 'refs'; keys %{ $base . '::'} }
176 # compiles a list of addresses stored as globals (possibly even catching
177 # class data in the form of method closures), so we can skip them further on
178 sub symtable_referenced_addresses {
182 my $dummy_addresslist;
191 $pkg = '' if $pkg eq '::';
194 # the unless regex at the end skips some dangerous namespaces outright
195 # (but does not prevent descent)
196 $refs_per_pkg->{$pkg} += visit_refs (
197 seen_refs => $seen_refs,
200 # This is so damn odd - if we feed a constsub {1} (or in fact almost
201 # anything other than the actionsub below, any scalarref will show
202 # up as a leak, trapped by... something...
203 # Ideally we should be able to const this to sub{1} and just return
204 # $seen_refs (in fact it is identical to the dummy list at the end of
205 # a run here). Alas this doesn't seem to work, so punt for now...
206 action => sub { ++$dummy_addresslist->{ hrefaddr $_[0] } },
208 refs => [ map { my $sym = $_;
209 # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
210 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
212 ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
217 ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
220 } qw(HASH ARRAY IO GLOB) ),
223 ) unless $pkg =~ /^ :: (?:
224 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
231 # { { $_ => $refs_per_pkg->{$_} } }
233 # {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
234 # keys %$refs_per_pkg
240 sub assert_empty_weakregistry {
241 my ($weak_registry, $quiet) = @_;
243 # in case we hooked bless any extra object creation will wreak
244 # havoc during the assert phase
245 local *CORE::GLOBAL::bless;
246 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
248 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
250 defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
251 for keys %$weak_registry;
253 return unless keys %$weak_registry;
255 my $tb = eval { Test::Builder->new }
256 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
258 for my $addr (keys %$weak_registry) {
259 $weak_registry->{$addr}{display_name} = join ' | ', (
261 { length $a <=> length $b or $a cmp $b }
262 keys %{$weak_registry->{$addr}{slot_names}}
265 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
266 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
269 # the walk is very expensive - if we are $quiet (running in an END block)
270 # we do not really need to be too thorough
272 delete $weak_registry->{$_} for keys %{ symtable_referenced_addresses() };
276 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
278 next if ! defined $weak_registry->{$addr}{weakref};
280 $leaks_found++ unless $tb->in_todo;
281 $tb->ok (0, "Leaked $weak_registry->{$addr}{display_name}");
284 local $Data::Dumper::Maxdepth = 1;
285 sprintf "\n%s (refcnt %d) => %s\n",
286 $weak_registry->{$addr}{display_name},
287 refcount($weak_registry->{$addr}{weakref}),
289 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
291 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
292 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
296 # FIXME - need to add a circular reference seeker based on the visitor
297 # (will need a bunch of modifications, punting with just a stub for now)
299 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
300 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
304 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
305 $diag .= " Reference first seen$stack";
310 # if ($leaks_found == 1) {
311 # # using the fh dumper due to intermittent buffering issues
312 # # in case we decide to exit soon after (possibly via _exit)
313 # require Devel::MAT::Dumper;
314 # local $Devel::MAT::Dumper::MAX_STRING = -1;
315 # open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
316 # Devel::MAT::Dumper::dumpfh( $fh );
317 # close ($fh) or die $!;
324 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
325 $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
330 if ($INC{'Test/Builder.pm'}) {
331 my $tb = Test::Builder->new;
333 # we check for test passage - a leak may be a part of a TODO
334 if ($leaks_found and !$tb->is_passing) {
337 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
338 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
339 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
340 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
344 $tb->note("Auto checked $refs_traced references for leaks - none detected");