718a0aad396040881042e2f989bc169d5ea678d1
[dbsrgits/DBIx-Class.git] / t / lib / DBICTest / Util / LeakTracer.pm
1 package DBICTest::Util::LeakTracer;
2
3 use warnings;
4 use strict;
5
6 use Carp;
7 use Scalar::Util qw(isweak weaken blessed reftype);
8 use DBIx::Class::_Util 'refcount';
9 use DBIx::Class::Optional::Dependencies;
10 use Data::Dumper::Concise;
11 use DBICTest::Util 'stacktrace';
12 use constant {
13   CV_TRACING => DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
14   SKIP_SCALAR_REFS => ( $] > 5.017 ) ? 1 : 0,
15 };
16
17 use base 'Exporter';
18 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry hrefaddr visit_refs);
19
20 my $refs_traced = 0;
21 my $leaks_found = 0;
22 my %reg_of_regs;
23
24 sub hrefaddr { sprintf '0x%x', &Scalar::Util::refaddr }
25
26 # so we don't trigger stringification
27 sub _describe_ref {
28   sprintf '%s%s(%s)',
29     (defined blessed $_[0]) ? blessed($_[0]) . '=' : '',
30     reftype $_[0],
31     hrefaddr $_[0],
32   ;
33 }
34
35 sub populate_weakregistry {
36   my ($weak_registry, $target, $note) = @_;
37
38   croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
39   croak 'Target is not a reference' unless length ref $target;
40
41   my $refaddr = hrefaddr $target;
42
43   # a registry could be fed to itself or another registry via recursive sweeps
44   return $target if $reg_of_regs{$refaddr};
45
46   weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
47     unless( $reg_of_regs{ hrefaddr($weak_registry) } );
48
49   # an explicit "garbage collection" pass every time we store a ref
50   # if we do not do this the registry will keep growing appearing
51   # as if the traced program is continuously slowly leaking memory
52   for my $reg (values %reg_of_regs) {
53     (defined $reg->{$_}{weakref}) or delete $reg->{$_}
54       for keys %$reg;
55   }
56
57   # FIXME/INVESTIGATE - something fishy is going on with refs to plain
58   # strings, perhaps something to do with the CoW work etc...
59   return $target if SKIP_SCALAR_REFS and reftype($target) eq 'SCALAR';
60
61   if (! defined $weak_registry->{$refaddr}{weakref}) {
62     $weak_registry->{$refaddr} = {
63       stacktrace => stacktrace(1),
64       weakref => $target,
65     };
66     weaken( $weak_registry->{$refaddr}{weakref} );
67     $refs_traced++;
68   }
69
70   my $desc = _describe_ref($target);
71   $weak_registry->{$refaddr}{slot_names}{$desc} = 1;
72   if ($note) {
73     $note =~ s/\s*\Q$desc\E\s*//g;
74     $weak_registry->{$refaddr}{slot_names}{$note} = 1;
75   }
76
77   $target;
78 }
79
80 # Regenerate the slots names on a thread spawn
81 sub CLONE {
82   my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
83   %reg_of_regs = ();
84
85   for my $reg (@individual_regs) {
86     my @live_slots = grep { defined $_->{weakref} } values %$reg
87       or next;
88
89     $reg = {};  # get a fresh hashref in the new thread ctx
90     weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
91
92     for my $slot_info (@live_slots) {
93       my $new_addr = hrefaddr $slot_info->{weakref};
94
95       # replace all slot names
96       $slot_info->{slot_names} = { map {
97         my $name = $_;
98         $name =~ s/\(0x[0-9A-F]+\)/sprintf ('(%s)', $new_addr)/ieg;
99         ($name => 1);
100       } keys %{$slot_info->{slot_names}} };
101
102       $reg->{$new_addr} = $slot_info;
103     }
104   }
105 }
106
107 sub 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}} ) {
114     next if isweak($args->{refs}[$i]);
115
116     my $r = $args->{refs}[$i];
117
118     next unless length ref $r;
119
120     # no diving into weakregistries
121     next if $reg_of_regs{hrefaddr $r};
122
123     next if $args->{seen_refs}{my $dec_addr = Scalar::Util::refaddr($r)}++;
124
125     $visited_cnt++;
126     $args->{action}->($r) or next;
127
128     # This may end up being necessarry some day, but do not slow things
129     # down for now
130     #if ( defined( my $t = tied($r) ) ) {
131     #  $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
132     #}
133
134     local $@;
135     eval {
136       my $type = reftype $r;
137       if ($type eq 'HASH') {
138         $visited_cnt += visit_refs({ %$args, refs => [ map {
139           ( !isweak($r->{$_}) ) ? $r->{$_} : ()
140         } keys %$r ] });
141       }
142       elsif ($type eq 'ARRAY') {
143         $visited_cnt += visit_refs({ %$args, refs => [ map {
144           ( !isweak($r->[$_]) ) ? $r->[$_] : ()
145         } 0..$#$r ] });
146       }
147       elsif ($type eq 'REF' and !isweak($$r)) {
148         $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
149       }
150       elsif (CV_TRACING and $type eq 'CODE') {
151         $visited_cnt += visit_refs({ %$args, refs => [ map {
152           ( !isweak($_) ) ? $_ : ()
153         } scalar PadWalker::closed_over($r) ] }); # scalar due to RT#92269
154       }
155       1;
156     } or warn "Could not descend into @{[ _describe_ref($r) ]}: $@\n";
157   }
158   $visited_cnt;
159 }
160
161 sub assert_empty_weakregistry {
162   my ($weak_registry, $quiet) = @_;
163
164   # in case we hooked bless any extra object creation will wreak
165   # havoc during the assert phase
166   local *CORE::GLOBAL::bless;
167   *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : caller() ) };
168
169   croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
170
171   return unless keys %$weak_registry;
172
173   my $tb = eval { Test::Builder->new }
174     or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
175
176   for my $addr (keys %$weak_registry) {
177     $weak_registry->{$addr}{display_name} = join ' | ', (
178       sort
179         { length $a <=> length $b or $a cmp $b }
180         keys %{$weak_registry->{$addr}{slot_names}}
181     );
182
183     $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
184       if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
185   }
186
187   # compile a list of refs stored as globals (possibly even catching
188   # class data in the form of method closures), so we can skip them
189   # further on
190   my ($seen_refs, $classdata_refs) = ({}, undef);
191
192   # the walk is very expensive - if we are $quiet (running in an END block)
193   # we do not really need to be too thorough
194   unless ($quiet) {
195     my ($symwalker, $symcounts);
196     $symwalker = sub {
197       no strict 'refs';
198       my $pkg = shift || '::';
199
200       # any non-weak globals are "clasdata" in all possible sense
201       #
202       # the unless regex at the end skips some dangerous namespaces outright
203       # (but does not prevent descent)
204       $symcounts->{$pkg} += visit_refs (
205         seen_refs => $seen_refs,
206         action => sub { ++$classdata_refs->{hrefaddr $_[0]} },
207         refs => [ map { my $sym = $_;
208           # *{"$pkg$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
209           ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}$sym") : () ),
210
211           ( defined *{"$pkg$sym"}{SCALAR} and length ref ${"$pkg$sym"} and ! isweak( ${"$pkg$sym"} ) )
212             ? ${"$pkg$sym"} : ()
213           ,
214           ( map {
215             ( defined *{"$pkg$sym"}{$_} and ! isweak(defined *{"$pkg$sym"}{$_}) )
216               ? *{"$pkg$sym"}{$_}
217               : ()
218           } qw(HASH ARRAY IO GLOB) ),
219         } keys %$pkg ],
220       ) unless $pkg =~ /^ :: (?:
221         DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
222       ) :: $/x;
223
224       $symwalker->("${pkg}$_") for grep { $_ =~ /(?<!^main)::$/ } keys %$pkg;
225     };
226
227     $symwalker->();
228
229 #    use Devel::Dwarn;
230 #    Ddie [ map
231 #      { { $_ => $symcounts->{$_} } }
232 #      sort
233 #        {$symcounts->{$a} <=> $symcounts->{$b} }
234 #        keys %$symcounts
235 #    ];
236   }
237
238   delete $weak_registry->{$_} for keys %$classdata_refs;
239
240   for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
241
242     next if ! defined $weak_registry->{$addr}{weakref};
243
244     $leaks_found++ unless $tb->in_todo;
245     $tb->ok (0, "Leaked $weak_registry->{$addr}{display_name}");
246
247     my $diag = do {
248       local $Data::Dumper::Maxdepth = 1;
249       sprintf "\n%s (refcnt %d) => %s\n",
250         $weak_registry->{$addr}{display_name},
251         refcount($weak_registry->{$addr}{weakref}),
252         (
253           ref($weak_registry->{$addr}{weakref}) eq 'CODE'
254             and
255           B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
256         ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
257       ;
258     };
259
260     # FIXME - need to add a circular reference seeker based on the visitor
261     # (will need a bunch of modifications, punting with just a stub for now)
262
263     $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
264       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
265
266     $diag =~ s/^/    /mg;
267
268     if (my $stack = $weak_registry->{$addr}{stacktrace}) {
269       $diag .= "    Reference first seen$stack";
270     }
271
272     $tb->diag($diag);
273
274 #    if ($leaks_found == 1) {
275 #      # using the fh dumper due to intermittent buffering issues
276 #      # in case we decide to exit soon after (possibly via _exit)
277 #      require Devel::MAT::Dumper;
278 #      local $Devel::MAT::Dumper::MAX_STRING = -1;
279 #      open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
280 #      Devel::MAT::Dumper::dumpfh( $fh );
281 #      close ($fh) or die $!;
282 #
283 #      use POSIX;
284 #      POSIX::_exit(1);
285 #    }
286   }
287
288   if (! $quiet and !$leaks_found and ! $tb->in_todo) {
289     $tb->ok(1, sprintf "No leaks found at %s line %d", (caller())[1,2] );
290   }
291 }
292
293 END {
294   if ($INC{'Test/Builder.pm'}) {
295     my $tb = Test::Builder->new;
296
297     # we check for test passage - a leak may be a part of a TODO
298     if ($leaks_found and !$tb->is_passing) {
299
300       $tb->diag(sprintf
301         "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
302       . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
303       . "\n\n%s\n%s\n\n", ('#' x 16) x 4
304       ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
305
306     }
307     else {
308       $tb->note("Auto checked $refs_traced references for leaks - none detected");
309     }
310   }
311 }
312
313 1;