This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Added porting tests for CUSTOMIZED files
[perl5.git] / t / op / magic.t
1 #!./perl
2
3 BEGIN {
4     $| = 1;
5     chdir 't' if -d 't';
6     @INC = '../lib';
7     require './test.pl';
8     plan (tests => 150);
9 }
10
11 # Test that defined() returns true for magic variables created on the fly,
12 # even before they have been created.
13 # This must come first, even before turning on warnings or setting up
14 # $SIG{__WARN__}, to avoid invalidating the tests.  warnings.pm currently
15 # does not mention any special variables, but that could easily change.
16 BEGIN {
17     # not available in miniperl
18     my %non_mini = map { $_ => 1 } qw(+ - [);
19     for (qw(
20         SIG ^OPEN ^TAINT ^UNICODE ^UTF8LOCALE ^WARNING_BITS 1 2 3 4 5 6 7 8
21         9 42 & ` ' : ? ! _ - [ ^ ~ = % . ( ) < > \ / $ | + ; ] ^A ^C ^D
22         ^E ^F ^H ^I ^L ^N ^O ^P ^S ^T ^V ^W ^UTF8CACHE ::12345 main::98732
23     )) {
24         my $v = $_;
25         # avoid using any global vars here:
26         if ($v =~ s/^\^(?=.)//) {
27             for(substr $v, 0, 1) {
28                 $_ = chr ord() - 64;
29             }
30         }
31         SKIP:
32         {
33             skip_if_miniperl("the module for *$_ may not be available in "
34                              . "miniperl", 1) if $non_mini{$_};
35             ok defined *$v, "*$_ appears to be defined at the outset";
36         }
37     }
38 }
39
40 # This must be in a separate BEGIN block, as the mere mention of ${^TAINT}
41 # will invalidate the test for it.
42 BEGIN {
43     $ENV{PATH} = '/bin' if ${^TAINT};
44     $SIG{__WARN__} = sub { die "Dying on warning: ", @_ };
45 }
46
47 use warnings;
48 use Config;
49
50
51 $Is_MSWin32  = $^O eq 'MSWin32';
52 $Is_NetWare  = $^O eq 'NetWare';
53 $Is_VMS      = $^O eq 'VMS';
54 $Is_Dos      = $^O eq 'dos';
55 $Is_os2      = $^O eq 'os2';
56 $Is_Cygwin   = $^O eq 'cygwin';
57 $Is_MPE      = $^O eq 'mpeix';          
58 $Is_BeOS     = $^O eq 'beos';
59
60 $PERL = $ENV{PERL}
61     || ($Is_NetWare           ? 'perl'   :
62        $Is_VMS                ? $^X      :
63        $Is_MSWin32            ? '.\perl' :
64        './perl');
65
66 END {
67     # On VMS, environment variable changes are peristent after perl exits
68     delete $ENV{'FOO'} if $Is_VMS;
69 }
70
71 eval '$ENV{"FOO"} = "hi there";';       # check that ENV is inited inside eval
72 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
73 # -- Nikola Knezevic
74 if ($Is_MSWin32)  { like `set FOO`, qr/^(?:FOO=)?hi there$/; }
75 elsif ($Is_VMS)   { is `write sys\$output f\$trnlnm("FOO")`, "hi there\n"; }
76 else              { is `echo \$FOO`, "hi there\n"; }
77
78 unlink_all 'ajslkdfpqjsjfk';
79 $! = 0;
80 open(FOO,'ajslkdfpqjsjfk');
81 isnt($!, 0);
82 close FOO; # just mention it, squelch used-only-once
83
84 SKIP: {
85     skip('SIGINT not safe on this platform', 5)
86         if $Is_MSWin32 || $Is_NetWare || $Is_Dos || $Is_MPE;
87   # the next tests are done in a subprocess because sh spits out a
88   # newline onto stderr when a child process kills itself with SIGINT.
89   # We use a pipe rather than system() because the VMS command buffer
90   # would overflow with a command that long.
91
92     # For easy interpolation of test numbers:
93     $next_test = curr_test() - 1;
94     sub TIEARRAY {bless[]}
95     sub FETCH { $next_test + pop }
96     tie my @tn, __PACKAGE__;
97
98     open( CMDPIPE, "| $PERL");
99
100     print CMDPIPE "\$t1 = $tn[1]; \$t2 = $tn[2];\n", <<'END';
101
102     $| = 1;             # command buffering
103
104     $SIG{"INT"} = "ok1";     kill "INT",$$; sleep 1;
105     $SIG{"INT"} = "IGNORE";  kill "INT",$$; sleep 1; print "ok $t2\n";
106     $SIG{"INT"} = "DEFAULT"; kill "INT",$$; sleep 1; print" not ok $t2\n";
107
108     sub ok1 {
109         if (($x = pop(@_)) eq "INT") {
110             print "ok $t1\n";
111         }
112         else {
113             print "not ok $t1 ($x @_)\n";
114         }
115     }
116
117 END
118
119     close CMDPIPE;
120
121     open( CMDPIPE, "| $PERL");
122     print CMDPIPE "\$t3 = $tn[3];\n", <<'END';
123
124     { package X;
125         sub DESTROY {
126             kill "INT",$$;
127         }
128     }
129     sub x {
130         my $x=bless [], 'X';
131         return sub { $x };
132     }
133     $| = 1;             # command buffering
134     $SIG{"INT"} = "ok3";
135     {
136         local $SIG{"INT"}=x();
137         print ""; # Needed to expose failure in 5.8.0 (why?)
138     }
139     sleep 1;
140     delete $SIG{"INT"};
141     kill "INT",$$; sleep 1;
142     sub ok3 {
143         print "ok $t3\n";
144     }
145 END
146     close CMDPIPE;
147     $? >>= 8 if $^O eq 'VMS'; # POSIX status hiding in 2nd byte
148     my $todo = ($^O eq 'os2' ? ' # TODO: EMX v0.9d_fix4 bug: wrong nibble? ' : '');
149     print $? & 0xFF ? "ok $tn[4]$todo\n" : "not ok $tn[4]$todo\n";
150
151     open(CMDPIPE, "| $PERL");
152     print CMDPIPE <<'END';
153
154     sub PVBM () { 'foo' }
155     index 'foo', PVBM;
156     my $pvbm = PVBM;
157
158     sub foo { exit 0 }
159
160     $SIG{"INT"} = $pvbm;
161     kill "INT", $$; sleep 1;
162 END
163     close CMDPIPE;
164     $? >>= 8 if $^O eq 'VMS';
165     print $? ? "not ok $tn[5]\n" : "ok $tn[5]\n";
166
167     curr_test(curr_test() + 5);
168 }
169
170 # can we slice ENV?
171 @val1 = @ENV{keys(%ENV)};
172 @val2 = values(%ENV);
173 is join(':',@val1), join(':',@val2);
174 cmp_ok @val1, '>', 1;
175
176 # regex vars
177 'foobarbaz' =~ /b(a)r/;
178 is $`, 'foo';
179 is $&, 'bar';
180 is $', 'baz';
181 is $+, 'a';
182
183 # $"
184 @a = qw(foo bar baz);
185 is "@a", "foo bar baz";
186 {
187     local $" = ',';
188     is "@a", "foo,bar,baz";
189 }
190
191 # $;
192 %h = ();
193 $h{'foo', 'bar'} = 1;
194 is((keys %h)[0], "foo\034bar");
195 {
196     local $; = 'x';
197     %h = ();
198     $h{'foo', 'bar'} = 1;
199     is((keys %h)[0], 'fooxbar');
200 }
201
202 # $?, $@, $$
203 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(0)"];
204 is $?, 0;
205 system qq[$PERL "-I../lib" -e "use vmsish qw(hushed); exit(1)"];
206 isnt $?, 0;
207
208 eval { die "foo\n" };
209 is $@, "foo\n";
210
211 cmp_ok($$, '>', 0);
212 my $pid = $$;
213 eval { $$ = 42 };
214 is $$, 42, '$$ can be modified';
215 SKIP: {
216     skip "no fork", 1 unless $Config{d_fork};
217     (my $kidpid = open my $fh, "-|") // skip "cannot fork: $!", 1;
218     if($kidpid) { # parent
219         my $kiddollars = <$fh>;
220         close $fh or die "cannot close pipe from kid proc: $!";
221         is $kiddollars, $kidpid, '$$ is reset on fork';
222     }
223     else { # child
224         print $$;
225         $::NO_ENDING = 1; # silence "Looks like you only ran..."
226         exit;
227     }
228 }
229 $$ = $pid; # Tests below use $$
230
231 # $^X and $0
232 {
233     my $is_abs = $Config{d_procselfexe} || $Config{usekernprocpathname}
234       || $Config{usensgetexecutablepath};
235     if ($^O eq 'qnx') {
236         chomp($wd = `/usr/bin/fullpath -t`);
237     }
238     elsif($Is_Cygwin || $is_abs) {
239        # Cygwin turns the symlink into the real file
240        chomp($wd = `pwd`);
241        $wd =~ s#/t$##;
242        $wd =~ /(.*)/; $wd = $1; # untaint
243        if ($Is_Cygwin) {
244            $wd = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($wd, 1));
245        }
246     }
247     elsif($Is_os2) {
248        $wd = Cwd::sys_cwd();
249     }
250     else {
251         $wd = '.';
252     }
253     my $perl = $Is_VMS || $is_abs ? $^X : "$wd/perl";
254     my $headmaybe = '';
255     my $middlemaybe = '';
256     my $tailmaybe = '';
257     $script = "$wd/show-shebang";
258     if ($Is_MSWin32) {
259         chomp($wd = `cd`);
260         $wd =~ s|\\|/|g;
261         $perl = "$wd/perl.exe";
262         $script = "$wd/show-shebang.bat";
263         $headmaybe = <<EOH ;
264 \@rem ='
265 \@echo off
266 $perl -x \%0
267 goto endofperl
268 \@rem ';
269 EOH
270         $tailmaybe = <<EOT ;
271
272 __END__
273 :endofperl
274 EOT
275     }
276     elsif ($Is_os2) {
277       $script = "./show-shebang";
278     }
279     elsif ($Is_VMS) {
280       $script = "[]show-shebang";
281     }
282     elsif ($Is_Cygwin) {
283       $middlemaybe = <<'EOX'
284 $^X = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($^X, 1));
285 $0 = Cygwin::win_to_posix_path(Cygwin::posix_to_win_path($0, 1));
286 EOX
287     }
288     if ($^O eq 'os390' or $^O eq 'posix-bc' or $^O eq 'vmesa') {  # no shebang
289         $headmaybe = <<EOH ;
290     eval 'exec ./perl -S \$0 \${1+"\$\@"}'
291         if 0;
292 EOH
293     }
294     $s1 = "\$^X is $perl, \$0 is $script\n";
295     ok open(SCRIPT, ">$script") or diag "Can't write to $script: $!";
296     ok print(SCRIPT $headmaybe . <<EOB . $middlemaybe . <<'EOF' . $tailmaybe) or diag $!;
297 #!$perl
298 EOB
299 print "\$^X is $^X, \$0 is $0\n";
300 EOF
301     ok close(SCRIPT) or diag $!;
302     ok chmod(0755, $script) or diag $!;
303     $_ = $Is_VMS ? `$perl $script` : `$script`;
304     s/\.exe//i if $Is_Dos or $Is_Cygwin or $Is_os2;
305     s{./$script}{$script} if $Is_BeOS; # revert BeOS execvp() side-effect
306     s{is perl}{is $perl}; # for systems where $^X is only a basename
307     s{\\}{/}g;
308     if ($Is_MSWin32 || $Is_os2) {
309         is uc $_, uc $s1;
310     } else {
311         is $_, $s1;
312     }
313     $_ = `$perl $script`;
314     s/\.exe//i if $Is_Dos or $Is_os2 or $Is_Cygwin;
315     s{./$perl}{$perl} if $Is_BeOS; # revert BeOS execvp() side-effect
316     s{\\}{/}g;
317     if ($Is_MSWin32 || $Is_os2) {
318         is uc $_, uc $s1;
319     } else {
320         is $_, $s1;
321     }
322     ok unlink($script) or diag $!;
323     # CHECK
324     # Could this be replaced with:
325     # unlink_all($script);
326 }
327
328 # $], $^O, $^T
329 cmp_ok $], '>=', 5.00319;
330 ok $^O;
331 cmp_ok $^T, '>', 850000000;
332
333 # Test change 25062 is working
334 my $orig_osname = $^O;
335 {
336 local $^I = '.bak';
337 is $^O, $orig_osname, 'Assigning $^I does not clobber $^O';
338 }
339 $^O = $orig_osname;
340
341 {
342     #RT #72422
343     foreach my $p (0, 1) {
344         fresh_perl_is(<<"EOP", '2 4 8', undef, "test \$^P = $p");
345 \$DB::single = 2;
346 \$DB::trace = 4;
347 \$DB::signal = 8;
348 \$^P = $p;
349 print "\$DB::single \$DB::trace \$DB::signal";
350 EOP
351     }
352 }
353
354 # Check that assigning to $0 on Linux sets the process name with both
355 # argv[0] assignment and by calling prctl()
356 {
357   SKIP: {
358     skip "We don't have prctl() here", 2 unless $Config{d_prctl_set_name};
359
360     # We don't really need these tests. prctl() is tested in the
361     # Kernel, but test it anyway for our sanity. If something doesn't
362     # work (like if the system doesn't have a ps(1) for whatever
363     # reason) just bail out gracefully.
364     my $maybe_ps = sub {
365         my ($cmd) = @_;
366         local ($?, $!);
367
368         no warnings;
369         my $res = `$cmd`;
370         skip "Couldn't shell out to '$cmd', returned code $?", 2 if $?;
371         return $res;
372     };
373
374     my $name = "Good Morning, Dave";
375     $0 = $name;
376
377     chomp(my $argv0 = $maybe_ps->("ps h $$"));
378     chomp(my $prctl = $maybe_ps->("ps hc $$"));
379
380     like($argv0, $name, "Set process name through argv[0] ($argv0)");
381     like($prctl, substr($name, 0, 15), "Set process name through prctl() ($prctl)");
382   }
383 }
384
385 {
386     my $ok = 1;
387     my $warn = '';
388     local $SIG{'__WARN__'} = sub { $ok = 0; $warn = join '', @_; $warn =~ s/\n$//; };
389     $! = undef;
390     local $TODO = $Is_VMS ? "'\$!=undef' does throw a warning" : '';
391     ok($ok, $warn);
392 }
393
394 SKIP: {
395     skip_if_miniperl("miniperl can't rely on loading %Errno", 2);
396    no warnings 'void';
397
398 # Make sure Errno hasn't been prematurely autoloaded
399
400    ok !keys %Errno::;
401
402 # Test auto-loading of Errno when %! is used
403
404    ok scalar eval q{
405       %!;
406       scalar %Errno::;
407    }, $@;
408 }
409
410 SKIP:  {
411     skip_if_miniperl("miniperl can't rely on loading %Errno", 1);
412     # Make sure that Errno loading doesn't clobber $!
413
414     undef %Errno::;
415     delete $INC{"Errno.pm"};
416
417     open(FOO, "nonesuch"); # Generate ENOENT
418     my %errs = %{"!"}; # Cause Errno.pm to be loaded at run-time
419     ok ${"!"}{ENOENT};
420 }
421
422 # Check that we don't auto-load packages
423 SKIP: {
424     skip "staticly linked; may be preloaded", 4 unless $Config{usedl};
425     foreach (['powie::!', 'Errno'],
426              ['powie::+', 'Tie::Hash::NamedCapture']) {
427         my ($symbol, $package) = @$_;
428         foreach my $scalar_first ('', '$$symbol;') {
429             my $desc = qq{Referencing %{"$symbol"}};
430             $desc .= qq{ after mentioning \${"$symbol"}} if $scalar_first;
431             $desc .= " doesn't load $package";
432
433             fresh_perl_is(<<"EOP", 0, {}, $desc);
434 use strict qw(vars subs);
435 my \$symbol = '$symbol';
436 $scalar_first;
437 1 if %{\$symbol};
438 print scalar %${package}::;
439 EOP
440         }
441     }
442 }
443
444 is $^S, 0;
445 eval { is $^S,1 };
446 eval " BEGIN { ok ! defined \$^S } ";
447 is $^S, 0;
448
449 my $taint = ${^TAINT};
450 is ${^TAINT}, $taint;
451 eval { ${^TAINT} = 1 };
452 is ${^TAINT}, $taint;
453
454 # 5.6.1 had a bug: @+ and @- were not properly interpolated
455 # into double-quoted strings
456 # 20020414 mjd-perl-patch+@plover.com
457 "I like pie" =~ /(I) (like) (pie)/;
458 is "@-",  "0 0 2 7";
459 is "@+", "10 1 6 10";
460
461 # Tests for the magic get of $\
462 {
463     my $ok = 0;
464     # [perl #19330]
465     {
466         local $\ = undef;
467         $\++; $\++;
468         $ok = $\ eq 2;
469     }
470     ok $ok;
471     $ok = 0;
472     {
473         local $\ = "a\0b";
474         $ok = "a$\b" eq "aa\0bb";
475     }
476     ok $ok;
477 }
478
479 # Test for bug [perl #36434]
480 # Can not do this test on VMS, EPOC, and SYMBIAN according to comments
481 # in mg.c/Perl_magic_clear_all_env()
482 SKIP: {
483     skip('Can\'t make assignment to \%ENV on this system', 3) if $Is_VMS;
484
485     local @ISA;
486     local %ENV;
487     # This used to be __PACKAGE__, but that causes recursive
488     #  inheritance, which is detected earlier now and broke
489     #  this test
490     eval { push @ISA, __FILE__ };
491     is $@, '', 'Push a constant on a magic array';
492     $@ and print "# $@";
493     eval { %ENV = (PATH => __PACKAGE__) };
494     is $@, '', 'Assign a constant to a magic hash';
495     $@ and print "# $@";
496     eval { my %h = qw(A B); %ENV = (PATH => (keys %h)[0]) };
497     is $@, '', 'Assign a shared key to a magic hash';
498     $@ and print "# $@";
499 }
500
501 # Tests for Perl_magic_clearsig
502 foreach my $sig (qw(__WARN__ INT)) {
503     $SIG{$sig} = lc $sig;
504     is $SIG{$sig}, 'main::' . lc $sig, "Can assign to $sig";
505     is delete $SIG{$sig}, 'main::' . lc $sig, "Can delete from $sig";
506     is $SIG{$sig}, undef, "$sig is now gone";
507     is delete $SIG{$sig}, undef, "$sig remains gone";
508 }
509
510 # And now one which doesn't exist;
511 {
512     no warnings 'signal';
513     $SIG{HUNGRY} = 'mmm, pie';
514 }
515 is $SIG{HUNGRY}, 'mmm, pie', 'Can assign to HUNGRY';
516 is delete $SIG{HUNGRY}, 'mmm, pie', 'Can delete from HUNGRY';
517 is $SIG{HUNGRY}, undef, "HUNGRY is now gone";
518 is delete $SIG{HUNGRY}, undef, "HUNGRY remains gone";
519
520 # Test deleting signals that we never set
521 foreach my $sig (qw(__DIE__ _BOGUS_HOOK KILL THIRSTY)) {
522     is $SIG{$sig}, undef, "$sig is not present";
523     is delete $SIG{$sig}, undef, "delete of $sig returns undef";
524 }
525
526 {
527     $! = 9999;
528     is int $!, 9999, q{[perl #72850] Core dump in bleadperl from perl -e '$! = 9999; $a = $!;'};
529
530 }
531
532 SKIP: {
533     skip_if_miniperl("No XS in miniperl", 3);
534
535     for ( [qw( %- Tie::Hash::NamedCapture )], [qw( $[ arybase )],
536           [qw( %! Errno )] ) {
537         my ($var, $mod) = @$_;
538         my $modfile = $mod =~ s|::|/|gr . ".pm";
539         fresh_perl_is
540            qq 'sub UNIVERSAL::AUTOLOAD{}
541                $mod\::foo() if 0;
542                $var;
543                print "ok\\n" if \$INC{"$modfile"}',
544           "ok\n",
545            { switches => [ '-X' ] },
546           "$var still loads $mod when stash and UNIVERSAL::AUTOLOAD exist";
547     }
548 }
549
550 # ^^^^^^^^^ New tests go here ^^^^^^^^^
551
552 SKIP: {
553     skip("%ENV manipulations fail or aren't safe on $^O", 4)
554         if $Is_VMS || $Is_Dos;
555
556  SKIP: {
557         skip("clearing \%ENV is not safe when running under valgrind")
558             if $ENV{PERL_VALGRIND};
559
560             $PATH = $ENV{PATH};
561             $PDL = $ENV{PERL_DESTRUCT_LEVEL} || 0;
562             $ENV{foo} = "bar";
563             %ENV = ();
564             $ENV{PATH} = $PATH;
565             $ENV{PERL_DESTRUCT_LEVEL} = $PDL || 0;
566             if ($Is_MSWin32) {
567                 is `set foo 2>NUL`, "";
568             } else {
569                 is `echo \$foo`, "\n";
570             }
571         }
572
573         $ENV{__NoNeSuCh} = "foo";
574         $0 = "bar";
575 # cmd.exe will echo 'variable=value' but 4nt will echo just the value
576 # -- Nikola Knezevic
577         if ($Is_MSWin32) {
578             like `set __NoNeSuCh`, qr/^(?:__NoNeSuCh=)?foo$/;
579         } else {
580             is `echo \$__NoNeSuCh`, "foo\n";
581         }
582     SKIP: {
583             skip("\$0 check only on Linux and FreeBSD", 2)
584                 unless $^O =~ /^(linux|freebsd)$/
585                     && open CMDLINE, "/proc/$$/cmdline";
586
587             chomp(my $line = scalar <CMDLINE>);
588             my $me = (split /\0/, $line)[0];
589             is $me, $0, 'altering $0 is effective (testing with /proc/)';
590             close CMDLINE;
591             # perlbug #22811
592             my $mydollarzero = sub {
593               my($arg) = shift;
594               $0 = $arg if defined $arg;
595               # In FreeBSD the ps -o command= will cause
596               # an empty header line, grab only the last line.
597               my $ps = (`ps -o command= -p $$`)[-1];
598               return if $?;
599               chomp $ps;
600               printf "# 0[%s]ps[%s]\n", $0, $ps;
601               $ps;
602             };
603             my $ps = $mydollarzero->("x");
604             ok(!$ps  # we allow that something goes wrong with the ps command
605                # In Linux 2.4 we would get an exact match ($ps eq 'x') but
606                # in Linux 2.2 there seems to be something funny going on:
607                # it seems as if the original length of the argv[] would
608                # be stored in the proc struct and then used by ps(1),
609                # no matter what characters we use to pad the argv[].
610                # (And if we use \0:s, they are shown as spaces.)  Sigh.
611                || $ps =~ /^x\s*$/
612                # FreeBSD cannot get rid of both the leading "perl :"
613                # and the trailing " (perl)": some FreeBSD versions
614                # can get rid of the first one.
615                || ($^O eq 'freebsd' && $ps =~ m/^(?:perl: )?x(?: \(perl\))?$/),
616                        'altering $0 is effective (testing with `ps`)');
617         }
618 }
619
620 # test case-insignificance of %ENV (these tests must be enabled only
621 # when perl is compiled with -DENV_IS_CASELESS)
622 SKIP: {
623     skip('no caseless %ENV support', 4) unless $Is_MSWin32 || $Is_NetWare;
624
625     %ENV = ();
626     $ENV{'Foo'} = 'bar';
627     $ENV{'fOo'} = 'baz';
628     is scalar(keys(%ENV)), 1;
629     ok exists $ENV{'FOo'};
630     is delete $ENV{'foO'}, 'baz';
631     is scalar(keys(%ENV)), 0;
632 }
633
634 __END__
635
636 # Put new tests before the various ENV tests, as they blow %ENV away.