28c915af7b3ec83a3bc72c452ff43c7443693e8f
[oweals/openssl.git] / test / testlib / OpenSSL / Test.pm
1 package OpenSSL::Test;
2
3 use strict;
4 use warnings;
5
6 use Test::More 0.96;
7
8 use Exporter;
9 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
10 $VERSION = "0.8";
11 @ISA = qw(Exporter);
12 @EXPORT = (@Test::More::EXPORT, qw(setup indir app perlapp test perltest run));
13 @EXPORT_OK = (@Test::More::EXPORT_OK, qw(bldtop_dir bldtop_file
14                                          srctop_dir srctop_file
15                                          pipe with cmdstr quotify));
16
17 =head1 NAME
18
19 OpenSSL::Test - a private extension of Test::More
20
21 =head1 SYNOPSIS
22
23   use OpenSSL::Test;
24
25   setup("my_test_name");
26
27   ok(run(app(["openssl", "version"])), "check for openssl presence");
28
29   indir "subdir" => sub {
30     ok(run(test(["sometest", "arg1"], stdout => "foo.txt")),
31        "run sometest with output to foo.txt");
32   };
33
34 =head1 DESCRIPTION
35
36 This module is a private extension of L<Test::More> for testing OpenSSL.
37 In addition to the Test::More functions, it also provides functions that
38 easily find the diverse programs within a OpenSSL build tree, as well as
39 some other useful functions.
40
41 This module I<depends> on the environment variables C<$TOP> or C<$SRCTOP>
42 and C<$BLDTOP>.  Without one of the combinations it refuses to work.
43 See L</ENVIRONMENT> below.
44
45 =cut
46
47 use File::Copy;
48 use File::Spec::Functions qw/file_name_is_absolute curdir canonpath splitdir
49                              catdir catfile splitpath catpath devnull abs2rel
50                              rel2abs/;
51 use File::Path 2.00 qw/rmtree mkpath/;
52
53
54 # The name of the test.  This is set by setup() and is used in the other
55 # functions to verify that setup() has been used.
56 my $test_name = undef;
57
58 # Directories we want to keep track of TOP, APPS, TEST and RESULTS are the
59 # ones we're interested in, corresponding to the environment variables TOP
60 # (mandatory), BIN_D, TEST_D, UTIL_D and RESULT_D.
61 my %directories = ();
62
63 # The environment variables that gave us the contents in %directories.  These
64 # get modified whenever we change directories, so that subprocesses can use
65 # the values of those environment variables as well
66 my @direnv = ();
67
68 # A bool saying if we shall stop all testing if the current recipe has failing
69 # tests or not.  This is set by setup() if the environment variable STOPTEST
70 # is defined with a non-empty value.
71 my $end_with_bailout = 0;
72
73 # A set of hooks that is affected by with() and may be used in diverse places.
74 # All hooks are expected to be CODE references.
75 my %hooks = (
76
77     # exit_checker is used by run() directly after completion of a command.
78     # it receives the exit code from that command and is expected to return
79     # 1 (for success) or 0 (for failure).  This is the value that will be
80     # returned by run().
81     # NOTE: When run() gets the option 'capture => 1', this hook is ignored.
82     exit_checker => sub { return shift == 0 ? 1 : 0 },
83
84     );
85
86 # Debug flag, to be set manually when needed
87 my $debug = 0;
88
89 # Declare some utility functions that are defined at the end
90 sub bldtop_file;
91 sub bldtop_dir;
92 sub srctop_file;
93 sub srctop_dir;
94 sub quotify;
95
96 # Declare some private functions that are defined at the end
97 sub __env;
98 sub __cwd;
99 sub __apps_file;
100 sub __results_file;
101 sub __fixup_cmd;
102 sub __build_cmd;
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<app ARRAYREF, OPTS>
214
215 =item B<test ARRAYREF, OPTS>
216
217 Both of these functions take a reference to a list that is a command and
218 its arguments, and some additional options (described further on).
219
220 C<app> expects to find the given command (the first item in the given list
221 reference) as an executable in C<$BIN_D> (if defined, otherwise C<$TOP/apps>
222 or C<$BLDTOP/apps>).
223
224 C<test> expects to find the given command (the first item in the given list
225 reference) as an executable in C<$TEST_D> (if defined, otherwise C<$TOP/test>
226 or C<$BLDTOP/test>).
227
228 Both return a CODEREF to be used by C<run>, C<pipe> or C<cmdstr>.
229
230 The options that both C<app> and C<test> can take are in the form of hash
231 values:
232
233 =over 4
234
235 =item B<stdin =E<gt> PATH>
236
237 =item B<stdout =E<gt> PATH>
238
239 =item B<stderr =E<gt> PATH>
240
241 In all three cases, the corresponding standard input, output or error is
242 redirected from (for stdin) or to (for the others) a file given by the
243 string PATH, I<or>, if the value is C<undef>, C</dev/null> or similar.
244
245 =back
246
247 =item B<perlapp ARRAYREF, OPTS>
248
249 =item B<perltest ARRAYREF, OPTS>
250
251 Both these functions function the same way as B<app> and B<test>, except
252 that they expect the command to be a perl script.  Also, they support one
253 more option:
254
255 =over 4
256
257 =item B<interpreter_args =E<gt> ARRAYref>
258
259 The array reference is a set of arguments for perl rather than the script.
260 Take care so that none of them can be seen as a script!  Flags and their
261 eventual arguments only!
262
263 =back
264
265 An example:
266
267   ok(run(perlapp(["foo.pl", "arg1"],
268                  interpreter_args => [ "-I", srctop_dir("test") ])));
269
270 =back
271
272 =cut
273
274 sub app {
275     my $cmd = shift;
276     my %opts = @_;
277     return sub { my $num = shift;
278                  return __build_cmd($num, \&__apps_file, $cmd, %opts); }
279 }
280
281 sub test {
282     my $cmd = shift;
283     my %opts = @_;
284     return sub { my $num = shift;
285                  return __build_cmd($num, \&__test_file, $cmd, %opts); }
286 }
287
288 sub perlapp {
289     my $cmd = shift;
290     my %opts = @_;
291     return sub { my $num = shift;
292                  return __build_cmd($num, \&__perlapps_file, $cmd, %opts); }
293 }
294
295 sub perltest {
296     my $cmd = shift;
297     my %opts = @_;
298     return sub { my $num = shift;
299                  return __build_cmd($num, \&__perltest_file, $cmd, %opts); }
300 }
301
302 =over 4
303
304 =item B<run CODEREF, OPTS>
305
306 This CODEREF is expected to be the value return by C<app> or C<test>,
307 anything else will most likely cause an error unless you know what you're
308 doing.
309
310 C<run> executes the command returned by CODEREF and return either the
311 resulting output (if the option C<capture> is set true) or a boolean indicating
312 if the command succeeded or not.
313
314 The options that C<run> can take are in the form of hash values:
315
316 =over 4
317
318 =item B<capture =E<gt> 0|1>
319
320 If true, the command will be executed with a perl backtick, and C<run> will
321 return the resulting output as an array of lines.  If false or not given,
322 the command will be executed with C<system()>, and C<run> will return 1 if
323 the command was successful or 0 if it wasn't.
324
325 =back
326
327 For further discussion on what is considered a successful command or not, see
328 the function C<with> further down.
329
330 =back
331
332 =cut
333
334 sub run {
335     my ($cmd, $display_cmd) = shift->(0);
336     my %opts = @_;
337
338     return () if !$cmd;
339
340     my $prefix = "";
341     if ( $^O eq "VMS" ) {       # VMS
342         $prefix = "pipe ";
343     }
344
345     my @r = ();
346     my $r = 0;
347     my $e = 0;
348
349     # The dance we do with $? is the same dance the Unix shells appear to
350     # do.  For example, a program that gets aborted (and therefore signals
351     # SIGABRT = 6) will appear to exit with the code 134.  We mimic this
352     # to make it easier to compare with a manual run of the command.
353     if ($opts{capture}) {
354         @r = `$prefix$cmd`;
355         $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
356     } else {
357         system("$prefix$cmd");
358         $e = ($? & 0x7f) ? ($? & 0x7f)|0x80 : ($? >> 8);
359         $r = $hooks{exit_checker}->($e);
360     }
361
362     print STDERR "$prefix$display_cmd => $e\n"
363         if !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
364
365     # At this point, $? stops being interesting, and unfortunately,
366     # there are Test::More versions that get picky if we leave it
367     # non-zero.
368     $? = 0;
369
370     if ($opts{capture}) {
371         return @r;
372     } else {
373         return $r;
374     }
375 }
376
377 END {
378     my $tb = Test::More->builder;
379     my $failure = scalar(grep { $_ == 0; } $tb->summary);
380     if ($failure && $end_with_bailout) {
381         BAIL_OUT("Stoptest!");
382     }
383 }
384
385 =head2 Utility functions
386
387 The following functions are exported on request when using C<OpenSSL::Test>.
388
389   # To only get the bldtop_file and srctop_file functions.
390   use OpenSSL::Test qw/bldtop_file srctop_file/;
391
392   # To only get the bldtop_file function in addition to the default ones.
393   use OpenSSL::Test qw/:DEFAULT bldtop_file/;
394
395 =cut
396
397 # Utility functions, exported on request
398
399 =over 4
400
401 =item B<bldtop_dir LIST>
402
403 LIST is a list of directories that make up a path from the top of the OpenSSL
404 build directory (as indicated by the environment variable C<$TOP> or
405 C<$BLDTOP>).
406 C<bldtop_dir> returns the resulting directory as a string, adapted to the local
407 operating system.
408
409 =back
410
411 =cut
412
413 sub bldtop_dir {
414     return __bldtop_dir(@_);    # This caters for operating systems that have
415                                 # a very distinct syntax for directories.
416 }
417
418 =over 4
419
420 =item B<bldtop_file LIST, FILENAME>
421
422 LIST is a list of directories that make up a path from the top of the OpenSSL
423 build directory (as indicated by the environment variable C<$TOP> or
424 C<$BLDTOP>) and FILENAME is the name of a file located in that directory path.
425 C<bldtop_file> returns the resulting file path as a string, adapted to the local
426 operating system.
427
428 =back
429
430 =cut
431
432 sub bldtop_file {
433     return __bldtop_file(@_);
434 }
435
436 =over 4
437
438 =item B<srctop_dir LIST>
439
440 LIST is a list of directories that make up a path from the top of the OpenSSL
441 source directory (as indicated by the environment variable C<$TOP> or
442 C<$SRCTOP>).
443 C<srctop_dir> returns the resulting directory as a string, adapted to the local
444 operating system.
445
446 =back
447
448 =cut
449
450 sub srctop_dir {
451     return __srctop_dir(@_);    # This caters for operating systems that have
452                                 # a very distinct syntax for directories.
453 }
454
455 =over 4
456
457 =item B<srctop_file LIST, FILENAME>
458
459 LIST is a list of directories that make up a path from the top of the OpenSSL
460 source directory (as indicated by the environment variable C<$TOP> or
461 C<$SRCTOP>) and FILENAME is the name of a file located in that directory path.
462 C<srctop_file> returns the resulting file path as a string, adapted to the local
463 operating system.
464
465 =back
466
467 =cut
468
469 sub srctop_file {
470     return __srctop_file(@_);
471 }
472
473 =over 4
474
475 =item B<pipe LIST>
476
477 LIST is a list of CODEREFs returned by C<app> or C<test>, from which C<pipe>
478 creates a new command composed of all the given commands put together in a
479 pipe.  C<pipe> returns a new CODEREF in the same manner as C<app> or C<test>,
480 to be passed to C<run> for execution.
481
482 =back
483
484 =cut
485
486 sub pipe {
487     my @cmds = @_;
488     return
489         sub {
490             my @cs  = ();
491             my @dcs = ();
492             my @els = ();
493             my $counter = 0;
494             foreach (@cmds) {
495                 my ($c, $dc, @el) = $_->(++$counter);
496
497                 return () if !$c;
498
499                 push @cs, $c;
500                 push @dcs, $dc;
501                 push @els, @el;
502             }
503             return (
504                 join(" | ", @cs),
505                 join(" | ", @dcs),
506                 @els
507                 );
508     };
509 }
510
511 =over 4
512
513 =item B<with HASHREF, CODEREF>
514
515 C<with> will temporarly install hooks given by the HASHREF and then execute
516 the given CODEREF.  Hooks are usually expected to have a coderef as value.
517
518 The currently available hoosk are:
519
520 =over 4
521
522 =item B<exit_checker =E<gt> CODEREF>
523
524 This hook is executed after C<run> has performed its given command.  The
525 CODEREF receives the exit code as only argument and is expected to return
526 1 (if the exit code indicated success) or 0 (if the exit code indicated
527 failure).
528
529 =back
530
531 =back
532
533 =cut
534
535 sub with {
536     my $opts = shift;
537     my %opts = %{$opts};
538     my $codeblock = shift;
539
540     my %saved_hooks = ();
541
542     foreach (keys %opts) {
543         $saved_hooks{$_} = $hooks{$_}   if exists($hooks{$_});
544         $hooks{$_} = $opts{$_};
545     }
546
547     $codeblock->();
548
549     foreach (keys %saved_hooks) {
550         $hooks{$_} = $saved_hooks{$_};
551     }
552 }
553
554 =over 4
555
556 =item B<cmdstr CODEREF, OPTS>
557
558 C<cmdstr> takes a CODEREF from C<app> or C<test> and simply returns the
559 command as a string.
560
561 C<cmdstr> takes some additiona options OPTS that affect the string returned:
562
563 =over 4
564
565 =item B<display =E<gt> 0|1>
566
567 When set to 0, the returned string will be with all decorations, such as a
568 possible redirect of stderr to the null device.  This is suitable if the
569 string is to be used directly in a recipe.
570
571 When set to 1, the returned string will be without extra decorations.  This
572 is suitable for display if that is desired (doesn't confuse people with all
573 internal stuff), or if it's used to pass a command down to a subprocess.
574
575 Default: 0
576
577 =back
578
579 =back
580
581 =cut
582
583 sub cmdstr {
584     my ($cmd, $display_cmd) = shift->(0);
585     my %opts = @_;
586
587     if ($opts{display}) {
588         return $display_cmd;
589     } else {
590         return $cmd;
591     }
592 }
593
594 =over 4
595
596 =item B<quotify LIST>
597
598 LIST is a list of strings that are going to be used as arguments for a
599 command, and makes sure to inject quotes and escapes as necessary depending
600 on the content of each string.
601
602 This can also be used to put quotes around the executable of a command.
603 I<This must never ever be done on VMS.>
604
605 =back
606
607 =cut
608
609 sub quotify {
610     # Unix setup (default if nothing else is mentioned)
611     my $arg_formatter =
612         sub { $_ = shift; /\s|[\{\}\\\$\[\]\*\?\|\&:;<>]/ ? "'$_'" : $_ };
613
614     if ( $^O eq "VMS") {        # VMS setup
615         $arg_formatter = sub {
616             $_ = shift;
617             if (/\s|["[:upper:]]/) {
618                 s/"/""/g;
619                 '"'.$_.'"';
620             } else {
621                 $_;
622             }
623         };
624     } elsif ( $^O eq "MSWin32") { # MSWin setup
625         $arg_formatter = sub {
626             $_ = shift;
627             if (/\s|["\|\&\*\;<>]/) {
628                 s/(["\\])/\\$1/g;
629                 '"'.$_.'"';
630             } else {
631                 $_;
632             }
633         };
634     }
635
636     return map { $arg_formatter->($_) } @_;
637 }
638
639 ######################################################################
640 # private functions.  These are never exported.
641
642 =head1 ENVIRONMENT
643
644 OpenSSL::Test depends on some environment variables.
645
646 =over 4
647
648 =item B<TOP>
649
650 This environment variable is mandatory.  C<setup> will check that it's
651 defined and that it's a directory that contains the file C<Configure>.
652 If this isn't so, C<setup> will C<BAIL_OUT>.
653
654 =item B<BIN_D>
655
656 If defined, its value should be the directory where the openssl application
657 is located.  Defaults to C<$TOP/apps> (adapted to the operating system).
658
659 =item B<TEST_D>
660
661 If defined, its value should be the directory where the test applications
662 are located.  Defaults to C<$TOP/test> (adapted to the operating system).
663
664 =item B<STOPTEST>
665
666 If defined, it puts testing in a different mode, where a recipe with
667 failures will result in a C<BAIL_OUT> at the end of its run.
668
669 =back
670
671 =cut
672
673 sub __env {
674     $directories{SRCTOP}  = $ENV{SRCTOP} || $ENV{TOP};
675     $directories{BLDTOP}  = $ENV{BLDTOP} || $ENV{TOP};
676     $directories{BLDAPPS} = $ENV{BIN_D}  || __bldtop_dir("apps");
677     $directories{SRCAPPS} =                 __srctop_dir("apps");
678     $directories{BLDTEST} = $ENV{TEST_D} || __bldtop_dir("test");
679     $directories{SRCTEST} =                 __srctop_dir("test");
680     $directories{RESULTS} = $ENV{RESULT_D} || $directories{BLDTEST};
681
682     push @direnv, "TOP"       if $ENV{TOP};
683     push @direnv, "SRCTOP"    if $ENV{SRCTOP};
684     push @direnv, "BLDTOP"    if $ENV{BLDTOP};
685     push @direnv, "BIN_D"     if $ENV{BIN_D};
686     push @direnv, "TEST_D"    if $ENV{TEST_D};
687     push @direnv, "RESULT_D"  if $ENV{RESULT_D};
688
689     $end_with_bailout     = $ENV{STOPTEST} ? 1 : 0;
690 };
691
692 sub __srctop_file {
693     BAIL_OUT("Must run setup() first") if (! $test_name);
694
695     my $f = pop;
696     return catfile($directories{SRCTOP},@_,$f);
697 }
698
699 sub __srctop_dir {
700     BAIL_OUT("Must run setup() first") if (! $test_name);
701
702     return catdir($directories{SRCTOP},@_);
703 }
704
705 sub __bldtop_file {
706     BAIL_OUT("Must run setup() first") if (! $test_name);
707
708     my $f = pop;
709     return catfile($directories{BLDTOP},@_,$f);
710 }
711
712 sub __bldtop_dir {
713     BAIL_OUT("Must run setup() first") if (! $test_name);
714
715     return catdir($directories{BLDTOP},@_);
716 }
717
718 sub __exeext {
719     my $ext = "";
720     if ($^O eq "VMS" ) {        # VMS
721         $ext = ".exe";
722     } elsif ($^O eq "MSWin32") { # Windows
723         $ext = ".exe";
724     }
725     return $ENV{"EXE_EXT"} || $ext;
726 }
727
728 sub __test_file {
729     BAIL_OUT("Must run setup() first") if (! $test_name);
730
731     my $f = pop . __exeext();
732     $f = catfile($directories{BLDTEST},@_,$f);
733     $f = catfile($directories{SRCTEST},@_,$f) unless -x $f;
734     return $f;
735 }
736
737 sub __perltest_file {
738     BAIL_OUT("Must run setup() first") if (! $test_name);
739
740     my $f = pop;
741     $f = catfile($directories{BLDTEST},@_,$f);
742     $f = catfile($directories{SRCTEST},@_,$f) unless -f $f;
743     return ($^X, $f);
744 }
745
746 sub __apps_file {
747     BAIL_OUT("Must run setup() first") if (! $test_name);
748
749     my $f = pop . __exeext();
750     $f = catfile($directories{BLDAPPS},@_,$f);
751     $f = catfile($directories{SRCAPPS},@_,$f) unless -x $f;
752     return $f;
753 }
754
755 sub __perlapps_file {
756     BAIL_OUT("Must run setup() first") if (! $test_name);
757
758     my $f = pop;
759     $f = catfile($directories{BLDAPPS},@_,$f);
760     $f = catfile($directories{SRCAPPS},@_,$f) unless -f $f;
761     return ($^X, $f);
762 }
763
764 sub __results_file {
765     BAIL_OUT("Must run setup() first") if (! $test_name);
766
767     my $f = pop;
768     return catfile($directories{RESULTS},@_,$f);
769 }
770
771 sub __cwd {
772     my $dir = catdir(shift);
773     my %opts = @_;
774     my $abscurdir = rel2abs(curdir());
775     my $absdir = rel2abs($dir);
776     my $reverse = abs2rel($abscurdir, $absdir);
777
778     # PARANOIA: if we're not moving anywhere, we do nothing more
779     if ($abscurdir eq $absdir) {
780         return $reverse;
781     }
782
783     # Do not support a move to a different volume for now.  Maybe later.
784     BAIL_OUT("FAILURE: \"$dir\" moves to a different volume, not supported")
785         if $reverse eq $abscurdir;
786
787     # If someone happened to give a directory that leads back to the current,
788     # it's extremely silly to do anything more, so just simulate that we did
789     # move.
790     # In this case, we won't even clean it out, for safety's sake.
791     return "." if $reverse eq "";
792
793     $dir = canonpath($dir);
794     if ($opts{create}) {
795         mkpath($dir);
796     }
797
798     # Should we just bail out here as well?  I'm unsure.
799     return undef unless chdir($dir);
800
801     if ($opts{cleanup}) {
802         rmtree(".", { safe => 0, keep_root => 1 });
803     }
804
805     # For each of these directory variables, figure out where they are relative
806     # to the directory we want to move to if they aren't absolute (if they are,
807     # they don't change!)
808     my @dirtags = sort keys %directories;
809     foreach (@dirtags) {
810         if (!file_name_is_absolute($directories{$_})) {
811             my $newpath = abs2rel(rel2abs($directories{$_}), rel2abs($dir));
812             $directories{$_} = $newpath;
813         }
814     }
815
816     # Treat each environment variable that was used to get us the values in
817     # %directories the same was as the paths in %directories, so any sub
818     # process can use their values properly as well
819     foreach (@direnv) {
820         if (!file_name_is_absolute($ENV{$_})) {
821             my $newpath = abs2rel(rel2abs($ENV{$_}), rel2abs($dir));
822             $ENV{$_} = $newpath;
823         }
824     }
825
826     if ($debug) {
827         print STDERR "DEBUG: __cwd(), directories and files:\n";
828         print STDERR "  \$directories{BLDTEST} = \"$directories{BLDTEST}\"\n";
829         print STDERR "  \$directories{SRCTEST} = \"$directories{SRCTEST}\"\n";
830         print STDERR "  \$directories{RESULTS} = \"$directories{RESULTS}\"\n";
831         print STDERR "  \$directories{BLDAPPS} = \"$directories{BLDAPPS}\"\n";
832         print STDERR "  \$directories{SRCAPPS} = \"$directories{SRCAPPS}\"\n";
833         print STDERR "  \$directories{SRCTOP}  = \"$directories{SRCTOP}\"\n";
834         print STDERR "  \$directories{BLDTOP}  = \"$directories{BLDTOP}\"\n";
835         print STDERR "\n";
836         print STDERR "  current directory is \"",curdir(),"\"\n";
837         print STDERR "  the way back is \"$reverse\"\n";
838     }
839
840     return $reverse;
841 }
842
843 sub __fixup_cmd {
844     my $prog = shift;
845     my $exe_shell = shift;
846
847     my $prefix = __bldtop_file("util", "shlib_wrap.sh")." ";
848
849     if (defined($exe_shell)) {
850         $prefix = "$exe_shell ";
851     } elsif ($^O eq "VMS" ) {   # VMS
852         $prefix = ($prog =~ /^(?:[\$a-z0-9_]+:)?[<\[]/i ? "mcr " : "mcr []");
853     } elsif ($^O eq "MSWin32") { # Windows
854         $prefix = "";
855     }
856
857     # We test both with and without extension.  The reason
858     # is that we might be passed a complete file spec, with
859     # extension.
860     if ( ! -x $prog ) {
861         my $prog = "$prog";
862         if ( ! -x $prog ) {
863             $prog = undef;
864         }
865     }
866
867     if (defined($prog)) {
868         # Make sure to quotify the program file on platforms that may
869         # have spaces or similar in their path name.
870         # To our knowledge, VMS is the exception where quotifying should
871         # never happem.
872         ($prog) = quotify($prog) unless $^O eq "VMS";
873         return $prefix.$prog;
874     }
875
876     print STDERR "$prog not found\n";
877     return undef;
878 }
879
880 sub __build_cmd {
881     BAIL_OUT("Must run setup() first") if (! $test_name);
882
883     my $num = shift;
884     my $path_builder = shift;
885     # Make a copy to not destroy the caller's array
886     my @cmdarray = ( @{$_[0]} ); shift;
887     my %opts = @_;
888
889     # We do a little dance, as $path_builder might return a list of
890     # more than one.  If so, only the first is to be considered a
891     # program to fix up, the rest is part of the arguments.  This
892     # happens for perl scripts, where $path_builder will return
893     # a list of two, $^X and the script name.
894     # Also, if $path_builder returned more than one, we don't apply
895     # the EXE_SHELL environment variable.
896     my @prog = ($path_builder->(shift @cmdarray));
897     my $first = shift @prog;
898     my $exe_shell = @prog ? undef : $ENV{EXE_SHELL};
899     my $cmd = __fixup_cmd($first, $exe_shell);
900     if (@prog) {
901         if ( ! -f $prog[0] ) {
902             print STDERR "$prog[0] not found\n";
903             $cmd = undef;
904         }
905     }
906     my @args = (@prog, @cmdarray);
907     if (defined($opts{interpreter_args})) {
908         unshift @args, @{$opts{interpreter_args}};
909     }
910
911     return () if !$cmd;
912
913     my $arg_str = "";
914     my $null = devnull();
915
916
917     $arg_str = " ".join(" ", quotify @args) if @args;
918
919     my $fileornull = sub { $_[0] ? $_[0] : $null; };
920     my $stdin = "";
921     my $stdout = "";
922     my $stderr = "";
923     my $saved_stderr = undef;
924     $stdin = " < ".$fileornull->($opts{stdin})  if exists($opts{stdin});
925     $stdout= " > ".$fileornull->($opts{stdout}) if exists($opts{stdout});
926     $stderr=" 2> ".$fileornull->($opts{stderr}) if exists($opts{stderr});
927
928     my $display_cmd = "$cmd$arg_str$stdin$stdout$stderr";
929
930     $stderr=" 2> ".$null
931         unless $stderr || !$ENV{HARNESS_ACTIVE} || $ENV{HARNESS_VERBOSE};
932
933     $cmd .= "$arg_str$stdin$stdout$stderr";
934
935     if ($debug) {
936         print STDERR "DEBUG[__build_cmd]: \$cmd = \"$cmd\"\n";
937         print STDERR "DEBUG[__build_cmd]: \$display_cmd = \"$display_cmd\"\n";
938     }
939
940     return ($cmd, $display_cmd);
941 }
942
943 =head1 SEE ALSO
944
945 L<Test::More>, L<Test::Harness>
946
947 =head1 AUTHORS
948
949 Richard Levitte E<lt>levitte@openssl.orgE<gt> with assitance and
950 inspiration from Andy Polyakov E<lt>appro@openssl.org<gt>.
951
952 =cut
953
954 1;