This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
regmatch(): do nextchr=*locinput at top of loop
[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 ($orig->{$key} ne $value) {
501         _print "# key ", _qq($key), " was ", _qq($orig->{$key}),
502                      " now ", _qq($value), "\n";
503         $fail = 1;
504       }
505     } else {
506       _print "# key ", _qq($key), " is ", _qq($value),
507                    ", not in original.\n";
508       $fail = 1;
509     }
510   }
511   foreach (keys %$orig) {
512     # Force a hash recompute if this perl's internals can cache the hash key.
513     $_ = "" . $_;
514     next if (exists $suspect->{$_});
515     _print "# key ", _qq($_), " was ", _qq($orig->{$_}), " now missing.\n";
516     $fail = 1;
517   }
518   !$fail;
519 }
520
521 # We only provide a subset of the Test::More functionality.
522 sub require_ok ($) {
523     my ($require) = @_;
524     if ($require =~ tr/[A-Za-z0-9:.]//c) {
525         fail("Invalid character in \"$require\", passed to require_ok");
526     } else {
527         eval <<REQUIRE_OK;
528 require $require;
529 REQUIRE_OK
530         is($@, '', _where(), "require $require");
531     }
532 }
533
534 sub use_ok ($) {
535     my ($use) = @_;
536     if ($use =~ tr/[A-Za-z0-9:.]//c) {
537         fail("Invalid character in \"$use\", passed to use");
538     } else {
539         eval <<USE_OK;
540 use $use;
541 USE_OK
542         is($@, '', _where(), "use $use");
543     }
544 }
545
546 # runperl - Runs a separate perl interpreter.
547 # Arguments :
548 #   switches => [ command-line switches ]
549 #   nolib    => 1 # don't use -I../lib (included by default)
550 #   non_portable => Don't warn if a one liner contains quotes
551 #   prog     => one-liner (avoid quotes)
552 #   progs    => [ multi-liner (avoid quotes) ]
553 #   progfile => perl script
554 #   stdin    => string to feed the stdin
555 #   stderr   => redirect stderr to stdout
556 #   args     => [ command-line arguments to the perl program ]
557 #   verbose  => print the command line
558
559 my $is_mswin    = $^O eq 'MSWin32';
560 my $is_netware  = $^O eq 'NetWare';
561 my $is_vms      = $^O eq 'VMS';
562 my $is_cygwin   = $^O eq 'cygwin';
563
564 sub _quote_args {
565     my ($runperl, $args) = @_;
566
567     foreach (@$args) {
568         # In VMS protect with doublequotes because otherwise
569         # DCL will lowercase -- unless already doublequoted.
570        $_ = q(").$_.q(") if $is_vms && !/^\"/ && length($_) > 0;
571        $runperl = $runperl . ' ' . $_;
572     }
573     return $runperl;
574 }
575
576 sub _create_runperl { # Create the string to qx in runperl().
577     my %args = @_;
578     my $runperl = which_perl();
579     if ($runperl =~ m/\s/) {
580         $runperl = qq{"$runperl"};
581     }
582     #- this allows, for example, to set PERL_RUNPERL_DEBUG=/usr/bin/valgrind
583     if ($ENV{PERL_RUNPERL_DEBUG}) {
584         $runperl = "$ENV{PERL_RUNPERL_DEBUG} $runperl";
585     }
586     unless ($args{nolib}) {
587         $runperl = $runperl . ' "-I../lib"'; # doublequotes because of VMS
588     }
589     if ($args{switches}) {
590         local $Level = 2;
591         die "test.pl:runperl(): 'switches' must be an ARRAYREF " . _where()
592             unless ref $args{switches} eq "ARRAY";
593         $runperl = _quote_args($runperl, $args{switches});
594     }
595     if (defined $args{prog}) {
596         die "test.pl:runperl(): both 'prog' and 'progs' cannot be used " . _where()
597             if defined $args{progs};
598         $args{progs} = [$args{prog}]
599     }
600     if (defined $args{progs}) {
601         die "test.pl:runperl(): 'progs' must be an ARRAYREF " . _where()
602             unless ref $args{progs} eq "ARRAY";
603         foreach my $prog (@{$args{progs}}) {
604             if ($prog =~ tr/'"// && !$args{non_portable}) {
605                 warn "quotes in prog >>$prog<< are not portable";
606             }
607             if ($is_mswin || $is_netware || $is_vms) {
608                 $runperl = $runperl . qq ( -e "$prog" );
609             }
610             else {
611                 $runperl = $runperl . qq ( -e '$prog' );
612             }
613         }
614     } elsif (defined $args{progfile}) {
615         $runperl = $runperl . qq( "$args{progfile}");
616     } else {
617         # You probably didn't want to be sucking in from the upstream stdin
618         die "test.pl:runperl(): none of prog, progs, progfile, args, "
619             . " switches or stdin specified"
620             unless defined $args{args} or defined $args{switches}
621                 or defined $args{stdin};
622     }
623     if (defined $args{stdin}) {
624         # so we don't try to put literal newlines and crs onto the
625         # command line.
626         $args{stdin} =~ s/\n/\\n/g;
627         $args{stdin} =~ s/\r/\\r/g;
628
629         if ($is_mswin || $is_netware || $is_vms) {
630             $runperl = qq{$Perl -e "print qq(} .
631                 $args{stdin} . q{)" | } . $runperl;
632         }
633         else {
634             $runperl = qq{$Perl -e 'print qq(} .
635                 $args{stdin} . q{)' | } . $runperl;
636         }
637     }
638     if (defined $args{args}) {
639         $runperl = _quote_args($runperl, $args{args});
640     }
641     $runperl = $runperl . ' 2>&1' if $args{stderr};
642     if ($args{verbose}) {
643         my $runperldisplay = $runperl;
644         $runperldisplay =~ s/\n/\n\#/g;
645         _print_stderr "# $runperldisplay\n";
646     }
647     return $runperl;
648 }
649
650 sub runperl {
651     die "test.pl:runperl() does not take a hashref"
652         if ref $_[0] and ref $_[0] eq 'HASH';
653     my $runperl = &_create_runperl;
654     my $result;
655
656     my $tainted = ${^TAINT};
657     my %args = @_;
658     exists $args{switches} && grep m/^-T$/, @{$args{switches}} and $tainted = $tainted + 1;
659
660     if ($tainted) {
661         # We will assume that if you're running under -T, you really mean to
662         # run a fresh perl, so we'll brute force launder everything for you
663         my $sep;
664
665         if (! eval {require Config; 1}) {
666             warn "test.pl had problems loading Config: $@";
667             $sep = ':';
668         } else {
669             $sep = $Config::Config{path_sep};
670         }
671
672         my @keys = grep {exists $ENV{$_}} qw(CDPATH IFS ENV BASH_ENV);
673         local @ENV{@keys} = ();
674         # Untaint, plus take out . and empty string:
675         local $ENV{'DCL$PATH'} = $1 if $is_vms && exists($ENV{'DCL$PATH'}) && ($ENV{'DCL$PATH'} =~ /(.*)/s);
676         $ENV{PATH} =~ /(.*)/s;
677         local $ENV{PATH} =
678             join $sep, grep { $_ ne "" and $_ ne "." and -d $_ and
679                 ($is_mswin or $is_vms or !(stat && (stat _)[2]&0022)) }
680                     split quotemeta ($sep), $1;
681         if ($is_cygwin) {   # Must have /bin under Cygwin
682             if (length $ENV{PATH}) {
683                 $ENV{PATH} = $ENV{PATH} . $sep;
684             }
685             $ENV{PATH} = $ENV{PATH} . '/bin';
686         }
687         $runperl =~ /(.*)/s;
688         $runperl = $1;
689
690         $result = `$runperl`;
691     } else {
692         $result = `$runperl`;
693     }
694     $result =~ s/\n\n/\n/ if $is_vms; # XXX pipes sometimes double these
695     return $result;
696 }
697
698 # Nice alias
699 *run_perl = *run_perl = \&runperl; # shut up "used only once" warning
700
701 sub DIE {
702     _print_stderr "# @_\n";
703     exit 1;
704 }
705
706 # A somewhat safer version of the sometimes wrong $^X.
707 sub which_perl {
708     unless (defined $Perl) {
709         $Perl = $^X;
710
711         # VMS should have 'perl' aliased properly
712         return $Perl if $is_vms;
713
714         my $exe;
715         if (! eval {require Config; 1}) {
716             warn "test.pl had problems loading Config: $@";
717             $exe = '';
718         } else {
719             $exe = $Config::Config{_exe};
720         }
721        $exe = '' unless defined $exe;
722
723         # This doesn't absolutize the path: beware of future chdirs().
724         # We could do File::Spec->abs2rel() but that does getcwd()s,
725         # which is a bit heavyweight to do here.
726
727         if ($Perl =~ /^perl\Q$exe\E$/i) {
728             my $perl = "perl$exe";
729             if (! eval {require File::Spec; 1}) {
730                 warn "test.pl had problems loading File::Spec: $@";
731                 $Perl = "./$perl";
732             } else {
733                 $Perl = File::Spec->catfile(File::Spec->curdir(), $perl);
734             }
735         }
736
737         # Build up the name of the executable file from the name of
738         # the command.
739
740         if ($Perl !~ /\Q$exe\E$/i) {
741             $Perl = $Perl . $exe;
742         }
743
744         warn "which_perl: cannot find $Perl from $^X" unless -f $Perl;
745
746         # For subcommands to use.
747         $ENV{PERLEXE} = $Perl;
748     }
749     return $Perl;
750 }
751
752 sub unlink_all {
753     my $count = 0;
754     foreach my $file (@_) {
755         1 while unlink $file;
756         if( -f $file ){
757             _print_stderr "# Couldn't unlink '$file': $!\n";
758         }else{
759             ++$count;
760         }
761     }
762     $count;
763 }
764
765 # _num_to_alpha - Returns a string of letters representing a positive integer.
766 # Arguments :
767 #   number to convert
768 #   maximum number of letters
769
770 # returns undef if the number is negative
771 # returns undef if the number of letters is greater than the maximum wanted
772
773 # _num_to_alpha( 0) eq 'A';
774 # _num_to_alpha( 1) eq 'B';
775 # _num_to_alpha(25) eq 'Z';
776 # _num_to_alpha(26) eq 'AA';
777 # _num_to_alpha(27) eq 'AB';
778
779 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);
780
781 # Avoid ++ -- ranges split negative numbers
782 sub _num_to_alpha{
783     my($num,$max_char) = @_;
784     return unless $num >= 0;
785     my $alpha = '';
786     my $char_count = 0;
787     $max_char = 0 if $max_char < 0;
788
789     while( 1 ){
790         $alpha = $letters[ $num % 26 ] . $alpha;
791         $num = int( $num / 26 );
792         last if $num == 0;
793         $num = $num - 1;
794
795         # char limit
796         next unless $max_char;
797         $char_count = $char_count + 1;
798         return if $char_count == $max_char;
799     }
800     return $alpha;
801 }
802
803 my %tmpfiles;
804 END { unlink_all keys %tmpfiles }
805
806 # A regexp that matches the tempfile names
807 $::tempfile_regexp = 'tmp\d+[A-Z][A-Z]?';
808
809 # Avoid ++, avoid ranges, avoid split //
810 my $tempfile_count = 0;
811 sub tempfile {
812     while(1){
813         my $try = "tmp$$";
814         my $alpha = _num_to_alpha($tempfile_count,2);
815         last unless defined $alpha;
816         $try = $try . $alpha;
817         $tempfile_count = $tempfile_count + 1;
818
819         # Need to note all the file names we allocated, as a second request may
820         # come before the first is created.
821         if (!$tmpfiles{$try} && !-e $try) {
822             # We have a winner
823             $tmpfiles{$try} = 1;
824             return $try;
825         }
826     }
827     die "Can't find temporary file name starting 'tmp$$'";
828 }
829
830 # This is the temporary file for _fresh_perl
831 my $tmpfile = tempfile();
832
833 sub _fresh_perl {
834     my($prog, $action, $expect, $runperl_args, $name) = @_;
835
836     # Given the choice of the mis-parsable {}
837     # (we want an anon hash, but a borked lexer might think that it's a block)
838     # or relying on taking a reference to a lexical
839     # (\ might be mis-parsed, and the reference counting on the pad may go
840     #  awry)
841     # it feels like the least-worse thing is to assume that auto-vivification
842     # works. At least, this is only going to be a run-time failure, so won't
843     # affect tests using this file but not this function.
844     $runperl_args->{progfile} ||= $tmpfile;
845     $runperl_args->{stderr}     = 1 unless exists $runperl_args->{stderr};
846
847     open TEST, ">$tmpfile" or die "Cannot open $tmpfile: $!";
848
849     # VMS adjustments
850     if( $is_vms ) {
851         $prog =~ s#/dev/null#NL:#;
852
853         # VMS file locking
854         $prog =~ s{if \(-e _ and -f _ and -r _\)}
855                   {if (-e _ and -f _)}
856     }
857
858     print TEST $prog;
859     close TEST or die "Cannot close $tmpfile: $!";
860
861     my $results = runperl(%$runperl_args);
862     my $status = $?;
863
864     # Clean up the results into something a bit more predictable.
865     $results  =~ s/\n+$//;
866     $results =~ s/at\s+$::tempfile_regexp\s+line/at - line/g;
867     $results =~ s/of\s+$::tempfile_regexp\s+aborted/of - aborted/g;
868
869     # bison says 'parse error' instead of 'syntax error',
870     # various yaccs may or may not capitalize 'syntax'.
871     $results =~ s/^(syntax|parse) error/syntax error/mig;
872
873     if ($is_vms) {
874         # some tests will trigger VMS messages that won't be expected
875         $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
876
877         # pipes double these sometimes
878         $results =~ s/\n\n/\n/g;
879     }
880
881     # Use the first line of the program as a name if none was given
882     unless( $name ) {
883         ($first_line, $name) = $prog =~ /^((.{1,50}).*)/;
884         $name = $name . '...' if length $first_line > length $name;
885     }
886
887     # Historically this was implemented using a closure, but then that means
888     # that the tests for closures avoid using this code. Given that there
889     # are exactly two callers, doing exactly two things, the simpler approach
890     # feels like a better trade off.
891     my $pass;
892     if ($action eq 'eq') {
893         $pass = is($results, $expect, $name);
894     } elsif ($action eq '=~') {
895         $pass = like($results, $expect, $name);
896     } else {
897         die "_fresh_perl can't process action '$action'";
898     }
899         
900     unless ($pass) {
901         _diag "# PROG: \n$prog\n";
902         _diag "# STATUS: $status\n";
903     }
904
905     return $pass;
906 }
907
908 #
909 # fresh_perl_is
910 #
911 # Combination of run_perl() and is().
912 #
913
914 sub fresh_perl_is {
915     my($prog, $expected, $runperl_args, $name) = @_;
916
917     # _fresh_perl() is going to clip the trailing newlines off the result.
918     # This will make it so the test author doesn't have to know that.
919     $expected =~ s/\n+$//;
920
921     local $Level = 2;
922     _fresh_perl($prog, 'eq', $expected, $runperl_args, $name);
923 }
924
925 #
926 # fresh_perl_like
927 #
928 # Combination of run_perl() and like().
929 #
930
931 sub fresh_perl_like {
932     my($prog, $expected, $runperl_args, $name) = @_;
933     local $Level = 2;
934     _fresh_perl($prog, '=~', $expected, $runperl_args, $name);
935 }
936
937 # Many tests use the same format in __DATA__ or external files to specify a
938 # sequence of (fresh) tests to run, extra files they may temporarily need, and
939 # what the expected output is. So have excatly one copy of the code to run that
940 #
941 # Each program is source code to run followed by an "EXPECT" line, followed
942 # by the expected output.
943 #
944 # The code to run may begin with a command line switch such as -w or -0777
945 # (alphanumerics only), and may contain (note the '# ' on each):
946 #   # TODO reason for todo
947 #   # SKIP reason for skip
948 #   # SKIP ?code to test if this should be skipped
949 #   # NAME name of the test (as with ok($ok, $name))
950 #
951 # The expected output may contain:
952 #   OPTION list of options
953 #   OPTIONS list of options
954 #   PREFIX
955 #     indicates that the supplied output is only a prefix to the
956 #     expected output
957 #
958 # The possible options for OPTION may be:
959 #   regex - the expected output is a regular expression
960 #   random - all lines match but in any order
961 #   fatal - the code will fail fatally (croak, die)
962 #
963 # If the actual output contains a line "SKIPPED" the test will be
964 # skipped.
965 #
966 # If the global variable $FATAL is true then OPTION fatal is the
967 # default.
968
969 sub run_multiple_progs {
970     my $up = shift;
971     my @prgs;
972     if ($up) {
973         # The tests in lib run in a temporary subdirectory of t, and always
974         # pass in a list of "programs" to run
975         @prgs = @_;
976     } else {
977         # The tests below t run in t and pass in a file handle.
978         my $fh = shift;
979         local $/;
980         @prgs = split "\n########\n", <$fh>;
981     }
982
983     my $tmpfile = tempfile();
984
985     for (@prgs){
986         unless (/\n/) {
987             print "# From $_\n";
988             next;
989         }
990         my $switch = "";
991         my @temps ;
992         my @temp_path;
993         if (s/^(\s*-\w+)//) {
994             $switch = $1;
995         }
996         my ($prog, $expected) = split(/\nEXPECT(?:\n|$)/, $_, 2);
997
998         my %reason;
999         foreach my $what (qw(skip todo)) {
1000             $prog =~ s/^#\s*\U$what\E\s*(.*)\n//m and $reason{$what} = $1;
1001             # If the SKIP reason starts ? then it's taken as a code snippet to
1002             # evaluate. This provides the flexibility to have conditional SKIPs
1003             if ($reason{$what} && $reason{$what} =~ s/^\?//) {
1004                 my $temp = eval $reason{$what};
1005                 if ($@) {
1006                     die "# In \U$what\E code reason:\n# $reason{$what}\n$@";
1007                 }
1008                 $reason{$what} = $temp;
1009             }
1010         }
1011         my $name = '';
1012         if ($prog =~ s/^#\s*NAME\s+(.+)\n//m) {
1013             $name = $1;
1014         }
1015
1016         if ($prog =~ /--FILE--/) {
1017             my @files = split(/\n--FILE--\s*([^\s\n]*)\s*\n/, $prog) ;
1018             shift @files ;
1019             die "Internal error: test $_ didn't split into pairs, got " .
1020                 scalar(@files) . "[" . join("%%%%", @files) ."]\n"
1021                     if @files % 2;
1022             while (@files > 2) {
1023                 my $filename = shift @files;
1024                 my $code = shift @files;
1025                 push @temps, $filename;
1026                 if ($filename =~ m#(.*)/# && $filename !~ m#^\.\./#) {
1027                     require File::Path;
1028                     File::Path::mkpath($1);
1029                     push(@temp_path, $1);
1030                 }
1031                 open my $fh, '>', $filename or die "Cannot open $filename: $!\n";
1032                 print $fh $code;
1033                 close $fh or die "Cannot close $filename: $!\n";
1034             }
1035             shift @files;
1036             $prog = shift @files;
1037         }
1038
1039         open my $fh, '>', $tmpfile or die "Cannot open >$tmpfile: $!";
1040         print $fh q{
1041         BEGIN {
1042             open STDERR, '>&', STDOUT
1043               or die "Can't dup STDOUT->STDERR: $!;";
1044         }
1045         };
1046         print $fh "\n#line 1\n";  # So the line numbers don't get messed up.
1047         print $fh $prog,"\n";
1048         close $fh or die "Cannot close $tmpfile: $!";
1049         my $results = runperl( stderr => 1, progfile => $tmpfile, $up
1050                                ? (switches => ["-I$up/lib", $switch], nolib => 1)
1051                                : (switches => [$switch])
1052                                 );
1053         my $status = $?;
1054         $results =~ s/\n+$//;
1055         # allow expected output to be written as if $prog is on STDIN
1056         $results =~ s/$::tempfile_regexp/-/g;
1057         if ($^O eq 'VMS') {
1058             # some tests will trigger VMS messages that won't be expected
1059             $results =~ s/\n?%[A-Z]+-[SIWEF]-[A-Z]+,.*//;
1060
1061             # pipes double these sometimes
1062             $results =~ s/\n\n/\n/g;
1063         }
1064         # bison says 'parse error' instead of 'syntax error',
1065         # various yaccs may or may not capitalize 'syntax'.
1066         $results =~ s/^(syntax|parse) error/syntax error/mig;
1067         # allow all tests to run when there are leaks
1068         $results =~ s/Scalars leaked: \d+\n//g;
1069
1070         $expected =~ s/\n+$//;
1071         my $prefix = ($results =~ s#^PREFIX(\n|$)##) ;
1072         # any special options? (OPTIONS foo bar zap)
1073         my $option_regex = 0;
1074         my $option_random = 0;
1075         my $fatal = $FATAL;
1076         if ($expected =~ s/^OPTIONS? (.+)\n//) {
1077             foreach my $option (split(' ', $1)) {
1078                 if ($option eq 'regex') { # allow regular expressions
1079                     $option_regex = 1;
1080                 }
1081                 elsif ($option eq 'random') { # all lines match, but in any order
1082                     $option_random = 1;
1083                 }
1084                 elsif ($option eq 'fatal') { # perl should fail
1085                     $fatal = 1;
1086                 }
1087                 else {
1088                     die "$0: Unknown OPTION '$option'\n";
1089                 }
1090             }
1091         }
1092         die "$0: can't have OPTION regex and random\n"
1093             if $option_regex + $option_random > 1;
1094         my $ok = 0;
1095         if ($results =~ s/^SKIPPED\n//) {
1096             print "$results\n" ;
1097             $ok = 1;
1098         }
1099         else {
1100             if ($option_random) {
1101                 my @got = sort split "\n", $results;
1102                 my @expected = sort split "\n", $expected;
1103
1104                 $ok = "@got" eq "@expected";
1105             }
1106             elsif ($option_regex) {
1107                 $ok = $results =~ /^$expected/;
1108             }
1109             elsif ($prefix) {
1110                 $ok = $results =~ /^\Q$expected/;
1111             }
1112             else {
1113                 $ok = $results eq $expected;
1114             }
1115
1116             if ($ok && $fatal && !($status >> 8)) {
1117                 $ok = 0;
1118             }
1119         }
1120
1121         local $::TODO = $reason{todo};
1122
1123         unless ($ok) {
1124             my $err_line = "PROG: $switch\n$prog\n" .
1125                            "EXPECTED:\n$expected\n";
1126             $err_line   .= "EXIT STATUS: != 0\n" if $fatal;
1127             $err_line   .= "GOT:\n$results\n";
1128             $err_line   .= "EXIT STATUS: " . ($status >> 8) . "\n" if $fatal;
1129             if ($::TODO) {
1130                 $err_line =~ s/^/# /mg;
1131                 print $err_line;  # Harness can't filter it out from STDERR.
1132             }
1133             else {
1134                 print STDERR $err_line;
1135             }
1136         }
1137
1138         ok($ok, $name);
1139
1140         foreach (@temps) {
1141             unlink $_ if $_;
1142         }
1143         foreach (@temp_path) {
1144             File::Path::rmtree $_ if -d $_;
1145         }
1146     }
1147 }
1148
1149 sub can_ok ($@) {
1150     my($proto, @methods) = @_;
1151     my $class = ref $proto || $proto;
1152
1153     unless( @methods ) {
1154         return _ok( 0, _where(), "$class->can(...)" );
1155     }
1156
1157     my @nok = ();
1158     foreach my $method (@methods) {
1159         local($!, $@);  # don't interfere with caller's $@
1160                         # eval sometimes resets $!
1161         eval { $proto->can($method) } || push @nok, $method;
1162     }
1163
1164     my $name;
1165     $name = @methods == 1 ? "$class->can('$methods[0]')"
1166                           : "$class->can(...)";
1167
1168     _ok( !@nok, _where(), $name );
1169 }
1170
1171
1172 # Call $class->new( @$args ); and run the result through object_ok.
1173 # See Test::More::new_ok
1174 sub new_ok {
1175     my($class, $args, $obj_name) = @_;
1176     $args ||= [];
1177     $object_name = "The object" unless defined $obj_name;
1178
1179     local $Level = $Level + 1;
1180
1181     my $obj;
1182     my $ok = eval { $obj = $class->new(@$args); 1 };
1183     my $error = $@;
1184
1185     if($ok) {
1186         object_ok($obj, $class, $object_name);
1187     }
1188     else {
1189         ok( 0, "new() died" );
1190         diag("Error was:  $@");
1191     }
1192
1193     return $obj;
1194
1195 }
1196
1197
1198 sub isa_ok ($$;$) {
1199     my($object, $class, $obj_name) = @_;
1200
1201     my $diag;
1202     $obj_name = 'The object' unless defined $obj_name;
1203     my $name = "$obj_name isa $class";
1204     if( !defined $object ) {
1205         $diag = "$obj_name isn't defined";
1206     }
1207     else {
1208         my $whatami = ref $object ? 'object' : 'class';
1209
1210         # We can't use UNIVERSAL::isa because we want to honor isa() overrides
1211         local($@, $!);  # eval sometimes resets $!
1212         my $rslt = eval { $object->isa($class) };
1213         my $error = $@;  # in case something else blows away $@
1214
1215         if( $error ) {
1216             if( $error =~ /^Can't call method "isa" on unblessed reference/ ) {
1217                 # It's an unblessed reference
1218                 $obj_name = 'The reference' unless defined $obj_name;
1219                 if( !UNIVERSAL::isa($object, $class) ) {
1220                     my $ref = ref $object;
1221                     $diag = "$obj_name isn't a '$class' it's a '$ref'";
1222                 }
1223             }
1224             elsif( $error =~ /Can't call method "isa" without a package/ ) {
1225                 # It's something that can't even be a class
1226                 $obj_name = 'The thing' unless defined $obj_name;
1227                 $diag = "$obj_name isn't a class or reference";
1228             }
1229             else {
1230                 die <<WHOA;
1231 WHOA! I tried to call ->isa on your object and got some weird error.
1232 This should never happen.  Please contact the author immediately.
1233 Here's the error.
1234 $@
1235 WHOA
1236             }
1237         }
1238         elsif( !$rslt ) {
1239             $obj_name = "The $whatami" unless defined $obj_name;
1240             my $ref = ref $object;
1241             $diag = "$obj_name isn't a '$class' it's a '$ref'";
1242         }
1243     }
1244
1245     _ok( !$diag, _where(), $name );
1246 }
1247
1248
1249 sub class_ok {
1250     my($class, $isa, $class_name) = @_;
1251
1252     # Written so as to count as one test
1253     local $Level = $Level + 1;
1254     if( ref $class ) {
1255         ok( 0, "$class is a refrence, not a class name" );
1256     }
1257     else {
1258         isa_ok($class, $isa, $class_name);
1259     }
1260 }
1261
1262
1263 sub object_ok {
1264     my($obj, $isa, $obj_name) = @_;
1265
1266     local $Level = $Level + 1;
1267     if( !ref $obj ) {
1268         ok( 0, "$obj is not a reference" );
1269     }
1270     else {
1271         isa_ok($obj, $isa, $obj_name);
1272     }
1273 }
1274
1275
1276 # Purposefully avoiding a closure.
1277 sub __capture {
1278     push @::__capture, join "", @_;
1279 }
1280     
1281 sub capture_warnings {
1282     my $code = shift;
1283
1284     local @::__capture;
1285     local $SIG {__WARN__} = \&__capture;
1286     &$code;
1287     return @::__capture;
1288 }
1289
1290 # This will generate a variable number of tests.
1291 # Use done_testing() instead of a fixed plan.
1292 sub warnings_like {
1293     my ($code, $expect, $name) = @_;
1294     local $Level = $Level + 1;
1295
1296     my @w = capture_warnings($code);
1297
1298     cmp_ok(scalar @w, '==', scalar @$expect, $name);
1299     foreach my $e (@$expect) {
1300         if (ref $e) {
1301             like(shift @w, $e, $name);
1302         } else {
1303             is(shift @w, $e, $name);
1304         }
1305     }
1306     if (@w) {
1307         diag("Saw these additional warnings:");
1308         diag($_) foreach @w;
1309     }
1310 }
1311
1312 sub _fail_excess_warnings {
1313     my($expect, $got, $name) = @_;
1314     local $Level = $Level + 1;
1315     # This will fail, and produce diagnostics
1316     is($expect, scalar @$got, $name);
1317     diag("Saw these warnings:");
1318     diag($_) foreach @$got;
1319 }
1320
1321 sub warning_is {
1322     my ($code, $expect, $name) = @_;
1323     die sprintf "Expect must be a string or undef, not a %s reference", ref $expect
1324         if ref $expect;
1325     local $Level = $Level + 1;
1326     my @w = capture_warnings($code);
1327     if (@w > 1) {
1328         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1329     } else {
1330         is($w[0], $expect, $name);
1331     }
1332 }
1333
1334 sub warning_like {
1335     my ($code, $expect, $name) = @_;
1336     die sprintf "Expect must be a regexp object"
1337         unless ref $expect eq 'Regexp';
1338     local $Level = $Level + 1;
1339     my @w = capture_warnings($code);
1340     if (@w > 1) {
1341         _fail_excess_warnings(0 + defined $expect, \@w, $name);
1342     } else {
1343         like($w[0], $expect, $name);
1344     }
1345 }
1346
1347 # Set a watchdog to timeout the entire test file
1348 # NOTE:  If the test file uses 'threads', then call the watchdog() function
1349 #        _AFTER_ the 'threads' module is loaded.
1350 sub watchdog ($;$)
1351 {
1352     my $timeout = shift;
1353     my $method  = shift || "";
1354     my $timeout_msg = 'Test process timed out - terminating';
1355
1356     # Valgrind slows perl way down so give it more time before dying.
1357     $timeout *= 10 if $ENV{PERL_VALGRIND};
1358
1359     my $pid_to_kill = $$;   # PID for this process
1360
1361     if ($method eq "alarm") {
1362         goto WATCHDOG_VIA_ALARM;
1363     }
1364
1365     # shut up use only once warning
1366     my $threads_on = $threads::threads && $threads::threads;
1367
1368     # Don't use a watchdog process if 'threads' is loaded -
1369     #   use a watchdog thread instead
1370     if (!$threads_on || $method eq "process") {
1371
1372         # On Windows and VMS, try launching a watchdog process
1373         #   using system(1, ...) (see perlport.pod)
1374         if ($is_mswin || $is_vms) {
1375             # On Windows, try to get the 'real' PID
1376             if ($is_mswin) {
1377                 eval { require Win32; };
1378                 if (defined(&Win32::GetCurrentProcessId)) {
1379                     $pid_to_kill = Win32::GetCurrentProcessId();
1380                 }
1381             }
1382
1383             # If we still have a fake PID, we can't use this method at all
1384             return if ($pid_to_kill <= 0);
1385
1386             # Launch watchdog process
1387             my $watchdog;
1388             eval {
1389                 local $SIG{'__WARN__'} = sub {
1390                     _diag("Watchdog warning: $_[0]");
1391                 };
1392                 my $sig = $is_vms ? 'TERM' : 'KILL';
1393                 my $cmd = _create_runperl( prog =>  "sleep($timeout);" .
1394                                                     "warn qq/# $timeout_msg" . '\n/;' .
1395                                                     "kill($sig, $pid_to_kill);");
1396                 $watchdog = system(1, $cmd);
1397             };
1398             if ($@ || ($watchdog <= 0)) {
1399                 _diag('Failed to start watchdog');
1400                 _diag($@) if $@;
1401                 undef($watchdog);
1402                 return;
1403             }
1404
1405             # Add END block to parent to terminate and
1406             #   clean up watchdog process
1407             eval "END { local \$! = 0; local \$? = 0;
1408                         wait() if kill('KILL', $watchdog); };";
1409             return;
1410         }
1411
1412         # Try using fork() to generate a watchdog process
1413         my $watchdog;
1414         eval { $watchdog = fork() };
1415         if (defined($watchdog)) {
1416             if ($watchdog) {   # Parent process
1417                 # Add END block to parent to terminate and
1418                 #   clean up watchdog process
1419                 eval "END { local \$! = 0; local \$? = 0;
1420                             wait() if kill('KILL', $watchdog); };";
1421                 return;
1422             }
1423
1424             ### Watchdog process code
1425
1426             # Load POSIX if available
1427             eval { require POSIX; };
1428
1429             # Execute the timeout
1430             sleep($timeout - 2) if ($timeout > 2);   # Workaround for perlbug #49073
1431             sleep(2);
1432
1433             # Kill test process if still running
1434             if (kill(0, $pid_to_kill)) {
1435                 _diag($timeout_msg);
1436                 kill('KILL', $pid_to_kill);
1437                 if ($is_cygwin) {
1438                     # sometimes the above isn't enough on cygwin
1439                     sleep 1; # wait a little, it might have worked after all
1440                     system("/bin/kill -f $pid_to_kill");
1441                 }
1442             }
1443
1444             # Don't execute END block (added at beginning of this file)
1445             $NO_ENDING = 1;
1446
1447             # Terminate ourself (i.e., the watchdog)
1448             POSIX::_exit(1) if (defined(&POSIX::_exit));
1449             exit(1);
1450         }
1451
1452         # fork() failed - fall through and try using a thread
1453     }
1454
1455     # Use a watchdog thread because either 'threads' is loaded,
1456     #   or fork() failed
1457     if (eval {require threads; 1}) {
1458         'threads'->create(sub {
1459                 # Load POSIX if available
1460                 eval { require POSIX; };
1461
1462                 # Execute the timeout
1463                 my $time_left = $timeout;
1464                 do {
1465                     $time_left = $time_left - sleep($time_left);
1466                 } while ($time_left > 0);
1467
1468                 # Kill the parent (and ourself)
1469                 select(STDERR); $| = 1;
1470                 _diag($timeout_msg);
1471                 POSIX::_exit(1) if (defined(&POSIX::_exit));
1472                 my $sig = $is_vms ? 'TERM' : 'KILL';
1473                 kill($sig, $pid_to_kill);
1474             })->detach();
1475         return;
1476     }
1477
1478     # If everything above fails, then just use an alarm timeout
1479 WATCHDOG_VIA_ALARM:
1480     if (eval { alarm($timeout); 1; }) {
1481         # Load POSIX if available
1482         eval { require POSIX; };
1483
1484         # Alarm handler will do the actual 'killing'
1485         $SIG{'ALRM'} = sub {
1486             select(STDERR); $| = 1;
1487             _diag($timeout_msg);
1488             POSIX::_exit(1) if (defined(&POSIX::_exit));
1489             my $sig = $is_vms ? 'TERM' : 'KILL';
1490             kill($sig, $pid_to_kill);
1491         };
1492     }
1493 }
1494
1495 my $cp_0037 =   # EBCDIC code page 0037
1496     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x25\x0B\x0C\x0D\x0E\x0F' .
1497     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1498     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1499     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1500     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1501     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBA\xE0\xBB\xB0\x6D' .
1502     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1503     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1504     '\x20\x21\x22\x23\x24\x15\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1505     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1506     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBD\xB4\x9A\x8A\x5F\xCA\xAF\xBC' .
1507     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1508     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1509     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xAD\xAE\x59' .
1510     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1511     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1512
1513 my $cp_1047 =   # EBCDIC code page 1047
1514     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1515     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1516     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1517     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1518     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1519     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xAD\xE0\xBD\x5F\x6D' .
1520     '\x79\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1521     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xC0\x4F\xD0\xA1\x07' .
1522     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1523     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\xFF' .
1524     '\x41\xAA\x4A\xB1\x9F\xB2\x6A\xB5\xBB\xB4\x9A\x8A\xB0\xCA\xAF\xBC' .
1525     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1526     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1527     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xFD\xFE\xFB\xFC\xBA\xAE\x59' .
1528     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1529     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xDD\xDE\xDB\xDC\x8D\x8E\xDF';
1530
1531 my $cp_bc = # EBCDIC code page POSiX-BC
1532     '\x00\x01\x02\x03\x37\x2D\x2E\x2F\x16\x05\x15\x0B\x0C\x0D\x0E\x0F' .
1533     '\x10\x11\x12\x13\x3C\x3D\x32\x26\x18\x19\x3F\x27\x1C\x1D\x1E\x1F' .
1534     '\x40\x5A\x7F\x7B\x5B\x6C\x50\x7D\x4D\x5D\x5C\x4E\x6B\x60\x4B\x61' .
1535     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\x7A\x5E\x4C\x7E\x6E\x6F' .
1536     '\x7C\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xD1\xD2\xD3\xD4\xD5\xD6' .
1537     '\xD7\xD8\xD9\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xBB\xBC\xBD\x6A\x6D' .
1538     '\x4A\x81\x82\x83\x84\x85\x86\x87\x88\x89\x91\x92\x93\x94\x95\x96' .
1539     '\x97\x98\x99\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xFB\x4F\xFD\xFF\x07' .
1540     '\x20\x21\x22\x23\x24\x25\x06\x17\x28\x29\x2A\x2B\x2C\x09\x0A\x1B' .
1541     '\x30\x31\x1A\x33\x34\x35\x36\x08\x38\x39\x3A\x3B\x04\x14\x3E\x5F' .
1542     '\x41\xAA\xB0\xB1\x9F\xB2\xD0\xB5\x79\xB4\x9A\x8A\xBA\xCA\xAF\xA1' .
1543     '\x90\x8F\xEA\xFA\xBE\xA0\xB6\xB3\x9D\xDA\x9B\x8B\xB7\xB8\xB9\xAB' .
1544     '\x64\x65\x62\x66\x63\x67\x9E\x68\x74\x71\x72\x73\x78\x75\x76\x77' .
1545     '\xAC\x69\xED\xEE\xEB\xEF\xEC\xBF\x80\xE0\xFE\xDD\xFC\xAD\xAE\x59' .
1546     '\x44\x45\x42\x46\x43\x47\x9C\x48\x54\x51\x52\x53\x58\x55\x56\x57' .
1547     '\x8C\x49\xCD\xCE\xCB\xCF\xCC\xE1\x70\xC0\xDE\xDB\xDC\x8D\x8E\xDF';
1548
1549 my $straight =  # Avoid ranges
1550     '\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F' .
1551     '\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F' .
1552     '\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F' .
1553     '\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F' .
1554     '\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F' .
1555     '\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F' .
1556     '\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F' .
1557     '\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F' .
1558     '\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F' .
1559     '\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F' .
1560     '\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF' .
1561     '\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF' .
1562     '\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF' .
1563     '\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF' .
1564     '\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF' .
1565     '\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF';
1566
1567 # The following 2 functions allow tests to work on both EBCDIC and
1568 # ASCII-ish platforms.  They convert string scalars between the native
1569 # character set and the set of 256 characters which is usually called
1570 # Latin1.
1571 #
1572 # These routines don't work on UTF-EBCDIC and UTF-8.
1573
1574 sub native_to_latin1($) {
1575     my $string = shift;
1576
1577     return $string if ord('^') == 94;   # ASCII, Latin1
1578     my $cp;
1579     if (ord('^') == 95) {    # EBCDIC 1047
1580         $cp = \$cp_1047;
1581     }
1582     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1583         $cp = \$cp_bc;
1584     }
1585     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1586         $cp = \$cp_0037;
1587     }
1588     else {
1589         die "Unknown native character set";
1590     }
1591
1592     eval '$string =~ tr/' . $$cp . '/' . $straight . '/';
1593     return $string;
1594 }
1595
1596 sub latin1_to_native($) {
1597     my $string = shift;
1598
1599     return $string if ord('^') == 94;   # ASCII, Latin1
1600     my $cp;
1601     if (ord('^') == 95) {    # EBCDIC 1047
1602         $cp = \$cp_1047;
1603     }
1604     elsif (ord('^') == 106) {   # EBCDIC POSIX-BC
1605         $cp = \$cp_bc;
1606     }
1607     elsif (ord('^') == 176)  {   # EBCDIC 037 */
1608         $cp = \$cp_0037;
1609     }
1610     else {
1611         die "Unknown native character set";
1612     }
1613
1614     eval '$string =~ tr/' . $straight . '/' . $$cp . '/';
1615     return $string;
1616 }
1617
1618 sub ord_latin1_to_native {
1619     # given an input code point, return the platform's native
1620     # equivalent value.  Anything above latin1 is itself.
1621
1622     my $ord = shift;
1623     return $ord if $ord > 255;
1624     return ord latin1_to_native(chr $ord);
1625 }
1626
1627 sub ord_native_to_latin1 {
1628     # given an input platform code point, return the latin1 equivalent value.
1629     # Anything above latin1 is itself.
1630
1631     my $ord = shift;
1632     return $ord if $ord > 255;
1633     return ord native_to_latin1(chr $ord);
1634 }
1635
1636 1;