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