This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Get t/uni/cache.t working under minitest
[perl5.git] / t / op / svleak.t
CommitLineData
d97c33b5
DM
1#!./perl
2
3# A place to put some simple leak tests. Uses XS::APItest to make
64dc9714 4# PL_sv_count available, allowing us to run a bit of code multiple times and
d97c33b5
DM
5# see if the count increases.
6
7BEGIN {
8 chdir 't';
9 @INC = '../lib';
10 require './test.pl';
11
12 eval { require XS::APItest; XS::APItest->import('sv_count'); 1 }
13 or skip_all("XS::APItest not available");
14}
15
ef09a500
DM
16use Config;
17
d06ddc79 18plan tests => 127;
d97c33b5
DM
19
20# run some code N times. If the number of SVs at the end of loop N is
21# greater than (N-1)*delta at the end of loop 1, we've got a leak
22#
23sub leak {
24 my ($n, $delta, $code, @rest) = @_;
25 my $sv0 = 0;
26 my $sv1 = 0;
27 for my $i (1..$n) {
28 &$code();
29 $sv1 = sv_count();
30 $sv0 = $sv1 if $i == 1;
31 }
32 cmp_ok($sv1-$sv0, '<=', ($n-1)*$delta, @rest);
33}
34
1cac5c33
FC
35# Like leak, but run a string eval instead.
36# The code is used instead of the test name
2e880be7
FC
37# if the name is absent.
38sub eleak {
39 my ($n,$delta,$code,@rest) = @_;
b29f65fc 40 no warnings 'deprecated'; # Silence the literal control character warning
1cac5c33 41 leak $n, $delta, sub { eval $code },
2e880be7
FC
42 @rest ? @rest : $code
43}
44
8bd05d90
DM
45# run some expression N times. The expr is concatenated N times and then
46# evaled, ensuring that that there are no scope exits between executions.
47# If the number of SVs at the end of expr N is greater than (N-1)*delta at
48# the end of expr 1, we've got a leak
49#
50sub leak_expr {
51 my ($n, $delta, $expr, @rest) = @_;
52 my $sv0 = 0;
53 my $sv1 = 0;
54 my $true = 1; # avoid stuff being optimised away
55 my $code1 = "($expr || \$true)";
56 my $code = "$code1 && (\$sv0 = sv_count())" . ("&& $code1" x 4)
57 . " && (\$sv1 = sv_count())";
58 if (eval $code) {
59 cmp_ok($sv1-$sv0, '<=', ($n-1)*$delta, @rest);
60 }
61 else {
62 fail("eval @rest: $@");
63 }
64}
65
66
d97c33b5
DM
67my @a;
68
69leak(5, 0, sub {}, "basic check 1 of leak test infrastructure");
70leak(5, 0, sub {push @a,1;pop @a}, "basic check 2 of leak test infrastructure");
71leak(5, 1, sub {push @a,1;}, "basic check 3 of leak test infrastructure");
459defa1 72
9332b95f
FC
73# delete
74{
75 my $key = "foo";
76 $key++ while exists $ENV{$key};
77 leak(2, 0, sub { delete local $ENV{$key} },
78 'delete local on nonexistent env var');
79}
80
38b1111c
FC
81# Fatal warnings
82my $f = "use warnings FATAL =>";
83my $all = "$f 'all';";
38b1111c
FC
84eleak(2, 0, "$f 'deprecated'; qq|\\c\{|", 'qq|\c{| with fatal warnings');
85eleak(2, 0, "$f 'syntax'; qq|\\c`|", 'qq|\c`| with fatal warnings');
86eleak(2, 0, "$all /\$\\ /", '/$\ / with fatal warnings');
87eleak(2, 0, "$all s//\\1/", 's//\1/ with fatal warnings');
88eleak(2, 0, "$all qq|\\i|", 'qq|\i| with fatal warnings');
89eleak(2, 0, "$f 'digit'; qq|\\o{9}|", 'qq|\o{9}| with fatal warnings');
63391a34 90eleak(3, 1, "$f 'misc'; sub foo{} sub foo:lvalue",
38b1111c
FC
91 'ignored :lvalue with fatal warnings');
92eleak(2, 0, "no warnings; use feature ':all'; $f 'misc';
93 my sub foo{} sub foo:lvalue",
94 'ignored mysub :lvalue with fatal warnings');
95eleak(2, 0, "no warnings; use feature ':all'; $all
96 my sub foo{} sub foo:lvalue{}",
97 'fatal mysub redef warning');
98eleak(2, 0, "$all sub foo{} sub foo{}", 'fatal sub redef warning');
99eleak(2, 0, "$all *x=sub {}",
100 'fatal sub redef warning with sub-to-glob assignment');
101eleak(2, 0, "$all *x=sub() {1}",
102 'fatal const sub redef warning with sub-to-glob assignment');
103eleak(2, 0, "$all XS::APItest::newCONSTSUB(\\%main::=>name=>0=>1)",
95934569 104 'newCONSTSUB sub redefinition with fatal warnings');
38b1111c
FC
105eleak(2, 0, "$f 'misc'; my\$a,my\$a", 'double my with fatal warnings');
106eleak(2, 0, "$f 'misc'; our\$a,our\$a", 'double our with fatal warnings');
107eleak(2, 0, "$f 'closure';
108 sub foo { my \$x; format=\n\@\n\$x\n.\n} write; ",
af32a010 109 'format closing over unavailable var with fatal warnings');
38b1111c
FC
110eleak(2, 0, "$all /(?{})?/ ", '(?{})? with fatal warnings');
111eleak(2, 0, "$all /(?{})+/ ", '(?{})+ with fatal warnings');
112eleak(2, 0, "$all /[\\i]/ ", 'invalid charclass escape with fatal warns');
113eleak(2, 0, "$all /[:foo:]/ ", '/[:foo:]/ with fatal warnings');
114eleak(2, 0, "$all /[a-\\d]/ ", '[a-\d] char class with fatal warnings');
115eleak(2, 0, "$all v111111111111111111111111111111111111111111111111",
116 'vstring num overflow with fatal warnings');
38b1111c 117
e88567f2 118eleak(2, 0, 'sub{<*>}');
11ddfebc
FC
119# Use a random number of ops, so that the glob op does not reuse the same
120# address each time, giving us false passes.
a1ba7ec6 121leak(2, 0, sub { eval '$x+'x(1 + rand() * 100) . '<*>'; },
11ddfebc 122 'freeing partly iterated glob');
e88567f2 123
110af908
FC
124eleak(2, 0, 'goto sub {}', 'goto &sub in eval');
125eleak(2, 0, '() = sort { goto sub {} } 1,2', 'goto &sub in sort');
126eleak(2, 0, '/(?{ goto sub {} })/', 'goto &sub in regexp');
127
459defa1
DM
128sub TIEARRAY { bless [], $_[0] }
129sub FETCH { $_[0]->[$_[1]] }
130sub STORE { $_[0]->[$_[1]] = $_[2] }
131
132# local $tied_elem[..] leaks <20020502143736.N16831@dansat.data-plan.com>"
133{
134 tie my @a, 'main';
135 leak(5, 0, sub {local $a[0]}, "local \$tied[0]");
136}
137
5f7f7af5
FC
138# Overloading
139require overload;
140eleak(2, 0, "BEGIN{overload::constant integer=>sub{}} 1,1,1,1,1,1,1,1,1,1",
141 '"too many errors" from constant overloading returning undef');
142# getting this one to leak was complicated; we have to unset LOCALIZE_HH:
143eleak(2, 0, 'BEGIN{overload::constant integer=>sub{}; $^H &= ~ 0x00020000}
144 1,1,1,1,1,1,1,1,1,1',
145 '"too many errors" from constant overloading with $^H sabotaged');
146eleak(2, 0, "BEGIN{overload::constant integer=>sub{}; undef %^H}
147 1,1,1,1,1,1,1,1,1,1",
148 '"too many errors" from constant overloading with %^H undefined');
149
150
8bd05d90
DM
151# [perl #74484] repeated tries leaked SVs on the tmps stack
152
2e64971a 153leak_expr(5, 0, q{"YYYYYa" =~ /.+?(a(.+?)|b)/ }, "trie leak");
b2a2a901
DM
154
155# [perl #48004] map/grep didn't free tmps till the end
156
157{
158 # qr/1/ just creates tmps that are hopefully freed per iteration
159
160 my $s;
161 my @a;
162 my @count = (0) x 4; # pre-allocate
5608dcc6
FC
163 # Using 0..3 with constant endpoints will cause an erroneous test fail-
164 # ure, as the SV in the op tree needs to be copied (to protect it),
165 # but copying happens *during iteration*, causing the number of SVs to
166 # go up. Using a variable (0..$_3) will cause evaluation of the range
167 # operator at run time, not compile time, so the values will already be
168 # on the stack before grep starts.
169 my $_3 = 3;
170
171 grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 172 is(@count[3] - @count[0], 0, "void grep expr: no new tmps per iter");
5608dcc6 173 grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
174 is(@count[3] - @count[0], 0, "void grep block: no new tmps per iter");
175
5608dcc6 176 $s = grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 177 is(@count[3] - @count[0], 0, "scalar grep expr: no new tmps per iter");
5608dcc6 178 $s = grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
179 is(@count[3] - @count[0], 0, "scalar grep block: no new tmps per iter");
180
5608dcc6 181 @a = grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 182 is(@count[3] - @count[0], 0, "list grep expr: no new tmps per iter");
5608dcc6 183 @a = grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
184 is(@count[3] - @count[0], 0, "list grep block: no new tmps per iter");
185
186
5608dcc6 187 map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 188 is(@count[3] - @count[0], 0, "void map expr: no new tmps per iter");
5608dcc6 189 map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
190 is(@count[3] - @count[0], 0, "void map block: no new tmps per iter");
191
5608dcc6 192 $s = map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 193 is(@count[3] - @count[0], 0, "scalar map expr: no new tmps per iter");
5608dcc6 194 $s = map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
195 is(@count[3] - @count[0], 0, "scalar map block: no new tmps per iter");
196
5608dcc6 197 @a = map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
b2a2a901 198 is(@count[3] - @count[0], 3, "list map expr: one new tmp per iter");
5608dcc6 199 @a = map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
b2a2a901
DM
200 is(@count[3] - @count[0], 3, "list map block: one new tmp per iter");
201
202}
a50d6ed0
TC
203
204SKIP:
205{ # broken by 304474c3, fixed by cefd5c7c, but didn't seem to cause
206 # any other test failures
207 # base test case from ribasushi (Peter Rabbitson)
208 eval { require Scalar::Util; Scalar::Util->import("weaken"); 1; }
209 or skip "no weaken", 1;
210 my $weak;
211 {
212 $weak = my $in = {};
213 weaken($weak);
214 my $out = { in => $in, in => undef }
215 }
216 ok(!$weak, "hash referenced weakened SV released");
217}
64dc9714 218
c9af70d5
FC
219# prototype() errors
220leak(2,0, sub { eval { prototype "CORE::fu" } }, 'prototype errors');
221
64dc9714
DM
222# RT #72246: rcatline memory leak on bad $/
223
224leak(2, 0,
225 sub {
226 my $f;
227 open CATLINE, '<', \$f;
228 local $/ = "\x{262E}";
229 my $str = "\x{2622}";
230 eval { $str .= <CATLINE> };
231 },
232 "rcatline leak"
233);
a17b8556
JP
234
235{
236 my $RE = qr/
237 (?:
238 <(?<tag>
239 \s*
240 [^>\s]+
241 )>
242 )??
243 /xis;
244
245 "<html><body></body></html>" =~ m/$RE/gcs;
246
247 leak(5, 0, sub {
248 my $tag = $+{tag};
249 }, "named regexp captures");
250}
bcb2959f 251
2e880be7
FC
252eleak(2,0,'/[:]/');
253eleak(2,0,'/[\xdf]/i');
f248b511 254eleak(2,0,'s![^/]!!');
3451022d
FC
255eleak(2,0,'/[pp]/');
256eleak(2,0,'/[[:ascii:]]/');
e5fcdda9
FC
257eleak(2,0,'/[[.zog.]]/');
258eleak(2,0,'/[.zog.]/');
1e4f0888 259eleak(2,0,'no warnings; /(?[])/');
a84e671a
FC
260eleak(2,0,'no warnings; /(?[[a]+[b]])/');
261eleak(2,0,'no warnings; /(?[[a]-[b]])/');
262eleak(2,0,'no warnings; /(?[[a]&[b]])/');
263eleak(2,0,'no warnings; /(?[[a]|[b]])/');
264eleak(2,0,'no warnings; /(?[[a]^[b]])/');
265eleak(2,0,'no warnings; /(?[![a]])/');
c80d037c 266eleak(2,0,'no warnings; /(?[\p{Word}])/');
4bc5d089 267eleak(2,0,'no warnings; /(?[[a]+)])/');
b573e700 268eleak(2,0,'no warnings; /(?[\d\d)])/');
7f5d1fb2
KW
269
270# These can generate one ref count, but just once.
271eleak(4,1,'chr(0x100) =~ /[[:punct:]]/');
272eleak(4,1,'chr(0x100) =~ /[[:^punct:]]/');
273eleak(4,1,'chr(0x100) =~ /[[:word:]]/');
274eleak(4,1,'chr(0x100) =~ /[[:^word:]]/');
275
4aca0fe6 276eleak(2,0,'chr(0x100) =~ /\P{Assigned}/');
e1ff3a88 277leak(2,0,sub { /(??{})/ }, '/(??{})/');
2e880be7 278
bcb2959f 279leak(2,0,sub { !$^V }, '[perl #109762] version object in boolean context');
d97935e0
DM
280
281
282# [perl #114356] run-time rexexp with unchanging pattern got
283# inflated refcounts
1cac5c33 284eleak(2, 0, q{ my $x = "x"; "abc" =~ /$x/ for 1..5 }, '#114356');
d97935e0 285
1cac5c33 286eleak(2, 0, 'sub', '"sub" with nothing following');
12d3c230 287eleak(2, 0, '+sub:a{}', 'anon subs with invalid attributes');
9ffcdca1 288eleak(2, 0, 'no warnings; sub a{1 1}', 'sub with syntax error');
4d2dfd15 289eleak(2, 0, 'no warnings; sub {1 1}', 'anon sub with syntax error');
8ca8859f
FC
290eleak(2, 0, 'no warnings; use feature ":all"; my sub a{1 1}',
291 'my sub with syntax error');
12d3c230 292
1cdc9186
FC
293# Reification (or lack thereof)
294leak(2, 0, sub { sub { local $_[0]; shift }->(1) },
295 'local $_[0] on surreal @_, followed by shift');
296leak(2, 0, sub { sub { local $_[0]; \@_ }->(1) },
297 'local $_[0] on surreal @_, followed by reification');
298
63391a34
FC
299sub recredef {}
300sub Recursive::Redefinition::DESTROY {
301 *recredef = sub { CORE::state $x } # state makes it cloneable
302}
303leak(2, 0, sub {
304 bless \&recredef, "Recursive::Redefinition"; eval "sub recredef{}"
305}, 'recursive sub redefinition');
306
47c8e7fe
FC
307# Syntax errors
308eleak(2, 0, '"${<<END}"
309 ', 'unterminated here-doc in quotes in multiline eval');
310eleak(2, 0, '"${<<END
311 }"', 'unterminated here-doc in multiline quotes in eval');
1cac5c33 312leak(2, 0, sub { eval { do './op/svleak.pl' } },
2d85e411 313 'unterminated here-doc in file');
47c8e7fe
FC
314eleak(2, 0, 'tr/9-0//');
315eleak(2, 0, 'tr/a-z-0//');
316eleak(2, 0, 'no warnings; nonexistent_function 33838',
a577af66 317 'bareword followed by number');
10002bc1
FC
318eleak(2, 0, '//dd;'x20, '"too many errors" when parsing m// flags');
319eleak(2, 0, 's///dd;'x20, '"too many errors" when parsing s/// flags');
1cac5c33 320eleak(2, 0, 'no warnings; 2 2;BEGIN{}',
9eb48717 321 'BEGIN block after syntax error');
600beb2e
FC
322{
323 local %INC; # in case Errno is already loaded
324 eleak(2, 0, 'no warnings; 2@!{',
325 'implicit "use Errno" after syntax error');
326}
3ce3dcd9 327eleak(2, 0, "\"\$\0\356\"", 'qq containing $ <null> something');
3ac7ff8f 328eleak(2, 0, 'END OF TERMS AND CONDITIONS', 'END followed by words');
14ca8ff4 329eleak(2, 0, "+ + +;qq|\\N{a}|"x10,'qq"\N{a}" after errors');
b6407c49
FC
330eleak(2, 0, "qq|\\N{%}|", 'qq"\N{%}" (invalid charname)');
331eleak(2, 0, "qq|\\N{au}|;", 'qq"\N{invalid}"');
38b1111c 332eleak(2, 0, "qq|\\c|;"x10, '"too many errors" from qq"\c"');
38b1111c
FC
333eleak(2, 0, "qq|\\o|;"x10, '"too many errors" from qq"\o"');
334eleak(2, 0, "qq|\\x{|;"x10, '"too many errors" from qq"\x{"');
335eleak(2, 0, "qq|\\N|;"x10, '"too many errors" from qq"\N"');
336eleak(2, 0, "qq|\\N{|;"x10, '"too many errors" from qq"\N{"');
337eleak(2, 0, "qq|\\N{U+GETG}|;"x10,'"too many errors" from qq"\N{U+JUNK}"');
9e942bf5 338
9fa29fa7
FC
339
340# [perl #114764] Attributes leak scalars
341leak(2, 0, sub { eval 'my $x : shared' }, 'my $x :shared used to leak');
895cdc83 342
c25611d5
FC
343eleak(2, 0, 'ref: 1', 'labels');
344
895cdc83
FC
345# Tied hash iteration was leaking if the hash was freed before itera-
346# tion was over.
347package t {
348 sub TIEHASH { bless [] }
349 sub FIRSTKEY { 0 }
350}
351leak(2, 0, sub {
352 my $h = {};
353 tie %$h, t;
354 each %$h;
355 undef $h;
356}, 'tied hash iteration does not leak');
9c744f4f 357
33b889b0
RZ
358package explosive_scalar {
359 sub TIESCALAR { my $self = shift; bless [undef, {@_}], $self }
360 sub FETCH { die 'FETCH' if $_[0][1]{FETCH}; $_[0][0] }
361 sub STORE { die 'STORE' if $_[0][1]{STORE}; $_[0][0] = $_[1] }
362}
363tie my $die_on_fetch, 'explosive_scalar', FETCH => 1;
364
39984de3
FC
365# List assignment was leaking when assigning explosive scalars to
366# aggregates.
9c744f4f 367leak(2, 0, sub {
33b889b0
RZ
368 eval {%a = ($die_on_fetch, 0)}; # key
369 eval {%a = (0, $die_on_fetch)}; # value
370 eval {%a = ($die_on_fetch, $die_on_fetch)}; # both
499ace3b 371 eval {%a = ($die_on_fetch)}; # key, odd elements
9c744f4f 372}, 'hash assignment does not leak');
39984de3 373leak(2, 0, sub {
33b889b0
RZ
374 eval {@a = ($die_on_fetch)};
375 eval {($die_on_fetch, $b) = ($b, $die_on_fetch)};
376 # restore
377 tie $die_on_fetch, 'explosive_scalar', FETCH => 1;
39984de3 378}, 'array assignment does not leak');
9c744f4f 379
0db511c0
FC
380# [perl #107000]
381package hhtie {
382 sub TIEHASH { bless [] }
383 sub STORE { $_[0][0]{$_[1]} = $_[2] }
384 sub FETCH { die if $explosive; $_[0][0]{$_[1]} }
385 sub FIRSTKEY { keys %{$_[0][0]}; each %{$_[0][0]} }
386 sub NEXTKEY { each %{$_[0][0]} }
387}
1cac5c33 388leak(2, 0, sub {
0db511c0
FC
389 eval q`
390 BEGIN {
391 $hhtie::explosive = 0;
392 tie %^H, hhtie;
393 $^H{foo} = bar;
394 $hhtie::explosive = 1;
395 }
396 { 1; }
397 `;
398}, 'hint-hash copying does not leak');
33b889b0
RZ
399
400package explosive_array {
401 sub TIEARRAY { bless [[], {}], $_[0] }
402 sub FETCH { die if $_[0]->[1]{FETCH}; $_[0]->[0][$_[1]] }
403 sub FETCHSIZE { die if $_[0]->[1]{FETCHSIZE}; scalar @{ $_[0]->[0] } }
404 sub STORE { die if $_[0]->[1]{STORE}; $_[0]->[0][$_[1]] = $_[2] }
405 sub CLEAR { die if $_[0]->[1]{CLEAR}; @{$_[0]->[0]} = () }
406 sub EXTEND { die if $_[0]->[1]{EXTEND}; return }
407 sub explode { my $self = shift; $self->[1] = {@_} }
408}
409
410leak(2, 0, sub {
411 tie my @a, 'explosive_array';
412 tied(@a)->explode( STORE => 1 );
413 my $x = 0;
414 eval { @a = ($x) };
415}, 'explosive array assignment does not leak');
416
417leak(2, 0, sub {
418 my ($a, $b);
419 eval { warn $die_on_fetch };
420}, 'explosive warn argument');
421
422leak(2, 0, sub {
423 my $foo = sub { return $die_on_fetch };
424 my $res = eval { $foo->() };
425 my @res = eval { $foo->() };
426}, 'function returning explosive does not leak');
427
428leak(2, 0, sub {
429 my $res = eval { {$die_on_fetch, 0} };
430 $res = eval { {0, $die_on_fetch} };
431}, 'building anon hash with explosives does not leak');
432
433leak(2, 0, sub {
3ed356df
FC
434 my $res = eval { [$die_on_fetch] };
435}, 'building anon array with explosives does not leak');
436
437leak(2, 0, sub {
33b889b0
RZ
438 my @a;
439 eval { push @a, $die_on_fetch };
440}, 'pushing exploding scalar does not leak');
ddac780e 441
644ac3a8
FC
442leak(2, 0, sub {
443 eval { push @-, '' };
444}, 'pushing onto read-only array does not leak');
445
ddac780e
FC
446
447# Run-time regexp code blocks
448{
2ac13048
FC
449 use re 'eval';
450 my @tests = ('[(?{})]','(?{})');
ddac780e 451 for my $t (@tests) {
1cac5c33 452 leak(2, 0, sub {
ddac780e
FC
453 / $t/;
454 }, "/ \$x/ where \$x is $t does not leak");
1cac5c33 455 leak(2, 0, sub {
ddac780e
FC
456 /(?{})$t/;
457 }, "/(?{})\$x/ where \$x is $t does not leak");
458 }
459}
104c40b0
FC
460
461
462{
463 use warnings FATAL => 'all';
464 leak(2, 0, sub {
d861347e 465 no warnings 'once';
104c40b0
FC
466 eval { printf uNopened 42 };
467 }, 'printfing to bad handle under fatal warnings does not leak');
c7bd8b84
FC
468 open my $fh, ">", \my $buf;
469 leak(2, 0, sub {
470 eval { printf $fh chr 2455 };
471 }, 'wide fatal warning does not make printf leak');
472 close $fh or die $!;
104c40b0 473}
1e5f02b3
FC
474
475
476leak(2,0,sub{eval{require untohunothu}}, 'requiring nonexistent module');
d06ddc79
TC
477
478# [perl #120939]
479use constant const_av_xsub_leaked => 1 .. 3;
480leak(5, 0, sub { scalar &const_av_xsub_leaked }, "const_av_sub in scalar context");