]> git.vpit.fr Git - perl/modules/Test-Valgrind.git/blob - lib/Test/Valgrind/Session.pm
ba00ee24e02028b4ac7a7d6c4e6ddc2c97671f9e
[perl/modules/Test-Valgrind.git] / lib / Test / Valgrind / Session.pm
1 package Test::Valgrind::Session;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 Test::Valgrind::Session - Test::Valgrind session object.
9
10 =head1 VERSION
11
12 Version 1.17
13
14 =cut
15
16 our $VERSION = '1.17';
17
18 =head1 DESCRIPTION
19
20 This class supervises the execution of the C<valgrind> process.
21 It also acts as a dispatcher between the different components.
22
23 =cut
24
25 use File::Spec   ();
26 use Scalar::Util ();
27
28 use Fcntl       (); # F_SETFD
29 use IO::Select;
30 use POSIX       (); # SIGKILL, _exit()
31
32 use base qw<Test::Valgrind::Carp>;
33
34 use Test::Valgrind::Version;
35
36 =head1 METHODS
37
38 =head2 C<new>
39
40     my $tvs = Test::Valgrind::Session->new(
41      search_dirs    => \@search_dirs,
42      valgrind       => $valgrind,  # One candidate
43      valgrind       => \@valgrind, # Several candidates
44      min_version    => $min_version,
45      regen_def_supp => $regen_def_supp,
46      no_def_supp    => $no_def_supp,
47      allow_no_supp  => $allow_no_supp,
48      extra_supps    => \@extra_supps,
49     );
50
51 The package constructor, which takes several options :
52
53 =over 4
54
55 =item *
56
57 All the directories from C<@search_dirs> will have F<valgrind> appended to create a list of candidates for the C<valgrind> executable.
58
59 Defaults to the current C<PATH> environment variable.
60
61 =item *
62
63 If a simple scalar C<$valgrind> is passed as the value to C<'valgrind'>, it will be the only candidate.
64 C<@search_dirs> will then be ignored.
65
66 If an array refernce C<\@valgrind> is passed, its values will be I<prepended> to the list of the candidates resulting from C<@search_dirs>.
67
68 =item *
69
70 C<$min_version> specifies the minimal C<valgrind> version required.
71 The constructor will croak if it's not able to find an adequate C<valgrind> from the supplied candidates list and search path.
72
73 Defaults to none.
74
75 =item *
76
77 If C<$regen_def_supp> is true, the default suppression file associated with the tool and the command will be forcefully regenerated.
78
79 Defaults to false.
80
81 =item *
82
83 If C<$no_def_supp> is true, C<valgrind> won't read the default suppression file associated with the tool and the command.
84
85 Defaults to false.
86
87 =item *
88
89 If C<$allow_no_supp> is true, the command will always be run into C<valgrind> even if no appropriate suppression file is available.
90
91 Defaults to false.
92
93 =item *
94
95 C<$extra_supps> is a reference to an array of optional suppression files that will be passed to C<valgrind>.
96
97 Defaults to none.
98
99 =back
100
101 =cut
102
103 sub new {
104  my $class = shift;
105  $class = ref($class) || $class;
106
107  my %args = @_;
108
109  my @paths;
110  my $vg = delete $args{valgrind};
111  if (defined $vg and not ref $vg) {
112   @paths = ($vg);
113  } else {
114   push @paths, @$vg if $vg and ref $vg eq 'ARRAY';
115   my $dirs = delete $args{search_dirs};
116   $dirs = [ File::Spec->path ] unless $dirs;
117   push @paths, map File::Spec->catfile($_, 'valgrind'), @$dirs
118                                                         if ref $dirs eq 'ARRAY';
119  }
120  $class->_croak('Empty valgrind candidates list') unless @paths;
121
122  my $min_version = delete $args{min_version};
123  if (defined $min_version) {
124   $min_version = Test::Valgrind::Version->new(string => $min_version);
125  }
126
127  my ($valgrind, $version);
128  for (@paths) {
129   next unless -x;
130   my $output = qx/$_ --version/;
131   $version   = do {
132    local $@;
133    eval { Test::Valgrind::Version->new(command_output => $output) };
134   };
135   if (defined $version) {
136    next if defined $min_version and $version < $min_version;
137    $valgrind = $_;
138    last;
139   }
140  }
141  $class->_croak('No appropriate valgrind executable could be found')
142                                                        unless defined $valgrind;
143
144  my $extra_supps = delete $args{extra_supps};
145  $extra_supps    = [ ] unless $extra_supps and ref $extra_supps eq 'ARRAY';
146  @$extra_supps   = grep { defined && -f $_ && -r _ } @$extra_supps;
147
148  bless {
149   valgrind       => $valgrind,
150   version        => $version,
151   regen_def_supp => delete($args{regen_def_supp}),
152   no_def_supp    => delete($args{no_def_supp}),
153   allow_no_supp  => delete($args{allow_no_supp}),
154   extra_supps    => $extra_supps,
155  }, $class;
156 }
157
158 =head2 C<valgrind>
159
160     my $valgrind_path = $tvs->valgrind;
161
162 The path to the selected C<valgrind> executable.
163
164 =head2 C<version>
165
166     my $valgrind_version = $tvs->version;
167
168 The L<Test::Valgrind::Version> object associated to the selected C<valgrind>.
169
170 =head2 C<regen_def_supp>
171
172     my $regen_def_supp = $tvs->regen_def_supp;
173
174 Read-only accessor for the C<regen_def_supp> option.
175
176 =cut
177
178 =head2 C<no_def_supp>
179
180     my $no_def_supp = $tvs->no_def_supp;
181
182 Read-only accessor for the C<no_def_supp> option.
183
184 =head2 C<allow_no_supp>
185
186     my $allow_no_supp = $tvs->allow_no_supp;
187
188 Read-only accessor for the C<allow_no_supp> option.
189
190 =cut
191
192 eval "sub $_ { \$_[0]->{$_} }" for qw<
193  valgrind
194  version
195  regen_def_supp
196  no_def_supp
197  allow_no_supp
198 >;
199
200 =head2 C<extra_supps>
201
202     my @extra_supps = $tvs->extra_supps;
203
204 Read-only accessor for the C<extra_supps> option.
205
206 =cut
207
208 sub extra_supps { @{$_[0]->{extra_supps} || []} }
209
210 =head2 C<run>
211
212     $tvs->run(
213      action  => $action,
214      tool    => $tool,
215      command => $command,
216     );
217
218 Runs the command C<$command> through C<valgrind> with the tool C<$tool>, which will report to the action C<$action>.
219
220 If the command is a L<Test::Valgrind::Command::Aggregate> object, the action and the tool will be initialized once before running all the aggregated commands.
221
222 =cut
223
224 sub run {
225  my ($self, %args) = @_;
226
227  for (qw<action tool command>) {
228   my $base = 'Test::Valgrind::' . ucfirst;
229   my $value = $args{$_};
230   $self->_croak("Invalid $_") unless Scalar::Util::blessed($value)
231                                                          and $value->isa($base);
232   $self->$_($args{$_})
233  }
234
235  my $cmd = $self->command;
236  if ($cmd->isa('Test::Valgrind::Command::Aggregate')) {
237   for my $subcmd ($cmd->commands) {
238    $args{command} = $subcmd;
239    $self->run(%args);
240   }
241   return;
242  }
243
244  $self->report($self->report_class->new_diag(
245   'Using valgrind ' . $self->version . ' located at ' . $self->valgrind
246  ));
247
248  my $env = $self->command->env($self);
249
250  my @supp_args;
251  if ($self->do_suppressions) {
252   push @supp_args, '--gen-suppressions=all';
253  } else {
254   if (!$self->no_def_supp) {
255    my $def_supp = $self->def_supp_file;
256    my $forced;
257    if ($self->regen_def_supp and -e $def_supp) {
258     1 while unlink $def_supp;
259     $forced = 1;
260    }
261    if (defined $def_supp and not -e $def_supp) {
262     $self->report($self->report_class->new_diag(
263      'Generating suppressions' . ($forced ? ' (forced)' : '') . '...'
264     ));
265     require Test::Valgrind::Suppressions;
266     Test::Valgrind::Suppressions->generate(
267      tool    => $self->tool,
268      command => $self->command,
269      target  => $def_supp,
270     );
271     $self->_croak('Couldn\'t generate suppressions') unless -e $def_supp;
272     $self->report($self->report_class->new_diag(
273      "Suppressions for this perl stored in $def_supp"
274     ));
275    }
276   }
277   my @supp_files = grep {
278    -e $_ and $self->command->check_suppressions_file($_)
279   } $self->suppressions;
280   if (@supp_files > 1) {
281    my $files_list = join "\n", map "    $_", @supp_files;
282    $self->report($self->report_class->new_diag(
283     "Using suppressions from:\n$files_list"
284    ));
285   } elsif (@supp_files) {
286    $self->report($self->report_class->new_diag(
287     "Using suppressions from $supp_files[0]"
288    ));
289   } elsif ($self->allow_no_supp) {
290    $self->report($self->report_class->new_diag("No suppressions used"));
291   } else {
292    $self->_croak("No compatible suppressions available");
293   }
294   @supp_args = map "--suppressions=$_", @supp_files;
295  }
296
297  my $error;
298  GUARDED: {
299   my $guard = Test::Valgrind::Session::Guard->new(sub { $self->finish });
300   $self->start;
301
302   pipe my $vrdr, my $vwtr or $self->_croak("pipe(\$vrdr, \$vwtr): $!");
303   {
304    my $oldfh = select $vrdr;
305    $|++;
306    select $oldfh;
307   }
308
309   pipe my $erdr, my $ewtr or $self->_croak("pipe(\$erdr, \$ewtr): $!");
310   {
311    my $oldfh = select $erdr;
312    $|++;
313    select $oldfh;
314   }
315
316   my $pid = fork;
317   $self->_croak("fork(): $!") unless defined $pid;
318
319   if ($pid == 0) {
320    {
321     local $@;
322     eval { setpgrp(0, 0) };
323    }
324
325    close $erdr or POSIX::_exit(255);
326
327    local $@;
328    eval {
329     close $vrdr or $self->_croak("close(\$vrdr): $!");
330
331     fcntl $vwtr, Fcntl::F_SETFD(), 0
332                               or $self->_croak("fcntl(\$vwtr, F_SETFD, 0): $!");
333
334     my @args = (
335      $self->valgrind,
336      $self->tool->args($self),
337      @supp_args,
338      $self->parser->args($self, $vwtr),
339      $self->command->args($self),
340     );
341
342     {
343      no warnings 'exec';
344      exec { $args[0] } @args;
345     }
346     $self->_croak("exec @args: $!");
347    };
348
349    print $ewtr $@;
350    close $ewtr;
351
352    POSIX::_exit(255);
353   }
354
355   local $@;
356   eval {
357    local $SIG{INT} = sub {
358     die 'valgrind analysis was interrupted';
359    };
360
361    close $vwtr or $self->_croak("close(\$vwtr): $!");
362    close $ewtr or $self->_croak("close(\$ewtr): $!");
363
364    SEL: {
365     my $sel = IO::Select->new($vrdr, $erdr);
366
367     my $child_err;
368     while (my @ready = $sel->can_read) {
369      last SEL if @ready == 1 and fileno $ready[0] == fileno $vrdr;
370
371      my $buf;
372      my $bytes_read = sysread $erdr, $buf, 4096;
373      if (not defined $bytes_read) {
374       $self->_croak("sysread(\$erdr): $!");
375      } elsif ($bytes_read) {
376       $sel->remove($vrdr) unless $child_err;
377       $child_err .= $buf;
378      } else {
379       $sel->remove($erdr);
380       die $child_err if $child_err;
381      }
382     }
383    }
384
385    my $aborted = $self->parser->parse($self, $vrdr);
386
387    if ($aborted) {
388     $self->report($self->report_class->new_diag("valgrind has aborted"));
389     return 0;
390    }
391
392    1;
393   } or do {
394    $error = $@;
395    kill -(POSIX::SIGKILL()) => $pid if kill 0 => $pid;
396    close $erdr;
397    close $vrdr;
398    waitpid $pid, 0;
399    # Force the guard destructor to trigger now so that old perls don't lose $@
400    last GUARDED;
401   };
402
403   $self->{exit_code} = (waitpid($pid, 0) == $pid) ? $? >> 8 : 255;
404
405   close $erdr or $self->_croak("close(\$erdr): $!");
406   close $vrdr or $self->_croak("close(\$vrdr): $!");
407
408   return;
409  }
410
411  die $error if $error;
412
413  return;
414 }
415
416 sub Test::Valgrind::Session::Guard::new     { bless \($_[1]), $_[0] }
417
418 sub Test::Valgrind::Session::Guard::DESTROY { ${$_[0]}->() }
419
420 =head2 C<action>
421
422 Read-only accessor for the C<action> associated to the current run.
423
424 =head2 C<tool>
425
426 Read-only accessor for the C<tool> associated to the current run.
427
428 =head2 C<parser>
429
430 Read-only accessor for the C<parser> associated to the current tool.
431
432 =head2 C<command>
433
434 Read-only accessor for the C<command> associated to the current run.
435
436 =cut
437
438 my @members;
439 BEGIN {
440  @members = qw<action tool command parser>;
441  for (@members) {
442   eval "sub $_ { \@_ <= 1 ? \$_[0]->{$_} : (\$_[0]->{$_} = \$_[1]) }";
443   die if $@;
444  }
445 }
446
447 =head2 C<do_suppressions>
448
449 Forwards to C<< ->action->do_suppressions >>.
450
451 =cut
452
453 sub do_suppressions { $_[0]->action->do_suppressions }
454
455 =head2 C<parser_class>
456
457 Calls C<< ->tool->parser_class >> with the current session object as the unique argument.
458
459 =cut
460
461 sub parser_class { $_[0]->tool->parser_class($_[0]) }
462
463 =head2 C<report_class>
464
465 Calls C<< ->tool->report_class >> with the current session object as the unique argument.
466
467 =cut
468
469 sub report_class { $_[0]->tool->report_class($_[0]) }
470
471 =head2 C<def_supp_file>
472
473 Returns an absolute path to the default suppression file associated to the current session.
474
475 C<undef> will be returned as soon as any of C<< ->command->suppressions_tag >> or C<< ->tool->suppressions_tag >> are also C<undef>.
476 Otherwise, the file part of the name is builded by joining those two together, and the directory part is roughly F<< File::HomeDir->my_home / .perl / Test-Valgrind / suppressions / $VERSION >>.
477
478 =cut
479
480 sub def_supp_file {
481  my ($self) = @_;
482
483  my $tool_tag = $self->tool->suppressions_tag($self);
484  return unless defined $tool_tag;
485
486  my $cmd_tag = $self->command->suppressions_tag($self);
487  return unless defined $cmd_tag;
488
489  require File::HomeDir; # So that it's not needed at configure time.
490
491  return File::Spec->catfile(
492   File::HomeDir->my_home,
493   '.perl',
494   'Test-Valgrind',
495   'suppressions',
496   $VERSION,
497   "$tool_tag-$cmd_tag.supp",
498  );
499 }
500
501 =head2 C<suppressions>
502
503     my @suppressions = $tvs->suppressions;
504
505 Returns the list of all the suppressions that will be passed to C<valgrind>.
506 Honors L</no_def_supp> and L</extra_supps>.
507
508 =cut
509
510 sub suppressions {
511  my ($self) = @_;
512
513  my @supps;
514  unless ($self->no_def_supp) {
515   my $def_supp = $self->def_supp_file;
516   push @supps, $def_supp if defined $def_supp;
517  }
518  push @supps, $self->extra_supps;
519
520  return @supps;
521 }
522
523 =head2 C<start>
524
525     $tvs->start;
526
527 Starts the action and tool associated to the current run.
528 It's automatically called at the beginning of L</run>.
529
530 =cut
531
532 sub start {
533  my $self = shift;
534
535  delete @{$self}{qw<last_status exit_code>};
536
537  $self->tool->start($self);
538  $self->parser($self->parser_class->new)->start($self);
539  $self->action->start($self);
540
541  return;
542 }
543
544 =head2 C<abort>
545
546     $tvs->abort($msg);
547
548 Forwards to C<< ->action->abort >> after unshifting the session object to the argument list.
549
550 =cut
551
552 sub abort {
553  my $self = shift;
554
555  $self->action->abort($self, @_);
556 }
557
558 =head2 C<report>
559
560     $tvs->report($report);
561
562 Forwards to C<< ->action->report >> after unshifting the session object to the argument list.
563
564 =cut
565
566 sub report {
567  my ($self, $report) = @_;
568
569  return unless defined $report;
570
571  for my $handler (qw<tool command>) {
572   $report = $self->$handler->filter($self, $report);
573   return unless defined $report;
574  }
575
576  $self->action->report($self, $report);
577 }
578
579 =head2 C<finish>
580
581     $tvs->finish;
582
583 Finishes the action and tool associated to the current run.
584 It's automatically called at the end of L</run>.
585
586 =cut
587
588 sub finish {
589  my ($self) = @_;
590
591  my $action = $self->action;
592
593  $action->finish($self);
594  $self->parser->finish($self);
595  $self->tool->finish($self);
596
597  my $status = $action->status($self);
598  $self->{last_status} = defined $status ? $status : $self->{exit_code};
599
600  $self->$_(undef) for @members;
601
602  return;
603 }
604
605 =head2 C<status>
606
607     my $status = $tvs->status;
608
609 Returns the status code of the last run of the session.
610
611 =cut
612
613 sub status { $_[0]->{last_status} }
614
615 =head1 SEE ALSO
616
617 L<Test::Valgrind>, L<Test::Valgrind::Action>, L<Test::Valgrind::Command>, L<Test::Valgrind::Tool>, L<Test::Valgrind::Parser>.
618
619 L<File::HomeDir>.
620
621 =head1 AUTHOR
622
623 Vincent Pit, C<< <perl at profvince.com> >>, L<http://www.profvince.com>.
624
625 You can contact me by mail or on C<irc.perl.org> (vincent).
626
627 =head1 BUGS
628
629 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>.
630 I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
631
632 =head1 SUPPORT
633
634 You can find documentation for this module with the perldoc command.
635
636     perldoc Test::Valgrind::Session
637
638 =head1 COPYRIGHT & LICENSE
639
640 Copyright 2009,2010,2011,2013,2015 Vincent Pit, all rights reserved.
641
642 This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
643
644 =cut
645
646 1; # End of Test::Valgrind::Session