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