c4799e864892ed2836f03ac57adf150dd91dec72
[openssl.git] / test / testlib / OpenSSL / Test.pm
1 # Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
2 #
3 # Licensed under the OpenSSL license (the "License").  You may not use
4 # this file except in compliance with the License.  You can obtain a copy
5 # in the file LICENSE in the source distribution or at
6 # https://www.openssl.org/source/license.html
7
8 package OpenSSL::Test;
9
10 use strict;
11 use warnings;
12
13 use Test::More 0.96;
14
15 use Exporter;
16 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
17 $VERSION = "0.8";
18 @ISA = qw(Exporter);
19 @EXPORT = (@Test::More::EXPORT, qw(setup run indir cmd app fuzz test
20                                    perlapp perltest));
21 @EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file
22                                          srctop_dir srctop_file
23                                          data_file
24                                          pipe with cmdstr quotify));
25
26 =head1 NAME
27
28 OpenSSL::Test - a private extension of Test::More
29
30 =head1 SYNOPSIS
31
32   use OpenSSL::Test;
33
34   setup("my_test_name");
35
36   ok(run(app(["openssl", "version"])), "check for openssl presence");
37
38   indir "subdir" => sub {
39     ok(run(test(["sometest", "arg1"], stdout => "foo.txt")),
40        "run sometest with output to foo.txt");
41   };
42
43 =head1 DESCRIPTION
44
45 This module is a private extension of L<Test::More> for testing OpenSSL.
46 In addition to the Test::More functions, it also provides functions that
47 easily find the diverse programs within a OpenSSL build tree, as well as
48 some other useful functions.
49
50 This module I<depends> on the environment variables C<$TOP> or C<$SRCTOP>
51 and C<$BLDTOP>.  Without one of the combinations it refuses to work.
52 See L</ENVIRONMENT> below.
53
54 With each test recipe, a parallel data directory with (almost) the same name
55 as the recipe is possible in the source directory tree.  For example, for a
56 recipe C<$SRCTOP/test/recipes/99-foo.t>, there could be a directory
57 C<$SRCTOP/test/recipes/99-foo_data/>.
58
59 =cut
60
61 use File::Copy;
62 use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir
63                              catdir catfile splitpath catpath devnull abs2rel
64                              rel2abs/;
65 use File::Path 2.00 qw/rmtree mkpath/;
66 use File::Basename;
67
68
69 # The name of the test.  This is set by setup() and is used in the other
70 # functions to verify that setup() has been used.
71 my $test_name = undef;
72
73 # Directories we want to keep track of TOP, APPS, TEST and RESULTS are the
74 # ones we're interested in, corresponding to the environment variables TOP
75 # (mandatory), BIN_D, TEST_D, UTIL_D and RESULT_D.
76 my %directories = ();
77
78 # The environment variables that gave us the contents in %directories.  These
79 # get modified whenever we change directories, so that subprocesses can use
80 # the values of those environment variables as well
81 my @direnv = ();
82
83 # A bool saying if we shall stop all testing if the current recipe has failing
84 # tests or not.  This is set by setup() if the environment variable STOPTEST
85 # is defined with a non-empty value.
86 my $end_with_bailout = 0;
87
88 # A set of hooks that is affected by with() and may be used in diverse places.
89 # All hooks are expected to be CODE references.
90 my %hooks = (
91
92     # exit_checker is used by run() directly after completion of a command.
93     # it receives the exit code from that command and is expected to return
94     # 1 (for success) or 0 (for failure).  This is the status value that run()
95     # will give back (through the |statusvar| referens and as returned value
96     # when capture => 1 doesn't apply).
97     exit_checker => sub { return shift == 0 ? 1 : 0 },
98
99     );
100
101 # Debug flag, to be set manually when needed
102 my $debug = 0;
103
104 =head2 Main functions
105
106 The following functions are exported by default when using C<OpenSSL::Test>.
107
108 =cut
109
110 =over 4
111
112 =item B<setup "NAME">
113
114 C<setup> is used for initial setup, and it is mandatory that it's used.
115 If it's not used in a OpenSSL test recipe, the rest of the recipe will
116 most likely refuse to run.
117
118 C<setup> checks for environment variables (see L</ENVIRONMENT> below),
119 checks that C<$TOP/Configure> or C<$SRCTOP/Configure> exists, C<chdir>
120 into the results directory (defined by the C<$RESULT_D> environment
121 variable if defined, otherwise C<$BLDTOP/test> or C<$TOP/test>, whichever
122 is defined).
123
124 =back
125
126 =cut
127
128 sub setup {
129     my $old_test_name = $test_name;
130     $test_name = shift;
131
132     BAIL_OUT("setup() must receive a name") unless $test_name;
133     warn "setup() detected test name change.  Innocuous, so we continue...\n"
134         if $old_test_name && $old_test_name ne $test_name;
135
136     return if $old_test_name;
137
138     BAIL_OUT("setup() needs \$TOP or \$SRCTOP and \$BLDTOP to be defined")
139         unless $ENV{TOP} || ($ENV{SRCTOP} && $ENV{BLDTOP});
140     BAIL_OUT("setup() found both \$TOP and \$SRCTOP or \$BLDTOP...")
141         if $ENV{TOP} && ($ENV{SRCTOP} || $ENV{BLDTOP});
142
143     __env();
144
145     BAIL_OUT("setup() expects the file Configure in the source top directory")
146         unless -f srctop_file("Configure");
147
148     __cwd($directories{RESULTS});
149 }
150
151 =over 4
152
153 =item B<indir "SUBDIR" =E<gt> sub BLOCK, OPTS>
154
155 C<indir> is used to run a part of the recipe in a different directory than
156 the one C<setup> moved into, usually a subdirectory, given by SUBDIR.
157 The part of the recipe that's run there is given by the codeblock BLOCK.
158
159 C<indir> takes some additional options OPTS that affect the subdirectory:
160
161 =over 4
162
163 =item B<create =E<gt> 0|1>
164
165 When set to 1 (or any value that perl preceives as true), the subdirectory
166 will be created if it doesn't already exist.  This happens before BLOCK
167 is executed.
168
169 =item B<cleanup =E<gt> 0|1>
170
171 When set to 1 (or any value that perl preceives as true), the subdirectory
172 will be cleaned out and removed.  This happens both before and after BLOCK
173 is executed.
174
175 =back
176
177 An example:
178
179   indir "foo" => sub {
180       ok(run(app(["openssl", "version"]), stdout => "foo.txt"));
181       if (ok(open(RESULT, "foo.txt"), "reading foo.txt")) {
182           my $line = <RESULT>;
183           close RESULT;
184           is($line, qr/^OpenSSL 1\./,
185              "check that we're using OpenSSL 1.x.x");
186       }
187   }, create => 1, cleanup => 1;
188
189 =back
190
191 =cut
192
193 sub indir {
194     my $subdir = shift;
195     my $codeblock = shift;
196     my %opts = @_;
197
198     my $reverse = __cwd($subdir,%opts);
199     BAIL_OUT("FAILURE: indir, \"$subdir\" wasn't possible to move into")
200         unless $reverse;
201
202     $codeblock->();
203
204     __cwd($reverse);
205
206     if ($opts{cleanup}) {
207         rmtree($subdir, { safe => 0 });
208     }
209 }
210
211 =over 4
212
213 =item B<cmd ARRAYREF, OPTS>
214
215 This functions build up a platform dependent command based on the
216 input.  It takes a reference to a list that is the executable or
217 script and its arguments, and some additional options (described
218 further on).  Where necessary, the command will be wrapped in a
219 suitable environment to make sure the correct shared libraries are
220 used (currently only on Unix).
221
222 It returns a CODEREF to be used by C<run>, C<pipe> or C<cmdstr>.
223
224 The options that C<cmd> can take are in the form of hash values:
225
226 =over 4
227
228 =item B<stdin =E<gt> PATH>
229
230 =item B<stdout =E<gt> PATH>
231
232 =item B<stderr =E<gt> PATH>
233
234 In all three cases, the corresponding standard input, output or error is
235 redirected from (for stdin) or to (for the others) a file given by the
236 string PATH, I<or>, if the value is C<undef>, C</dev/null> or similar.
237
238 =back
239
240 =item B<app ARRAYREF, OPTS>
241
242 =item B<test ARRAYREF, OPTS>
243
244 Both of these are specific applications of C<cmd>, with just a couple
245 of small difference:
246
247 C<app> expects to find the given command (the first item in the given list
248 reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps>
249 or C<$BLDTOP/apps>).
250
251 C<test> expects to find the given command (the first item in the given list
252 reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test>
253 or C<$BLDTOP/test>).
254
255 Also, for both C<app> and C<test>, the command may be prefixed with
256 the content of the environment variable C<$EXE_SHELL>, which is useful
257 in case OpenSSL has been cross compiled.
258
259 =item B<perlapp ARRAYREF, OPTS>
260
261 =item B<perltest ARRAYREF, OPTS>
262
263 These are also specific applications of C<cmd>, where the interpreter
264 is predefined to be C<perl>, and they expect the script to be
265 interpreted to reside in the same location as C<app> and C<test>.
266
267 C<perlapp> and C<perltest> will also take the following option:
268
269 =over 4
270
271 =item B<interpreter_args =E<gt> ARRAYref>
272
273 The array reference is a set of arguments for the interpreter rather
274 than the script.  Take care so that none of them can be seen as a
275 script!  Flags and their eventual arguments only!
276
277 =back
278
279 An example:
280
281   ok(run(perlapp(["foo.pl", "arg1"],
282                  interpreter_args => [ "-I", srctop_dir("test") ])));
283
284 =back
285
286 =begin comment
287
288 One might wonder over the complexity of C<apps>, C<fuzz>, C<test>, ...
289 with all the lazy evaluations and all that.  The reason for this is that
290 we want to make sure the directory in which those programs are found are
291 correct at the time these commands are used.  Consider the following code
292 snippet:
293
294   my $cmd = app(["openssl", ...]);
295
296   indir "foo", sub {
297       ok(run($cmd), "Testing foo")
298   };
299
300 If there wasn't this lazy evaluation, the directory where C<openssl> is
301 found would be incorrect at the time C<run> is called, because it was
302 calculated before we moved into the directory "foo".
303
304 =end comment
305
306 =cut
307
308 sub cmd {
309     my $cmd = shift;
310     my %opts = @_;
311     return sub {
312         my $num = shift;
313         # Make a copy to not destroy the caller's array
314         my @cmdargs = ( @$cmd );
315         my @prog = __wrap_cmd(shift @cmdargs, $opts{exe_shell} // ());
316
317         return __decorate_cmd($num, [ @prog, quotify(@cmdargs) ],
318                               %opts);
319     }
320 }
321
322 sub app {
323     my $cmd = shift;
324     my %opts = @_;
325     return sub {
326         my @cmdargs = ( @{$cmd} );
327         my @prog = __fixup_prg(__apps_file(shift @cmdargs, __exeext()));
328         return cmd([ @prog, @cmdargs ],
329                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
330     }
331 }
332
333 sub fuzz {
334     my $cmd = shift;
335     my %opts = @_;
336     return sub {
337         my @cmdargs = ( @{$cmd} );
338         my @prog = __fixup_prg(__fuzz_file(shift @cmdargs, __exeext()));
339         return cmd([ @prog, @cmdargs ],
340                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
341     }
342 }
343
344 sub test {
345     my $cmd = shift;
346     my %opts = @_;
347     return sub {
348         my @cmdargs = ( @{$cmd} );
349         my @prog = __fixup_prg(__test_file(shift @cmdargs, __exeext()));
350         return cmd([ @prog, @cmdargs ],
351                    exe_shell => $ENV{EXE_SHELL}, %opts) -> (shift);
352     }
353 }
354
355 sub perlapp {
356     my $cmd = shift;
357     my %opts = @_;
358     return sub {
359         my @interpreter_args = defined $opts{interpreter_args} ?
360             @{$opts{interpreter_args}} : ();
361         my @interpreter = __fixup_prg($^X);
362         my @cmdargs = ( @{$cmd} );
363         my @prog = __apps_file(shift @cmdargs, undef);
364         return cmd([ @interpreter, @interpreter_args,
365                      @prog, @cmdargs ], %opts) -> (shift);
366     }
367 }
368
369 sub perltest {
370     my $cmd = shift;
371     my %opts = @_;
372     return sub {
373         my @interpreter_args = defined $opts{interpreter_args} ?
374             @{$opts{interpreter_args}} : ();
375         my @interpreter = __fixup_prg($^X);
376         my @cmdargs = ( @{$cmd} );
377         my @prog = __test_file(shift @cmdargs, undef);
378         return cmd([ @interpreter, @interpreter_args,
379                      @prog, @cmdargs ], %opts) -> (shift);
380     }
381 }
382
383 =over 4
384
385 =item B<run CODEREF, OPTS>
386
387 CODEREF is expected to be the value return by C<cmd> or any of its
388 derivatives, anything else will most likely cause an error unless you
389 know what you're doing.
390
391 C<run> executes the command returned by CODEREF and return either the
392 resulting output (if the option C<capture> is set true) or a boolean
393 indicating if the command succeeded or not.
394
395 The options that C<run> can take are in the form of hash values:
396
397 =over 4
398
399 =item B<capture =E<gt> 0|1>
400
401 If true, the command will be executed with a perl backtick, and C<run> will
402 return the resulting output as an array of lines.  If false or not given,
403 the command will be executed with C<system()>, and C<run> will return 1 if
404 the command was successful or 0 if it wasn't.
405
406 =item B<prefix =E<gt> EXPR>
407
408 If specified, EXPR will be used as a string to prefix the output from the
409 command.  This is useful if the output contains lines starting with C<ok >
410 or C<not ok > that can disturb Test::Harness.
411
412 =item B<statusvar =E<gt> VARREF>
413
414 If used, B<VARREF> must be a reference to a scalar variable.  It will be
415 assigned a boolean indicating if the command succeeded or not.  This is
416 particularly useful together with B<capture>.
417
418 =back
419
420 For further discussion on what is considered a successful command or not, see
421 the function C<with> further down.
422
423 =back
424
425 =cut
426
427 sub run {
428     my ($cmd, $display_cmd) = shift->(0);
429     my %opts = @_;
430
431     return () if !$cmd;
432
433     my $prefix = "";
434     if ( $^O eq "VMS" ) {       # VMS
435         $prefix = "pipe ";
436     }
437
438     my @r = ();
439     my $r = 0;
440     my $e = 0;
441
442     die "OpenSSL::Test::run(): statusvar value not a scalar reference"
443         if $opts{statusvar} && ref($opts{statusvar}) ne "SCALAR";
444
445     # In non-verbose, we want to shut up the command interpreter, in case
446     # it has something to complain about.  On VMS, it might complain both
447     # on stdout and stderr
448     my $save_STDOUT;
449     my $save_STDERR;
450     if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
451         open $save_STDOUT, '>&', \*STDOUT or die "Can't dup STDOUT: $!";
452         open $save_STDERR, '>&', \*STDERR or die "Can't dup STDERR: $!";
453         open STDOUT, ">", devnull();
454         open STDERR, ">", devnull();
455     }
456
457     # The dance we do with $? is the same dance the Unix shells appear to
458     # do.  For example, a program that gets aborted (and therefore signals
459     # SIGABRT = 6) will appear to exit with the code 134.  We mimic this
460     # to make it easier to compare with a manual run of the command.
461     if ($opts{capture} || defined($opts{prefix})) {
462         my $pipe;
463         local $_;
464
465         open($pipe, '-|', "$prefix$cmd") or die "Can't start command: $!";
466         while(<$pipe>) {
467             my $l = ($opts{prefix} // "") . $_;
468             if ($opts{capture}) {
469                 push @r, $l;
470             } else {
471                 print STDOUT $l;
472             }
473         }
474         close $pipe;
475     } else {
476         system("$prefix$cmd");
477     }
478     $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
479     $r = $hooks{exit_checker}->($e);
480     if ($opts{statusvar}) {
481         ${$opts{statusvar}} = $r;
482     }
483
484     if ($ENV{HARNESS_ACTIVE} && !$ENV{HARNESS_VERBOSE}) {
485         close STDOUT;
486         close STDERR;
487         open STDOUT, '>&', $save_STDOUT or die "Can't restore STDOUT: $!";
488         open STDERR, '>&', $save_STDERR or die "Can't restore STDERR: $!";
489     }
490
491     print STDERR "$prefix$display_cmd => $e\n"
492         if !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
493
494     # At this point, $? stops being interesting, and unfortunately,
495     # there are Test::More versions that get picky if we leave it
496     # non-zero.
497     $? = 0;
498
499     if ($opts{capture}) {
500         return @r;
501     } else {
502         return $r;
503     }
504 }
505
506 END {
507     my $tb = Test::More->builder;
508     my $failure = scalar(grep { $_ == 0; } $tb->summary);
509     if ($failure && $end_with_bailout) {
510         BAIL_OUT("Stoptest!");
511     }
512 }
513
514 =head2 Utility functions
515
516 The following functions are exported on request when using C<OpenSSL::Test>.
517
518   # To only get the bldtop_file and srctop_file functions.
519   use OpenSSL::Test qw/bldtop_file srctop_file/;
520
521   # To only get the bldtop_file function in addition to the default ones.
522   use OpenSSL::Test qw/:DEFAULT bldtop_file/;
523
524 =cut
525
526 # Utility functions, exported on request
527
528 =over 4
529
530 =item B<bldtop_dir LIST>
531
532 LIST is a list of directories that make up a path from the top of the OpenSSL
533 build directory (as indicated by the environment variable C<$TOP> or
534 C<$BLDTOP>).
535 C<bldtop_dir> returns the resulting directory as a string, adapted to the local
536 operating system.
537
538 =back
539
540 =cut
541
542 sub bldtop_dir {
543     return __bldtop_dir(@_);    # This caters for operating systems that have
544                                 # a very distinct syntax for directories.
545 }
546
547 =over 4
548
549 =item B<bldtop_file LIST, FILENAME>
550
551 LIST is a list of directories that make up a path from the top of the OpenSSL
552 build directory (as indicated by the environment variable C<$TOP> or
553 C<$BLDTOP>) and FILENAME is the name of a file located in that directory path.
554 C<bldtop_file> returns the resulting file path as a string, adapted to the local
555 operating system.
556
557 =back
558
559 =cut
560
561 sub bldtop_file {
562     return __bldtop_file(@_);
563 }
564
565 =over 4
566
567 =item B<srctop_dir LIST>
568
569 LIST is a list of directories that make up a path from the top of the OpenSSL
570 source directory (as indicated by the environment variable C<$TOP> or
571 C<$SRCTOP>).
572 C<srctop_dir> returns the resulting directory as a string, adapted to the local
573 operating system.
574
575 =back
576
577 =cut
578
579 sub srctop_dir {
580     return __srctop_dir(@_);    # This caters for operating systems that have
581                                 # a very distinct syntax for directories.
582 }
583
584 =over 4
585
586 =item B<srctop_file LIST, FILENAME>
587
588 LIST is a list of directories that make up a path from the top of the OpenSSL
589 source directory (as indicated by the environment variable C<$TOP> or
590 C<$SRCTOP>) and FILENAME is the name of a file located in that directory path.
591 C<srctop_file> returns the resulting file path as a string, adapted to the local
592 operating system.
593
594 =back
595
596 =cut
597
598 sub srctop_file {
599     return __srctop_file(@_);
600 }
601
602 =over 4
603
604 =item B<data_file LIST, FILENAME>
605
606 LIST is a list of directories that make up a path from the data directory
607 associated with the test (see L</DESCRIPTION> above) and FILENAME is the name
608 of a file located in that directory path.  C<data_file> returns the resulting
609 file path as a string, adapted to the local operating system.
610
611 =back
612
613 =cut
614
615 sub data_file {
616     return __data_file(@_);
617 }
618
619 =over 4
620
621 =item B<pipe LIST>
622
623 LIST is a list of CODEREFs returned by C<app> or C<test>, from which C<pipe>
624 creates a new command composed of all the given commands put together in a
625 pipe.  C<pipe> returns a new CODEREF in the same manner as C<app> or C<test>,
626 to be passed to C<run> for execution.
627
628 =back
629
630 =cut
631
632 sub pipe {
633     my @cmds = @_;
634     return
635         sub {
636             my @cs  = ();
637             my @dcs = ();
638             my @els = ();
639             my $counter = 0;
640             foreach (@cmds) {
641                 my ($c, $dc, @el) = $_->(++$counter);
642
643                 return () if !$c;
644
645                 push @cs, $c;
646                 push @dcs, $dc;
647                 push @els, @el;
648             }
649             return (
650                 join(" | ", @cs),
651                 join(" | ", @dcs),
652                 @els
653                 );
654     };
655 }
656
657 =over 4
658
659 =item B<with HASHREF, CODEREF>
660
661 C<with> will temporarly install hooks given by the HASHREF and then execute
662 the given CODEREF.  Hooks are usually expected to have a coderef as value.
663
664 The currently available hoosk are:
665
666 =over 4
667
668 =item B<exit_checker =E<gt> CODEREF>
669
670 This hook is executed after C<run> has performed its given command.  The
671 CODEREF receives the exit code as only argument and is expected to return
672 1 (if the exit code indicated success) or 0 (if the exit code indicated
673 failure).
674
675 =back
676
677 =back
678
679 =cut
680
681 sub with {
682     my $opts = shift;
683     my %opts = %{$opts};
684     my $codeblock = shift;
685
686     my %saved_hooks = ();
687
688     foreach (keys %opts) {
689         $saved_hooks{$_} = $hooks{$_}   if exists($hooks{$_});
690         $hooks{$_} = $opts{$_};
691     }
692
693     $codeblock->();
694
695     foreach (keys %saved_hooks) {
696         $hooks{$_} = $saved_hooks{$_};
697     }
698 }
699
700 =over 4
701
702 =item B<cmdstr CODEREF, OPTS>
703
704 C<cmdstr> takes a CODEREF from C<app> or C<test> and simply returns the
705 command as a string.
706
707 C<cmdstr> takes some additiona options OPTS that affect the string returned:
708
709 =over 4
710
711 =item B<display =E<gt> 0|1>
712
713 When set to 0, the returned string will be with all decorations, such as a
714 possible redirect of stderr to the null device.  This is suitable if the
715 string is to be used directly in a recipe.
716
717 When set to 1, the returned string will be without extra decorations.  This
718 is suitable for display if that is desired (doesn't confuse people with all
719 internal stuff), or if it's used to pass a command down to a subprocess.
720
721 Default: 0
722
723 =back
724
725 =back
726
727 =cut
728
729 sub cmdstr {
730     my ($cmd, $display_cmd) = shift->(0);
731     my %opts = @_;
732
733     if ($opts{display}) {
734         return $display_cmd;
735     } else {
736         return $cmd;
737     }
738 }
739
740 =over 4
741
742 =item B<quotify LIST>
743
744 LIST is a list of strings that are going to be used as arguments for a
745 command, and makes sure to inject quotes and escapes as necessary depending
746 on the content of each string.
747
748 This can also be used to put quotes around the executable of a command.
749 I<This must never ever be done on VMS.>
750
751 =back
752
753 =cut
754
755 sub quotify {
756     # Unix setup (default if nothing else is mentioned)
757     my $arg_formatter =
758         sub { $_ = shift; /\s|[\{\}\\\$\[\]\*\?\|\&:;<>]/ ? "'$_'" : $_ };
759
760     if ( $^O eq "VMS") {        # VMS setup
761         $arg_formatter = sub {
762             $_ = shift;
763             if (/\s|["[:upper:]]/) {
764                 s/"/""/g;
765                 '"'.$_.'"';
766             } else {
767                 $_;
768             }
769         };
770     } elsif ( $^O eq "MSWin32") { # MSWin setup
771         $arg_formatter = sub {
772             $_ = shift;
773             if (/\s|["\|\&\*\;<>]/) {
774                 s/(["\\])/\\$1/g;
775                 '"'.$_.'"';
776             } else {
777                 $_;
778             }
779         };
780     }
781
782     return map { $arg_formatter->($_) } @_;
783 }
784
785 ######################################################################
786 # private functions.  These are never exported.
787
788 =head1 ENVIRONMENT
789
790 OpenSSL::Test depends on some environment variables.
791
792 =over 4
793
794 =item B<TOP>
795
796 This environment variable is mandatory.  C<setup> will check that it's
797 defined and that it's a directory that contains the file C<Configure>.
798 If this isn't so, C<setup> will C<BAIL_OUT>.
799
800 =item B<BIN_D>
801
802 If defined, its value should be the directory where the openssl application
803 is located.  Defaults to C<$TOP/apps> (adapted to the operating system).
804
805 =item B<TEST_D>
806
807 If defined, its value should be the directory where the test applications
808 are located.  Defaults to C<$TOP/test> (adapted to the operating system).
809
810 =item B<STOPTEST>
811
812 If defined, it puts testing in a different mode, where a recipe with
813 failures will result in a C<BAIL_OUT> at the end of its run.
814
815 =back
816
817 =cut
818
819 sub __env {
820     (my $recipe_datadir = basename($0)) =~ s/\.t$/_data/i;
821
822     $directories{SRCTOP}  = $ENV{SRCTOP} || $ENV{TOP};
823     $directories{BLDTOP}  = $ENV{BLDTOP} || $ENV{TOP};
824     $directories{BLDAPPS} = $ENV{BIN_D}  || __bldtop_dir("apps");
825     $directories{SRCAPPS} =                 __srctop_dir("apps");
826     $directories{BLDFUZZ} =                 __bldtop_dir("fuzz");
827     $directories{SRCFUZZ} =                 __srctop_dir("fuzz");
828     $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
829     $directories{SRCTEST} =                 __srctop_dir("test");
830     $directories{SRCDATA} =                 __srctop_dir("test", "recipes",
831                                                          $recipe_datadir);
832     $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
833
834     push @direnv, "TOP"       if $ENV{TOP};
835     push @direnv, "SRCTOP"    if $ENV{SRCTOP};
836     push @direnv, "BLDTOP"    if $ENV{BLDTOP};
837     push @direnv, "BIN_D"     if $ENV{BIN_D};
838     push @direnv, "TEST_D"    if $ENV{TEST_D};
839     push @direnv, "RESULT_D"  if $ENV{RESULT_D};
840
841     $end_with_bailout     = $ENV{STOPTEST} ? 1 : 0;
842 };
843
844 # __srctop_file and __srctop_dir are helpers to build file and directory
845 # names on top of the source directory.  They depend on $SRCTOP, and
846 # therefore on the proper use of setup() and when needed, indir().
847 # __bldtop_file and __bldtop_dir do the same thing but relative to $BLDTOP.
848 # __srctop_file and __bldtop_file take the same kind of argument as
849 # File::Spec::Functions::catfile.
850 # Similarly, __srctop_dir and __bldtop_dir take the same kind of argument
851 # as File::Spec::Functions::catdir
852 sub __srctop_file {
853     BAIL_OUT("Must run setup() first") if (! $test_name);
854
855     my $f = pop;
856     return catfile($directories{SRCTOP},@_,$f);
857 }
858
859 sub __srctop_dir {
860     BAIL_OUT("Must run setup() first") if (! $test_name);
861
862     return catdir($directories{SRCTOP},@_);
863 }
864
865 sub __bldtop_file {
866     BAIL_OUT("Must run setup() first") if (! $test_name);
867
868     my $f = pop;
869     return catfile($directories{BLDTOP},@_,$f);
870 }
871
872 sub __bldtop_dir {
873     BAIL_OUT("Must run setup() first") if (! $test_name);
874
875     return catdir($directories{BLDTOP},@_);
876 }
877
878 # __exeext is a function that returns the platform dependent file extension
879 # for executable binaries, or the value of the environment variable $EXE_EXT
880 # if that one is defined.
881 sub __exeext {
882     my $ext = "";
883     if ($^O eq "VMS" ) {        # VMS
884         $ext = ".exe";
885     } elsif ($^O eq "MSWin32") { # Windows
886         $ext = ".exe";
887     }
888     return $ENV{"EXE_EXT"} || $ext;
889 }
890
891 # __test_file, __apps_file and __fuzz_file return the full path to a file
892 # relative to the test/, apps/ or fuzz/ directory in the build tree or the
893 # source tree, depending on where the file is found.  Note that when looking
894 # in the build tree, the file name with an added extension is looked for, if
895 # an extension is given.  The intent is to look for executable binaries (in
896 # the build tree) or possibly scripts (in the source tree).
897 # These functions all take the same arguments as File::Spec::Functions::catfile,
898 # *plus* a mandatory extension argument.  This extension argument can be undef,
899 # and is ignored in such a case.
900 sub __test_file {
901     BAIL_OUT("Must run setup() first") if (! $test_name);
902
903     my $e = pop || "";
904     my $f = pop;
905     $f = catfile($directories{BLDTEST},@_,$f . $e);
906     $f = catfile($directories{SRCTEST},@_,$f) unless -f $f;
907     return $f;
908 }
909
910 sub __apps_file {
911     BAIL_OUT("Must run setup() first") if (! $test_name);
912
913     my $e = pop || "";
914     my $f = pop;
915     $f = catfile($directories{BLDAPPS},@_,$f . $e);
916     $f = catfile($directories{SRCAPPS},@_,$f) unless -f $f;
917     return $f;
918 }
919
920 sub __fuzz_file {
921     BAIL_OUT("Must run setup() first") if (! $test_name);
922
923     my $e = pop || "";
924     my $f = pop;
925     $f = catfile($directories{BLDFUZZ},@_,$f . $e);
926     $f = catfile($directories{SRCFUZZ},@_,$f) unless -f $f;
927     return $f;
928 }
929
930 sub __data_file {
931     BAIL_OUT("Must run setup() first") if (! $test_name);
932
933     my $f = pop;
934     return catfile($directories{SRCDATA},@_,$f);
935 }
936
937 sub __results_file {
938     BAIL_OUT("Must run setup() first") if (! $test_name);
939
940     my $f = pop;
941     return catfile($directories{RESULTS},@_,$f);
942 }
943
944 # __cwd DIR
945 # __cwd DIR, OPTS
946 #
947 # __cwd changes directory to DIR (string) and changes all the relative
948 # entries in %directories accordingly.  OPTS is an optional series of
949 # hash style arguments to alter __cwd's behavior:
950 #
951 #    create = 0|1       The directory we move to is created if 1, not if 0.
952 #    cleanup = 0|1      The directory we move from is removed if 1, not if 0.
953
954 sub __cwd {
955     my $dir = catdir(shift);
956     my %opts = @_;
957     my $abscurdir = rel2abs(curdir());
958     my $absdir = rel2abs($dir);
959     my $reverse = abs2rel($abscurdir, $absdir);
960
961     # PARANOIA: if we're not moving anywhere, we do nothing more
962     if ($abscurdir eq $absdir) {
963         return $reverse;
964     }
965
966     # Do not support a move to a different volume for now.  Maybe later.
967     BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
968         if $reverse eq $abscurdir;
969
970     # If someone happened to give a directory that leads back to the current,
971     # it's extremely silly to do anything more, so just simulate that we did
972     # move.
973     # In this case, we won't even clean it out, for safety's sake.
974     return "." if $reverse eq "";
975
976     $dir = canonpath($dir);
977     if ($opts{create}) {
978         mkpath($dir);
979     }
980
981     # We are recalculating the directories we keep track of, but need to save
982     # away the result for after having moved into the new directory.
983     my %tmp_directories = ();
984     my %tmp_ENV = ();
985
986     # For each of these directory variables, figure out where they are relative
987     # to the directory we want to move to if they aren't absolute (if they are,
988     # they don't change!)
989     my @dirtags = sort keys %directories;
990     foreach (@dirtags) {
991         if (!file_name_is_absolute($directories{$_})) {
992             my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
993             $tmp_directories{$_} = $newpath;
994         }
995     }
996
997     # Treat each environment variable that was used to get us the values in
998     # %directories the same was as the paths in %directories, so any sub
999     # process can use their values properly as well
1000     foreach (@direnv) {
1001         if (!file_name_is_absolute($ENV{$_})) {
1002             my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
1003             $tmp_ENV{$_} = $newpath;
1004         }
1005     }
1006
1007     # Should we just bail out here as well?  I'm unsure.
1008     return undef unless chdir($dir);
1009
1010     if ($opts{cleanup}) {
1011         rmtree(".", { safe => 0, keep_root => 1 });
1012     }
1013
1014     # We put back new values carefully.  Doing the obvious
1015     # %directories = ( %tmp_irectories )
1016     # will clear out any value that happens to be an absolute path
1017     foreach (keys %tmp_directories) {
1018         $directories{$_} = $tmp_directories{$_};
1019     }
1020     foreach (keys %tmp_ENV) {
1021         $ENV{$_} = $tmp_ENV{$_};
1022     }
1023
1024     if ($debug) {
1025         print STDERR "DEBUG: __cwd(), directories and files:\n";
1026         print STDERR "  \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
1027         print STDERR "  \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
1028         print STDERR "  \$directories{SRCDATA} = \"$directories{SRCDATA}\"\n";
1029         print STDERR "  \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
1030         print STDERR "  \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
1031         print STDERR "  \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
1032         print STDERR "  \$directories{SRCTOP}  = \"$directories{SRCTOP}\"\n";
1033         print STDERR "  \$directories{BLDTOP}  = \"$directories{BLDTOP}\"\n";
1034         print STDERR "\n";
1035         print STDERR "  current directory is \"",curdir(),"\"\n";
1036         print STDERR "  the way back is \"$reverse\"\n";
1037     }
1038
1039     return $reverse;
1040 }
1041
1042 # __wrap_cmd CMD
1043 # __wrap_cmd CMD, EXE_SHELL
1044 #
1045 # __wrap_cmd "wraps" CMD (string) with a beginning command that makes sure
1046 # the command gets executed with an appropriate environment.  If EXE_SHELL
1047 # is given, it is used as the beginning command.
1048 #
1049 # __wrap_cmd returns a list that should be used to build up a larger list
1050 # of command tokens, or be joined together like this:
1051 #
1052 #    join(" ", __wrap_cmd($cmd))
1053 sub __wrap_cmd {
1054     my $cmd = shift;
1055     my $exe_shell = shift;
1056
1057     my @prefix = ( __bldtop_file("util", "shlib_wrap.sh") );
1058
1059     if(defined($exe_shell)) {
1060         @prefix = ( $exe_shell );
1061     } elsif ($^O eq "VMS" || $^O eq "MSWin32") {
1062         # VMS and Windows don't use any wrapper script for the moment
1063         @prefix = ();
1064     }
1065
1066     return (@prefix, $cmd);
1067 }
1068
1069 # __fixup_prg PROG
1070 #
1071 # __fixup_prg does whatever fixup is needed to execute an executable binary
1072 # given by PROG (string).
1073 #
1074 # __fixup_prg returns a string with the possibly prefixed program path spec.
1075 sub __fixup_prg {
1076     my $prog = shift;
1077
1078     my $prefix = "";
1079
1080     if ($^O eq "VMS" ) {
1081         $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
1082     }
1083
1084     # We test if the program to use exists.
1085     if ( ! -x $prog ) {
1086         $prog = undef;
1087     }
1088
1089     if (defined($prog)) {
1090         # Make sure to quotify the program file on platforms that may
1091         # have spaces or similar in their path name.
1092         # To our knowledge, VMS is the exception where quotifying should
1093         # never happen.
1094         ($prog) = quotify($prog) unless $^O eq "VMS";
1095         return $prefix.$prog;
1096     }
1097
1098     print STDERR "$prog not found\n";
1099     return undef;
1100 }
1101
1102 # __decorate_cmd NUM, CMDARRAYREF
1103 #
1104 # __decorate_cmd takes a command number NUM and a command token array
1105 # CMDARRAYREF, builds up a command string from them and decorates it
1106 # with necessary redirections.
1107 # __decorate_cmd returns a list of two strings, one with the command
1108 # string to actually be used, the other to be displayed for the user.
1109 # The reason these strings might differ is that we redirect stderr to
1110 # the null device unless we're verbose and unless the user has
1111 # explicitly specified a stderr redirection.
1112 sub __decorate_cmd {
1113     BAIL_OUT("Must run setup() first") if (! $test_name);
1114
1115     my $num = shift;
1116     my $cmd = shift;
1117     my %opts = @_;
1118
1119     my $cmdstr = join(" ", @$cmd);
1120     my $null = devnull();
1121     my $fileornull = sub { $_[0] ? $_[0] : $null; };
1122     my $stdin = "";
1123     my $stdout = "";
1124     my $stderr = "";
1125     my $saved_stderr = undef;
1126     $stdin = " < ".$fileornull->($opts{stdin})  if exists($opts{stdin});
1127     $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
1128     $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
1129
1130     my $display_cmd = "$cmdstr$stdin$stdout$stderr";
1131
1132     $stderr=" 2> ".$null
1133         unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
1134
1135     $cmdstr .= "$stdin$stdout$stderr";
1136
1137     if ($debug) {
1138         print STDERR "DEBUG[__decorate_cmd]: \$cmdstr = \"$cmdstr\"\n";
1139         print STDERR "DEBUG[__decorate_cmd]: \$display_cmd = \"$display_cmd\"\n";
1140     }
1141
1142     return ($cmdstr, $display_cmd);
1143 }
1144
1145 =head1 SEE ALSO
1146
1147 L<Test::More>, L<Test::Harness>
1148
1149 =head1 AUTHORS
1150
1151 Richard Levitte E<lt>levitte@openssl.orgE<gt> with assitance and
1152 inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
1153
1154 =cut
1155
1156 1;