This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
skip trying to constant fold an incomplete op tree
[perl5.git] / t / op / ref.t
1 #!./perl
2
3 BEGIN {
4     chdir 't' if -d 't';
5     require './test.pl';
6     set_up_inc( qw(. ../lib) );
7 }
8
9 use strict qw(refs subs);
10
11 plan(254);
12
13 # Test this first before we extend the stack with other operations.
14 # This caused an asan failure due to a bad write past the end of the stack.
15 eval { die  1..127, $_=\() };
16
17 # Test glob operations.
18
19 $bar = "one";
20 $foo = "two";
21 {
22     local(*foo) = *bar;
23     is($foo, 'one');
24 }
25 is ($foo, 'two');
26
27 $baz = "three";
28 $foo = "four";
29 {
30     local(*foo) = 'baz';
31     is ($foo, 'three');
32 }
33 is ($foo, 'four');
34
35 $foo = "global";
36 {
37     local(*foo);
38     is ($foo, undef);
39     $foo = "local";
40     is ($foo, 'local');
41 }
42 is ($foo, 'global');
43
44 {
45     no strict 'refs';
46 # Test fake references.
47
48     $baz = "valid";
49     $bar = 'baz';
50     $foo = 'bar';
51     is ($$$foo, 'valid');
52 }
53
54 # Test real references.
55
56 $FOO = \$BAR;
57 $BAR = \$BAZ;
58 $BAZ = "hit";
59 is ($$$FOO, 'hit');
60
61 # Test references to real arrays.
62
63 my $test = curr_test();
64 @ary = ($test,$test+1,$test+2,$test+3);
65 $ref[0] = \@a;
66 $ref[1] = \@b;
67 $ref[2] = \@c;
68 $ref[3] = \@d;
69 for $i (3,1,2,0) {
70     push(@{$ref[$i]}, "ok $ary[$i]\n");
71 }
72 print @a;
73 print ${$ref[1]}[0];
74 print @{$ref[2]}[0];
75 {
76     no strict 'refs';
77     print @{'d'};
78 }
79 curr_test($test+4);
80
81 # Test references to references.
82
83 $refref = \\$x;
84 $x = "Good";
85 is ($$$refref, 'Good');
86
87 # Test nested anonymous arrays.
88
89 $ref = [[],2,[3,4,5,]];
90 is (scalar @$ref, 3);
91 is ($$ref[1], 2);
92 is (${$$ref[2]}[2], 5);
93 is (scalar @{$$ref[0]}, 0);
94
95 is ($ref->[1], 2);
96 is ($ref->[2]->[0], 3);
97
98 # Test references to hashes of references.
99
100 $refref = \%whatever;
101 $refref->{"key"} = $ref;
102 is ($refref->{"key"}->[2]->[0], 3);
103
104 # Test to see if anonymous subarrays spring into existence.
105
106 $spring[5]->[0] = 123;
107 $spring[5]->[1] = 456;
108 push(@{$spring[5]}, 789);
109 is (join(':',@{$spring[5]}), "123:456:789");
110
111 # Test to see if anonymous subhashes spring into existence.
112
113 @{$spring2{"foo"}} = (1,2,3);
114 $spring2{"foo"}->[3] = 4;
115 is (join(':',@{$spring2{"foo"}}), "1:2:3:4");
116
117 # Test references to subroutines.
118
119 {
120     my $called;
121     sub mysub { $called++; }
122     $subref = \&mysub;
123     &$subref;
124     is ($called, 1);
125 }
126 is ref eval {\&{""}}, "CODE", 'reference to &{""} [perl #94476]';
127 delete $My::{"Foo::"}; 
128 is ref \&My::Foo::foo, "CODE",
129   'creating stub with \&deleted_stash::foo [perl #128532]';
130
131
132 # Test references to return values of operators (TARGs/PADTMPs)
133 {
134     my @refs;
135     for("a", "b") {
136         push @refs, \"$_"
137     }
138     is join(" ", map $$_, @refs), "a b", 'refgen+PADTMP';
139 }
140
141 $subrefref = \\&mysub2;
142 is ($$subrefref->("GOOD"), "good");
143 sub mysub2 { lc shift }
144
145 # Test REGEXP assignment
146
147 SKIP: {
148     skip_if_miniperl("no dynamic loading on miniperl, so can't load re", 5);
149     require re;
150     my $x = qr/x/;
151     my $str = "$x"; # regex stringification may change
152
153     my $y = $$x;
154     is ($y, $str, "bare REGEXP stringifies correctly");
155     ok (eval { "x" =~ $y }, "bare REGEXP matches correctly");
156     
157     my $z = \$y;
158     ok (re::is_regexp($z), "new ref to REXEXP passes is_regexp");
159     is ($z, $str, "new ref to REGEXP stringifies correctly");
160     ok (eval { "x" =~ $z }, "new ref to REGEXP matches correctly");
161 }
162 {
163     my ($x, $str);
164     {
165         my $y = qr/x/;
166         $str = "$y";
167         $x = $$y;
168     }
169     is ($x, $str, "REGEXP keeps a ref to its mother_re");
170     ok (eval { "x" =~ $x }, "REGEXP with mother_re still matches");
171 }
172
173 # test dereferencing errors
174 {
175     format STDERR =
176 .
177     my $ref;
178     foreach $ref (*STDOUT{IO}, *STDERR{FORMAT}) {
179         eval q/ $$ref /;
180         like($@, qr/Not a SCALAR reference/, "Scalar dereference");
181         eval q/ @$ref /;
182         like($@, qr/Not an ARRAY reference/, "Array dereference");
183         eval q/ %$ref /;
184         like($@, qr/Not a HASH reference/, "Hash dereference");
185         eval q/ &$ref /;
186         like($@, qr/Not a CODE reference/, "Code dereference");
187     }
188
189     $ref = *STDERR{FORMAT};
190     eval q/ *$ref /;
191     like($@, qr/Not a GLOB reference/, "Glob dereference");
192
193     $ref = *STDOUT{IO};
194     eval q/ *$ref /;
195     is($@, '', "Glob dereference of PVIO is acceptable");
196
197     is($ref, *{$ref}{IO}, "IO slot of the temporary glob is set correctly");
198 }
199
200 # Test the ref operator.
201
202 sub PVBM () { 'foo' }
203 { my $dummy = index 'foo', PVBM }
204
205 my $pviv = 1; "$pviv";
206 my $pvnv = 1.0; "$pvnv";
207 my $x;
208
209 # we don't test
210 #   tied lvalue => SCALAR, as we haven't tested tie yet
211 #   BIND, 'cos we can't create them yet
212 #   REGEXP, 'cos that requires overload or Scalar::Util
213
214 for (
215     [ 'undef',          SCALAR  => \undef               ],
216     [ 'constant IV',    SCALAR  => \1                   ],
217     [ 'constant NV',    SCALAR  => \1.0                 ],
218     [ 'constant PV',    SCALAR  => \'f'                 ],
219     [ 'scalar',         SCALAR  => \$x                  ],
220     [ 'PVIV',           SCALAR  => \$pviv               ],
221     [ 'PVNV',           SCALAR  => \$pvnv               ],
222     [ 'PVMG',           SCALAR  => \$0                  ],
223     [ 'PVBM',           SCALAR  => \PVBM                ],
224     [ 'scalar @array',  SCALAR  => \scalar @array       ],
225     [ 'scalar %hash',   SCALAR  => \scalar %hash        ],
226     [ 'vstring',        VSTRING => \v1                  ],
227     [ 'ref',            REF     => \\1                  ],
228     [ 'substr lvalue',  LVALUE  => \substr($x, 0, 0)    ],
229     [ 'pos lvalue',     LVALUE  => \pos                 ],
230     [ 'vec lvalue',     LVALUE  => \vec($x,0,1)         ],     
231     [ 'named array',    ARRAY   => \@ary                ],
232     [ 'anon array',     ARRAY   => [ 1 ]                ],
233     [ 'named hash',     HASH    => \%whatever           ],
234     [ 'anon hash',      HASH    => { a => 1 }           ],
235     [ 'named sub',      CODE    => \&mysub,             ],
236     [ 'anon sub',       CODE    => sub { 1; }           ],
237     [ 'glob',           GLOB    => \*foo                ],
238     [ 'format',         FORMAT  => *STDERR{FORMAT}      ],
239 ) {
240     my ($desc, $type, $ref) = @$_;
241     is (ref $ref, $type, "ref() for ref to $desc");
242     like ("$ref", qr/^$type\(0x[0-9a-f]+\)$/, "stringify for ref to $desc");
243 }
244
245 is (ref *STDOUT{IO}, 'IO::File', 'IO refs are blessed into IO::File');
246 like (*STDOUT{IO}, qr/^IO::File=IO\(0x[0-9a-f]+\)$/,
247     'stringify for IO refs');
248
249 { # Test re-use of ref's TARG [perl #101738]
250   my $obj = bless [], '____';
251   my $uniobj = bless [], chr 256;
252   my $get_ref = sub { ref shift };
253   my $dummy = &$get_ref($uniobj);
254      $dummy = &$get_ref($obj);
255   ok exists { ____ => undef }->{$dummy}, 'ref sets UTF8 flag correctly';
256 }
257
258 # Test anonymous hash syntax.
259
260 $anonhash = {};
261 is (ref $anonhash, 'HASH');
262 $anonhash2 = {FOO => 'BAR', ABC => 'XYZ',};
263 is (join('', sort values %$anonhash2), 'BARXYZ');
264
265 # Test bless operator.
266
267 package MYHASH;
268
269 $object = bless $main'anonhash2;
270 main::is (ref $object, 'MYHASH');
271 main::is ($object->{ABC}, 'XYZ');
272
273 $object2 = bless {};
274 main::is (ref $object2, 'MYHASH');
275
276 # Test ordinary call on object method.
277
278 &mymethod($object,"argument");
279
280 sub mymethod {
281     local($THIS, @ARGS) = @_;
282     die 'Got a "' . ref($THIS). '" instead of a MYHASH'
283         unless ref $THIS eq 'MYHASH';
284     main::is ($ARGS[0], "argument");
285     main::is ($THIS->{FOO}, 'BAR');
286 }
287
288 # Test automatic destructor call.
289
290 $string = "bad";
291 $object = "foo";
292 $string = "good";
293 $main'anonhash2 = "foo";
294 $string = "";
295
296 DESTROY {
297     return unless $string;
298     main::is ($string, 'good');
299
300     # Test that the object has not already been "cursed".
301     main::isnt (ref shift, 'HASH');
302 }
303
304 # Now test inheritance of methods.
305
306 package OBJ;
307
308 @ISA = ('BASEOBJ');
309
310 $main'object = bless {FOO => 'foo', BAR => 'bar'};
311
312 package main;
313
314 # Test arrow-style method invocation.
315
316 is ($object->doit("BAR"), 'bar');
317
318 # Test indirect-object-style method invocation.
319
320 $foo = doit $object "FOO";
321 main::is ($foo, 'foo');
322
323 sub BASEOBJ'doit {
324     local $ref = shift;
325     die "Not an OBJ" unless ref $ref eq 'OBJ';
326     $ref->{shift()};
327 }
328
329 package UNIVERSAL;
330 @ISA = 'LASTCHANCE';
331
332 package LASTCHANCE;
333 sub foo { main::is ($_[1], 'works') }
334
335 package WHATEVER;
336 foo WHATEVER "works";
337
338 #
339 # test the \(@foo) construct
340 #
341 package main;
342 @foo = \(1..3);
343 @bar = \(@foo);
344 @baz = \(1,@foo,@bar);
345 is (scalar (@bar), 3);
346 is (scalar grep(ref($_), @bar), 3);
347 is (scalar (@baz), 3);
348
349 my(@fuu) = \(1..2,3);
350 my(@baa) = \(@fuu);
351 my(@bzz) = \(1,@fuu,@baa);
352 is (scalar (@baa), 3);
353 is (scalar grep(ref($_), @baa), 3);
354 is (scalar (@bzz), 3);
355
356 # also, it can't be an lvalue
357 # (That’s what *you* think!  --sprout)
358 eval '\\($x, $y) = (1, 2);';
359 like ($@, qr/Can\'t modify.*ref.*in.*assignment(?x:
360            )|Experimental aliasing via reference not enabled/);
361
362 # test for proper destruction of lexical objects
363 $test = curr_test();
364 sub larry::DESTROY { print "# larry\nok $test\n"; }
365 sub curly::DESTROY { print "# curly\nok ", $test + 1, "\n"; }
366 sub moe::DESTROY   { print "# moe\nok ", $test + 2, "\n"; }
367
368 {
369     my ($joe, @curly, %larry);
370     my $moe = bless \$joe, 'moe';
371     my $curly = bless \@curly, 'curly';
372     my $larry = bless \%larry, 'larry';
373     print "# leaving block\n";
374 }
375
376 print "# left block\n";
377 curr_test($test + 3);
378
379 # another glob test
380
381
382 $foo = "garbage";
383 { local(*bar) = "foo" }
384 $bar = "glob 3";
385 local(*bar) = *bar;
386 is ($bar, "glob 3");
387
388 $var = "glob 4";
389 $_   = \$var;
390 is ($$_, 'glob 4');
391
392
393 # test if reblessing during destruction results in more destruction
394 $test = curr_test();
395 {
396     package A;
397     sub new { bless {}, shift }
398     DESTROY { print "# destroying 'A'\nok ", $test + 1, "\n" }
399     package _B;
400     sub new { bless {}, shift }
401     DESTROY { print "# destroying '_B'\nok $test\n"; bless shift, 'A' }
402     package main;
403     my $b = _B->new;
404 }
405 curr_test($test + 2);
406
407 # test if $_[0] is properly protected in DESTROY()
408
409 {
410     my $test = curr_test();
411     my $i = 0;
412     local $SIG{'__DIE__'} = sub {
413         my $m = shift;
414         if ($i++ > 4) {
415             print "# infinite recursion, bailing\nnot ok $test\n";
416             exit 1;
417         }
418         like ($m, qr/^Modification of a read-only/);
419     };
420     package C;
421     sub new { bless {}, shift }
422     DESTROY { $_[0] = 'foo' }
423     {
424         print "# should generate an error...\n";
425         my $c = C->new;
426     }
427     print "# good, didn't recurse\n";
428 }
429
430 # test that DESTROY is called on all objects during global destruction,
431 # even those without hard references [perl #36347]
432
433 is(
434   runperl(
435    stderr => 1, prog => 'sub DESTROY { print qq-aaa\n- } bless \$a[0]'
436   ),
437  "aaa\n", 'DESTROY called on array elem'
438 );
439 is(
440   runperl(
441    stderr => 1,
442    prog => '{ bless \my@x; *a=sub{@x}}sub DESTROY { print qq-aaa\n- }'
443   ),
444  "aaa\n",
445  'DESTROY called on closure variable'
446 );
447
448 # But cursing objects must not result in double frees
449 # This caused "Attempt to free unreferenced scalar" in 5.16.
450 fresh_perl_is(
451   'bless \%foo::, bar::; bless \%bar::, foo::; print "ok\n"', "ok\n",
452    { stderr => 1 },
453   'no double free when stashes are blessed into each other');
454
455
456 # test if refgen behaves with autoviv magic
457 {
458     my @a;
459     $a[1] = "good";
460     my $got;
461     for (@a) {
462         $got .= ${\$_};
463         $got .= ';';
464     }
465     is ($got, ";good;");
466 }
467
468 # This test is the reason for postponed destruction in sv_unref
469 $a = [1,2,3];
470 $a = $a->[1];
471 is ($a, 2);
472
473 # This test used to coredump. The BEGIN block is important as it causes the
474 # op that created the constant reference to be freed. Hence the only
475 # reference to the constant string "pass" is in $a. The hack that made
476 # sure $a = $a->[1] would work didn't work with references to constants.
477
478
479 foreach my $lexical ('', 'my $a; ') {
480   my $expect = "pass\n";
481   my $result = runperl (switches => ['-wl'], stderr => 1,
482     prog => $lexical . 'BEGIN {$a = \q{pass}}; $a = $$a; print $a');
483
484   is ($?, 0);
485   is ($result, $expect);
486 }
487
488 $test = curr_test();
489 sub x::DESTROY {print "ok ", $test + shift->[0], "\n"}
490 { my $a1 = bless [3],"x";
491   my $a2 = bless [2],"x";
492   { my $a3 = bless [1],"x";
493     my $a4 = bless [0],"x";
494     567;
495   }
496 }
497 curr_test($test+4);
498
499 is (runperl (switches=>['-l'],
500              prog=> 'print 1; print qq-*$\*-;print 1;'),
501     "1\n*\n*\n1\n");
502
503 # bug #21347
504
505 runperl(prog => 'sub UNIVERSAL::AUTOLOAD { qr// } a->p' );
506 is ($?, 0, 'UNIVERSAL::AUTOLOAD called when freeing qr//');
507
508 runperl(prog => 'sub UNIVERSAL::DESTROY { warn } bless \$a, A', stderr => 1);
509 is ($?, 0, 'warn called inside UNIVERSAL::DESTROY');
510
511
512 # bug #22719
513
514 runperl(prog => 'sub f { my $x = shift; *z = $x; } f({}); f();');
515 is ($?, 0, 'coredump on typeglob = (SvRV && !SvROK)');
516
517 # bug #27268: freeing self-referential typeglobs could trigger
518 # "Attempt to free unreferenced scalar" warnings
519
520 is (runperl(
521     prog => 'use Symbol;my $x=bless \gensym,q{t}; print;*$$x=$x',
522     stderr => 1
523 ), '', 'freeing self-referential typeglob');
524
525 # using a regex in the destructor for STDOUT segfaulted because the
526 # REGEX pad had already been freed (ithreads build only). The
527 # object is required to trigger the early freeing of GV refs to STDOUT
528
529 TODO: {
530     local $TODO = "works but output through pipe is mangled" if $^O eq 'VMS';
531     like (runperl(
532         prog => '$x=bless[]; sub IO::Handle::DESTROY{$_=q{bad};s/bad/ok/;print}',
533         stderr => 1
534           ), qr/^(ok)+$/, 'STDOUT destructor');
535 }
536
537 {
538     no strict 'refs';
539     $name8 = chr 163;
540     $name_utf8 = $name8 . chr 256;
541     chop $name_utf8;
542
543     is ($$name8, undef, 'Nothing before we start');
544     is ($$name_utf8, undef, 'Nothing before we start');
545     $$name8 = "Pound";
546     is ($$name8, "Pound", 'Accessing via 8 bit symref works');
547     is ($$name_utf8, "Pound", 'Accessing via UTF8 symref works');
548 }
549
550 {
551     no strict 'refs';
552     $name_utf8 = $name = chr 9787;
553     utf8::encode $name_utf8;
554
555     is (length $name, 1, "Name is 1 char");
556     is (length $name_utf8, 3, "UTF8 representation is 3 chars");
557
558     is ($$name, undef, 'Nothing before we start');
559     is ($$name_utf8, undef, 'Nothing before we start');
560     $$name = "Face";
561     is ($$name, "Face", 'Accessing via Unicode symref works');
562     is ($$name_utf8, undef,
563         'Accessing via the UTF8 byte sequence gives nothing');
564 }
565
566 {
567     no strict 'refs';
568     $name1 = "\0Chalk";
569     $name2 = "\0Cheese";
570
571     isnt ($name1, $name2, "They differ");
572
573     is ($$name1, undef, 'Nothing before we start (scalars)');
574     is ($$name2, undef, 'Nothing before we start');
575     $$name1 = "Yummy";
576     is ($$name1, "Yummy", 'Accessing via the correct name works');
577     is ($$name2, undef,
578         'Accessing via a different NUL-containing name gives nothing');
579     # defined uses a different code path
580     ok (defined $$name1, 'defined via the correct name works');
581     ok (!defined $$name2,
582         'defined via a different NUL-containing name gives nothing');
583
584     is ($name1->[0], undef, 'Nothing before we start (arrays)');
585     is ($name2->[0], undef, 'Nothing before we start');
586     $name1->[0] = "Yummy";
587     is ($name1->[0], "Yummy", 'Accessing via the correct name works');
588     is ($name2->[0], undef,
589         'Accessing via a different NUL-containing name gives nothing');
590     ok (defined $name1->[0], 'defined via the correct name works');
591     ok (!defined$name2->[0],
592         'defined via a different NUL-containing name gives nothing');
593
594     my (undef, $one) = @{$name1}[2,3];
595     my (undef, $two) = @{$name2}[2,3];
596     is ($one, undef, 'Nothing before we start (array slices)');
597     is ($two, undef, 'Nothing before we start');
598     @{$name1}[2,3] = ("Very", "Yummy");
599     (undef, $one) = @{$name1}[2,3];
600     (undef, $two) = @{$name2}[2,3];
601     is ($one, "Yummy", 'Accessing via the correct name works');
602     is ($two, undef,
603         'Accessing via a different NUL-containing name gives nothing');
604     ok (defined $one, 'defined via the correct name works');
605     ok (!defined $two,
606         'defined via a different NUL-containing name gives nothing');
607
608     is ($name1->{PWOF}, undef, 'Nothing before we start (hashes)');
609     is ($name2->{PWOF}, undef, 'Nothing before we start');
610     $name1->{PWOF} = "Yummy";
611     is ($name1->{PWOF}, "Yummy", 'Accessing via the correct name works');
612     is ($name2->{PWOF}, undef,
613         'Accessing via a different NUL-containing name gives nothing');
614     ok (defined $name1->{PWOF}, 'defined via the correct name works');
615     ok (!defined $name2->{PWOF},
616         'defined via a different NUL-containing name gives nothing');
617
618     my (undef, $one) = @{$name1}{'SNIF', 'BEEYOOP'};
619     my (undef, $two) = @{$name2}{'SNIF', 'BEEYOOP'};
620     is ($one, undef, 'Nothing before we start (hash slices)');
621     is ($two, undef, 'Nothing before we start');
622     @{$name1}{'SNIF', 'BEEYOOP'} = ("Very", "Yummy");
623     (undef, $one) = @{$name1}{'SNIF', 'BEEYOOP'};
624     (undef, $two) = @{$name2}{'SNIF', 'BEEYOOP'};
625     is ($one, "Yummy", 'Accessing via the correct name works');
626     is ($two, undef,
627         'Accessing via a different NUL-containing name gives nothing');
628     ok (defined $one, 'defined via the correct name works');
629     ok (!defined $two,
630         'defined via a different NUL-containing name gives nothing');
631
632     $name1 = "Left"; $name2 = "Left\0Right";
633     my $glob2 = *{$name2};
634
635     is ($glob1, undef, "We get different typeglobs. In fact, undef");
636
637     *{$name1} = sub {"One"};
638     *{$name2} = sub {"Two"};
639
640     is (&{$name1}, "One");
641     is (&{$name2}, "Two");
642 }
643
644 # test derefs after list slice
645
646 is ( ({foo => "bar"})[0]{foo}, "bar", 'hash deref from list slice w/o ->' );
647 is ( ({foo => "bar"})[0]->{foo}, "bar", 'hash deref from list slice w/ ->' );
648 is ( ([qw/foo bar/])[0][1], "bar", 'array deref from list slice w/o ->' );
649 is ( ([qw/foo bar/])[0]->[1], "bar", 'array deref from list slice w/ ->' );
650 is ( (sub {"bar"})[0](), "bar", 'code deref from list slice w/o ->' );
651 is ( (sub {"bar"})[0]->(), "bar", 'code deref from list slice w/ ->' );
652
653 # deref on empty list shouldn't autovivify
654 {
655     local $@;
656     eval { ()[0]{foo} };
657     like ( "$@", qr/Can't use an undefined value as a HASH reference/,
658            "deref of undef from list slice fails" );
659 }
660
661 # these will segfault if they fail
662
663 my $pvbm = PVBM;
664 my $rpvbm = \$pvbm;
665
666 ok (!eval { *$rpvbm }, 'PVBM ref is not a GLOB ref');
667 ok (!eval { *$pvbm }, 'PVBM is not a GLOB ref');
668 ok (!eval { $$pvbm }, 'PVBM is not a SCALAR ref');
669 ok (!eval { @$pvbm }, 'PVBM is not an ARRAY ref');
670 ok (!eval { %$pvbm }, 'PVBM is not a HASH ref');
671 ok (!eval { $pvbm->() }, 'PVBM is not a CODE ref');
672 ok (!eval { $rpvbm->foo }, 'PVBM is not an object');
673
674 # bug 24254
675 is( runperl(stderr => 1, prog => 'map eval qq(exit),1 for 1'), "");
676 is( runperl(stderr => 1, prog => 'eval { for (1) { map { die } 2 } };'), "");
677 is( runperl(stderr => 1, prog => 'for (125) { map { exit } (213)}'), "");
678 my $hushed = $^O eq 'VMS' ? 'use vmsish qw(hushed);' : '';
679 is( runperl(stderr => 1, prog => $hushed . 'map die,4 for 3'), "Died at -e line 1.\n");
680 is( runperl(stderr => 1, prog => $hushed . 'grep die,4 for 3'), "Died at -e line 1.\n");
681 is( runperl(stderr => 1, prog => $hushed . 'for $a (3) {@b=sort {die} 4,5}'), "Died at -e line 1.\n");
682
683 # bug 57564
684 is( runperl(stderr => 1, prog => 'my $i;for $i (1) { for $i (2) { } }'), "");
685
686 # The mechanism for freeing objects in globs used to leave dangling
687 # pointers to freed SVs. To test this, we construct this nested structure:
688 #    GV => blessed(AV) => RV => GV => blessed(SV)
689 # all with a refcnt of 1, and hope that the second GV gets processed first
690 # by do_clean_named_objs.  Then when the first GV is processed, it mustn't
691 # find anything nasty left by the previous GV processing.
692 # The eval is stop things in the main body of the code holding a reference
693 # to a GV, and the print at the end seems to bee necessary to ensure
694 # the correct freeing order of *x and *y (no, I don't know why - DAPM).
695
696 is (runperl(
697         prog => 'eval q[bless \@y; bless \$x; $y[0] = \*x; $z = \*y; ]; '
698                 . 'delete $::{x}; delete $::{y}; print qq{ok\n};',
699         stderr => 1),
700     "ok\n", 'freeing freed glob in global destruction');
701
702
703 # Test undefined hash references as arguments to %{} in boolean context
704 # [perl #81750]
705 {
706  no strict 'refs';
707  eval { my $foo; %$foo;             }; ok !$@, '%$undef';
708  eval { my $foo; scalar %$foo;      }; ok !$@, 'scalar %$undef';
709  eval { my $foo; !%$foo;            }; ok !$@, '!%$undef';
710  eval { my $foo; if ( %$foo) {}     }; ok !$@, 'if ( %$undef) {}';
711  eval { my $foo; if (!%$foo) {}     }; ok !$@, 'if (!%$undef) {}';
712  eval { my $foo; unless ( %$foo) {} }; ok !$@, 'unless ( %$undef) {}';
713  eval { my $foo; unless (!%$foo) {} }; ok !$@, 'unless (!%$undef) {}';
714  eval { my $foo; 1 if %$foo;        }; ok !$@, '1 if %$undef';
715  eval { my $foo; 1 if !%$foo;       }; ok !$@, '1 if !%$undef';
716  eval { my $foo; 1 unless %$foo;    }; ok !$@, '1 unless %$undef;';
717  eval { my $foo; 1 unless ! %$foo;  }; ok !$@, '1 unless ! %$undef';
718  eval { my $foo;  %$foo ? 1 : 0;    }; ok !$@, ' %$undef ? 1 : 0';
719  eval { my $foo; !%$foo ? 1 : 0;    }; ok !$@, '!%$undef ? 1 : 0';
720 }
721
722 # RT #88330
723 # Make sure that a leaked thinggy with multiple weak references to
724 # it doesn't trigger a panic with multiple rounds of global cleanup
725 # (Perl_sv_clean_all).
726
727 SKIP: {
728     skip_if_miniperl('no Scalar::Util under miniperl', 4);
729
730     local $ENV{PERL_DESTRUCT_LEVEL} = 2;
731
732     # we do all permutations of array/hash, 1ref/2ref, to account
733     # for the different way backref magic is stored
734
735     fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'array with 1 weak ref');
736 use Scalar::Util qw(weaken);
737 my $r = [];
738 Internals::SvREFCNT(@$r, 9);
739 my $r1 = $r;
740 weaken($r1);
741 print "ok";
742 EOF
743
744     fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'array with 2 weak refs');
745 use Scalar::Util qw(weaken);
746 my $r = [];
747 Internals::SvREFCNT(@$r, 9);
748 my $r1 = $r;
749 weaken($r1);
750 my $r2 = $r;
751 weaken($r2);
752 print "ok";
753 EOF
754
755     fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'hash with 1 weak ref');
756 use Scalar::Util qw(weaken);
757 my $r = {};
758 Internals::SvREFCNT(%$r, 9);
759 my $r1 = $r;
760 weaken($r1);
761 print "ok";
762 EOF
763
764     fresh_perl_is(<<'EOF', 'ok', { stderr => 1 }, 'hash with 2 weak refs');
765 use Scalar::Util qw(weaken);
766 my $r = {};
767 Internals::SvREFCNT(%$r, 9);
768 my $r1 = $r;
769 weaken($r1);
770 my $r2 = $r;
771 weaken($r2);
772 print "ok";
773 EOF
774
775 }
776
777 SKIP:{
778     skip_if_miniperl "no Scalar::Util on miniperl", 1;
779     my $error;
780     *hassgropper::DESTROY = sub {
781         require Scalar::Util;
782         eval { Scalar::Util::weaken($_[0]) };
783         $error = $@;
784         # This line caused a crash before weaken refused to weaken a
785         # read-only reference:
786         $do::not::overwrite::this = $_[0];
787     };
788     my $xs = bless [], "hassgropper";
789     undef $xs;
790     like $error, qr/^Modification of a read-only/,
791        'weaken refuses to weaken a read-only ref';
792     # Now that the test has passed, avoid sabotaging global destruction:
793     undef *hassgropper::DESTROY;
794     undef $do::not::overwrite::this;
795 }
796
797
798 is ref( bless {}, "nul\0clean" ), "nul\0clean", "ref() is nul-clean";
799
800 # Test constants and references thereto.
801 for (3) {
802     eval { $_ = 4 };
803     like $@, qr/^Modification of a read-only/,
804        'assignment to value aliased to literal number';
805     eval { ${\$_} = 4 };
806     like $@, qr/^Modification of a read-only/,
807        'refgen does not allow assignment to value aliased to literal number';
808 }
809 for ("4eounthouonth") {
810     eval { $_ = 4 };
811     like $@, qr/^Modification of a read-only/,
812        'assignment to value aliased to literal string';
813     eval { ${\$_} = 4 };
814     like $@, qr/^Modification of a read-only/,
815        'refgen does not allow assignment to value aliased to literal string';
816 }
817 {
818     my $aref = \123;
819     is \$$aref, $aref,
820         '[perl #109746] referential identity of \literal under threads+mad'
821 }
822
823 # ref in boolean context
824 {
825     my $false = 0;
826     my $true  = 1;
827     my $plain = [];
828     my $obj     = bless {}, "Foo";
829     my $objnull = bless [], "";
830     my $obj0    = bless [], "0";
831     my $obj00   = bless [], "00";
832     my $obj1    = bless [], "1";
833
834     is !ref $false,   1, '!ref $false';
835     is !ref $true,    1, '!ref $true';
836     is !ref $plain,   "", '!ref $plain';
837     is !ref $obj,     "", '!ref $obj';
838     is !ref $objnull, "", '!ref $objnull';
839     is !ref $obj0   , 1, '!ref $obj0';
840     is !ref $obj00,   "", '!ref $obj00';
841     is !ref $obj1,    "", '!ref $obj1';
842
843     is ref $obj || 0,               "Foo",   'ref $obj || 0';
844     is ref $obj // 0,               "Foo",   'ref $obj // 0';
845     is $true && ref $obj,           "Foo",   '$true && ref $obj';
846     is ref $obj ? "true" : "false", "true",  'ref $obj ? "true" : "false"';
847
848     my $r = 2;
849     if (ref $obj) { $r = 1 };
850     is $r, 1, 'if (ref $obj)';
851
852     $r = 2;
853     if (ref $obj0) { $r = 1 };
854     is $r, 2, 'if (ref $obj0)';
855
856     $r = 2;
857     if (ref $obj) { $r = 1 } else { $r = 0 };
858     is $r, 1, 'if (ref $obj) else';
859
860     $r = 2;
861     if (ref $obj0) { $r = 1 } else { $r = 0 };
862     is $r, 0, 'if (ref $obj0) else';
863 }
864
865 {
866     # RT #78288
867     # if an op returns &PL_sv_zero rather than newSViv(0), the
868     # value should be mutable. So ref (via the PADTMP flag) should
869     # make a mutable copy
870
871     my @a = ();
872     my $r = \ scalar grep $_ == 1, @a;
873     $$r += 10;
874     is $$r, 10, "RT #78288 - mutable PL_sv_zero copy";
875 }
876
877
878 # RT#130861: heap-use-after-free in pp_rv2sv, from asan fuzzing
879 SKIP: {
880     skip_if_miniperl("no dynamic loading on miniperl, so can't load arybase", 1);
881     # this value is critical - its just enough so that the stack gets
882     # grown which loading/calling arybase
883     my $n = 125;
884
885     my $code = <<'EOF';
886 $ary = '[';
887 my @a = map $$ary, 1..NNN;
888 print "@a\n";
889 EOF
890     $code =~ s/NNN/$n/g;
891     my @exp = ("0") x $n;
892     fresh_perl_is($code, "@exp", { stderr => 1 },
893                     'rt#130861: heap uaf in pp_rv2sv');
894 }
895
896 # Bit of a hack to make test.pl happy. There are 3 more tests after it leaves.
897 $test = curr_test();
898 curr_test($test + 3);
899 # test global destruction
900
901 my $test1 = $test + 1;
902 my $test2 = $test + 2;
903
904 package FINALE;
905
906 {
907     $ref3 = bless ["ok $test2\n"];      # package destruction
908     my $ref2 = bless ["ok $test1\n"];   # lexical destruction
909     local $ref1 = bless ["ok $test\n"]; # dynamic destruction
910     1;                                  # flush any temp values on stack
911 }
912
913 DESTROY {
914     print $_[0][0];
915 }
916