File Coverage

blib/lib/Devel/LeakGuard/Object.pm
Criterion Covered Total %
statement 124 135 91.8
branch 36 56 64.2
condition 7 10 70.0
subroutine 24 26 92.3
pod 4 4 100.0
total 195 231 84.4


line stmt bran cond sub pod time code
1             package Devel::LeakGuard::Object;
2              
3 6     6   97360 use 5.008;
  6         22  
4              
5 6     6   34 use strict;
  6         12  
  6         1249  
6 6     6   32 use warnings;
  6         12  
  6         156  
7              
8 6     6   29 use Carp;
  6         11  
  6         449  
9 6     6   5563 use Data::Dumper;
  6         57240  
  6         414  
10 6     6   42 use Scalar::Util qw( blessed refaddr weaken );
  6         11  
  6         604  
11              
12 6     6   2522 use Devel::LeakGuard::Object::State;
  6         76  
  6         182  
13              
14 6     6   34 use base qw( Exporter );
  6         10  
  6         3778  
15              
16             our @EXPORT_OK = qw( track leakstate status leakguard );
17              
18             our %OPTIONS = (
19             at_end => 0,
20             stderr => 0
21             );
22              
23             our ( %DESTROY_NEXT, %DESTROY_ORIGINAL, %DESTROY_STUBBED, %OBJECT_COUNT,
24             %TRACKED );
25              
26             =encoding utf8
27              
28             =head1 NAME
29              
30             Devel::LeakGuard::Object - Scoped checks for object leaks
31              
32             =head1 VERSION
33              
34             This document describes Devel::LeakGuard::Object version 0.07
35              
36             =cut
37              
38             our $VERSION = '0.07';
39              
40             =head1 SYNOPSIS
41              
42             # Track a single object
43             use Devel::LeakGuard::Object;
44             my $obj = Foo::Bar->new;
45             Devel::LeakGuard::Object::track($obj);
46              
47             # Track every object
48             use Devel::LeakGuard::Object qw( GLOBAL_bless );
49              
50             # Track every object, summary at exit
51             use Devel::LeakGuard::Object qw( GLOBAL_bless :at_end );
52              
53             # Track a block of code, warning on leaks
54             leakguard {
55             # your potentially leaky code here
56             };
57              
58             # Track a block of code, die on leaks
59             leakguard {
60             # your potentially leaky code here
61             }
62             on_leak => 'die';
63              
64             =head1 DESCRIPTION
65              
66             This module provides tracking of objects, for the purpose of
67             detecting memory leaks due to circular references or innappropriate
68             caching schemes.
69              
70             It is derived from, and backwards compatible with Adam Kennedy's
71             L. Any errors are mine.
72              
73             It works by overridding C and adding a synthetic C
74             method to any tracked classes so that it can maintain a count of blessed
75             objects per-class.
76              
77             Object tracking can be enabled:
78              
79             =over
80              
81             =item * for an individual object
82              
83             =item * for a block of code
84              
85             =item * globally
86              
87             =back
88              
89             =head2 Tracking an individual object
90              
91             Track individual objects like this:
92              
93             use Devel::LeakGuard::Object qw( track );
94              
95             # Later...
96             track( my $obj = new Foo );
97              
98             =head2 Tracking object leaks in a block of code
99              
100             To detect any object leaks in a block of code:
101              
102             use Devel::LeakGuard::Object qw( leakguard );
103              
104             leakguard {
105             # your code here.
106             };
107              
108             =head2 Tracking global object leaks
109              
110             use Devel::LeakGuard::Object qw( GLOBAL_bless );
111              
112             =head2 Finding out what leaked
113              
114             If you use C (recommended) then by default a warning is
115             thrown when leaks are detected. You can customise this behaviour by
116             passing options to C; see the documentation for L
117             for more information.
118              
119             If you use C or C then you can also specify the
120             C<:at_end> option
121              
122             use Devel::LeakGuard::Object qw( GLOBAL_bless :at_end );
123              
124             in which case a summary of leaks will be displayed at program exit.
125              
126             =head2 Load early!
127              
128             C can only track allocations of objects
129             compiled after it is loaded - so load it as early as possible.
130              
131             =head2 What is a leak?
132              
133             This module counts the number of blessed instances of each tracked
134             class. When we talk about a 'leak' what we really mean here is an
135             imbalance in the number of allocated objects across some boundary. Using
136             this definition we see a leak even in the case of expected imbalances.
137              
138             When interpreting the results you need to remember that it may be quite
139             legitimate for certain allocations to live beyond the scope of the code
140             under test.
141              
142             You can use the various options that C supports to filter
143             out such legitimate allocations that live beyond the life of the block
144             being checked.
145              
146             =head2 Performance
147              
148             As soon as C is loaded C is overloaded.
149             That means that C gets a little slower everywhere. When not
150             actually tracking the overloaded C is quite fast - but still
151             around four times slower than the built-in C.
152              
153             Bear in mind that C is fast and unless your program is doing a
154             huge amount of blessing you're unlikely to notice a difference. On my
155             machine core bless takes around 0.5 μS and loading
156             C slows that down to around 2 μS.
157              
158             =head1 INTERFACE
159              
160             =cut
161              
162             {
163             my $magic = 0;
164              
165             my $plain_bless = sub {
166 39     39   105105 my $ref = shift;
167 39 100       128 my $class = @_ ? shift : scalar caller;
168 39         402 return CORE::bless( $ref, $class );
169             };
170              
171             my $magic_bless = sub {
172 7     7   18037 my $ref = shift;
173 7 100       24 my $class = @_ ? shift : scalar caller;
174 7         22 my $object = CORE::bless( $ref, $class );
175 7 50       101 unless ( $class->isa( 'Devel::LeakGuard::Object::State' ) ) {
176 7         18 Devel::LeakGuard::Object::track( $object );
177             }
178 7         66 return $object;
179             };
180              
181             sub import {
182 8     8   143 my $class = shift;
183 8         19 my @args = @_;
184 8         17 my @import = ();
185              
186 8 50       62 unless ( *CORE::GLOBAL::bless eq $plain_bless ) {
187             # We don't actually need to install our version of bless here but
188             # it'd be nice if any problems that it caused showed up sooner
189             # rather than later.
190             local $SIG{__WARN__} = sub {
191 0     0   0 warn "It looks as if something else is already "
192             . "overloading bless; there may be troubles ahead";
193 8         57 };
194 8         52 *CORE::GLOBAL::bless = $plain_bless;
195             }
196              
197 8         29 for my $a ( @args ) {
198 2 100       10 if ( 'GLOBAL_bless' eq $a ) {
    50          
199 1         5 _adj_magic( 1 );
200             }
201             elsif ( $a =~ /^:(.+)$/ ) {
202 0 0       0 croak "Bad option: $1" unless exists $OPTIONS{$1};
203 0         0 $OPTIONS{$1}++;
204             }
205             else {
206 1         3 push @import, $a;
207             }
208             }
209              
210 8         3107 return __PACKAGE__->export_to_level( 1, $class, @import );
211             }
212              
213             sub _adj_magic {
214 43     43   54 my $adj = shift;
215 43         51 my $old_magic = $magic;
216 43 50       94 $magic = 0 if ( $magic += $adj ) < 0;
217             {
218 6     6   32 no warnings 'redefine';
  6         17  
  6         891  
  43         46  
219 43 100 66     250 if ( $old_magic > 0 && $magic == 0 ) {
    50 33        
220 21         67 *CORE::GLOBAL::bless = $plain_bless;
221             }
222             elsif ( $old_magic == 0 && $magic > 0 ) {
223 22         81 *CORE::GLOBAL::bless = $magic_bless;
224             }
225             }
226             }
227             }
228              
229             =head2 C<< leakguard >>
230              
231             Run a block of code tracking object creation and destruction and report
232             any leaks at block exit.
233              
234             At its simplest C runs a block of code and warns if leaks
235             are found:
236              
237             leakguard {
238             my $foo = Foo->new;
239             $foo->{me} = $foo; # leak
240             };
241              
242             # Displays this warning:
243             Object leaks found:
244             Class Before After Delta
245             Foo 3 4 1
246             Detected at foo.pl line 23
247              
248             If you really don't want to leak you can die instead of warning:
249              
250             leakguard {
251             my $foo = Foo->new;
252             $foo->{me} = $foo; # leak
253             }
254             on_leak => 'die';
255              
256             If you need to do something more complex you can pass a coderef to the
257             C option:
258              
259             leakguard {
260             my $foo = Foo->new;
261             $foo->{me} = $foo; # leak
262             my $bar = Bar->new;
263             $bar->{me} = $bar; # leak again
264             }
265             on_leak => sub {
266             my $report = shift;
267             for my $pkg ( sort keys %$report ) {
268             printf "%s %d %d\n", $pkg, @{ $report->{$pkg} };
269             }
270             # do something
271             };
272              
273             In the event of a leak the sub will be called with a reference to a
274             hash. The keys of the hash are the names of classes that have leaked;
275             the values are refs to two-element arrays containing the bless count for
276             that class before and after the block so the example above would print:
277              
278             Foo 0 1
279             Bar 0 1
280              
281             =head3 Options
282              
283             Other options are supported. Here's the full list:
284              
285             =over
286              
287             =item C
288              
289             What to do if a leak is detected. May be 'warn' (the default), 'die',
290             'ignore' or a code reference. If C is set to 'ignore' no leak
291             tracking will be performed.
292              
293             =item C
294              
295             If you need to concentrate on a subset of classes use C to limit
296             leak tracking to a subset of classes:
297              
298             leakguard {
299             # do stuff
300             }
301             only => 'My::Stuff::*';
302              
303             The pattern to match can be a string (with '*' as a shell-style
304             wildcard), a C, a coderef or a reference to an array of any of
305             the above. This (improbable) example illustrates all of these:
306              
307             leakguard {
308             # do stuff
309             }
310             only => [
311             'My::Stuff::*',
312             qr{Leaky},
313             sub { length $_ > 20 }
314             ];
315              
316             That would track classes beginning with 'My::Stuff::', containing
317             'Leaky' or whose length is greater than 20 characters.
318              
319             =item C
320              
321             To track all classes apart from a few exceptions use C. The
322             C spec is like an C spec but classes that match will be
323             excluded from tracking.
324              
325             =item C
326              
327             Sometimes a certain amount of 'leakage' is acceptable. Imagine, for
328             example, an application that maintains a single cached database
329             connection in a class called C. The connection is created on
330             demand and deleted after it has been used 100 times - to be created
331             again next time it's needed.
332              
333             We could use C to ignore this class - but then we'd miss the
334             case where something goes wrong and we create 5 connections at a time.
335              
336             Using C we can specify that no more than one C should
337             be created or destroyed:
338              
339             leakguard {
340             # do stuff
341             }
342             expect => {
343             'My::DB' => [ -1, 1 ]
344             };
345              
346             =back
347              
348             =cut
349              
350 6     6   10032 use Devel::Peek;
  6         6308  
  6         39  
351              
352             sub leakguard(&@) {
353 20     20 1 15051 my $block = shift;
354 20         82 my $leakstate = Devel::LeakGuard::Object::State->new( @_ );
355 20         56 $block->();
356 20         214 $leakstate->done();
357 19         229 return;
358             }
359              
360             =head2 C<< leakstate >>
361              
362             Get the current allocation counts for all tracked objects. If
363             C is in force this will include all blessed objects. If
364             you are using the finer-grained tracking tools (L and
365             L) then only allocations that they cover will be included.
366              
367             Returns a reference to a hash with package names as keys and allocation
368             counts as values.
369              
370             =cut
371              
372 42     42 1 177 sub leakstate { return {%OBJECT_COUNT} }
373              
374             =head2 C<< track >>
375              
376             Track an individual object. Tracking an object increases the allocation
377             count for its package by one. When the object is destroyed the
378             allocation count is decreased by one. Current allocation counts may be
379             retrieved using L.
380              
381             If the object is reblessed into a different package the count for the
382             new package will be incremented and the count for the old package
383             decremented.
384              
385             =cut
386              
387             sub track {
388 73     73 1 8484 my $object = shift;
389 73         233 my $class = blessed $object;
390              
391 73 50       182 carp "Devel::LeakGuard::Object::track was passed a non-object"
392             unless defined $class;
393              
394 73         138 my $address = refaddr $object;
395 73 100       189 if ( $TRACKED{$address} ) {
396              
397             # Reblessing into the same class, ignore
398             return $OBJECT_COUNT{$class}
399 1 50       5 if $class eq $TRACKED{$address};
400              
401             # Reblessing into a different class
402 1         4 $OBJECT_COUNT{ $TRACKED{$address} }--;
403             }
404              
405 73         180 $TRACKED{$address} = $class;
406              
407 73 100       166 unless ( $DESTROY_STUBBED{$class} ) {
408 6     6   5095 no strict 'refs';
  6         10  
  6         433  
409 6     6   240 no warnings 'redefine';
  6         10  
  6         12567  
410              
411 16 50 100     25 if ( exists ${ $class . '::' }{DESTROY}
  16         154  
412 1         9 and *{ $class . '::DESTROY' }{CODE} ) {
413 0         0 $DESTROY_ORIGINAL{$class} = \&{ $class . '::DESTROY' };
  0         0  
414             }
415              
416 16         35 $DESTROY_STUBBED{$class} = 1;
417              
418 16         53 *{"${class}::DESTROY"} = _mk_destroy( $class );
  16         101  
419              
420 16         69 _mk_next( $class );
421             }
422              
423 73         199 $OBJECT_COUNT{ $TRACKED{$address} }++;
424             }
425              
426             sub _mk_destroy {
427 16     16   30 my $pkg = shift;
428              
429             return sub {
430 22     22   28904 my $self = $_[0];
431 22         89 my $class = blessed $self;
432 22         223 my $address = refaddr $self;
433              
434 22 50       66 die "Unexpected error: First param to DESTROY is no an object"
435             unless defined $class;
436              
437             # Don't do anything unless tracking for the specific object is set
438 22         52 my $original = $TRACKED{$address};
439 22 100       53 if ( $original ) {
440              
441 12 50       39 warn "Object class '$class' does",
442             " not match original $TRACKED{$address}"
443             if $class ne $original;
444              
445 12         27 $OBJECT_COUNT{$original}--;
446              
447             warn "Object count for $TRACKED{$address}",
448             " negative ($OBJECT_COUNT{$original})"
449 12 50       37 if $OBJECT_COUNT{$original} < 0;
450              
451 12         30 delete $TRACKED{$address};
452              
453 0         0 goto &{ $DESTROY_ORIGINAL{$original} }
454 12 50       42 if $DESTROY_ORIGINAL{$original};
455             }
456             else {
457 10         20 $original = $class;
458             }
459              
460             # If we don't have the DESTROY_NEXT for this class, populate it
461 22         59 _mk_next( $original );
462 22         50 my $super = $DESTROY_NEXT{$original}{$pkg};
463 22 100       60 goto &{"${super}::DESTROY"} if $super;
  5         49  
464 17         137 return;
465 16         108 };
466             }
467              
468             sub _mk_next {
469 38     38   61 my $class = shift;
470              
471 6     6   34 no strict 'refs';
  6         9  
  6         7636  
472 38 100       126 return if $DESTROY_NEXT{$class};
473              
474 18         46 $DESTROY_NEXT{$class} = {};
475              
476 18         114 my @stack = ( $class );
477 18         55 my %seen = ( UNIVERSAL => 1 );
478 18         27 my @queue = ();
479              
480 18         63 while ( my $c = pop @stack ) {
481 31 50       99 next if $seen{$c}++;
482              
483             my $has_destroy
484             = $DESTROY_STUBBED{$c}
485             ? exists $DESTROY_ORIGINAL{$c}
486 31 100 100     96 : ( exists ${"${c}::"}{DESTROY} and *{"${c}::DESTROY"}{CODE} );
487              
488 31 100       68 if ( $has_destroy ) {
489 2         15 $DESTROY_NEXT{$class}{$_} = $c for @queue;
490 2         6 @queue = ();
491             }
492             else {
493 29         62 push @queue, $c;
494             }
495              
496 31         41 push @stack, reverse @{"${c}::ISA"};
  31         222  
497             }
498              
499 18         111 $DESTROY_NEXT{$class}{$_} = '' for @queue;
500             }
501              
502             =head2 C
503              
504             Print out a L style summary of current object
505             allocations. If you
506              
507             use Devel::LeakGuard::Object qw( GLOBAL_bless :at_end );
508              
509             then C will be called at program exit to dump a summary of
510             outstanding allocations.
511              
512             =cut
513              
514             sub status {
515 0 0   0 1 0 my $fh = $OPTIONS{stderr} ? *STDERR : *STDOUT;
516 0         0 print $fh "Tracked objects by class:\n";
517 0         0 for ( sort keys %OBJECT_COUNT ) {
518 0 0       0 next unless $OBJECT_COUNT{$_}; # Don't list class with count zero
519 0         0 print $fh sprintf "%-40s %d\n", $_, $OBJECT_COUNT{$_};
520             }
521             }
522              
523 6 50   6   5642 END { status() if $OPTIONS{at_end} }
524              
525             1;
526              
527             __END__