Switch several caller() invocations to explicit CORE::caller()
[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
95 sub visit_refs {
96   my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
97
98   $args->{seen_refs} ||= {};
99
100   my $visited_cnt = '0E0';
101   for my $i (0 .. $#{$args->{refs}} ) {
102
103     next unless length ref $args->{refs}[$i]; # not-a-ref
104
105     my $addr = hrefaddr $args->{refs}[$i];
106
107     # no diving into weakregistries
108     next if $reg_of_regs{$addr};
109
110     next if $args->{seen_refs}{$addr}++;
111     $visited_cnt++;
112
113     my $r = $args->{refs}[$i];
114
115     $args->{action}->($r) or next;
116
117     # This may end up being necessarry some day, but do not slow things
118     # down for now
119     #if ( defined( my $t = tied($r) ) ) {
120     #  $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
121     #}
122
123     my $type = reftype $r;
124
125     local $@;
126     eval {
127       if ($type eq 'HASH') {
128         $visited_cnt += visit_refs({ %$args, refs => [ map {
129           ( !isweak($r->{$_}) ) ? $r->{$_} : ()
130         } keys %$r ] });
131       }
132       elsif ($type eq 'ARRAY') {
133         $visited_cnt += visit_refs({ %$args, refs => [ map {
134           ( !isweak($r->[$_]) ) ? $r->[$_] : ()
135         } 0..$#$r ] });
136       }
137       elsif ($type eq 'REF' and !isweak($$r)) {
138         $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
139       }
140       elsif (CV_TRACING and $type eq 'CODE') {
141         $visited_cnt += visit_refs({ %$args, refs => [ map {
142           ( !isweak($_) ) ? $_ : ()
143         } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
144       }
145       1;
146     } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
147   }
148   $visited_cnt;
149 }
150
151 # compiles a list of addresses stored as globals (possibly even catching
152 # class data in the form of method closures), so we can skip them further on
153 sub symtable_referenced_addresses {
154
155   my $refs_per_pkg;
156
157   my $seen_refs = {};
158   visit_namespaces(
159     action => sub {
160
161       no strict 'refs';
162
163       my $pkg = shift;
164
165       # the unless regex at the end skips some dangerous namespaces outright
166       # (but does not prevent descent)
167       $refs_per_pkg->{$pkg} += visit_refs (
168         seen_refs => $seen_refs,
169
170         action => sub { 1 },
171
172         refs => [ map { my $sym = $_;
173           # *{"${pkg}::$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
174           ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}::$sym") : () ),
175
176           ( defined *{"${pkg}::$sym"}{SCALAR} and length ref ${"${pkg}::$sym"} and ! isweak( ${"${pkg}::$sym"} ) )
177             ? ${"${pkg}::$sym"} : ()
178           ,
179
180           ( map {
181             ( defined *{"${pkg}::$sym"}{$_} and ! isweak(defined *{"${pkg}::$sym"}{$_}) )
182               ? *{"${pkg}::$sym"}{$_}
183               : ()
184           } qw(HASH ARRAY IO GLOB) ),
185
186         } keys %{"${pkg}::"} ],
187       ) unless $pkg =~ /^ (?:
188         DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
189       ) $/x;
190     }
191   );
192
193 #  use Devel::Dwarn;
194 #  Ddie [ map
195 #    { { $_ => $refs_per_pkg->{$_} } }
196 #    sort
197 #      {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
198 #      keys %$refs_per_pkg
199 #  ];
200
201   $seen_refs;
202 }
203
204 sub assert_empty_weakregistry {
205   my ($weak_registry, $quiet) = @_;
206
207   # in case we hooked bless any extra object creation will wreak
208   # havoc during the assert phase
209   local *CORE::GLOBAL::bless;
210   *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : CORE::caller() ) };
211
212   croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
213
214   defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
215     for keys %$weak_registry;
216
217   return unless keys %$weak_registry;
218
219   my $tb = eval { Test::Builder->new }
220     or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
221
222   for my $addr (keys %$weak_registry) {
223     $weak_registry->{$addr}{display_name} = join ' | ', (
224       sort
225         { length $a <=> length $b or $a cmp $b }
226         keys %{$weak_registry->{$addr}{slot_names}}
227     );
228
229     $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
230       if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
231   }
232
233   # the symtable walk is very expensive
234   # if we are $quiet (running in an END block) we do not really need to be
235   # that thorough - can get by with only %Sub::Quote::QUOTED
236   delete $weak_registry->{$_} for $quiet
237     ? do {
238       my $refs = {};
239       visit_refs (
240         # only look at the closed over stuffs
241         refs => [ grep { length ref $_ } map { values %{$_->[2]} } grep { ref $_ eq 'ARRAY' } values %Sub::Quote::QUOTED ],
242         seen_refs => $refs,
243         action => sub { 1 },
244       );
245       keys %$refs;
246     }
247     : (
248       # full sumtable walk, starting from ::
249       keys %{ symtable_referenced_addresses() }
250     )
251   ;
252
253   for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
254
255     next if ! defined $weak_registry->{$addr}{weakref};
256
257     $leaks_found++ unless $tb->in_todo;
258     $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
259
260     my $diag = do {
261       local $Data::Dumper::Maxdepth = 1;
262       sprintf "\n%s (refcnt %d) => %s\n",
263         $weak_registry->{$addr}{display_name},
264         refcount($weak_registry->{$addr}{weakref}),
265         (
266           ref($weak_registry->{$addr}{weakref}) eq 'CODE'
267             and
268           B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
269         ) ? '__XSUB__' : Dumper( $weak_registry->{$addr}{weakref} )
270       ;
271     };
272
273     # FIXME - need to add a circular reference seeker based on the visitor
274     # (will need a bunch of modifications, punting with just a stub for now)
275
276     $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
277       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
278
279     $diag =~ s/^/    /mg;
280
281     if (my $stack = $weak_registry->{$addr}{stacktrace}) {
282       $diag .= "    Reference first seen$stack";
283     }
284
285     $tb->diag($diag);
286
287 #    if ($leaks_found == 1) {
288 #      # using the fh dumper due to intermittent buffering issues
289 #      # in case we decide to exit soon after (possibly via _exit)
290 #      require Devel::MAT::Dumper;
291 #      local $Devel::MAT::Dumper::MAX_STRING = -1;
292 #      open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
293 #      Devel::MAT::Dumper::dumpfh( $fh );
294 #      close ($fh) or die $!;
295 #
296 #      require POSIX;
297 #      POSIX::_exit(1);
298 #    }
299   }
300
301   if (! $quiet and !$leaks_found and ! $tb->in_todo) {
302     $tb->ok(1, sprintf "No leaks found at %s line %d", (CORE::caller())[1,2] );
303   }
304 }
305
306 END {
307   if (
308     $INC{'Test/Builder.pm'}
309       and
310     my $tb = do {
311       local $@;
312       my $t = eval { Test::Builder->new }
313         or warn "Test::Builder->new failed:\n$@\n";
314       $t;
315     }
316   ) {
317     # we check for test passage - a leak may be a part of a TODO
318     if ($leaks_found and !$tb->is_passing) {
319
320       $tb->diag(sprintf
321         "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
322       . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
323       . "\n\n%s\n%s\n\n", ('#' x 16) x 4
324       ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
325
326     }
327     else {
328       $tb->note("Auto checked $refs_traced references for leaks - none detected");
329     }
330
331     # also while we are here and not in plain runmode: make sure we never
332     # loaded any of the strictures XS bullshit (it's a leak in a sense)
333     unless (
334       $ENV{MOO_FATAL_WARNINGS}
335         or
336       # FIXME - SQLT loads strictures explicitly, /facedesk
337       # remove this INC check when 0fb58589 and 45287c815 are rectified
338       $INC{'SQL/Translator.pm'}
339         or
340       DBICTest::RunMode->is_plain
341     ) {
342       for (qw(indirect multidimensional bareword::filehandles)) {
343         exists $INC{ Module::Runtime::module_notional_filename($_) }
344           and
345         $tb->ok(0, "$_ load should not have been attempted!!!" )
346       }
347     }
348   }
349 }
350
351 1;