Change the leaktracer to no longer rely on %Sub::Quote::QUOTED
[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 ANFANG;
7 use Carp;
8 use Scalar::Util qw(isweak weaken blessed reftype);
9 use DBIx::Class::_Util qw(refcount hrefaddr refdesc dump_value visit_namespaces);
10 use DBICTest::RunMode;
11 use DBICTest::Util 'stacktrace';
12 use constant {
13   CV_TRACING => !!(
14     !DBICTest::RunMode->is_plain
15       &&
16     require DBIx::Class::Optional::Dependencies
17       &&
18     DBIx::Class::Optional::Dependencies->req_ok_for ('test_leaks_heavy')
19   ),
20 };
21
22 use base 'Exporter';
23 our @EXPORT_OK = qw(populate_weakregistry assert_empty_weakregistry visit_refs);
24
25 my $refs_traced = 0;
26 my $leaks_found = 0;
27 my %reg_of_regs;
28
29 sub populate_weakregistry {
30   my ($weak_registry, $target, $note) = @_;
31
32   croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
33   croak 'Target is not a reference' unless length ref $target;
34
35   my $refaddr = hrefaddr $target;
36
37   # a registry could be fed to itself or another registry via recursive sweeps
38   return $target if $reg_of_regs{$refaddr};
39
40   weaken( $reg_of_regs{ hrefaddr($weak_registry) } = $weak_registry )
41     unless( $reg_of_regs{ hrefaddr($weak_registry) } );
42
43   # an explicit "garbage collection" pass every time we store a ref
44   # if we do not do this the registry will keep growing appearing
45   # as if the traced program is continuously slowly leaking memory
46   for my $reg (values %reg_of_regs) {
47     (defined $reg->{$_}{weakref}) or delete $reg->{$_}
48       for keys %$reg;
49   }
50
51   return $target if (
52     DBIx::Class::_ENV_::BROKEN_WEAK_SCALARREF_VALUES
53       and
54     ref $target eq 'SCALAR'
55   );
56
57   if (! defined $weak_registry->{$refaddr}{weakref}) {
58
59     # replace slot entirely
60     $weak_registry->{$refaddr} = {
61       stacktrace => stacktrace(1),
62       weakref => $target,
63     };
64
65     weaken( $weak_registry->{$refaddr}{weakref} );
66
67     $refs_traced++;
68   }
69
70   my $desc = refdesc $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 DBICTest::__LeakTracer_iThreads_handler__::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   # Dummy NEXTSTATE ensuring the all temporaries on the stack are garbage
107   # collected before leaving this scope. Depending on the code above, this
108   # may very well be just a preventive measure guarding future modifications
109   undef;
110 }
111
112 sub visit_refs {
113   my $args = { (ref $_[0]) ? %{$_[0]} : @_ };
114
115   $args->{seen_refs} ||= {};
116
117   my $visited_cnt = '0E0';
118   for my $i (0 .. $#{$args->{refs}} ) {
119
120     next unless length ref $args->{refs}[$i]; # not-a-ref
121
122     my $addr = hrefaddr $args->{refs}[$i];
123
124     # no diving into weakregistries
125     next if $reg_of_regs{$addr};
126
127     next if $args->{seen_refs}{$addr}++;
128     $visited_cnt++;
129
130     my $r = $args->{refs}[$i];
131
132     $args->{action}->($r) or next;
133
134     # This may end up being necessarry some day, but do not slow things
135     # down for now
136     #if ( defined( my $t = tied($r) ) ) {
137     #  $visited_cnt += visit_refs({ %$args, refs => [ $t ] });
138     #}
139
140     my $type = reftype $r;
141
142     local $SIG{__DIE__} if $SIG{__DIE__};
143     local $@;
144     eval {
145       if ($type eq 'HASH') {
146         $visited_cnt += visit_refs({ %$args, refs => [ map {
147           ( !isweak($r->{$_}) ) ? $r->{$_} : ()
148         } keys %$r ] });
149       }
150       elsif ($type eq 'ARRAY') {
151         $visited_cnt += visit_refs({ %$args, refs => [ map {
152           ( !isweak($r->[$_]) ) ? $r->[$_] : ()
153         } 0..$#$r ] });
154       }
155       elsif ($type eq 'REF' and !isweak($$r)) {
156         $visited_cnt += visit_refs({ %$args, refs => [ $$r ] });
157       }
158       elsif (CV_TRACING and $type eq 'CODE') {
159         $visited_cnt += visit_refs({ %$args, refs => [ map {
160           ( !isweak($_) ) ? $_ : ()
161         } values %{ scalar PadWalker::closed_over($r) } ] }); # scalar due to RT#92269
162       }
163       1;
164     } or warn "Could not descend into @{[ refdesc $r ]}: $@\n";
165   }
166   $visited_cnt;
167 }
168
169 # compiles a list of addresses stored as globals (possibly even catching
170 # class data in the form of method closures), so we can skip them further on
171 sub symtable_referenced_addresses {
172
173   my $refs_per_pkg;
174
175   my $seen_refs = {};
176   visit_namespaces(
177     action => sub {
178
179       no strict 'refs';
180
181       my $pkg = shift;
182
183       # the unless regex at the end skips some dangerous namespaces outright
184       # (but does not prevent descent)
185       $refs_per_pkg->{$pkg} += visit_refs (
186         seen_refs => $seen_refs,
187
188         action => sub { 1 },
189
190         refs => [ map { my $sym = $_;
191           # *{"${pkg}::$sym"}{CODE} won't simply work - MRO-cached CVs are invisible there
192           ( CV_TRACING ? Class::MethodCache::get_cv("${pkg}::$sym") : () ),
193
194           ( defined *{"${pkg}::$sym"}{SCALAR} and length ref ${"${pkg}::$sym"} and ! isweak( ${"${pkg}::$sym"} ) )
195             ? ${"${pkg}::$sym"} : ()
196           ,
197
198           ( map {
199             ( defined *{"${pkg}::$sym"}{$_} and ! isweak(defined *{"${pkg}::$sym"}{$_}) )
200               ? *{"${pkg}::$sym"}{$_}
201               : ()
202           } qw(HASH ARRAY IO GLOB) ),
203
204         } keys %{"${pkg}::"} ],
205       ) unless $pkg =~ /^ (?:
206         DB | next | B | .+? ::::ISA (?: ::CACHE ) | Class::C3
207       ) $/x;
208     }
209   );
210
211 #  use Devel::Dwarn;
212 #  Ddie [ map
213 #    { { $_ => $refs_per_pkg->{$_} } }
214 #    sort
215 #      {$refs_per_pkg->{$a} <=> $refs_per_pkg->{$b} }
216 #      keys %$refs_per_pkg
217 #  ];
218
219   $seen_refs;
220 }
221
222 sub assert_empty_weakregistry {
223   my ($weak_registry, $quiet) = @_;
224
225   # in case we hooked bless any extra object creation will wreak
226   # havoc during the assert phase
227   local *CORE::GLOBAL::bless;
228   *CORE::GLOBAL::bless = sub { CORE::bless( $_[0], (@_ > 1) ? $_[1] : CORE::caller() ) };
229
230   croak 'Expecting a registry hashref' unless ref $weak_registry eq 'HASH';
231
232   defined $weak_registry->{$_}{weakref} or delete $weak_registry->{$_}
233     for keys %$weak_registry;
234
235   return unless keys %$weak_registry;
236
237   my $tb = eval { Test::Builder->new }
238     or croak "Calling assert_empty_weakregistry in $0 without a loaded Test::Builder makes no sense";
239
240   for my $addr (keys %$weak_registry) {
241     $weak_registry->{$addr}{display_name} = join ' | ', (
242       sort
243         { length $a <=> length $b or $a cmp $b }
244         keys %{$weak_registry->{$addr}{slot_names}}
245     );
246
247     $tb->BAILOUT("!!!! WEAK REGISTRY SLOT $weak_registry->{$addr}{display_name} IS NOT A WEAKREF !!!!")
248       if defined $weak_registry->{$addr}{weakref} and ! isweak( $weak_registry->{$addr}{weakref} );
249   }
250
251   # the symtable walk is very expensive
252   # if we are $quiet (running in an END block) we do not really need to be
253   # that thorough - can get by with our own registry
254   delete $weak_registry->{$_} for $quiet
255     ? do {
256       my $refs = {};
257       visit_refs (
258         # only look at the closed over stuffs
259         refs => [ values %DBIx::Class::_Util::refs_closed_over_by_quote_sub_installed_crefs ],
260         seen_refs => $refs,
261         action => sub { 1 },
262       );
263       keys %$refs;
264     }
265     : (
266       # full sumtable walk, starting from ::
267       keys %{ symtable_referenced_addresses() }
268     )
269   ;
270
271   for my $addr (sort { $weak_registry->{$a}{display_name} cmp $weak_registry->{$b}{display_name} } keys %$weak_registry) {
272
273     next if ! defined $weak_registry->{$addr}{weakref};
274
275     $leaks_found++ unless $tb->in_todo;
276     $tb->ok (0, "Expected garbage collection of $weak_registry->{$addr}{display_name}");
277
278     my $diag = do {
279       local $Data::Dumper::Maxdepth = 1;
280       sprintf "\n%s (refcnt %d) => %s\n",
281         $weak_registry->{$addr}{display_name},
282         refcount($weak_registry->{$addr}{weakref}),
283         (
284           ref($weak_registry->{$addr}{weakref}) eq 'CODE'
285             and
286           B::svref_2object($weak_registry->{$addr}{weakref})->XSUB
287         ) ? '__XSUB__' : dump_value $weak_registry->{$addr}{weakref}
288       ;
289     };
290
291     # FIXME - need to add a circular reference seeker based on the visitor
292     # (will need a bunch of modifications, punting with just a stub for now)
293
294     $diag .= Devel::FindRef::track ($weak_registry->{$addr}{weakref}, 50) . "\n"
295       if ( $ENV{TEST_VERBOSE} && eval { require Devel::FindRef });
296
297     $diag =~ s/^/    /mg;
298
299     if (my $stack = $weak_registry->{$addr}{stacktrace}) {
300       $diag .= "    Reference first seen$stack";
301     }
302
303     $tb->diag($diag);
304
305 #    if ($leaks_found == 1) {
306 #      # using the fh dumper due to intermittent buffering issues
307 #      # in case we decide to exit soon after (possibly via _exit)
308 #      require Devel::MAT::Dumper;
309 #      local $Devel::MAT::Dumper::MAX_STRING = -1;
310 #      open( my $fh, '>:raw', "leaked_${addr}_pid$$.pmat" ) or die $!;
311 #      Devel::MAT::Dumper::dumpfh( $fh );
312 #      close ($fh) or die $!;
313 #
314 #      require POSIX;
315 #      POSIX::_exit(1);
316 #    }
317   }
318
319   if (! $quiet and !$leaks_found and ! $tb->in_todo) {
320     $tb->ok(1, sprintf "No leaks found at %s line %d", (CORE::caller())[1,2] );
321   }
322 }
323
324 END {
325   if (
326     $INC{'Test/Builder.pm'}
327       and
328     my $tb = do {
329       local $@;
330       my $t = eval { Test::Builder->new }
331         or warn "Test::Builder->new failed:\n$@\n";
332       $t;
333     }
334   ) {
335     # we check for test passage - a leak may be a part of a TODO
336     if ($leaks_found and !$tb->is_passing) {
337
338       $tb->diag(sprintf
339         "\n\n%s\n%s\n\nInstall Devel::FindRef and re-run the test with set "
340       . '$ENV{TEST_VERBOSE} (prove -v) to see a more detailed leak-report'
341       . "\n\n%s\n%s\n\n", ('#' x 16) x 4
342       ) if ( !$ENV{TEST_VERBOSE} or !$INC{'Devel/FindRef.pm'} );
343
344     }
345     else {
346       $tb->note("Auto checked $refs_traced references for leaks - none detected");
347     }
348
349     # also while we are here and not in plain runmode: make sure we never
350     # loaded any of the strictures XS bullshit (it's a leak in a sense)
351     unless (
352       $ENV{MOO_FATAL_WARNINGS}
353         or
354       # FIXME - SQLT loads strictures explicitly, /facedesk
355       # remove this INC check when 0fb58589 and 45287c815 are rectified
356       $INC{'SQL/Translator.pm'}
357         or
358       DBICTest::RunMode->is_plain
359     ) {
360       for (qw(indirect multidimensional bareword::filehandles)) {
361         exists $INC{ Module::Runtime::module_notional_filename($_) }
362           and
363         $tb->ok(0, "$_ load should not have been attempted!!!" )
364       }
365     }
366   }
367 }
368
369 1;