This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Remove the two "VMS adjustments" from test.pl's _fresh_perl
[perl5.git] / t / test.pl
1 #
2 # t/test.pl - most of Test::More functionality without the fuss, plus
3 # has mappings native_to_latin1 and latin1_to_native so that fewer tests
4 # on non ASCII-ish platforms need to be skipped
5
6
7 # NOTE:
8 #
9 # Increment ($x++) has a certain amount of cleverness for things like
10 #
11 #   $x = 'zz';
12 #   $x++; # $x eq 'aaa';
13 #
14 # stands more chance of breaking than just a simple
15 #
16 #   $x = $x + 1
17 #
18 # In this file, we use the latter "Baby Perl" approach, and increment
19 # will be worked over by t/op/inc.t
20
21 $Level = 1;
22 my $test = 1;
23 my $planned;
24 my $noplan;
25 my $Perl;       # Safer version of $^X set by which_perl()
26
27 # This defines ASCII/UTF-8 vs EBCDIC/UTF-EBCDIC
28 $::IS_ASCII  = ord 'A' ==  65;
29 $::IS_EBCDIC = ord 'A' == 193;
30
31 $TODO = 0;
32 $NO_ENDING = 0;
33 $Tests_Are_Passing = 1;
34
35 # Use this instead of print to avoid interference while testing globals.
36 sub _print {
37     local($\, $", $,) = (undef, ' ', '');
38     print STDOUT @_;
39 }
40
41 sub _print_stderr {
42     local($\, $", $,) = (undef, ' ', '');
43     print STDERR @_;
44 }
45
46 sub plan {
47     my $n;
48     if (@_ == 1) {
49         $n = shift;
50         if ($n eq 'no_plan') {
51           undef $n;
52           $noplan = 1;
53         }
54     } else {
55         my %plan = @_;
56         $n = $plan{tests};
57     }
58     _print "1..$n\n" unless $noplan;
59     $planned = $n;
60 }
61
62
63 # Set the plan at the end.  See Test::More::done_testing.
64 sub done_testing {
65     my $n = $test - 1;
66     $n = shift if @_;
67
68     _print "1..$n\n";
69     $planned = $n;
70 }
71
72
73 END {
74     my $ran = $test - 1;
75     if (!$NO_ENDING) {
76         if (defined $planned && $planned != $ran) {
77             _print_stderr
78                 "# Looks like you planned $planned tests but ran $ran.\n";
79         } elsif ($noplan) {
80             _print "1..$ran\n";
81         }
82     }
83 }
84
85 sub _diag {
86     return unless @_;
87     my @mess = _comment(@_);
88     $TODO ? _print(@mess) : _print_stderr(@mess);
89 }
90
91 # Use this instead of "print STDERR" when outputting failure diagnostic
92 # messages
93 sub diag {
94     _diag(@_);
95 }
96
97 # Use this instead of "print" when outputting informational messages
98 sub note {
99     return unless @_;
100     _print( _comment(@_) );
101 }
102
103 sub is_miniperl {
104     return !defined &DynaLoader::boot_DynaLoader;
105 }
106
107 sub _comment {
108     return map { /^#/ ? "$_\n" : "# $_\n" }
109            map { split /\n/ } @_;
110 }
111
112 sub _have_dynamic_extension {
113     my $extension = shift;
114     unless (eval {require Config; 1}) {
115         warn "test.pl had problems loading Config: $@";
116         return 1;
117     }
118     $extension =~ s!::!/!g;
119     return 1 if ($Config::Config{extensions} =~ /\b$extension\b/);
120 }
121
122 sub skip_all {
123     if (@_) {
124         _print "1..0 # Skip @_\n";
125     } else {
126         _print "1..0\n";
127     }
128     exit(0);
129 }
130
131 sub skip_all_if_miniperl {
132     skip_all(@_) if is_miniperl();
133 }
134
135 sub skip_all_without_dynamic_extension {
136     my ($extension) = @_;
137     skip_all("no dynamic loading on miniperl, no $extension") if is_miniperl();
138     return if &_have_dynamic_extension;
139     skip_all("$extension was not built");
140 }
141
142 sub skip_all_without_perlio {
143     skip_all('no PerlIO') unless PerlIO::Layer->find('perlio');
144 }
145
146 sub skip_all_without_config {
147     unless (eval {require Config; 1}) {
148         warn "test.pl had problems loading Config: $@";
149         return;
150     }
151     foreach (@_) {
152         next if $Config::Config{$_};
153         my $key = $_; # Need to copy, before trying to modify.
154         $key =~ s/^use//;
155         $key =~ s/^d_//;
156         skip_all("no $key");
157     }
158 }
159
160 sub find_git_or_skip {
161     my ($source_dir, $reason);
162     if (-d '.git') {
163         $source_dir = '.';
164     } elsif (-l 'MANIFEST' && -l 'AUTHORS') {
165         my $where = readlink 'MANIFEST';
166         die "Can't readling MANIFEST: $!" unless defined $where;
167         die "Confusing symlink target for MANIFEST, '$where'"
168             unless $where =~ s!/MANIFEST\z!!;
169         if (-d "$where/.git") {
170             # Looks like we are in a symlink tree
171             if (exists $ENV{GIT_DIR}) {
172                 diag("Found source tree at $where, but \$ENV{GIT_DIR} is $ENV{GIT_DIR}. Not changing it");
173             } else {
174                 note("Found source tree at $where, setting \$ENV{GIT_DIR}");
175                 $ENV{GIT_DIR} = "$where/.git";
176             }
177             $source_dir = $where;
178         }
179     }
180     if ($source_dir) {
181         my $version_string = `git --version`;
182         if (defined $version_string
183               && $version_string =~ /\Agit version (\d+\.\d+\.\d+)(.*)/) {
184             return $source_dir if eval "v$1 ge v1.5.0";
185             # If you have earlier than 1.5.0 and it works, change this test
186             $reason = "in git checkout, but git version '$1$2' too old";
187         } else {
188             $reason = "in git checkout, but cannot run git";
189         }
190     } else {
191         $reason = 'not being run from a git checkout';
192     }
193     skip_all($reason) if $_[0] && $_[0] eq 'all';
194     skip($reason, @_);
195 }
196
197 sub BAIL_OUT {
198     my ($reason) = @_;
199     _print("Bail out!  $reason\n");
200     exit 255;
201 }
202
203 sub _ok {
204     my ($pass, $where, $name, @mess) = @_;
205     # Do not try to microoptimize by factoring out the "not ".
206     # VMS will avenge.
207     my $out;
208     if ($name) {
209         # escape out '#' or it will interfere with '# skip' and such
210         $name =~ s/#/\\#/g;
211         $out = $pass ? "ok $test - $name" : "not ok $test - $name";
212     } else {
213         $out = $pass ? "ok $test" : "not ok $test";
214     }
215
216     if ($TODO) {
217         $out = $out . " # TODO $TODO";
218     } else {
219         $Tests_Are_Passing = 0 unless $pass;
220     }
221
222     _print "$out\n";
223
224     if ($pass) {
225         note @mess; # Ensure that the message is properly escaped.
226     }
227     else {
228         my $msg = "# Failed test $test - ";
229         $msg.= "$name " if $name;
230         $msg .= "$where\n";
231         _diag $msg;
232         _diag @mess;
233     }
234
235     $test = $test + 1; # don't use ++
236
237     return $pass;
238 }
239
240 sub _where {
241     my @caller = caller($Level);
242     return "at $caller[1] line $caller[2]";
243 }
244
245 # DON'T use this for matches. Use like() instead.
246 sub ok ($@) {
247     my ($pass, $name, @mess) = @_;
248     _ok($pass, _where(), $name, @mess);
249 }
250
251 sub _q {
252     my $x = shift;
253     return 'undef' unless defined $x;
254     my $q = $x;
255     $q =~ s/\\/\\\\/g;
256     $q =~ s/'/\\'/g;
257     return "'$q'";
258 }
259
260 sub _qq {
261     my $x = shift;
262     return defined $x ? '"' . display ($x) . '"' : 'undef';
263 };
264
265 # keys are the codes \n etc map to, values are 2 char strings such as \n
266 my %backslash_escape;
267 foreach my $x (split //, 'nrtfa\\\'"') {
268     $backslash_escape{ord eval "\"\\$x\""} = "\\$x";
269 }
270 # A way to display scalars containing control characters and Unicode.
271 # Trying to avoid setting $_, or relying on local $_ to work.
272 sub display {
273     my @result;
274     foreach my $x (@_) {
275         if (defined $x and not ref $x) {
276             my $y = '';
277             foreach my $c (unpack("U*", $x)) {
278                 if ($c > 255) {
279                     $y = $y . sprintf "\\x{%x}", $c;
280                 } elsif ($backslash_escape{$c}) {
281                     $y = $y . $backslash_escape{$c};
282                 } else {
283                     my $z = chr $c; # Maybe we can get away with a literal...
284                     if ($z =~ /[[:^print:]]/) {
285
286                         # Use octal for characters traditionally expressed as
287                         # such: the low controls
288                         if ($c <= 037) {
289                             $z = sprintf "\\%03o", $c;
290                         } else {
291                             $z = sprintf "\\x{%x}", $c;
292                         }
293                     }
294                     $y = $y . $z;
295                 }
296             }
297             $x = $y;
298         }
299         return $x unless wantarray;
300         push @result, $x;
301     }
302     return @result;
303 }
304
305 sub is ($$@) {
306     my ($got, $expected, $name, @mess) = @_;
307
308     my $pass;
309     if( !defined $got || !defined $expected ) {
310         # undef only matches undef
311         $pass = !defined $got && !defined $expected;
312     }
313     else {
314         $pass = $got eq $expected;
315     }
316
317     unless ($pass) {
318         unshift(@mess, "#      got "._qq($got)."\n",
319                        "# expected "._qq($expected)."\n");
320     }
321     _ok($pass, _where(), $name, @mess);
322 }
323
324 sub isnt ($$@) {
325     my ($got, $isnt, $name, @mess) = @_;
326
327     my $pass;
328     if( !defined $got || !defined $isnt ) {
329         # undef only matches undef
330         $pass = defined $got || defined $isnt;
331     }
332     else {
333         $pass = $got ne $isnt;
334     }
335
336     unless( $pass ) {
337         unshift(@mess, "# it should not be "._qq($got)."\n",
338                        "# but it is.\n");
339     }
340     _ok($pass, _where(), $name, @mess);
341 }
342
343 sub cmp_ok ($$$@) {
344     my($got, $type, $expected, $name, @mess) = @_;
345
346     my $pass;
347     {
348         local $^W = 0;
349         local($@,$!);   # don't interfere with $@
350                         # eval() sometimes resets $!
351         $pass = eval "\$got $type \$expected";
352     }
353     unless ($pass) {
354         # It seems Irix long doubles can have 2147483648 and 2147483648
355         # that stringify to the same thing but are actually numerically
356         # different. Display the numbers if $type isn't a string operator,
357         # and the numbers are stringwise the same.
358         # (all string operators have alphabetic names, so tr/a-z// is true)
359         # This will also show numbers for some unneeded cases, but will
360         # definitely be helpful for things such as == and <= that fail
361         if ($got eq $expected and $type !~ tr/a-z//) {
362             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
363         }
364         unshift(@mess, "#      got "._qq($got)."\n",
365                        "# expected $type "._qq($expected)."\n");
366     }
367     _ok($pass, _where(), $name, @mess);
368 }
369
370 # Check that $got is within $range of $expected
371 # if $range is 0, then check it's exact
372 # else if $expected is 0, then $range is an absolute value
373 # otherwise $range is a fractional error.
374 # Here $range must be numeric, >= 0
375 # Non numeric ranges might be a useful future extension. (eg %)
376 sub within ($$$@) {
377     my ($got, $expected, $range, $name, @mess) = @_;
378     my $pass;
379     if (!defined $got or !defined $expected or !defined $range) {
380         # This is a fail, but doesn't need extra diagnostics
381     } elsif ($got !~ tr/0-9// or $expected !~ tr/0-9// or $range !~ tr/0-9//) {
382         # This is a fail
383         unshift @mess, "# got, expected and range must be numeric\n";
384     } elsif ($range < 0) {
385         # This is also a fail
386         unshift @mess, "# range must not be negative\n";
387     } elsif ($range == 0) {
388         # Within 0 is ==
389         $pass = $got == $expected;
390     } elsif ($expected == 0) {
391         # If expected is 0, treat range as absolute
392         $pass = ($got <= $range) && ($got >= - $range);
393     } else {
394         my $diff = $got - $expected;
395         $pass = abs ($diff / $expected) < $range;
396     }
397     unless ($pass) {
398         if ($got eq $expected) {
399             unshift @mess, "# $got - $expected = " . ($got - $expected) . "\n";
400         }
401         unshift@mess, "#      got "._qq($got)."\n",
402                       "# expected "._qq($expected)." (within "._qq($range).")\n";
403     }
404     _ok($pass, _where(), $name, @mess);
405 }
406
407 # Note: this isn't quite as fancy as Test::More::like().
408
409 sub like   ($$@) { like_yn (0,@_) }; # 0 for -
410 sub unlike ($$@) { like_yn (1,@_) }; # 1 for un-
411
412 sub like_yn ($$$@) {
413     my ($flip, undef, $expected, $name, @mess) = @_;
414     my $pass;
415     $pass = $_[1] =~ /$expected/ if !$flip;
416     $pass = $_[1] !~ /$expected/ if $flip;
417     unless ($pass) {
418         unshift(@mess, "#      got '$_[1]'\n",
419                 $flip
420                 ? "# expected !~ /$expected/\n" : "# expected /$expected/\n");
421     }
422     local $Level = $Level + 1;
423     _ok($pass, _where(), $name, @mess);
424 }
425
426 sub pass {
427     _ok(1, '', @_);
428 }
429
430 sub fail {
431     _ok(0, _where(), @_);
432 }
433
434 sub curr_test {
435     $test = shift if @_;
436     return $test;
437 }
438
439 sub next_test {
440   my $retval = $test;
441   $test = $test + 1; # don't use ++
442   $retval;
443 }
444
445 # Note: can't pass multipart messages since we try to
446 # be compatible with Test::More::skip().
447 sub skip {
448     my $why = shift;
449     my $n    = @_ ? shift : 1;
450     for (1..$n) {
451         _print "ok $test # skip $why\n";
452         $test = $test + 1;
453     }
454     local $^W = 0;
455     last SKIP;
456 }
457
458 sub skip_if_miniperl {
459     skip(@_) if is_miniperl();
460 }
461
462 sub skip_without_dynamic_extension {
463     my ($extension) = @_;
464     skip("no dynamic loading on miniperl, no $extension") if is_miniperl();
465     return if &_have_dynamic_extension;
466     skip("$extension was not built");
467 }
468
469 sub todo_skip {
470     my $why = shift;
471     my $n   = @_ ? shift : 1;
472
473     for (1..$n) {
474         _print "not ok $test # TODO & SKIP $why\n";
475         $test = $test + 1;
476     }
477     local $^W = 0;
478     last TODO;
479 }
480
481 sub eq_array {
482     my ($ra, $rb) = @_;
483     return 0 unless $#$ra == $#$rb;
484     for my $i (0..$#$ra) {
485         next     if !defined $ra->[$i] && !defined $rb->[$i];
486         return 0 if !defined $ra->[$i];
487         return 0 if !defined $rb->[$i];
488         return 0 unless $ra->[$i] eq $rb->[$i];
489     }
490     return 1;
491 }
492
493 sub eq_hash {
494   my ($orig, $suspect) = @_;
495   my $fail;
496   while (my ($key, $value) = each %$suspect) {
497     # Force a hash recompute if this perl's internals can cache the hash key.
498     $key = "" . $key;
499     if (exists $orig->{$key}) {
500       if (
501         defined $orig->{$key} != defined $value
502         || (defined $value && $orig->{$key} ne $value)
503       ) {
504         _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
505                      " now ", _qq($value), "\n";
506         $fail = 1;
507       }
508     } else {
509       _print "# key ", _qq($key), " is ", _qq($value),
510                    ", not in original.\n";
511       $fail = 1;
512     }
513   }
514   foreach (keys %$orig) {
515     # Force a hash recompute if this perl's internals can cache the hash key.
516     $_ = "" . $_;
517     next if (exists $suspect->{$_});
518     _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
519     $fail = 1;
520   }
521   !$fail;
522 }
523
524 # We only provide a subset of the Test::More functionality.
525 sub require_ok ($) {
526     my ($require) = @_;
527     if ($require =~ tr/[A-Za-z0-9:.]//c) {
528         fail("Invalid character in \"$require\", passed to require_ok");
529     } else {
530         eval <<REQUIRE_OK;
531 require $require;
532 REQUIRE_OK
533         is($@, '', _where(), "require $require");
534     }
535 }
536
537 sub use_ok ($) {
538     my ($use) = @_;
539     if ($use =~ tr/[A-Za-z0-9:.]//c) {
540         fail("Invalid character in \"$use\", passed to use");
541     } else {
542         eval <<USE_OK;
543 use $use;
544 USE_OK
545         is($@, '', _where(), "use $use");
546     }
547 }
548
549 # runperl - Runs a separate perl interpreter.
550 # Arguments :
551 #   switches => [ command-line switches ]
552 #   nolib    => 1 # don't use -I../lib (included by default)
553 #   non_portable => Don't warn if a one liner contains quotes
554 #   prog     => one-liner (avoid quotes)
555 #   progs    => [ multi-liner (avoid quotes) ]
556 #   progfile => perl script
557 #   stdin    => string to feed the stdin
558 #   stderr   => redirect stderr to stdout
559 #   args     => [ command-line arguments to the perl program ]
560 #   verbose  => print the command line
561
562 my $is_mswin    = $^O eq 'MSWin32';
563 my $is_netware  = $^O eq 'NetWare';
564 my $is_vms      = $^O eq 'VMS';
565 my $is_cygwin   = $^O eq 'cygwin';
566
567 sub _quote_args {
568     my ($runperl, $args) = @_;
569
570     foreach (@$args) {
571         # In VMS protect with doublequotes because otherwise
572         # DCL will lowercase -- unless already doublequoted.
573        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
574        $runperl = $runperl . ' ' . $_;
575     }
576     return $runperl;
577 }
578
579 sub _create_runperl { # Create the string to qx in runperl().
580     my %args = @_;
581     my $runperl = which_perl();
582     if ($runperl =~ m/\s/) {
583         $runperl = qq{"$runperl"};
584     }
585     #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
586     if ($ENV{PERL_RUNPERL_DEBUG}) {
587         $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
588     }
589     unless ($args{nolib}) {
590         $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
591     }
592     if ($args{switches}) {
593         local $Level = 2;
594         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
595             unless ref $args{switches} eq "ARRAY";
596         $runperl = _quote_args($runperl, $args{switches});
597     }
598     if (defined $args{prog}) {
599         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
600             if defined $args{progs};
601         $args{progs} = [$args{prog}]
602     }
603     if (defined $args{progs}) {
604         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
605             unless ref $args{progs} eq "ARRAY";
606         foreach my $prog (@{$args{progs}}) {
607             if ($prog =~ tr/'"// && !$args{non_portable}) {
608                 warn "quotes in prog >>$prog<< are not portable";
609             }
610             if ($is_mswin || $is_netware || $is_vms) {
611                 $runperl = $runperl . qq ( -e "$prog" );
612             }
613             else {
614                 $runperl = $runperl . qq ( -e '$prog' );
615             }
616         }
617     } elsif (defined $args{progfile}) {
618         $runperl = $runperl . qq( "$args{progfile}");
619     } else {
620         # You probably didn't want to be sucking in from the upstream stdin
621         die "test.pl:runperl(): none of prog, progs, progfile, args, "
622             . " switches or stdin specified"
623             unless defined $args{args} or defined $args{switches}
624                 or defined $args{stdin};
625     }
626     if (defined $args{stdin}) {
627         # so we don't try to put literal newlines and crs onto the
628         # command line.
629         $args{stdin} =~ s/\n/\\n/g;
630         $args{stdin} =~ s/\r/\\r/g;
631
632         if ($is_mswin || $is_netware || $is_vms) {
633             $runperl = qq{$Perl -e "print qq(} .
634                 $args{stdin} . q{)" | } . $runperl;
635         }
636         else {
637             $runperl = qq{$Perl -e 'print qq(} .
638                 $args{stdin} . q{)' | } . $runperl;
639         }
640     }
641     if (defined $args{args}) {
642         $runperl = _quote_args($runperl, $args{args});
643     }
644     $runperl = $runperl . ' 2>&1' if $args{stderr};
645     if ($args{verbose}) {
646         my $runperldisplay = $runperl;
647         $runperldisplay =~ s/\n/\n\#/g;
648         _print_stderr "# $runperldisplay\n";
649     }
650     return $runperl;
651 }
652
653 sub runperl {
654     die "test.pl:runperl() does not take a hashref"
655         if ref $_[0] and ref $_[0] eq 'HASH';
656     my $runperl = &_create_runperl;
657     my $result;
658
659     my $tainted = ${^TAINT};
660     my %args = @_;
661     exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
662
663     if ($tainted) {
664         # We will assume that if you're running under -T, you really mean to
665         # run a fresh perl, so we'll brute force launder everything for you
666         my $sep;
667
668         if (! eval {require Config; 1}) {
669             warn "test.pl had problems loading Config: $@";
670             $sep = ':';
671         } else {
672             $sep = $Config::Config{path_sep};
673         }
674
675         my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
676         local @ENV{@keys} = ();
677         # Untaint, plus take out . and empty string:
678         local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
679         $ENV{PATH} =~ /(.*)/s;
680         local $ENV{PATH} =
681             join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
682                 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
683                     split quotemeta ($sep), $1;
684         if ($is_cygwin) {   # Must have /bin under Cygwin
685             if (length $ENV{PATH}) {
686                 $ENV{PATH} = $ENV{PATH} . $sep;
687             }
688             $ENV{PATH} = $ENV{PATH} . '/bin';
689         }
690         $runperl =~ /(.*)/s;
691         $runperl = $1;
692
693         $result = `$runperl`;
694     } else {
695         $result = `$runperl`;
696     }
697     $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
698     return $result;
699 }
700
701 # Nice alias
702 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
703
704 sub DIE {
705     _print_stderr "# @_\n";
706     exit 1;
707 }
708
709 # A somewhat safer version of the sometimes wrong $^X.
710 sub which_perl {
711     unless (defined $Perl) {
712         $Perl = $^X;
713
714         # VMS should have 'perl' aliased properly
715         return $Perl if $is_vms;
716
717         my $exe;
718         if (! eval {require Config; 1}) {
719             warn "test.pl had problems loading Config: $@";
720             $exe = '';
721         } else {
722             $exe = $Config::Config{_exe};
723         }
724        $exe = '' unless defined $exe;
725
726         # This doesn't absolutize the path: beware of future chdirs().
727         # We could do File::Spec->abs2rel() but that does getcwd()s,
728         # which is a bit heavyweight to do here.
729
730         if ($Perl =~ /^perl\Q$exe\E$/i) {
731             my $perl = "perl$exe";
732             if (! eval {require File::Spec; 1}) {
733                 warn "test.pl had problems loading File::Spec: $@";
734                 $Perl = "./$perl";
735             } else {
736                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
737             }
738         }
739
740         # Build up the name of the executable file from the name of
741         # the command.
742
743         if ($Perl !~ /\Q$exe\E$/i) {
744             $Perl = $Perl . $exe;
745         }
746
747         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
748
749         # For subcommands to use.
750         $ENV{PERLEXE} = $Perl;
751     }
752     return $Perl;
753 }
754
755 sub unlink_all {
756     my $count = 0;
757     foreach my $file (@_) {
758         1 while unlink $file;
759         if( -f $file ){
760             _print_stderr "# Couldn't unlink '$file': $!\n";
761         }else{
762             ++$count;
763         }
764     }
765     $count;
766 }
767
768 # _num_to_alpha - Returns a string of letters representing a positive integer.
769 # Arguments :
770 #   number to convert
771 #   maximum number of letters
772
773 # returns undef if the number is negative
774 # returns undef if the number of letters is greater than the maximum wanted
775
776 # _num_to_alpha( 0) eq 'A';
777 # _num_to_alpha( 1) eq 'B';
778 # _num_to_alpha(25) eq 'Z';
779 # _num_to_alpha(26) eq 'AA';
780 # _num_to_alpha(27) eq 'AB';
781
782 my @letters = qw(A B C D E F G H I J K L M N O P Q R S T U V W X Y Z);
783
784 # Avoid ++ -- ranges split negative numbers
785 sub _num_to_alpha{
786     my($num,$max_char) = @_;
787     return unless $num >= 0;
788     my $alpha = '';
789     my $char_count = 0;
790     $max_char = 0 if $max_char < 0;
791
792     while( 1 ){
793         $alpha = $letters[ $num % 26 ] . $alpha;
794         $num = int( $num / 26 );
795         last if $num == 0;
796         $num = $num - 1;
797
798         # char limit
799         next unless $max_char;
800         $char_count = $char_count + 1;
801         return if $char_count == $max_char;
802     }
803     return $alpha;
804 }
805
806 my %tmpfiles;
807 END { unlink_all keys %tmpfiles }
808
809 # A regexp that matches the tempfile names
810 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
811
812 # Avoid ++, avoid ranges, avoid split //
813 my $tempfile_count = 0;
814 sub tempfile {
815     while(1){
816         my $try = "tmp$$";
817         my $alpha = _num_to_alpha($tempfile_count,2);
818         last unless defined $alpha;
819         $try = $try . $alpha;
820         $tempfile_count = $tempfile_count + 1;
821
822         # Need to note all the file names we allocated, as a second request may
823         # come before the first is created.
824         if (!$tmpfiles{$try} && !-e $try) {
825             # We have a winner
826             $tmpfiles{$try} = 1;
827             return $try;
828         }
829     }
830     die "Can't find temporary file name starting \"tmp$$\"";
831 }
832
833 # This is the temporary file for _fresh_perl
834 my $tmpfile = tempfile();
835
836 sub _fresh_perl {
837     my($prog, $action, $expect, $runperl_args, $name) = @_;
838
839     # Given the choice of the mis-parsable {}
840     # (we want an anon hash, but a borked lexer might think that it's a block)
841     # or relying on taking a reference to a lexical
842     # (\ might be mis-parsed, and the reference counting on the pad may go
843     #  awry)
844     # it feels like the least-worse thing is to assume that auto-vivification
845     # works. At least, this is only going to be a run-time failure, so won't
846     # affect tests using this file but not this function.
847     $runperl_args->{progfile} ||= $tmpfile;
848     $runperl_args->{stderr}     = 1 unless exists $runperl_args->{stderr};
849
850     open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
851     print TEST $prog;
852     close TEST or die "Cannot close $tmpfile: $!";
853
854     my $results = runperl(%$runperl_args);
855     my $status = $?;
856
857     # Clean up the results into something a bit more predictable.
858     $results  =~ s/\n+$//;
859     $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
860     $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
861
862     # bison says 'parse error' instead of 'syntax error',
863     # various yaccs may or may not capitalize 'syntax'.
864     $results =~ s/^(syntax|parse) error/syntax error/mig;
865
866     if ($is_vms) {
867         # some tests will trigger VMS messages that won't be expected
868         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
869
870         # pipes double these sometimes
871         $results =~ s/\n\n/\n/g;
872     }
873
874     # Use the first line of the program as a name if none was given
875     unless( $name ) {
876         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
877         $name = $name . '...' if length $first_line > length $name;
878     }
879
880     # Historically this was implemented using a closure, but then that means
881     # that the tests for closures avoid using this code. Given that there
882     # are exactly two callers, doing exactly two things, the simpler approach
883     # feels like a better trade off.
884     my $pass;
885     if ($action eq 'eq') {
886         $pass = is($results, $expect, $name);
887     } elsif ($action eq '=~') {
888         $pass = like($results, $expect, $name);
889     } else {
890         die "_fresh_perl can't process action '$action'";
891     }
892         
893     unless ($pass) {
894         _diag "# PROG: \n$prog\n";
895         _diag "# STATUS: $status\n";
896     }
897
898     return $pass;
899 }
900
901 #
902 # fresh_perl_is
903 #
904 # Combination of run_perl() and is().
905 #
906
907 sub fresh_perl_is {
908     my($prog, $expected, $runperl_args, $name) = @_;
909
910     # _fresh_perl() is going to clip the trailing newlines off the result.
911     # This will make it so the test author doesn't have to know that.
912     $expected =~ s/\n+$//;
913
914     local $Level = 2;
915     _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
916 }
917
918 #
919 # fresh_perl_like
920 #
921 # Combination of run_perl() and like().
922 #
923
924 sub fresh_perl_like {
925     my($prog, $expected, $runperl_args, $name) = @_;
926     local $Level = 2;
927     _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
928 }
929
930 # Many tests use the same format in __DATA__ or external files to specify a
931 # sequence of (fresh) tests to run, extra files they may temporarily need, and
932 # what the expected output is. So have excatly one copy of the code to run that
933 #
934 # Each program is source code to run followed by an "EXPECT" line, followed
935 # by the expected output.
936 #
937 # The code to run may begin with a command line switch such as -w or -0777
938 # (alphanumerics only), and may contain (note the '# ' on each):
939 #   # TODO reason for todo
940 #   # SKIP reason for skip
941 #   # SKIP ?code to test if this should be skipped
942 #   # NAME name of the test (as with ok($ok, $name))
943 #
944 # The expected output may contain:
945 #   OPTION list of options
946 #   OPTIONS list of options
947 #
948 # The possible options for OPTION may be:
949 #   regex - the expected output is a regular expression
950 #   random - all lines match but in any order
951 #   fatal - the code will fail fatally (croak, die)
952 #
953 # If the actual output contains a line "SKIPPED" the test will be
954 # skipped.
955 #
956 # If the actual output contains a line "PREFIX", any output starting with that
957 # line will be ignored when comparing with the expected output
958 #
959 # If the global variable $FATAL is true then OPTION fatal is the
960 # default.
961
962 sub _setup_one_file {
963     my $fh = shift;
964     # Store the filename as a program that started at line 0.
965     # Real files count lines starting at line 1.
966     my @these = (0, shift);
967     my ($lineno, $current);
968     while (<$fh>) {
969         if ($_ eq "########\n") {
970             if (defined $current) {
971                 push @these, $lineno, $current;
972             }
973             undef $current;
974         } else {
975             if (!defined $current) {
976                 $lineno = $.;
977             }
978             $current .= $_;
979         }
980     }
981     if (defined $current) {
982         push @these, $lineno, $current;
983     }
984     ((scalar @these) / 2 - 1, @these);
985 }
986
987 sub setup_multiple_progs {
988     my ($tests, @prgs);
989     foreach my $file (@_) {
990         next if $file =~ /(?:~|\.orig|,v)$/;
991         next if $file =~ /perlio$/ && !PerlIO::Layer->find('perlio');
992         next if -d $file;
993
994         open my $fh, '<', $file or die "Cannot open $file: $!\n" ;
995         my $found;
996         while (<$fh>) {
997             if (/^__END__/) {
998                 ++$found;
999                 last;
1000             }
1001         }
1002         # This is an internal error, and should never happen. All bar one of
1003         # the files had an __END__ marker to signal the end of their preamble,
1004         # although for some it wasn't technically necessary as they have no
1005         # tests. It might be possible to process files without an __END__ by
1006         # seeking back to the start and treating the whole file as tests, but
1007         # it's simpler and more reliable just to make the rule that all files
1008         # must have __END__ in. This should never fail - a file without an
1009         # __END__ should not have been checked in, because the regression tests
1010         # would not have passed.
1011         die "Could not find '__END__' in $file"
1012             unless $found;
1013
1014         my ($t, @p) = _setup_one_file($fh, $file);
1015         $tests += $t;
1016         push @prgs, @p;
1017
1018         close $fh
1019             or die "Cannot close $file: $!\n";
1020     }
1021     return ($tests, @prgs);
1022 }
1023
1024 sub run_multiple_progs {
1025     my $up = shift;
1026     my @prgs;
1027     if ($up) {
1028         # The tests in lib run in a temporary subdirectory of t, and always
1029         # pass in a list of "programs" to run
1030         @prgs = @_;
1031     } else {
1032         # The tests below t run in t and pass in a file handle. In theory we
1033         # can pass (caller)[1] as the second argument to report errors with
1034         # the filename of our caller, as the handle is always DATA. However,
1035         # line numbers in DATA count from the __END__ token, so will be wrong.
1036         # Which is more confusing than not providing line numbers. So, for now,
1037         # don't provide line numbers. No obvious clean solution - one hack
1038         # would be to seek DATA back to the start and read to the __END__ token,
1039         # but that feels almost like we should just open $0 instead.
1040
1041         # Not going to rely on undef in list assignment.
1042         my $dummy;
1043         ($dummy, @prgs) = _setup_one_file(shift);
1044     }
1045
1046     my $tmpfile = tempfile();
1047
1048     my ($file, $line);
1049   PROGRAM:
1050     while (defined ($line = shift @prgs)) {
1051         $_ = shift @prgs;
1052         unless ($line) {
1053             $file = $_;
1054             if (defined $file) {
1055                 print "# From $file\n";
1056             }
1057             next;
1058         }
1059         my $switch = "";
1060         my @temps ;
1061         my @temp_path;
1062         if (s/^(\s*-\w+)//) {
1063             $switch = $1;
1064         }
1065         my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
1066
1067         my %reason;
1068         foreach my $what (qw(skip todo)) {
1069             $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1070             # If the SKIP reason starts ? then it's taken as a code snippet to
1071             # evaluate. This provides the flexibility to have conditional SKIPs
1072             if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1073                 my $temp = eval $reason{$what};
1074                 if ($@) {
1075                     die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1076                 }
1077                 $reason{$what} = $temp;
1078             }
1079         }
1080
1081         my $name = '';
1082         if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1083             $name = $1;
1084         }
1085
1086         if ($reason{skip}) {
1087         SKIP:
1088           {
1089             skip($name ? "$name - $reason{skip}" : $reason{skip}, 1);
1090           }
1091           next PROGRAM;
1092         }
1093
1094         if ($prog =~ /--FILE--/) {
1095             my @files = split(/\n?--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1096             shift @files ;
1097             die "Internal error: test $_ didn't split into pairs, got " .
1098                 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1099                     if @files % 2;
1100             while (@files > 2) {
1101                 my $filename = shift @files;
1102                 my $code = shift @files;
1103                 push @temps, $filename;
1104                 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1105                     require File::Path;
1106                     File::Path::mkpath($1);
1107                     push(@temp_path, $1);
1108                 }
1109                 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1110                 print $fh $code;
1111                 close $fh or die "Cannot close $filename: $!\n";
1112             }
1113             shift @files;
1114             $prog = shift @files;
1115         }
1116
1117         open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1118         print $fh q{
1119         BEGIN {
1120             open STDERR, '>&', STDOUT
1121               or die "Can't dup STDOUT->STDERR: $!;";
1122         }
1123         };
1124         print $fh "\n#line 1\n";  # So the line numbers don't get messed up.
1125         print $fh $prog,"\n";
1126         close $fh or die "Cannot close $tmpfile: $!";
1127         my $results = runperl( stderr => 1, progfile => $tmpfile,
1128                                stdin => '', $up
1129                                ? (switches => ["-I$up/lib", $switch], nolib => 1)
1130                                : (switches => [$switch])
1131                                 );
1132         my $status = $?;
1133         $results =~ s/\n+$//;
1134         # allow expected output to be written as if $prog is on STDIN
1135         $results =~ s/$::tempfile_regexp/-/g;
1136         if ($^O eq 'VMS') {
1137             # some tests will trigger VMS messages that won't be expected
1138             $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1139
1140             # pipes double these sometimes
1141             $results =~ s/\n\n/\n/g;
1142         }
1143         # bison says 'parse error' instead of 'syntax error',
1144         # various yaccs may or may not capitalize 'syntax'.
1145         $results =~ s/^(syntax|parse) error/syntax error/mig;
1146         # allow all tests to run when there are leaks
1147         $results =~ s/Scalars leaked: \d+\n//g;
1148
1149         $expected =~ s/\n+$//;
1150         my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1151         # any special options? (OPTIONS foo bar zap)
1152         my $option_regex = 0;
1153         my $option_random = 0;
1154         my $fatal = $FATAL;
1155         if ($expected =~ s/^OPTIONS? (.+)\n//) {
1156             foreach my $option (split(' ', $1)) {
1157                 if ($option eq 'regex') { # allow regular expressions
1158                     $option_regex = 1;
1159                 }
1160                 elsif ($option eq 'random') { # all lines match, but in any order
1161                     $option_random = 1;
1162                 }
1163                 elsif ($option eq 'fatal') { # perl should fail
1164                     $fatal = 1;
1165                 }
1166                 else {
1167                     die "$0: Unknown OPTION '$option'\n";
1168                 }
1169             }
1170         }
1171         die "$0: can't have OPTION regex and random\n"
1172             if $option_regex + $option_random > 1;
1173         my $ok = 0;
1174         if ($results =~ s/^SKIPPED\n//) {
1175             print "$results\n" ;
1176             $ok = 1;
1177         }
1178         else {
1179             if ($option_random) {
1180                 my @got = sort split "\n", $results;
1181                 my @expected = sort split "\n", $expected;
1182
1183                 $ok = "@got" eq "@expected";
1184             }
1185             elsif ($option_regex) {
1186                 $ok = $results =~ /^$expected/;
1187             }
1188             elsif ($prefix) {
1189                 $ok = $results =~ /^\Q$expected/;
1190             }
1191             else {
1192                 $ok = $results eq $expected;
1193             }
1194
1195             if ($ok && $fatal && !($status >> 8)) {
1196                 $ok = 0;
1197             }
1198         }
1199
1200         local $::TODO = $reason{todo};
1201
1202         unless ($ok) {
1203             my $err_line = "PROG: $switch\n$prog\n" .
1204                            "EXPECTED:\n$expected\n";
1205             $err_line   .= "EXIT STATUS: != 0\n" if $fatal;
1206             $err_line   .= "GOT:\n$results\n";
1207             $err_line   .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1208             if ($::TODO) {
1209                 $err_line =~ s/^/# /mg;
1210                 print $err_line;  # Harness can't filter it out from STDERR.
1211             }
1212             else {
1213                 print STDERR $err_line;
1214             }
1215         }
1216
1217         if (defined $file) {
1218             _ok($ok, "at $file line $line", $name);
1219         } else {
1220             # We don't have file and line number data for the test, so report
1221             # errors as coming from our caller.
1222             local $Level = $Level + 1;
1223             ok($ok, $name);
1224         }
1225
1226         foreach (@temps) {
1227             unlink $_ if $_;
1228         }
1229         foreach (@temp_path) {
1230             File::Path::rmtree $_ if -d $_;
1231         }
1232     }
1233 }
1234
1235 sub can_ok ($@) {
1236     my($proto, @methods) = @_;
1237     my $class = ref $proto || $proto;
1238
1239     unless( @methods ) {
1240         return _ok( 0, _where(), "$class->can(...)" );
1241     }
1242
1243     my @nok = ();
1244     foreach my $method (@methods) {
1245         local($!, $@);  # don't interfere with caller's $@
1246                         # eval sometimes resets $!
1247         eval { $proto->can($method) } || push @nok, $method;
1248     }
1249
1250     my $name;
1251     $name = @methods == 1 ? "$class->can('$methods[0]')"
1252                           : "$class->can(...)";
1253
1254     _ok( !@nok, _where(), $name );
1255 }
1256
1257
1258 # Call $class->new( @$args ); and run the result through object_ok.
1259 # See Test::More::new_ok
1260 sub new_ok {
1261     my($class, $args, $obj_name) = @_;
1262     $args ||= [];
1263     $object_name = "The object" unless defined $obj_name;
1264
1265     local $Level = $Level + 1;
1266
1267     my $obj;
1268     my $ok = eval { $obj = $class->new(@$args); 1 };
1269     my $error = $@;
1270
1271     if($ok) {
1272         object_ok($obj, $class, $object_name);
1273     }
1274     else {
1275         ok( 0, "new() died" );
1276         diag("Error was:  $@");
1277     }
1278
1279     return $obj;
1280
1281 }
1282
1283
1284 sub isa_ok ($$;$) {
1285     my($object, $class, $obj_name) = @_;
1286
1287     my $diag;
1288     $obj_name = 'The object' unless defined $obj_name;
1289     my $name = "$obj_name isa $class";
1290     if( !defined $object ) {
1291         $diag = "$obj_name isn't defined";
1292     }
1293     else {
1294         my $whatami = ref $object ? 'object' : 'class';
1295
1296         # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1297         local($@, $!);  # eval sometimes resets $!
1298         my $rslt = eval { $object->isa($class) };
1299         my $error = $@;  # in case something else blows away $@
1300
1301         if( $error ) {
1302             if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1303                 # It's an unblessed reference
1304                 $obj_name = 'The reference' unless defined $obj_name;
1305                 if( !UNIVERSAL::isa($object, $class) ) {
1306                     my $ref = ref $object;
1307                     $diag = "$obj_name isn't a '$class' it's a '$ref'";
1308                 }
1309             }
1310             elsif( $error =~ /Can't call method "isa" without a package/ ) {
1311                 # It's something that can't even be a class
1312                 $obj_name = 'The thing' unless defined $obj_name;
1313                 $diag = "$obj_name isn't a class or reference";
1314             }
1315             else {
1316                 die <<WHOA;
1317 WHOA! I tried to call ->isa on your object and got some weird error.
1318 This should never happen.  Please contact the author immediately.
1319 Here's the error.
1320 $@
1321 WHOA
1322             }
1323         }
1324         elsif( !$rslt ) {
1325             $obj_name = "The $whatami" unless defined $obj_name;
1326             my $ref = ref $object;
1327             $diag = "$obj_name isn't a '$class' it's a '$ref'";
1328         }
1329     }
1330
1331     _ok( !$diag, _where(), $name );
1332 }
1333
1334
1335 sub class_ok {
1336     my($class, $isa, $class_name) = @_;
1337
1338     # Written so as to count as one test
1339     local $Level = $Level + 1;
1340     if( ref $class ) {
1341         ok( 0, "$class is a refrence, not a class name" );
1342     }
1343     else {
1344         isa_ok($class, $isa, $class_name);
1345     }
1346 }
1347
1348
1349 sub object_ok {
1350     my($obj, $isa, $obj_name) = @_;
1351
1352     local $Level = $Level + 1;
1353     if( !ref $obj ) {
1354         ok( 0, "$obj is not a reference" );
1355     }
1356     else {
1357         isa_ok($obj, $isa, $obj_name);
1358     }
1359 }
1360
1361
1362 # Purposefully avoiding a closure.
1363 sub __capture {
1364     push @::__capture, join "", @_;
1365 }
1366     
1367 sub capture_warnings {
1368     my $code = shift;
1369
1370     local @::__capture;
1371     local $SIG {__WARN__} = \&__capture;
1372     &$code;
1373     return @::__capture;
1374 }
1375
1376 # This will generate a variable number of tests.
1377 # Use done_testing() instead of a fixed plan.
1378 sub warnings_like {
1379     my ($code, $expect, $name) = @_;
1380     local $Level = $Level + 1;
1381
1382     my @w = capture_warnings($code);
1383
1384     cmp_ok(scalar @w, '==', scalar @$expect, $name);
1385     foreach my $e (@$expect) {
1386         if (ref $e) {
1387             like(shift @w, $e, $name);
1388         } else {
1389             is(shift @w, $e, $name);
1390         }
1391     }
1392     if (@w) {
1393         diag("Saw these additional warnings:");
1394         diag($_) foreach @w;
1395     }
1396 }
1397
1398 sub _fail_excess_warnings {
1399     my($expect, $got, $name) = @_;
1400     local $Level = $Level + 1;
1401     # This will fail, and produce diagnostics
1402     is($expect, scalar @$got, $name);
1403     diag("Saw these warnings:");
1404     diag($_) foreach @$got;
1405 }
1406
1407 sub warning_is {
1408     my ($code, $expect, $name) = @_;
1409     die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1410         if ref $expect;
1411     local $Level = $Level + 1;
1412     my @w = capture_warnings($code);
1413     if (@w > 1) {
1414         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1415     } else {
1416         is($w[0], $expect, $name);
1417     }
1418 }
1419
1420 sub warning_like {
1421     my ($code, $expect, $name) = @_;
1422     die sprintf "Expect must be a regexp object"
1423         unless ref $expect eq 'Regexp';
1424     local $Level = $Level + 1;
1425     my @w = capture_warnings($code);
1426     if (@w > 1) {
1427         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1428     } else {
1429         like($w[0], $expect, $name);
1430     }
1431 }
1432
1433 # Set a watchdog to timeout the entire test file
1434 # NOTE:  If the test file uses 'threads', then call the watchdog() function
1435 #        _AFTER_ the 'threads' module is loaded.
1436 sub watchdog ($;$)
1437 {
1438     my $timeout = shift;
1439     my $method  = shift || "";
1440     my $timeout_msg = 'Test process timed out - terminating';
1441
1442     # Valgrind slows perl way down so give it more time before dying.
1443     $timeout *= 10 if $ENV{PERL_VALGRIND};
1444
1445     my $pid_to_kill = $$;   # PID for this process
1446
1447     if ($method eq "alarm") {
1448         goto WATCHDOG_VIA_ALARM;
1449     }
1450
1451     # shut up use only once warning
1452     my $threads_on = $threads::threads && $threads::threads;
1453
1454     # Don't use a watchdog process if 'threads' is loaded -
1455     #   use a watchdog thread instead
1456     if (!$threads_on || $method eq "process") {
1457
1458         # On Windows and VMS, try launching a watchdog process
1459         #   using system(1, ...) (see perlport.pod)
1460         if ($is_mswin || $is_vms) {
1461             # On Windows, try to get the 'real' PID
1462             if ($is_mswin) {
1463                 eval { require Win32; };
1464                 if (defined(&Win32::GetCurrentProcessId)) {
1465                     $pid_to_kill = Win32::GetCurrentProcessId();
1466                 }
1467             }
1468
1469             # If we still have a fake PID, we can't use this method at all
1470             return if ($pid_to_kill <= 0);
1471
1472             # Launch watchdog process
1473             my $watchdog;
1474             eval {
1475                 local $SIG{'__WARN__'} = sub {
1476                     _diag("Watchdog warning: $_[0]");
1477                 };
1478                 my $sig = $is_vms ? 'TERM' : 'KILL';
1479                 my $cmd = _create_runperl( prog =>  "sleep($timeout);" .
1480                                                     "warn qq/# $timeout_msg" . '\n/;' .
1481                                                     "kill($sig, $pid_to_kill);");
1482                 $watchdog = system(1, $cmd);
1483             };
1484             if ($@ || ($watchdog <= 0)) {
1485                 _diag('Failed to start watchdog');
1486                 _diag($@) if $@;
1487                 undef($watchdog);
1488                 return;
1489             }
1490
1491             # Add END block to parent to terminate and
1492             #   clean up watchdog process
1493             eval "END { local \$! = 0; local \$? = 0;
1494                         wait() if kill('KILL', $watchdog); };";
1495             return;
1496         }
1497
1498         # Try using fork() to generate a watchdog process
1499         my $watchdog;
1500         eval { $watchdog = fork() };
1501         if (defined($watchdog)) {
1502             if ($watchdog) {   # Parent process
1503                 # Add END block to parent to terminate and
1504                 #   clean up watchdog process
1505                 eval "END { local \$! = 0; local \$? = 0;
1506                             wait() if kill('KILL', $watchdog); };";
1507                 return;
1508             }
1509
1510             ### Watchdog process code
1511
1512             # Load POSIX if available
1513             eval { require POSIX; };
1514
1515             # Execute the timeout
1516             sleep($timeout - 2) if ($timeout > 2);   # Workaround for perlbug #49073
1517             sleep(2);
1518
1519             # Kill test process if still running
1520             if (kill(0, $pid_to_kill)) {
1521                 _diag($timeout_msg);
1522                 kill('KILL', $pid_to_kill);
1523                 if ($is_cygwin) {
1524                     # sometimes the above isn't enough on cygwin
1525                     sleep 1; # wait a little, it might have worked after all
1526                     system("/bin/kill -f $pid_to_kill");
1527                 }
1528             }
1529
1530             # Don't execute END block (added at beginning of this file)
1531             $NO_ENDING = 1;
1532
1533             # Terminate ourself (i.e., the watchdog)
1534             POSIX::_exit(1) if (defined(&POSIX::_exit));
1535             exit(1);
1536         }
1537
1538         # fork() failed - fall through and try using a thread
1539     }
1540
1541     # Use a watchdog thread because either 'threads' is loaded,
1542     #   or fork() failed
1543     if (eval {require threads; 1}) {
1544         'threads'->create(sub {
1545                 # Load POSIX if available
1546                 eval { require POSIX; };
1547
1548                 # Execute the timeout
1549                 my $time_left = $timeout;
1550                 do {
1551                     $time_left = $time_left - sleep($time_left);
1552                 } while ($time_left > 0);
1553
1554                 # Kill the parent (and ourself)
1555                 select(STDERR); $| = 1;
1556                 _diag($timeout_msg);
1557                 POSIX::_exit(1) if (defined(&POSIX::_exit));
1558                 my $sig = $is_vms ? 'TERM' : 'KILL';
1559                 kill($sig, $pid_to_kill);
1560             })->detach();
1561         return;
1562     }
1563
1564     # If everything above fails, then just use an alarm timeout
1565 WATCHDOG_VIA_ALARM:
1566     if (eval { alarm($timeout); 1; }) {
1567         # Load POSIX if available
1568         eval { require POSIX; };
1569
1570         # Alarm handler will do the actual 'killing'
1571         $SIG{'ALRM'} = sub {
1572             select(STDERR); $| = 1;
1573             _diag($timeout_msg);
1574             POSIX::_exit(1) if (defined(&POSIX::_exit));
1575             my $sig = $is_vms ? 'TERM' : 'KILL';
1576             kill($sig, $pid_to_kill);
1577         };
1578     }
1579 }
1580
1581 my $cp_0037 =   # EBCDIC code page 0037
1582     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' .
1583     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1584     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1585     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1586     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1587     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBA\xE0\xBB\xB0\x6D' .
1588     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1589     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1590     '\x20\x21\x22\x23\x24\x15\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1591     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1592     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBD\xB4\x9A\x8A\x5F\xCA\xAF\xBC' .
1593     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1594     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1595     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xAD\xAE\x59' .
1596     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1597     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1598
1599 my $cp_1047 =   # EBCDIC code page 1047
1600     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1601     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1602     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1603     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1604     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1605     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D' .
1606     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1607     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1608     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1609     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1610     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBB\xB4\x9A\x8A\xB0\xCA\xAF\xBC' .
1611     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1612     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1613     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xBA\xAE\x59' .
1614     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1615     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1616
1617 my $cp_bc = # EBCDIC code page POSiX-BC
1618     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1619     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1620     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1621     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1622     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1623     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBB\xBC\xBD\x6A\x6D' .
1624     '\x4A\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1625     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xFB\x4F\xFD\xFF\x07' .
1626     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1627     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\x5F' .
1628     '\x41\xAA\xB0\xB1\x9F\xB2\xD0\xB5\x79\xB4\x9A\x8A\xBA\xCA\xAF\xA1' .
1629     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1630     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1631     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xE0\xFE\xDD\xFC\xAD\xAE\x59' .
1632     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1633     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xC0\xDE\xDB\xDC\x8D\x8E\xDF';
1634
1635 my $straight =  # Avoid ranges
1636     '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' .
1637     '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F' .
1638     '\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F' .
1639     '\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F' .
1640     '\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F' .
1641     '\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F' .
1642     '\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F' .
1643     '\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F' .
1644     '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F' .
1645     '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F' .
1646     '\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF' .
1647     '\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF' .
1648     '\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF' .
1649     '\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF' .
1650     '\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF' .
1651     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF';
1652
1653 # The following 2 functions allow tests to work on both EBCDIC and
1654 # ASCII-ish platforms.  They convert string scalars between the native
1655 # character set and the set of 256 characters which is usually called
1656 # Latin1.
1657 #
1658 # These routines don't work on UTF-EBCDIC and UTF-8.
1659
1660 sub native_to_latin1($) {
1661     my $string = shift;
1662
1663     return $string if ord('^') == 94;   # ASCII, Latin1
1664     my $cp;
1665     if (ord('^') == 95) {    # EBCDIC 1047
1666         $cp = \$cp_1047;
1667     }
1668     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1669         $cp = \$cp_bc;
1670     }
1671     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1672         $cp = \$cp_0037;
1673     }
1674     else {
1675         die "Unknown native character set";
1676     }
1677
1678     eval '$string =~ tr/' . $$cp . '/' . $straight . '/';
1679     return $string;
1680 }
1681
1682 sub latin1_to_native($) {
1683     my $string = shift;
1684
1685     return $string if ord('^') == 94;   # ASCII, Latin1
1686     my $cp;
1687     if (ord('^') == 95) {    # EBCDIC 1047
1688         $cp = \$cp_1047;
1689     }
1690     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1691         $cp = \$cp_bc;
1692     }
1693     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1694         $cp = \$cp_0037;
1695     }
1696     else {
1697         die "Unknown native character set";
1698     }
1699
1700     eval '$string =~ tr/' . $straight . '/' . $$cp . '/';
1701     return $string;
1702 }
1703
1704 sub ord_latin1_to_native {
1705     # given an input code point, return the platform's native
1706     # equivalent value.  Anything above latin1 is itself.
1707
1708     my $ord = shift;
1709     return $ord if $ord > 255;
1710     return ord latin1_to_native(chr $ord);
1711 }
1712
1713 sub ord_native_to_latin1 {
1714     # given an input platform code point, return the latin1 equivalent value.
1715     # Anything above latin1 is itself.
1716
1717     my $ord = shift;
1718     return $ord if $ord > 255;
1719     return ord native_to_latin1(chr $ord);
1720 }
1721
1722 1;