]> git.vpit.fr Git - perl/modules/Test-Valgrind.git/blob - lib/Test/Valgrind.pm
Search for the first file and fallback to the first module if there's not
[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 Test::More;
9
10 use Perl::Destruct::Level level => 3;
11
12 use Test::Valgrind::Suppressions;
13
14 =head1 NAME
15
16 Test::Valgrind - Test Perl code through valgrind.
17
18 =head1 VERSION
19
20 Version 0.051
21
22 =cut
23
24 our $VERSION = '0.051';
25
26 =head1 SYNOPSIS
27
28     use Test::More;
29     eval 'use Test::Valgrind';
30     plan skip_all => 'Test::Valgrind is required to test your distribution with valgrind' if $@;
31
32     # Code to inspect for memory leaks/errors.
33
34 =head1 DESCRIPTION
35
36 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.
37
38 You can also use it from the command-line to test a given script :
39
40     perl -MTest::Valgrind leaky.pl
41
42 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.
43
44 =head1 CONFIGURATION
45
46 You can pass parameters to C<import> as a list of key / value pairs, where valid keys are :
47
48 =over 4
49
50 =item *
51
52 C<< supp => $file >>
53
54 Also use suppressions from C<$file> besides perl's.
55
56 =item *
57
58 C<< no_supp => $bool >>
59
60 If true, do not use any suppressions.
61
62 =item *
63
64 C<< callers => $number >>
65
66 Specify the maximum stack depth studied when valgrind encounters an error. Raising this number improves granularity. Default is 12.
67
68 =item *
69
70 C<< extra => [ @args ] >>
71
72 Add C<@args> to valgrind parameters.
73
74 =item *
75
76 C<< diag => $bool >>
77
78 If true, print the raw output of valgrind as diagnostics (may be quite verbose).
79
80 =item *
81
82 C<< no_test => $bool >>
83
84 If true, do not actually output the plan and the tests results.
85
86 =item *
87
88 C<< cb => sub { my ($val, $name) = @_; ...; return $passed } >>
89
90 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
91
92     sub {
93      is($_[0], 0, $_[1]);
94      (defined $_[0] and $_[0] == 0) : 1 : 0
95     }
96
97 =back
98
99 =cut
100
101 my $run;
102
103 sub _counter {
104  (defined $_[0] and $_[0] == 0) ? 1 : 0;
105 }
106
107 sub _tester {
108  is($_[0], 0, $_[1]);
109  _counter(@_);
110 }
111
112 sub import {
113  shift;
114  croak 'Optional arguments must be passed as key => value pairs' if @_ % 2;
115  my %args = @_;
116  if (!defined $args{run} && !$run) {
117   my ($file, $pm, $next);
118   my $l = 0;
119   while ($l < 1000) {
120    $next = (caller $l++)[1];
121    last unless defined $next;
122    next unless $next ne '-e' and $next !~ /^\s*\(\s*eval\s*\d*\s*\)\s*$/
123                              and -f $next;
124    if ($next =~ /\.pm$/) {
125     $pm = $next;
126    } else {
127     $file = $next;
128    }
129   }
130   unless (defined $file) {
131    $file = $pm;
132    return unless defined $pm;
133   }
134   my $callers = $args{callers};
135   $callers = 12 unless defined $callers;
136   $callers = int $callers;
137   my $vg = Test::Valgrind::Suppressions::VG_PATH;
138   if (!$vg || !-x $vg) {
139    for (split /:/, $ENV{PATH}) {
140     $_ .= '/valgrind';
141     if (-x) {
142      $vg = $_;
143      last;
144     }
145    }
146    if (!$vg) {
147     plan skip_all => 'No valgrind executable could be found in your path';
148     return;
149    } 
150   }
151   pipe my $rdr, my $wtr or croak "pipe(\$rdr, \$wtr): $!";
152   my $pid = fork;
153   if (!defined $pid) {
154    croak "fork(): $!";
155   } elsif ($pid == 0) {
156    setpgrp 0, 0 or croak "setpgrp(0, 0): $!";
157    close $rdr or croak "close(\$rdr): $!";
158    open STDERR, '>&', $wtr or croak "open(STDERR, '>&', \$wtr): $!";
159    my @args = (
160     '--tool=memcheck',
161     '--leak-check=full',
162     '--leak-resolution=high',
163     '--num-callers=' . $callers,
164     '--error-limit=yes'
165    );
166    unless ($args{no_supp}) {
167     for (Test::Valgrind::Suppressions::supp_path(), $args{supp}) {
168      push @args, '--suppressions=' . $_ if $_;
169     }
170    }
171    if (defined $args{extra} and ref $args{extra} eq 'ARRAY') {
172     push @args, @{$args{extra}};
173    }
174    push @args, $^X;
175    push @args, '-I' . $_ for @INC;
176    push @args, '-MTest::Valgrind=run,1', $file;
177    print STDERR "valgrind @args\n" if $args{diag};
178    local $ENV{PERL_DESTRUCT_LEVEL} = 3;
179    local $ENV{PERL_DL_NONLAZY} = 1;
180    exec $vg, @args;
181   }
182   close $wtr or croak "close(\$wtr): $!";
183   local $SIG{INT} = sub { kill -(SIGTERM) => $pid };
184   plan tests => 5 unless $args{no_test};
185   my @tests = (
186    'errors',
187    'definitely lost', 'indirectly lost', 'possibly lost', 'still reachable'
188   );
189   my %res = map { $_ => 0 } @tests;
190   while (<$rdr>) {
191    diag $_ if $args{diag};
192    if (/^=+\d+=+\s*FATAL\s*:\s*(.*)/) {
193     chomp(my $err = $1);
194     diag "Valgrind error: $err";
195     $res{$_} = undef for @tests;
196    }
197    if (/ERROR\s+SUMMARY\s*:\s+(\d+)/) {
198     $res{errors} = int $1;
199    } elsif (/([a-z][a-z\s]*[a-z])\s*:\s*([\d.,]+)/) {
200     my ($cat, $count) = ($1, $2);
201     if (exists $res{$cat}) {
202      $cat =~ s/\s+/ /g;
203      $count =~ s/[.,]//g;
204      $res{$cat} = int $count;
205     }
206    }
207   }
208   waitpid $pid, 0;
209   my $failed = 5;
210   my $cb = ($args{no_test} ? \&_counter
211                            : ($args{cb} ? $args{cb} : \&_tester));
212   for (@tests) {
213    $failed -= $cb->($res{$_}, 'valgrind ' . $_) ? 1 : 0;
214   }
215   exit $failed;
216  } else {
217   $run = 1;
218  }
219 }
220
221 =head1 CAVEATS
222
223 You can't use this module to test code given by the C<-e> command-line switch.
224
225 Results will most likely be better if your perl is built with debugging enabled. Using the latest valgrind available will also help.
226
227 This module is not really secure. It's definitely not taint safe. That shouldn't be a problem for test files.
228
229 If your tests output to STDERR, everything will be eaten in the process. In particular, running this module against test files will obliterate their original test results.
230
231 =head1 DEPENDENCIES
232
233 Valgrind 3.1.0 (L<http://valgrind.org>).
234
235 L<Carp>, L<POSIX> (core modules since perl 5) and L<Test::More> (since 5.6.2).
236
237 L<Perl::Destruct::Level>.
238
239 =head1 SEE ALSO
240
241 L<Devel::Leak>, L<Devel::LeakTrace>, L<Devel::LeakTrace::Fast>.
242
243 =head1 AUTHOR
244
245 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
246
247 You can contact me by mail or on #perl @ FreeNode (vincent or Prof_Vince).
248
249 =head1 BUGS
250
251 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.
252
253 =head1 SUPPORT
254
255 You can find documentation for this module with the perldoc command.
256
257     perldoc Test::Valgrind
258
259 =head1 ACKNOWLEDGEMENTS
260
261 RafaĆ«l Garcia-Suarez, for writing and instructing me about the existence of L<Perl::Destruct::Level> (Elizabeth Mattijsen is a close second).
262
263 H.Merijn Brand, for daring to test this thing.
264
265 =head1 COPYRIGHT & LICENSE
266
267 Copyright 2008 Vincent Pit, all rights reserved.
268
269 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
270
271 =cut
272
273 1; # End of Test::Valgrind