]> git.vpit.fr Git - perl/modules/Test-Valgrind.git/blob - lib/Test/Valgrind.pm
Remove entries from @dl_unload_file when unload succeed instead of undefining them
[perl/modules/Test-Valgrind.git] / lib / Test / Valgrind.pm
1 package Test::Valgrind;
2
3 use strict;
4 use warnings;
5
6 use Carp qw/croak/;
7 use POSIX qw/SIGTERM/;
8 use Fcntl qw/F_SETFD/;
9 use Test::Builder;
10
11 use Perl::Destruct::Level level => 3;
12
13 use Test::Valgrind::Suppressions;
14
15 =head1 NAME
16
17 Test::Valgrind - Test Perl code through valgrind.
18
19 =head1 VERSION
20
21 Version 0.07
22
23 =cut
24
25 our $VERSION = '0.07';
26
27 =head1 SYNOPSIS
28
29     use Test::More;
30     eval 'use Test::Valgrind';
31     plan skip_all => 'Test::Valgrind is required to test your distribution with valgrind' if $@;
32
33     # Code to inspect for memory leaks/errors.
34
35 =head1 DESCRIPTION
36
37 This module lets you run some code through the B<valgrind> memory debugger, to test it for memory errors and leaks. Just add C<use Test::Valgrind> at the beginning of the code you want to test. Behind the hood, C<Test::Valgrind::import> forks so that the child can basically C<exec 'valgrind', $^X, $0> (except that of course C<$0> isn't right there). The parent then parses the report output by valgrind and pass or fail tests accordingly.
38
39 You can also use it from the command-line to test a given script :
40
41     perl -MTest::Valgrind leaky.pl
42
43 Due to the nature of perl's memory allocator, this module can't track leaks of Perl objects. This includes non-mortalized scalars and memory cycles. However, it can track leaks of chunks of memory allocated in XS extensions with C<Newx> and friends or C<malloc>. As such, it's complementary to the other very good leak detectors listed in the L</SEE ALSO> section.
44
45 =head1 CONFIGURATION
46
47 You can pass parameters to C<import> as a list of key / value pairs, where valid keys are :
48
49 =over 4
50
51 =item *
52
53 C<< supp => $file >>
54
55 Also use suppressions from C<$file> besides perl's.
56
57 =item *
58
59 C<< no_supp => $bool >>
60
61 If true, do not use any suppressions.
62
63 =item *
64
65 C<< callers => $number >>
66
67 Specify the maximum stack depth studied when valgrind encounters an error. Raising this number improves granularity. Default is 12.
68
69 =item *
70
71 C<< extra => [ @args ] >>
72
73 Add C<@args> to valgrind parameters.
74
75 =item *
76
77 C<< diag => $bool >>
78
79 If true, print the raw output of valgrind as diagnostics (may be quite verbose).
80
81 =item *
82
83 C<< no_test => $bool >>
84
85 If true, do not actually output the plan and the tests results.
86
87 =item *
88
89 C<< cb => sub { my ($val, $name) = @_; ...; return $passed } >>
90
91 Specifies a subroutine to execute for each test instead of C<Test::More::is>. It receives the number of bytes leaked in C<$_[0]> and the test name in C<$_[1]>, and is expected to return true if the test passed and false otherwise. Defaults to
92
93     sub {
94      is($_[0], 0, $_[1]);
95      (defined $_[0] and $_[0] == 0) : 1 : 0
96     }
97
98 =back
99
100 =cut
101
102 my $Test = Test::Builder->new;
103
104 my $run;
105
106 sub _counter {
107  (defined $_[0] and $_[0] == 0) ? 1 : 0;
108 }
109
110 sub _tester {
111  $Test->is_num($_[0], 0, $_[1]);
112  _counter(@_);
113 }
114
115 sub import {
116  shift;
117  croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
118  my %args = @_;
119  if (!defined $args{run} && !$run) {
120   my ($file, $pm, $next);
121   my $l = 0;
122   while ($l < 1000) {
123    $next = (caller $l++)[1];
124    last unless defined $next;
125    next unless $next ne '-e' and $next !~ /^\s*\(\s*eval\s*\d*\s*\)\s*$/
126                              and -f $next;
127    if ($next =~ /\.pm$/) {
128     $pm = $next;
129    } else {
130     $file = $next;
131    }
132   }
133   unless (defined $file) {
134    $file = $pm;
135    return unless defined $pm;
136   }
137   my $callers = $args{callers};
138   $callers = 12 unless defined $callers;
139   $callers = int $callers;
140   my $vg = Test::Valgrind::Suppressions::VG_PATH;
141   if (!$vg || !-x $vg) {
142    require Config;
143    for (split /$Config::Config{path_sep}/, $ENV{PATH}) {
144     $_ .= '/valgrind';
145     if (-x) {
146      $vg = $_;
147      last;
148     }
149    }
150    if (!$vg) {
151     $Test->skip_all('No valgrind executable could be found in your path');
152     return;
153    } 
154   }
155   pipe my $ordr, my $owtr or die "pipe(\$ordr, \$owtr): $!";
156   pipe my $vrdr, my $vwtr or die "pipe(\$vrdr, \$vwtr): $!";
157   my $pid = fork;
158   if (!defined $pid) {
159    die "fork(): $!";
160   } elsif ($pid == 0) {
161    setpgrp 0, 0 or die "setpgrp(0, 0): $!";
162    close $ordr or die "close(\$ordr): $!";
163    open STDOUT, '>&=', $owtr or die "open(STDOUT, '>&=', \$owtr): $!";
164    close $vrdr or die "close(\$vrdr): $!";
165    fcntl $vwtr, F_SETFD, 0 or die "fcntl(\$vwtr, F_SETFD, 0): $!";
166    my @args = (
167     $vg,
168     '--tool=memcheck',
169     '--leak-check=full',
170     '--leak-resolution=high',
171     '--num-callers=' . $callers,
172     '--error-limit=yes',
173     '--log-fd=' . fileno($vwtr)
174    );
175    unless ($args{no_supp}) {
176     for (Test::Valgrind::Suppressions::supp_path(), $args{supp}) {
177      push @args, '--suppressions=' . $_ if $_;
178     }
179    }
180    if (defined $args{extra} and ref $args{extra} eq 'ARRAY') {
181     push @args, @{$args{extra}};
182    }
183    push @args, $^X;
184    push @args, '-I' . $_ for @INC;
185    push @args, '-MTest::Valgrind=run,1', $file;
186    print STDOUT "valgrind @args\n";
187    local $ENV{PERL_DESTRUCT_LEVEL} = 3;
188    local $ENV{PERL_DL_NONLAZY} = 1;
189    exec { $args[0] } @args;
190    die "exec @args: $!";
191   }
192   local $SIG{INT} = sub { kill -(SIGTERM) => $pid };
193   $Test->plan(tests => 5) unless $args{no_test} or defined $Test->has_plan;
194   my @tests = (
195    'errors',
196    'definitely lost', 'indirectly lost', 'possibly lost', 'still reachable'
197   );
198   my %res = map { $_ => 0 } @tests;
199   close $owtr or die "close(\$owtr): $!";
200   close $vwtr or die "close(\$vwtr): $!";
201   while (<$vrdr>) {
202    $Test->diag($_) if $args{diag};
203    if (/^=+\d+=+\s*FATAL\s*:\s*(.*)/) {
204     chomp(my $err = $1);
205     $Test->diag("Valgrind error: $err");
206     $res{$_} = undef for @tests;
207    }
208    if (/ERROR\s+SUMMARY\s*:\s+(\d+)/) {
209     $res{errors} = int $1;
210    } elsif (/([a-z][a-z\s]*[a-z])\s*:\s*([\d.,]+)/) {
211     my ($cat, $count) = ($1, $2);
212     if (exists $res{$cat}) {
213      $cat =~ s/\s+/ /g;
214      $count =~ s/[.,]//g;
215      $res{$cat} = int $count;
216     }
217    }
218   }
219   waitpid $pid, 0;
220   $Test->diag(do { local $/; <$ordr> }) if $args{diag};
221   close $ordr or die "close(\$ordr): $!";
222   my $failed = 5;
223   my $cb = ($args{no_test} ? \&_counter
224                            : ($args{cb} ? $args{cb} : \&_tester));
225   for (@tests) {
226    $failed -= $cb->($res{$_}, 'valgrind ' . $_) ? 1 : 0;
227   }
228   exit $failed;
229  } else {
230   $run = 1;
231  }
232 }
233
234 END {
235  if ($run and eval { require DynaLoader; 1 }) {
236   my @rest;
237   DynaLoader::dl_unload_file($_) and push @rest, $_ for @DynaLoader::dl_librefs;
238   @DynaLoader::dl_librefs = @rest;
239  }
240 }
241
242 =head1 CAVEATS
243
244 You can't use this module to test code given by the C<-e> command-line switch.
245
246 Perl 5.8 is notorious for leaking like there's no tomorrow, so the suppressions are very likely not to be very accurate on it. Anyhow, results will most likely be better if your perl is built with debugging enabled. Using the latest valgrind available will also help.
247
248 This module is not really secure. It's definitely not taint safe. That shouldn't be a problem for test files.
249
250 What your tests output to STDOUT is eaten unless you pass the C<diag> option, in which case it will be reprinted as diagnostics. STDERR is kept untouched.
251
252 =head1 DEPENDENCIES
253
254 Valgrind 3.1.0 (L<http://valgrind.org>).
255
256 L<Carp>, L<Fcntl>, L<POSIX> (core modules since perl 5) and L<Test::Builder> (since 5.6.2).
257
258 L<Perl::Destruct::Level>.
259
260 =head1 SEE ALSO
261
262 L<Devel::Leak>, L<Devel::LeakTrace>, L<Devel::LeakTrace::Fast>.
263
264 =head1 AUTHOR
265
266 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
267
268 You can contact me by mail or on C<irc.perl.org> (vincent).
269
270 =head1 BUGS
271
272 Please report any bugs or feature requests to C<bug-test-valgrind at rt.cpan.org>, or through the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Test-Valgrind>.  I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
273
274 =head1 SUPPORT
275
276 You can find documentation for this module with the perldoc command.
277
278     perldoc Test::Valgrind
279
280 =head1 ACKNOWLEDGEMENTS
281
282 RafaĆ«l Garcia-Suarez, for writing and instructing me about the existence of L<Perl::Destruct::Level> (Elizabeth Mattijsen is a close second).
283
284 H.Merijn Brand, for daring to test this thing.
285
286 =head1 COPYRIGHT & LICENSE
287
288 Copyright 2008 Vincent Pit, all rights reserved.
289
290 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
291
292 =cut
293
294 1; # End of Test::Valgrind