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