Proper fix for the lazy workaround in 7e1774f7
[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 qw(refcount hrefaddr refdesc);
9 use DBIx::Class::Optional::Dependencies;
10 use Data::Dumper::Concise;
11 use DBICTest::Util qw( stacktrace visit_namespaces );
12 use constant {
13   CV_TRACING => !DBICTest::RunMode->is_plain && DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy'),
14 };
15
16 use base 'Exporter';
17 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
18
19 my $refs_traced = 0;
20 my $leaks_found = 0;
21 my %reg_of_regs;
22
23 sub populate_weakregistry {
24   my ($weak_registry, $target, $note) = @_;
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
29   my $refaddr = hrefaddr $target;
30
31   # a registry could be fed to itself or another registry via recursive sweeps
32   return $target if $reg_of_regs{$refaddr};
33
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
45   if (! defined $weak_registry->{$refaddr}{weakref}) {
46     $weak_registry->{$refaddr} = {
47       stacktrace => stacktrace(1),
48       weakref => $target,
49     };
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};
56   }
57
58   my $desc = refdesc $target;
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
65   $target;
66 }
67
68 # Regenerate the slots names on a thread spawn
69 sub CLONE {
70   my @individual_regs = grep { scalar keys %{$_||{}} } values %reg_of_regs;
71   %reg_of_regs = ();
72
73   for my $reg (@individual_regs) {
74     my @live_slots = grep { defined $_->{weakref} } values %$reg
75       or next;
76
77     $reg = {};  # get a fresh hashref in the new thread ctx
78     weaken( $reg_of_regs{hrefaddr($reg)} = $reg );
79
80     for my $slot_info (@live_slots) {
81       my $new_addr = hrefaddr $slot_info->{weakref};
82
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}} };
89
90       $reg->{$new_addr} = $slot_info;
91     }
92   }
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;
98 }
99
100 sub 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}} ) {
107
108     next unless length ref $args->{refs}[$i]; # not-a-ref
109
110     my $addr = hrefaddr $args->{refs}[$i];
111
112     # no diving into weakregistries
113     next if $reg_of_regs{$addr};
114
115     next if $args->{seen_refs}{$addr}++;
116     $visited_cnt++;
117
118     my $r = $args->{refs}[$i];
119
120     $args->{action}->($r) or next;
121
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
128     my $type = reftype $r;
129
130     local $@;
131     eval {
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($_) ) ? $_ : ()
148         } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
149       }
150       1;
151     } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
152   }
153   $visited_cnt;
154 }
155
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
158 sub symtable_referenced_addresses {
159
160   my $refs_per_pkg;
161
162   my $seen_refs = {};
163   visit_namespaces(
164     action => sub {
165
166       no strict 'refs';
167
168       my $pkg = shift;
169
170       # the unless regex at the end skips some dangerous namespaces outright
171       # (but does not prevent descent)
172       $refs_per_pkg->{$pkg} += visit_refs (
173         seen_refs => $seen_refs,
174
175         action => sub { 1 },
176
177         refs => [ map { my $sym = $_;
178           # *{"${pkg}::$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
179           ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}::$sym") : () ),
180
181           ( defined *{"${pkg}::$sym"}{SCALAR} and length ref ${"${pkg}::$sym"} and ! isweak( ${"${pkg}::$sym"} ) )
182             ? ${"${pkg}::$sym"} : ()
183           ,
184
185           ( map {
186             ( defined *{"${pkg}::$sym"}{$_} and ! isweak(defined *{"${pkg}::$sym"}{$_}) )
187               ? *{"${pkg}::$sym"}{$_}
188               : ()
189           } qw(HASH ARRAY IO GLOB) ),
190
191         } keys %{"${pkg}::"} ],
192       ) unless $pkg =~ /^ (?:
193         DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
194       ) $/x;
195     }
196   );
197
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
209 sub 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;
215   *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : CORE::caller() ) };
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;
223
224   my $tb = eval { Test::Builder->new }
225     or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
226
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
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   ;
257
258   for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
259
260     next if ! defined $weak_registry->{$addr}{weakref};
261
262     $leaks_found++ unless $tb->in_todo;
263     $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
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       ;
276     };
277
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
281     $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
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);
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 #
301 #      require POSIX;
302 #      POSIX::_exit(1);
303 #    }
304   }
305
306   if (! $quiet and !$leaks_found and ! $tb->in_todo) {
307     $tb->ok(1, sprintf "No leaks found at %s line %d", (CORE::caller())[1,2] );
308   }
309 }
310
311 END {
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   ) {
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     }
335
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)
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     ) {
347       for (qw(indirect multidimensional bareword::filehandles)) {
348         exists $INC{ Module::Runtime::module_notional_filename($_) }
349           and
350         $tb->ok(0, "$_ load should not have been attempted!!!" )
351       }
352     }
353   }
354 }
355
356 1;