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'),
17 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
23 sub populate_weakregistry {
24 my ($weak_registry, $target, $note) = @_;
26 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
27 croak 'Target is not a reference' unless length ref $target;
29 my $refaddr = hrefaddr $target;
31 # a registry could be fed to itself or another registry via recursive sweeps
32 return $target if $reg_of_regs{$refaddr};
34 weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
35 unless( $reg_of_regs{ hrefaddr($weak_registry) } );
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->{$_}
45 if (! defined $weak_registry->{$refaddr}{weakref}) {
46 $weak_registry->{$refaddr} = {
47 stacktrace => stacktrace(1),
50 weaken( $weak_registry->{$refaddr}{weakref} );
54 my $desc = refdesc $target;
55 $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
57 $note =~ s/\s*\Q$desc\E\s*//g;
58 $weak_registry->{$refaddr}{slot_names}{$note} = 1;
64 # Regenerate the slots names on a thread spawn
66 my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
69 for my $reg (@individual_regs) {
70 my @live_slots = grep { defined $_->{weakref} } values %$reg
73 $reg = {}; # get a fresh hashref in the new thread ctx
74 weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
76 for my $slot_info (@live_slots) {
77 my $new_addr = hrefaddr $slot_info->{weakref};
79 # replace all slot names
80 $slot_info->{slot_names} = { map {
82 $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
84 } keys %{$slot_info->{slot_names}} };
86 $reg->{$new_addr} = $slot_info;
92 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
94 $args->{seen_refs} ||= {};
96 my $visited_cnt = '0E0';
97 for my $i (0 .. $#{$args->{refs}} ) {
99 next unless length ref $args->{refs}[$i]; # not-a-ref
101 my $addr = hrefaddr $args->{refs}[$i];
103 # no diving into weakregistries
104 next if $reg_of_regs{$addr};
106 next if $args->{seen_refs}{$addr}++;
109 my $r = $args->{refs}[$i];
111 $args->{action}->($r) or next;
113 # This may end up being necessarry some day, but do not slow things
115 #if ( defined( my $t = tied($r) ) ) {
116 # $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
119 my $type = reftype $r;
123 if ($type eq 'HASH') {
124 $visited_cnt += visit_refs({ %$args, refs => [ map {
125 ( !isweak($r->{$_}) ) ? $r->{$_} : ()
128 elsif ($type eq 'ARRAY') {
129 $visited_cnt += visit_refs({ %$args, refs => [ map {
130 ( !isweak($r->[$_]) ) ? $r->[$_] : ()
133 elsif ($type eq 'REF' and !isweak($$r)) {
134 $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
136 elsif (CV_TRACING and $type eq 'CODE') {
137 $visited_cnt += visit_refs({ %$args, refs => [ map {
138 ( !isweak($_) ) ? $_ : ()
139 } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
142 } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
147 sub visit_namespaces {
148 my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
152 $args->{package} ||= '::';
153 $args->{package} = '::' if $args->{package} eq 'main';
155 if ( $args->{action}->($args->{package}) ) {
157 my $base = $args->{package};
158 $base = '' if $base eq '::';
161 $visited += visit_namespaces({ %$args, package => $_ }) for map
162 { $_ =~ /(.+?)::$/ ? "${base}::$1" : () }
164 { $_ =~ /(?<!^main)::$/ }
165 do { no strict 'refs'; keys %{ $base . '::'} }
171 # compiles a list of addresses stored as globals (possibly even catching
172 # class data in the form of method closures), so we can skip them further on
173 sub symtable_referenced_addresses {
184 $pkg = '' if $pkg eq '::';
187 # the unless regex at the end skips some dangerous namespaces outright
188 # (but does not prevent descent)
189 $refs_per_pkg->{$pkg} += visit_refs (
190 seen_refs => $seen_refs,
194 refs => [ map { my $sym = $_;
195 # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
196 ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
198 ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
203 ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
206 } qw(HASH ARRAY IO GLOB) ),
209 ) unless $pkg =~ /^ :: (?:
210 DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
217 # { { $_ => $refs_per_pkg->{$_} } }
219 # {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
220 # keys %$refs_per_pkg
226 sub assert_empty_weakregistry {
227 my ($weak_registry, $quiet) = @_;
229 Sub::Defer::undefer_all();
231 # in case we hooked bless any extra object creation will wreak
232 # havoc during the assert phase
233 local *CORE::GLOBAL::bless;
234 *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
236 croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
238 defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
239 for keys %$weak_registry;
241 return unless keys %$weak_registry;
243 my $tb = eval { Test::Builder->new }
244 or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
246 for my $addr (keys %$weak_registry) {
247 $weak_registry->{$addr}{display_name} = join ' | ', (
249 { length $a <=> length $b or $a cmp $b }
250 keys %{$weak_registry->{$addr}{slot_names}}
253 $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
254 if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
257 # the symtable walk is very expensive
258 # if we are $quiet (running in an END block) we do not really need to be
259 # that thorough - can get by with only %Sub::Quote::QUOTED
260 delete $weak_registry->{$_} for $quiet
264 # only look at the closed over stuffs
265 refs => [ grep { length ref $_ } map { values %{$_->[2]} } grep { ref $_ eq 'ARRAY' } values %Sub::Quote::QUOTED ],
272 # full sumtable walk, starting from ::
273 keys %{ symtable_referenced_addresses() }
277 for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
279 next if ! defined $weak_registry->{$addr}{weakref};
281 $leaks_found++ unless $tb->in_todo;
282 $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
285 local $Data::Dumper::Maxdepth = 1;
286 sprintf "\n%s (refcnt %d) => %s\n",
287 $weak_registry->{$addr}{display_name},
288 refcount($weak_registry->{$addr}{weakref}),
290 ref($weak_registry->{$addr}{weakref}) eq 'CODE'
292 B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
293 ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
297 # FIXME - need to add a circular reference seeker based on the visitor
298 # (will need a bunch of modifications, punting with just a stub for now)
300 $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
301 if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
305 if (my $stack = $weak_registry->{$addr}{stacktrace}) {
306 $diag .= " Reference first seen$stack";
311 # if ($leaks_found == 1) {
312 # # using the fh dumper due to intermittent buffering issues
313 # # in case we decide to exit soon after (possibly via _exit)
314 # require Devel::MAT::Dumper;
315 # local $Devel::MAT::Dumper::MAX_STRING = -1;
316 # open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
317 # Devel::MAT::Dumper::dumpfh( $fh );
318 # close ($fh) or die $!;
325 if (! $quiet and !$leaks_found and ! $tb->in_todo) {
326 $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
332 $INC{'Test/Builder.pm'}
336 my $t = eval { Test::Builder->new }
337 or warn "Test::Builder->new failed:\n$@\n";
341 # we check for test passage - a leak may be a part of a TODO
342 if ($leaks_found and !$tb->is_passing) {
345 "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
346 . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
347 . "\n\n%s\n%s\n\n", ('#' x 16) x 4
348 ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
352 $tb->note("Auto checked $refs_traced references for leaks - none detected");
355 # also while we are here and not in plain runmode: make sure we never
356 # loaded any of the strictures XS bullshit (it's a leak in a sense)
358 $ENV{MOO_FATAL_WARNINGS}
360 # FIXME - SQLT loads strictures explicitly, /facedesk
361 # remove this INC check when 0fb58589 and 45287c815 are rectified
362 $INC{'SQL/Translator.pm'}
364 DBICTest::RunMode->is_plain
366 for (qw(indirect multidimensional bareword::filehandles)) {
367 exists $INC{ Module::Runtime::module_notional_filename($_) }
369 $tb->ok(0, "$_ load should not have been attempted!!!" )