This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #123816] fix stat stacking
[perl5.git] / t / op / gv.t
1 #!./perl
2
3 #
4 # various typeglob tests
5 #
6
7 BEGIN {
8     chdir 't' if -d 't';
9     require './test.pl';
10     set_up_inc('../lib');
11 }
12
13 use warnings;
14
15 plan( tests => 273 );
16
17 # type coercion on assignment
18 $foo = 'foo';
19 $bar = *main::foo;
20 $bar = $foo;
21 is(ref(\$bar), 'SCALAR');
22 $foo = *main::bar;
23
24 # type coercion (not) on misc ops
25
26 ok($foo);
27 is(ref(\$foo), 'GLOB');
28
29 unlike ($foo, qr/abcd/);
30 is(ref(\$foo), 'GLOB');
31
32 is($foo, '*main::bar');
33 is(ref(\$foo), 'GLOB');
34
35 {
36  no warnings;
37  ${\*$foo} = undef;
38  is(ref(\$foo), 'GLOB', 'no type coercion when assigning to *{} retval');
39  $::{phake} = *bar;
40  is(
41    \$::{phake}, \*{"phake"},
42    'symbolic *{} returns symtab entry when FAKE'
43  );
44  ${\*{"phake"}} = undef;
45  is(
46    ref(\$::{phake}), 'GLOB',
47   'no type coercion when assigning to retval of symbolic *{}'
48  );
49  $::{phaque} = *bar;
50  eval '
51    is(
52      \$::{phaque}, \*phaque,
53      "compile-time *{} returns symtab entry when FAKE"
54    );
55    ${\*phaque} = undef;
56  ';
57  is(
58    ref(\$::{phaque}), 'GLOB',
59   'no type coercion when assigning to retval of compile-time *{}'
60  );
61 }
62
63 # type coercion on substitutions that match
64 $a = *main::foo;
65 $b = $a;
66 $a =~ s/^X//;
67 is(ref(\$a), 'GLOB');
68 $a =~ s/^\*//;
69 is($a, 'main::foo');
70 is(ref(\$b), 'GLOB');
71
72 # typeglobs as lvalues
73 substr($foo, 0, 1) = "XXX";
74 is(ref(\$foo), 'SCALAR');
75 is($foo, 'XXXmain::bar');
76
77 # returning glob values
78 sub foo {
79   local($bar) = *main::foo;
80   $foo = *main::bar;
81   return ($foo, $bar);
82 }
83
84 ($fuu, $baa) = foo();
85 ok(defined $fuu);
86 is(ref(\$fuu), 'GLOB');
87
88
89 ok(defined $baa);
90 is(ref(\$baa), 'GLOB');
91
92 # nested package globs
93 # NOTE:  It's probably OK if these semantics change, because the
94 #        fact that %X::Y:: is stored in %X:: isn't documented.
95 #        (I hope.)
96
97 { package Foo::Bar; no warnings 'once'; $test=1; }
98 ok(exists $Foo::{'Bar::'});
99 is($Foo::{'Bar::'}, '*Foo::Bar::');
100
101
102 # test undef operator clearing out entire glob
103 $foo = 'stuff';
104 @foo = qw(more stuff);
105 %foo = qw(even more random stuff);
106 undef *foo;
107 is ($foo, undef);
108 is (scalar @foo, 0);
109 is (scalar %foo, 0);
110
111 {
112     # test warnings from assignment of undef to glob
113     my $msg = '';
114     local $SIG{__WARN__} = sub { $msg = $_[0] };
115     use warnings;
116     *foo = 'bar';
117     is($msg, '');
118     *foo = undef;
119     like($msg, qr/Undefined value assigned to typeglob/);
120
121     no warnings 'once';
122     # test warnings for converting globs to other forms
123     my $copy = *PWOMPF;
124     foreach ($copy, *SKREEE) {
125         $msg = '';
126         my $victim = sprintf "%d", $_;
127         like($msg, qr/Argument "\*main::[A-Z]{6}" isn't numeric in sprintf/,
128              "Warning on conversion to IV");
129         is($victim, 0);
130
131         $msg = '';
132         $victim = sprintf "%u", $_;
133         like($msg, qr/Argument "\*main::[A-Z]{6}" isn't numeric in sprintf/,
134              "Warning on conversion to UV");
135         is($victim, 0);
136
137         $msg = '';
138         $victim = sprintf "%e", $_;
139         like($msg, qr/Argument "\*main::[A-Z]{6}" isn't numeric in sprintf/,
140              "Warning on conversion to NV");
141         like($victim, qr/^0\.0+E\+?00/i, "Expect floating point zero");
142
143         $msg = '';
144         $victim = sprintf "%s", $_;
145         is($msg, '', "No warning on stringification");
146         is($victim, '' . $_);
147     }
148 }
149
150 my $test = curr_test();
151 # test *glob{THING} syntax
152 $x = "ok $test\n";
153 ++$test;
154 @x = ("ok $test\n");
155 ++$test;
156 %x = ("ok $test" => "\n");
157 ++$test;
158 sub x { "ok $test\n" }
159 print ${*x{SCALAR}}, @{*x{ARRAY}}, %{*x{HASH}}, &{*x{CODE}};
160 # This needs to go here, after the print, as sub x will return the current
161 # value of test
162 ++$test;
163 format x =
164 XXX This text isn't used. Should it be?
165 .
166 curr_test($test);
167
168 is (ref *x{FORMAT}, "FORMAT");
169 is ("@{sub { *_{ARRAY} }->(1..3)}", "1 2 3",
170     'returning *_{ARRAY} from sub');
171 *x = *STDOUT;
172 is (*{*x{GLOB}}, "*main::STDOUT");
173
174 {
175     my $test = curr_test();
176
177     print {*x{IO}} "ok $test\n";
178     ++$test;
179
180     my $warn;
181     local $SIG{__WARN__} = sub {
182         $warn .= $_[0];
183     };
184     my $val = *x{FILEHANDLE};
185     print {*x{IO}} ($warn =~ /is deprecated/
186                     ? "ok $test\n" : "not ok $test\n");
187     curr_test(++$test);
188 }
189
190 is *x{NAME}, 'x', '*foo{NAME}';
191 is *x{PACKAGE}, 'main', '*foo{PACKAGE}';
192 { no warnings 'once'; *x = *Foo::y; }
193 is *x, '*Foo::y', 'glob stringifies as assignee after glob-to-glob assign';
194 is *x{NAME}, 'x', 'but *foo{NAME} still returns the original name';
195 is *x{PACKAGE}, 'main', 'and *foo{PACKAGE} the original package';
196
197 {
198     # test if defined() doesn't create any new symbols
199
200     my $a = "SYM000";
201     ok(!defined *{$a});
202
203     ok(!defined ${$a});
204     ok(!defined *{$a});
205
206     ok(!defined &{$a});
207     ok(!defined *{$a});
208
209     my $state = "not";
210     *{$a} = sub { $state = "ok" };
211     ok(defined &{$a});
212     ok(defined *{$a});
213     &{$a};
214     is ($state, 'ok');
215 }
216
217 {
218     # although it *should* if you're talking about magicals
219
220     my $a = "]";
221     ok(defined *{$a});
222     ok(defined ${$a});
223
224     $a = "1";
225     "o" =~ /(o)/;
226     ok(${$a});
227     ok(defined *{$a});
228     $a = "2";
229     ok(!${$a});
230     ok(defined *{$a});
231     $a = "1x";
232     ok(!defined ${$a});
233     ok(!defined *{$a});
234     $a = "11";
235     "o" =~ /(((((((((((o)))))))))))/;
236     ok(${$a});
237     ok(defined *{$a});
238 }
239
240 # [ID 20010526.001] localized glob loses value when assigned to
241
242 $j=1; %j=(a=>1); @j=(1); local *j=*j; *j = sub{};
243
244 is($j, 1);
245 is($j{a}, 1);
246 is($j[0], 1);
247
248 {
249     # does pp_readline() handle glob-ness correctly?
250     my $g = *foo;
251     $g = <DATA>;
252     is ($g, "Perl\n");
253 }
254
255 {
256     my $w = '';
257     local $SIG{__WARN__} = sub { $w = $_[0] };
258     sub abc1 ();
259     local *abc1 = sub { };
260     is ($w, '');
261     sub abc2 ();
262     local *abc2;
263     *abc2 = sub { };
264     is ($w, '');
265     sub abc3 ();
266     *abc3 = sub { };
267     like ($w, qr/Prototype mismatch/);
268 }
269
270 {
271     # [17375] rcatline to formerly-defined undef was broken. Fixed in
272     # do_readline by checking SvOK. AMS, 20020918
273     my $x = "not ";
274     $x  = undef;
275     $x .= <DATA>;
276     is ($x, "Rules\n");
277 }
278
279 {
280     # test the assignment of a GLOB to an LVALUE
281     my $e = '';
282     local $SIG{__DIE__} = sub { $e = $_[0] };
283     my %v;
284     sub f { $_[0] = 0; $_[0] = "a"; $_[0] = *DATA }
285     f($v{v});
286     is ($v{v}, '*main::DATA');
287     is (ref\$v{v}, 'GLOB', 'lvalue assignment preserves globs');
288     my $x = readline $v{v};
289     is ($x, "perl\n");
290     is ($e, '', '__DIE__ handler never called');
291 }
292
293 {
294     my $e = '';
295     # GLOB assignment to tied element
296     local $SIG{__DIE__} = sub { $e = $_[0] };
297     sub T::TIEARRAY  { bless [] => "T" }
298     sub T::STORE     { $_[0]->[ $_[1] ] = $_[2] }
299     sub T::FETCH     { $_[0]->[ $_[1] ] }
300     sub T::FETCHSIZE { @{$_[0]} }
301     tie my @ary => "T";
302     $ary[0] = *DATA;
303     is ($ary[0], '*main::DATA');
304     is (
305       ref\tied(@ary)->[0], 'GLOB',
306      'tied elem assignment preserves globs'
307     );
308     is ($e, '', '__DIE__ handler not called');
309     my $x = readline $ary[0];
310     is($x, "rocks\n");
311     is ($e, '', '__DIE__ handler never called');
312 }
313
314 {
315     # Need some sort of die or warn to get the global destruction text if the
316     # bug is still present
317     my $output = runperl(prog => <<'EOPROG');
318 package M;
319 $| = 1;
320 sub DESTROY {eval {die qq{Farewell $_[0]}}; print $@}
321 package main;
322
323 bless \$A::B, q{M};
324 *A:: = \*B::;
325 EOPROG
326     like($output, qr/^Farewell M=SCALAR/, "DESTROY was called");
327     unlike($output, qr/global destruction/,
328            "unreferenced symbol tables should be cleaned up immediately");
329 }
330
331 # Possibly not the correct test file for these tests.
332 # There are certain space optimisations implemented via promotion rules to
333 # GVs
334
335 foreach (qw (oonk ga_shloip)) {
336     ok(!exists $::{$_}, "no symbols of any sort to start with for $_");
337 }
338
339 # A string in place of the typeglob is promoted to the function prototype
340 $::{oonk} = "pie";
341 my $proto = eval 'prototype \&oonk';
342 die if $@;
343 is ($proto, "pie", "String is promoted to prototype");
344
345
346 # A reference to a value is used to generate a constant subroutine
347 foreach my $value (3, "Perl rules", \42, qr/whatever/, [1,2,3], {1=>2},
348                    \*STDIN, \&ok, \undef, *STDOUT) {
349     delete $::{oonk};
350     $::{oonk} = \$value;
351     $proto = eval 'prototype \&oonk';
352     die if $@;
353     is ($proto, '', "Prototype for a constant subroutine is empty");
354
355     my $got = eval 'oonk';
356     die if $@;
357     is (ref $got, ref $value, "Correct type of value (" . ref($value) . ")");
358     is ($got, $value, "Value is correctly set");
359 }
360
361 delete $::{oonk};
362 $::{oonk} = \"Value";
363
364 *{"ga_shloip"} = \&{"oonk"};
365
366 is (ref $::{ga_shloip}, 'SCALAR', "Export of proxy constant as is");
367 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
368 is (eval 'ga_shloip', "Value", "Constant has correct value");
369 is (ref $::{ga_shloip}, 'SCALAR',
370     "Inlining of constant doesn't change representation");
371
372 delete $::{ga_shloip};
373
374 eval 'sub ga_shloip (); 1' or die $@;
375 is ($::{ga_shloip}, '', "Prototype is stored as an empty string");
376
377 # Check that a prototype expands.
378 *{"ga_shloip"} = \&{"oonk"};
379
380 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
381 is (eval 'ga_shloip', "Value", "Constant has correct value");
382 is (ref \$::{ga_shloip}, 'GLOB', "Symbol table has full typeglob");
383
384
385 @::zwot = ('Zwot!');
386
387 # Check that assignment to an existing typeglob works
388 {
389   my $w = '';
390   local $SIG{__WARN__} = sub { $w = $_[0] };
391   *{"zwot"} = \&{"oonk"};
392   is($w, '', "Should be no warning");
393 }
394
395 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
396 is (eval 'zwot', "Value", "Constant has correct value");
397 is (ref \$::{zwot}, 'GLOB', "Symbol table has full typeglob");
398 is (join ('!', @::zwot), 'Zwot!', "Existing array still in typeglob");
399
400 sub spritsits () {
401     "Traditional";
402 }
403
404 # Check that assignment to an existing subroutine works
405 {
406   my $w = '';
407   local $SIG{__WARN__} = sub { $w = $_[0] };
408   *{"spritsits"} = \&{"oonk"};
409   like($w, qr/^Constant subroutine main::spritsits redefined/,
410        "Redefining a constant sub should warn");
411 }
412
413 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
414 is (eval 'spritsits', "Value", "Constant has correct value");
415 is (ref \$::{spritsits}, 'GLOB', "Symbol table has full typeglob");
416
417 # Check that assignment to an existing typeglob works
418 {
419   my $w = '';
420   local $SIG{__WARN__} = sub { $w = $_[0] };
421   *{"plunk"} = [];
422   *{"plunk"} = \&{"oonk"};
423   is($w, '', "Should be no warning");
424 }
425
426 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
427 is (eval 'plunk', "Value", "Constant has correct value");
428 is (ref \$::{plunk}, 'GLOB', "Symbol table has full typeglob");
429
430 my $gr = eval '\*plunk' or die;
431
432 {
433   my $w = '';
434   local $SIG{__WARN__} = sub { $w = $_[0] };
435   *{$gr} = \&{"oonk"};
436   is($w, '', "Redefining a constant sub to another constant sub with the same underlying value should not warn (It's just re-exporting, and that was always legal)");
437 }
438
439 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
440 is (eval 'plunk', "Value", "Constant has correct value");
441 is (ref \$::{plunk}, 'GLOB', "Symbol table has full typeglob");
442
443 # Non-void context should defeat the optimisation, and will cause the original
444 # to be promoted (what change 26482 intended)
445 my $result;
446 {
447   my $w = '';
448   local $SIG{__WARN__} = sub { $w = $_[0] };
449   $result = *{"awkkkkkk"} = \&{"oonk"};
450   is($w, '', "Should be no warning");
451 }
452
453 is (ref \$result, 'GLOB',
454     "Non void assignment should still return a typeglob");
455
456 is (ref \$::{oonk}, 'GLOB', "This export does affect original");
457 is (eval 'plunk', "Value", "Constant has correct value");
458 is (ref \$::{plunk}, 'GLOB', "Symbol table has full typeglob");
459
460 delete $::{oonk};
461 $::{oonk} = \"Value";
462
463 sub non_dangling {
464   my $w = '';
465   local $SIG{__WARN__} = sub { $w = $_[0] };
466   *{"zap"} = \&{"oonk"};
467   is($w, '', "Should be no warning");
468 }
469
470 non_dangling();
471 is (ref $::{oonk}, 'SCALAR', "Export doesn't affect original");
472 is (eval 'zap', "Value", "Constant has correct value");
473 is (ref $::{zap}, 'SCALAR', "Exported target is also a PCS");
474
475 sub dangling {
476   local $SIG{__WARN__} = sub { die $_[0] };
477   *{"biff"} = \&{"oonk"};
478 }
479
480 dangling();
481 is (ref \$::{oonk}, 'GLOB', "This export does affect original");
482 is (eval 'biff', "Value", "Constant has correct value");
483 is (ref \$::{biff}, 'GLOB', "Symbol table has full typeglob");
484
485 $::{yarrow} = [4,5,6];
486 is join("-", eval "yarrow()"), '4-5-6', 'array ref as stash elem';
487 is ref $::{yarrow}, "ARRAY", 'stash elem is still array ref after use';
488 is join("-", eval "&yarrow"), '4-5-6', 'calling const list with &';
489 is join("-", eval "&yarrow(1..10)"), '4-5-6', 'const list ignores & args';
490 is prototype "yarrow", "", 'const list has "" prototype';
491 is eval "yarrow", 3, 'const list in scalar cx returns length';
492
493 $::{borage} = \&ok;
494 eval 'borage("sub ref in stash")' or fail "sub ref in stash";
495
496 {
497     use vars qw($glook $smek $foof);
498     # Check reference assignment isn't affected by the SV type (bug #38439)
499     $glook = 3;
500     $smek = 4;
501     $foof = "halt and cool down";
502
503     my $rv = \*smek;
504     is($glook, 3);
505     *glook = $rv;
506     is($glook, 4);
507
508     my $pv = "";
509     $pv = \*smek;
510     is($foof, "halt and cool down");
511     *foof = $pv;
512     is($foof, 4);
513 }
514
515 format =
516 .
517
518 foreach my $value ({1=>2}, *STDOUT{IO}, *STDOUT{FORMAT}) {
519     # *STDOUT{IO} returns a reference to a PVIO. As it's blessed, ref returns
520     # IO::Handle, which isn't what we want.
521     my $type = $value;
522     $type =~ s/.*=//;
523     $type =~ s/\(.*//;
524     delete $::{oonk};
525     $::{oonk} = $value;
526     $proto = eval 'prototype \&oonk';
527     like ($@, qr/^Cannot convert a reference to $type to typeglob/,
528           "Cannot upgrade ref-to-$type to typeglob");
529 }
530
531 {
532     no warnings qw(once uninitialized);
533     my $g = \*clatter;
534     my $r = eval {no strict; ${*{$g}{SCALAR}}};
535     is ($@, '', "PERL_DONT_CREATE_GVSV shouldn't affect thingy syntax");
536
537     $g = \*vowm;
538     $r = eval {use strict; ${*{$g}{SCALAR}}};
539     is ($@, '',
540         "PERL_DONT_CREATE_GVSV shouldn't affect thingy syntax under strict");
541 }
542
543 {
544     # Bug reported by broquaint on IRC
545     *slosh::{HASH}->{ISA}=[];
546     slosh->import;
547     pass("gv_fetchmeth coped with the unexpected");
548
549     # An audit found these:
550     {
551         package slosh;
552         sub rip {
553             my $s = shift;
554             $s->SUPER::rip;
555         }
556     }
557     eval {slosh->rip;};
558     like ($@, qr/^Can't locate object method "rip"/, "Even with SUPER");
559
560     is(slosh->isa('swoosh'), '');
561
562     $CORE::GLOBAL::{"lock"}=[];
563     eval "no warnings; lock";
564     like($@, qr/^Not enough arguments for lock/,
565        "Can't trip up general keyword overloading");
566
567     $CORE::GLOBAL::{"readline"}=[];
568     eval "<STDOUT> if 0";
569     is($@, '', "Can't trip up readline overloading");
570
571     $CORE::GLOBAL::{"readpipe"}=[];
572     eval "`` if 0";
573     is($@, '', "Can't trip up readpipe overloading");
574 }
575
576 {
577     die if exists $::{BONK};
578     $::{BONK} = \"powie";
579     *{"BONK"} = \&{"BONK"};
580     eval 'is(BONK(), "powie",
581              "Assignment works when glob created midway (bug 45607)"); 1'
582         or die $@;
583 }
584
585 # For now these tests are here, but they would probably be better in a file for
586 # tests for croaks. (And in turn, that probably deserves to be in a different
587 # directory. Gerard Goossen has a point about the layout being unclear
588
589 sub coerce_integer {
590     no warnings 'numeric';
591     $_[0] |= 0;
592 }
593 sub coerce_number {
594     no warnings 'numeric';
595     $_[0] += 0;
596 }
597 sub coerce_string {
598     $_[0] .= '';
599 }
600
601 foreach my $type (qw(integer number string)) {
602     my $prog = "coerce_$type(*STDERR)";
603     is (scalar eval "$prog; 1", undef, "$prog failed...");
604     like ($@, qr/Can't coerce GLOB to $type in/,
605           "with the correct error message");
606 }
607
608 # RT #65582 anonymous glob should be defined, and not coredump when
609 # stringified. The behaviours are:
610 #
611 #        defined($glob)    "$glob"                   $glob .= ...
612 # 5.8.8     false           "" with uninit warning   "" with uninit warning
613 # 5.10.0    true            (coredump)               (coredump)
614 # 5.1[24]   true            ""                       "" with uninit warning
615 # 5.16      true            "*__ANON__::..."         "*__ANON__::..."
616
617 {
618     my $io_ref = *STDOUT{IO};
619     my $glob = *$io_ref;
620     ok(defined $glob, "RT #65582 anon glob should be defined");
621
622     my $warn = '';
623     local $SIG{__WARN__} = sub { $warn = $_[0] };
624     use warnings;
625     my $str = "$glob";
626     is($warn, '', "RT #65582 anon glob stringification shouldn't warn");
627     is($str,  '*__ANON__::__ANONIO__',
628         "RT #65582/#96326 anon glob stringification");
629 }
630
631 # Another stringification bug: Test that recursion does not cause lexical
632 # handles to lose their names.
633 sub r {
634     my @output;
635     @output = r($_[0]-1) if $_[0];
636     open my $fh, "TEST";
637     push @output, $$fh;
638     close $fh;
639     @output;
640 }
641 is join(' ', r(4)),
642   '*main::$fh *main::$fh *main::$fh *main::$fh *main::$fh',
643   'recursion does not cause lex handles to lose their names';
644
645 # And sub cloning, too; not just recursion
646 my $close_over_me;
647 is join(' ', sub {
648     () = $close_over_me;
649     my @output;
650     @output = CORE::__SUB__->($_[0]-1) if $_[0];
651     open my $fh, "TEST";
652     push @output, $$fh;
653     close $fh;
654     @output;
655    }->(4)),
656   '*main::$fh *main::$fh *main::$fh *main::$fh *main::$fh',
657   'sub cloning does not cause lex handles to lose their names';
658
659 # [perl #71254] - Assigning a glob to a variable that has a current
660 # match position. (We are testing that Perl_magic_setmglob respects globs'
661 # special used of SvSCREAM.)
662 {
663     $m = 2; $m=~s/./0/gems; $m= *STDERR;
664     is(
665         "$m", "*main::STDERR",
666         '[perl #71254] assignment of globs to vars with pos'
667     );
668 }
669
670 # [perl #72740] - indirect object syntax, heuristically imputed due to
671 # the non-existence of a function, should not cause a stash entry to be
672 # created for the non-existent function.
673 {
674         package RT72740a;
675         my $f = bless({}, RT72740b);
676         sub s1 { s2 $f; }
677         our $s4;
678         sub s3 { s4 $f; }
679 }
680 {
681         package RT72740b;
682         sub s2 { "RT72740b::s2" }
683         sub s4 { "RT72740b::s4" }
684 }
685 ok(exists($RT72740a::{s1}), "RT72740a::s1 exists");
686 ok(!exists($RT72740a::{s2}), "RT72740a::s2 does not exist");
687 ok(exists($RT72740a::{s3}), "RT72740a::s3 exists");
688 ok(exists($RT72740a::{s4}), "RT72740a::s4 exists");
689 is(RT72740a::s1(), "RT72740b::s2", "RT72740::s1 parsed correctly");
690 is(RT72740a::s3(), "RT72740b::s4", "RT72740::s3 parsed correctly");
691
692 # [perl #71686] Globs that are in symbol table can be un-globbed
693 $sym = undef;
694 $::{fake} = *sym;
695 is (eval 'local *::fake = \"chuck"; $fake', 'chuck',
696         "Localized glob didn't coerce into a RV");
697 is ($@, '', "Can localize FAKE glob that's present in stash");
698 is (scalar $::{fake}, "*main::sym",
699         "Localized FAKE glob's value was correctly restored");
700
701 # [perl #1804] *$x assignment when $x is a copy of another glob
702 # And [perl #77508] (same thing with list assignment)
703 {
704     no warnings 'once';
705     my $x = *_random::glob_that_is_not_used_elsewhere;
706     *$x = sub{};
707     is(
708       "$x", '*_random::glob_that_is_not_used_elsewhere',
709       '[perl #1804] *$x assignment when $x is FAKE',
710     );
711     $x = *_random::glob_that_is_not_used_elsewhere;
712     (my $dummy, *$x) = (undef,[]);
713     is(
714       "$x", '*_random::glob_that_is_not_used_elsewhere',
715       '[perl #77508] *$x list assignment when $x is FAKE',
716     ) or require Devel::Peek, Devel::Peek::Dump($x);
717 }
718
719 # [perl #76540]
720 # this caused panics or 'Attempt to free unreferenced scalar'
721 # (its a compile-time issue, so the die lets us skip the prints)
722 {
723     my @warnings;
724     local $SIG{__WARN__} = sub { push @warnings, @_ };
725
726     eval <<'EOF';
727 BEGIN { $::{FOO} = \'bar' }
728 die "made it";
729 print FOO, "\n";
730 print FOO, "\n";
731 EOF
732
733     like($@, qr/made it/, "#76540 - no panic");
734     ok(!@warnings, "#76540 - no 'Attempt to free unreferenced scalar'");
735 }
736
737 # [perl #77362] various bugs related to globs as PVLVs
738 {
739  no warnings qw 'once void';
740  my %h; # We pass a key of this hash to the subroutine to get a PVLV.
741  sub { for(shift) {
742   # Set up our glob-as-PVLV
743   $_ = *hon;
744
745   # Bad symbol for array
746   ok eval{ @$_; 1 }, 'PVLV glob slots can be autovivified' or diag $@;
747
748   # This should call TIEHANDLE, not TIESCALAR
749   *thext::TIEHANDLE = sub{};
750   ok eval{ tie *$_, 'thext'; 1 }, 'PVLV globs can be tied as handles'
751    or diag $@;
752
753   # Assigning undef to the glob should not overwrite it...
754   {
755    my $w;
756    local $SIG{__WARN__} = sub { $w = shift };
757    *$_ = undef;
758    is $_, "*main::hon", 'PVLV: assigning undef to the glob does nothing';
759    like $w, qr\Undefined value assigned to typeglob\,
760     'PVLV: assigning undef to the glob warns';
761   }
762
763   # Neither should reference assignment.
764   *$_ = [];
765   is $_, "*main::hon", "PVLV: arrayref assignment assigns to the AV slot";
766
767   # Concatenation should still work.
768   ok eval { $_ .= 'thlew' }, 'PVLV concatenation does not die' or diag $@;
769   is $_, '*main::honthlew', 'PVLV concatenation works';
770
771   # And we should be able to overwrite it with a string, number, or refer-
772   # ence, too, if we omit the *.
773   $_ = *hon; $_ = 'tzor';
774   is $_, 'tzor', 'PVLV: assigning a string over a glob';
775   $_ = *hon; $_ = 23;
776   is $_, 23, 'PVLV: assigning an integer over a glob';
777   $_ = *hon; $_ = 23.23;
778   is $_, 23.23, 'PVLV: assigning a float over a glob';
779   $_ = *hon; $_ = \my $sthat;
780   is $_, \$sthat, 'PVLV: assigning a reference over a glob';
781
782   # This bug was found by code inspection. Could this ever happen in
783   # real life? :-)
784   # This duplicates a file handle, accessing it through a PVLV glob, the
785   # glob having been removed from the symbol table, so a stringified form
786   # of it does not work. This checks that sv_2io does not stringify a PVLV.
787   $_ = *quin;
788   open *quin, "test.pl"; # test.pl is as good a file as any
789   delete $::{quin};
790   ok eval { open my $zow, "<&", $_ }, 'PVLV: sv_2io stringifieth not'
791    or diag $@;
792
793   # Similar tests to make sure sv_2cv etc. do not stringify.
794   *$_ = sub { 1 };
795   ok eval { &$_ }, "PVLV glob can be called as a sub" or diag $@;
796   *flelp = sub { 2 };
797   $_ = 'flelp';
798   is eval { &$_ }, 2, 'PVLV holding a string can be called as a sub'
799    or diag $@;
800
801   # Coderef-to-glob assignment when the glob is no longer accessible
802   # under its name: These tests are to make sure the OPpASSIGN_CV_TO_GV
803   # optimisation takes PVLVs into account, which is why the RHSs have to be
804   # named subs.
805   use constant gheen => 'quare';
806   $_ = *ming;
807   delete $::{ming};
808   *$_ = \&gheen;
809   is eval { &$_ }, 'quare',
810    'PVLV: constant assignment when the glob is detached from the symtab'
811     or diag $@;
812   $_ = *bength;
813   delete $::{bength};
814   *gheck = sub { 'lon' };
815   *$_ = \&gheck;
816   is eval { &$_ }, 'lon',
817    'PVLV: coderef assignment when the glob is detached from the symtab'
818     or diag $@;
819
820 SKIP: {
821     skip_if_miniperl("no dynamic loading on miniperl, so can't load PerlIO::scalar", 1);
822     # open should accept a PVLV as its first argument
823     $_ = *hon;
824     ok eval { open $_,'<', \my $thlext }, 'PVLV can be the first arg to open'
825         or diag $@;
826   }
827
828   # -t should not stringify
829   $_ = *thlit; delete $::{thlit};
830   *$_ = *STDOUT{IO};
831   ok defined -t $_, 'PVLV: -t does not stringify';
832
833   # neither should -T
834   # but some systems don’t support this on file handles
835   my $pass;
836   ok
837     eval {
838      open my $quile, "<", 'test.pl';
839      $_ = *$quile;
840      $pass = -T $_;
841      1
842     } ? $pass : $@ =~ /not implemented on filehandles/,
843    "PVLV: -T does not stringify";
844   
845   # Unopened file handle
846   {
847    my $w;
848    local $SIG{__WARN__} = sub { $w .= shift };
849    $_ = *vor;
850    close $_;
851    like $w, qr\unopened filehandle vor\,
852     'PVLV globs get their names reported in unopened error messages';
853   }
854
855  }}->($h{k});
856 }
857
858 *aieee = 4;
859 pass('Can assign integers to typeglobs');
860 *aieee = 3.14;
861 pass('Can assign floats to typeglobs');
862 *aieee = 'pi';
863 pass('Can assign strings to typeglobs');
864
865 {
866   package thrext;
867   sub TIESCALAR{bless[]}
868   sub STORE{ die "No!"}
869   sub FETCH{ no warnings 'once'; *thrit }
870   tie my $a, "thrext";
871   () = "$a"; # do a fetch; now $a holds a glob
872   eval { *$a = sub{} };
873   untie $a;
874   eval { $a = "bar" };
875   ::is $a, "bar",
876     "[perl #77812] Globs in tied scalars can be reified if STORE dies"
877 }
878
879 # These two crashed prior to 5.13.6. In 5.13.6 they were fatal errors. They
880 # were fixed in 5.13.7.
881 ok eval {
882   my $glob = \*heen::ISA;
883   delete $::{"heen::"};
884   *$glob = *bar; 
885 }, "glob-to-*ISA assignment works when *ISA has lost its stash";
886 ok eval {
887   my $glob = \*slare::ISA;
888   delete $::{"slare::"};
889   *$glob = []; 
890 }, "array-to-*ISA assignment works when *ISA has lost its stash";
891 # These two crashed in 5.13.6. They were likewise fixed in 5.13.7.
892 ok eval {
893   sub greck;
894   my $glob = do { no warnings "once"; \*phing::foo};
895   delete $::{"phing::"};
896   *$glob = *greck; 
897 }, "Assigning a glob-with-sub to a glob that has lost its stash works";
898 ok eval {
899   sub pon::foo;
900   my $glob = \*pon::foo;
901   delete $::{"pon::"};
902   *$glob = *foo; 
903 }, "Assigning a glob to a glob-with-sub that has lost its stash works";
904
905 {
906   package Tie::Alias;
907   sub TIESCALAR{ bless \\pop }
908   sub FETCH { $${$_[0]} }
909   sub STORE { $${$_[0]} = $_[1] }
910   package main;
911   tie my $alias, 'Tie::Alias', my $var;
912   no warnings 'once';
913   $var = *galobbe;
914   {
915     local *$alias = [];
916     $var = 3;
917     is $alias, 3, "[perl #77926] Glob reification during localisation";
918   }
919 }
920
921 # This code causes gp_free to call a destructor when a glob is being
922 # restored on scope exit. The destructor used to see SVs with a refcount of
923 # zero inside the glob, which could result in crashes (though not in this
924 # test case, which just panics).
925 {
926  no warnings 'once';
927  my $survived;
928  *Trit::DESTROY = sub {
929    $thwext = 42;  # panic
930    $survived = 1;
931  };
932  {
933   local *thwext;
934   $thwext = bless[],'Trit';
935   ();
936  }
937  ok $survived,
938   'no error when gp_free calls a destructor that assigns to the gv';
939 }
940
941 # This is a similar test, for destructors seeing a GV without a reference
942 # count on its gp.
943 sub undefine_me_if_you_dare {}
944 bless \&undefine_me_if_you_dare, "Undefiner";
945 sub Undefiner::DESTROY {
946     undef *undefine_me_if_you_dare;
947 }
948 {
949     my $w;
950     local $SIG{__WARN__} = sub { $w .= shift };
951     undef *undefine_me_if_you_dare;
952     is $w, undef,
953       'undeffing a gv in DESTROY triggered by undeffing the same gv'
954 }
955
956 # [perl #121242]
957 # More gp_free madness.  gp_free could call a destructor that frees the gv
958 # whose gp is being freed.
959 sub Fred::AUTOLOAD { $Fred::AUTOLOAD }
960 undef *{"Fred::AUTOLOAD"};
961 pass 'no crash from gp_free triggering gv_try_downgrade';
962 sub _121242::DESTROY { delete $_121242::{$_[0][0]} };
963 ${"_121242::foo"} = bless ["foo"], _121242::;
964 undef *{"_121242::foo"};
965 pass 'no crash from pp_undef/gp_free freeing the gv';
966 ${"_121242::bar"} = bless ["bar"], _121242::;
967 *{"_121242::bar"} = "bar";
968 pass 'no crash from sv_setsv/gp_free freeing the gv';
969 ${"_121242::baz"} = bless ["baz"], _121242::;
970 *{"_121242::baz"} = *foo;
971 pass 'no crash from glob_assign_glob/gp_free freeing the gv';
972 {
973     my $foo;
974     undef *_121242::DESTROY;
975     *_121242::DESTROY = sub { undef $foo };
976     my $set_up_foo = sub {
977         # Make $$foo into a fake glob whose array slot holds a blessed
978         # array that undefines $foo, freeing the fake glob.
979         $foo = undef;
980         $$foo = do {local *bar};
981         *$$foo = bless [], _121242::;
982     };
983     &$set_up_foo;
984     $$foo = 3;
985     pass 'no crash from sv_setsv/sv_unglob/gp_free freeing the gv';
986     &$set_up_foo;
987     utf8::encode $$foo;
988     pass 'no crash from sv_utf8_encode/sv_unglob/gp_free freeing the gv';
989     &$set_up_foo;
990     open BAR, "TEST";
991     $$foo .= <BAR>;
992     pass 'no crash from do_readline/sv_unglob/gp_free freeing the gv';
993     close BAR;
994     &$set_up_foo;
995     $$foo .= 3;
996     pass 'no crash from pp_concat/sv_unglob/gp_free freeing the gv';
997     &$set_up_foo;
998     no warnings;
999     $$foo++;
1000     pass 'no crash from sv_inc/sv_unglob/gp_free freeing the gv';
1001     &$set_up_foo;
1002     $$foo--;
1003     pass 'no crash from sv_dec/sv_unglob/gp_free freeing the gv';
1004     &$set_up_foo;
1005     undef $$foo;
1006     pass 'no crash from pp_undef/sv_unglob/gp_free freeing the gv';
1007     $foo = undef;
1008     $$foo = 3;
1009     $$foo =~ s/3/$$foo = do {local *bar}; *$$foo = bless [],_121242::; 4/e;
1010     pass 'no crash from pp_substcont/sv_unglob/gp_free freeing the gv';
1011 }
1012
1013 # *{undef}
1014 eval { *{my $undef} = 3 };
1015 like $@, qr/^Can't use an undefined value as a symbol reference at /,
1016   '*{ $undef } assignment';
1017 eval { *{;undef} = 3 };
1018 like $@, qr/^Can't use an undefined value as a symbol reference at /,
1019   '*{ ;undef } assignment';
1020
1021 # [perl #99142] defined &{"foo"} when there is a constant stub
1022 # If I break your module, you get to have it mentioned in Perl's tests. :-)
1023 package HTTP::MobileAttribute::Plugin::Locator {
1024     use constant LOCATOR_GPS => 1;
1025     ::ok defined &{__PACKAGE__."::LOCATOR_GPS"},
1026         'defined &{"name of constant"}';
1027     ::ok Internals::SvREFCNT(${__PACKAGE__."::"}{LOCATOR_GPS}),
1028        "stash elem for slot is not freed prematurely";
1029 }
1030
1031 # Check that constants promoted to CVs point to the right GVs when the name
1032 # contains a null.
1033 package lrcg {
1034   use constant x => 3;
1035   # These two lines abuse the optimisation that copies the scalar ref from
1036   # one stash element to another, to get a constant with a null in its name
1037   *{"yz\0a"} = \&{"x"};
1038   my $ref = \&{"yz\0a"};
1039   ::ok !exists $lrcg::{yz},
1040     'constants w/nulls in their names point 2 the right GVs when promoted';
1041 }
1042
1043 {
1044   no warnings 'io';
1045   stat *{"try_downgrade"};
1046   -T _;
1047   $bang = $!;
1048   eval "*try_downgrade if 0";
1049   -T _;
1050   is "$!",$bang,
1051      'try_downgrade does not touch PL_statgv (last stat handle)';
1052   readline *{"try_downgrade2"};
1053   my $lastfh = "${^LAST_FH}";
1054   eval "*try_downgrade2 if 0";
1055   is ${^LAST_FH}, $lastfh, 'try_downgrade does not touch PL_last_in_gv';
1056 }
1057
1058 is runperl(prog => '$s = STDERR; close $s; undef *$s;'
1059                   .'eval q-*STDERR if 0-; *$s = *STDOUT{IO}; warn'),
1060   "Warning: something's wrong at -e line 1.\n",
1061   "try_downgrade does not touch PL_stderrgv";
1062
1063 is runperl(prog =>
1064              'use constant foo=>1; BEGIN { $x = \&foo } undef &$x; $x->()',
1065            stderr=>1),
1066   "Undefined subroutine &main::foo called at -e line 1.\n",
1067   "gv_try_downgrade does not anonymise CVs referenced elsewhere";
1068
1069 SKIP: {
1070     skip_if_miniperl("no dynamic loading on miniperl, so can't load IO::File", 4);
1071
1072 package glob_constant_test {
1073   sub foo { 42 }
1074   use constant bar => *foo;
1075   BEGIN { undef *foo }
1076   ::is eval { bar->() }, eval { &{+bar} },
1077     'glob_constant->() is not mangled at compile time';
1078   ::is "$@", "", 'no error from eval { &{+glob_constant} }';
1079   use constant quux => do {
1080     local *F;
1081     my $f = *F;
1082     *$f = *STDOUT{IO};
1083   };
1084   ::is eval { quux->autoflush; 420 }, 420,
1085     'glob_constant->method() works';
1086   ::is "$@", "", 'no error from eval { glob_constant->method() }';
1087 }
1088
1089 }
1090
1091 {
1092   my $free2;
1093   local $SIG{__WARN__} = sub { ++$free2 if shift =~ /Attempt to free/ };
1094   my $handleref;
1095   my $proxy = \$handleref;
1096   open $$proxy, "TEST";
1097   delete $::{*$handleref{NAME}};  # delete *main::_GEN_xxx
1098   undef $handleref;
1099   is $free2, undef,
1100     'no double free because of bad rv2gv/newGVgen refcounting';
1101 }
1102
1103 # Look away, please.
1104 # This violates perl's internal structures by fiddling with stashes in a
1105 # way that should never happen, but perl should not start trying to free
1106 # unallocated memory as a result.  There is no ok() or is() because the
1107 # panic that used to occur only occurred during global destruction, and
1108 # only with PERL_DESTRUCT_LEVEL=2.  (The panic itself was sufficient for
1109 # the harness to consider this test script to have failed.)
1110 $::{aoeuaoeuaoeaoeu} = __PACKAGE__; # cow
1111 () = *{"aoeuaoeuaoeaoeu"};
1112
1113 $x = *_119051;
1114 $y = \&$x;
1115 undef $x;
1116 eval { &$y };
1117 pass "No crash due to CvGV(vivified stub) pointing to flattened glob copy";
1118 # Not really supported, but this should not crash either:
1119 $x = *_119051again;
1120 delete $::{_119051again};
1121 $::{_119051again} = $x;    # now we have a fake glob under the right name
1122 $y = \&$x;                 # so when this tries to look up the right GV for
1123 undef $::{_119051again};   # CvGV, it still gets a fake one
1124 eval { $y->() };
1125 pass "No crash due to CvGV pointing to glob copy in the stash";
1126
1127 # Aliasing should disable no-common-vars optimisation.
1128 {
1129     *x = *y;
1130     $x = 3;
1131     ($x, my $z) = (1, $y);
1132     is $z, 3, 'list assignment after aliasing [perl #89646]';
1133 }
1134
1135
1136 __END__
1137 Perl
1138 Rules
1139 perl
1140 rocks