3 # A place to put some simple leak tests. Uses XS::APItest to make
4 # PL_sv_count available, allowing us to run a bit of code multiple times and
5 # see if the count increases.
12 eval { require XS::APItest; XS::APItest->import('sv_count'); 1 }
13 or skip_all("XS::APItest not available");
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
24 my ($n, $delta, $code, @rest) = @_;
30 $sv0 = $sv1 if $i == 1;
32 cmp_ok($sv1-$sv0, '<=', ($n-1)*$delta, @rest);
35 # Like leak, but run a string eval instead.
36 # The code is used instead of the test name
37 # if the name is absent.
39 my ($n,$delta,$code,@rest) = @_;
40 no warnings 'deprecated'; # Silence the literal control character warning
41 leak $n, $delta, sub { eval $code },
45 # run some expression N times. The expr is concatenated N times and then
46 # evaled, ensuring 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
51 my ($n, $delta, $expr, @rest) = @_;
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())";
59 cmp_ok($sv1-$sv0, '<=', ($n-1)*$delta, @rest);
62 fail("eval @rest: $@");
69 leak(5, 0, sub {}, "basic check 1 of leak test infrastructure");
70 leak(5, 0, sub {push @a,1;pop @a}, "basic check 2 of leak test infrastructure");
71 leak(5, 1, sub {push @a,1;}, "basic check 3 of leak test infrastructure");
76 $key++ while exists $ENV{$key};
77 leak(2, 0, sub { delete local $ENV{$key} },
78 'delete local on nonexistent env var');
82 leak(2, 0, sub { defined *{"!"} }, 'defined *{"!"}');
83 leak(2, 0, sub { defined *{"["} }, 'defined *{"["}');
84 leak(2, 0, sub { defined *{"-"} }, 'defined *{"-"}');
85 sub def_bang { defined *{"!"}; delete $::{"!"} }
87 leak(2, 0, \&def_bang,'defined *{"!"} vivifying GV');
88 leak(2, 0, sub { defined *{"["}; delete $::{"["} },
89 'defined *{"["} vivifying GV');
90 sub def_neg { defined *{"-"}; delete $::{"-"} }
92 leak(2, 0, \&def_neg, 'defined *{"-"} vivifying GV');
95 my $f = "use warnings FATAL =>";
96 my $all = "$f 'all';";
97 eleak(2, 0, "$f 'deprecated'; qq|\\c\{|", 'qq|\c{| with fatal warnings');
98 eleak(2, 0, "$f 'syntax'; qq|\\c`|", 'qq|\c`| with fatal warnings');
99 eleak(2, 0, "$all /\$\\ /", '/$\ / with fatal warnings');
100 eleak(2, 0, "$all s//\\1/", 's//\1/ with fatal warnings');
101 eleak(2, 0, "$all qq|\\i|", 'qq|\i| with fatal warnings');
102 eleak(2, 0, "$f 'digit'; qq|\\o{9}|", 'qq|\o{9}| with fatal warnings');
103 eleak(3, 1, "$f 'misc'; sub foo{} sub foo:lvalue",
104 'ignored :lvalue with fatal warnings');
105 eleak(2, 0, "no warnings; use feature ':all'; $f 'misc';
106 my sub foo{} sub foo:lvalue",
107 'ignored mysub :lvalue with fatal warnings');
108 eleak(2, 0, "no warnings; use feature ':all'; $all
109 my sub foo{} sub foo:lvalue{}",
110 'fatal mysub redef warning');
111 eleak(2, 0, "$all sub foo{} sub foo{}", 'fatal sub redef warning');
112 eleak(2, 0, "$all *x=sub {}",
113 'fatal sub redef warning with sub-to-glob assignment');
114 eleak(2, 0, "$all *x=sub() {1}",
115 'fatal const sub redef warning with sub-to-glob assignment');
116 eleak(2, 0, "$all XS::APItest::newCONSTSUB(\\%main::=>name=>0=>1)",
117 'newCONSTSUB sub redefinition with fatal warnings');
118 eleak(2, 0, "$f 'misc'; my\$a,my\$a", 'double my with fatal warnings');
119 eleak(2, 0, "$f 'misc'; our\$a,our\$a", 'double our with fatal warnings');
120 eleak(2, 0, "$f 'closure';
121 sub foo { my \$x; format=\n\@\n\$x\n.\n} write; ",
122 'format closing over unavailable var with fatal warnings');
123 eleak(2, 0, "$all /(?{})?/ ", '(?{})? with fatal warnings');
124 eleak(2, 0, "$all /(?{})+/ ", '(?{})+ with fatal warnings');
125 eleak(2, 0, "$all /[\\i]/ ", 'invalid charclass escape with fatal warns');
126 eleak(2, 0, "$all /[:foo:]/ ", '/[:foo:]/ with fatal warnings');
127 eleak(2, 0, "$all /[a-\\d]/ ", '[a-\d] char class with fatal warnings');
128 eleak(2, 0, "$all v111111111111111111111111111111111111111111111111",
129 'vstring num overflow with fatal warnings');
131 eleak(2, 0, 'sub{<*>}');
132 # Use a random number of ops, so that the glob op does not reuse the same
133 # address each time, giving us false passes.
134 leak(2, 0, sub { eval '$x+'x(1 + rand() * 100) . '<*>'; },
135 'freeing partly iterated glob');
137 eleak(2, 0, 'goto sub {}', 'goto &sub in eval');
138 eleak(2, 0, '() = sort { goto sub {} } 1,2', 'goto &sub in sort');
139 eleak(2, 0, '/(?{ goto sub {} })/', 'goto &sub in regexp');
141 sub TIEARRAY { bless [], $_[0] }
142 sub FETCH { $_[0]->[$_[1]] }
143 sub STORE { $_[0]->[$_[1]] = $_[2] }
145 # local $tied_elem[..] leaks <20020502143736.N16831@dansat.data-plan.com>"
148 leak(5, 0, sub {local $a[0]}, "local \$tied[0]");
153 eleak(2, 0, "BEGIN{overload::constant integer=>sub{}} 1,1,1,1,1,1,1,1,1,1",
154 '"too many errors" from constant overloading returning undef');
155 # getting this one to leak was complicated; we have to unset LOCALIZE_HH:
156 eleak(2, 0, 'BEGIN{overload::constant integer=>sub{}; $^H &= ~ 0x00020000}
157 1,1,1,1,1,1,1,1,1,1',
158 '"too many errors" from constant overloading with $^H sabotaged');
159 eleak(2, 0, "BEGIN{overload::constant integer=>sub{}; undef %^H}
160 1,1,1,1,1,1,1,1,1,1",
161 '"too many errors" from constant overloading with %^H undefined');
164 # [perl #74484] repeated tries leaked SVs on the tmps stack
166 leak_expr(5, 0, q{"YYYYYa" =~ /.+?(a(.+?)|b)/ }, "trie leak");
168 # [perl #48004] map/grep didn't free tmps till the end
171 # qr/1/ just creates tmps that are hopefully freed per iteration
175 my @count = (0) x 4; # pre-allocate
176 # Using 0..3 with constant endpoints will cause an erroneous test fail-
177 # ure, as the SV in the op tree needs to be copied (to protect it),
178 # but copying happens *during iteration*, causing the number of SVs to
179 # go up. Using a variable (0..$_3) will cause evaluation of the range
180 # operator at run time, not compile time, so the values will already be
181 # on the stack before grep starts.
184 grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
185 is(@count[3] - @count[0], 0, "void grep expr: no new tmps per iter");
186 grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
187 is(@count[3] - @count[0], 0, "void grep block: no new tmps per iter");
189 $s = grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
190 is(@count[3] - @count[0], 0, "scalar grep expr: no new tmps per iter");
191 $s = grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
192 is(@count[3] - @count[0], 0, "scalar grep block: no new tmps per iter");
194 @a = grep qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
195 is(@count[3] - @count[0], 0, "list grep expr: no new tmps per iter");
196 @a = grep { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
197 is(@count[3] - @count[0], 0, "list grep block: no new tmps per iter");
200 map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
201 is(@count[3] - @count[0], 0, "void map expr: no new tmps per iter");
202 map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
203 is(@count[3] - @count[0], 0, "void map block: no new tmps per iter");
205 $s = map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
206 is(@count[3] - @count[0], 0, "scalar map expr: no new tmps per iter");
207 $s = map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
208 is(@count[3] - @count[0], 0, "scalar map block: no new tmps per iter");
210 @a = map qr/1/ && ($count[$_] = sv_count()) && 99, 0..$_3;
211 is(@count[3] - @count[0], 3, "list map expr: one new tmp per iter");
212 @a = map { qr/1/ && ($count[$_] = sv_count()) && 99 } 0..$_3;
213 is(@count[3] - @count[0], 3, "list map block: one new tmp per iter");
217 # Map plus sparse array
221 leak(3, 0, sub { my @b = map 1, @a },
222 'map reading from sparse array');
226 { # broken by 304474c3, fixed by cefd5c7c, but didn't seem to cause
227 # any other test failures
228 # base test case from ribasushi (Peter Rabbitson)
229 eval { require Scalar::Util; Scalar::Util->import("weaken"); 1; }
230 or skip "no weaken", 1;
235 my $out = { in => $in, in => undef }
237 ok(!$weak, "hash referenced weakened SV released");
241 leak(2,0, sub { eval { prototype "CORE::fu" } }, 'prototype errors');
243 # RT #72246: rcatline memory leak on bad $/
248 open CATLINE, '<', \$f;
249 local $/ = "\x{262E}";
250 my $str = "\x{2622}";
251 eval { $str .= <CATLINE> };
266 "<html><body></body></html>" =~ m/$RE/gcs;
270 }, "named regexp captures");
274 eleak(2,0,'/[\xdf]/i');
275 eleak(2,0,'s![^/]!!');
277 eleak(2,0,'/[[:ascii:]]/');
278 eleak(2,0,'/[[.zog.]]/');
279 eleak(2,0,'/[.zog.]/');
280 eleak(2,0,'/|\W/', '/|\W/ [perl #123198]');
281 eleak(2,0,'/a\sb/', '/a\sb/ [GH #18604]');
282 eleak(2,0,'no warnings; /(?[])/');
283 eleak(2,0,'no warnings; /(?[[a]+[b]])/');
284 eleak(2,0,'no warnings; /(?[[a]-[b]])/');
285 eleak(2,0,'no warnings; /(?[[a]&[b]])/');
286 eleak(2,0,'no warnings; /(?[[a]|[b]])/');
287 eleak(2,0,'no warnings; /(?[[a]^[b]])/');
288 eleak(2,0,'no warnings; /(?[![a]])/');
289 eleak(2,0,'no warnings; /(?[\p{Word}])/');
290 eleak(2,0,'no warnings; /(?[[a]+)])/');
291 eleak(2,0,'no warnings; /(?[\d\d)])/');
293 # These can generate one ref count, but just once.
294 eleak(4,1,'chr(0x100) =~ /[[:punct:]]/');
295 eleak(4,1,'chr(0x100) =~ /[[:^punct:]]/');
296 eleak(4,1,'chr(0x100) =~ /[[:word:]]/');
297 eleak(4,1,'chr(0x100) =~ /[[:^word:]]/');
299 eleak(2,0,'chr(0x100) =~ /\P{Assigned}/');
300 leak(2,0,sub { /(??{})/ }, '/(??{})/');
302 leak(2,0,sub { !$^V }, '[perl #109762] version object in boolean context');
305 # [perl #114356] run-time rexexp with unchanging pattern got
307 eleak(2, 0, q{ my $x = "x"; "abc" =~ /$x/ for 1..5 }, '#114356');
309 eleak(2, 0, 'sub', '"sub" with nothing following');
310 eleak(2, 0, '+sub:a{}', 'anon subs with invalid attributes');
311 eleak(2, 0, 'no warnings; sub a{1 1}', 'sub with syntax error');
312 eleak(2, 0, 'no warnings; sub {1 1}', 'anon sub with syntax error');
313 eleak(2, 0, 'no warnings; use feature ":all"; my sub a{1 1}',
314 'my sub with syntax error');
316 # Reification (or lack thereof)
317 leak(2, 0, sub { sub { local $_[0]; shift }->(1) },
318 'local $_[0] on surreal @_, followed by shift');
319 leak(2, 0, sub { sub { local $_[0]; \@_ }->(1) },
320 'local $_[0] on surreal @_, followed by reification');
323 sub Recursive::Redefinition::DESTROY {
324 *recredef = sub { CORE::state $x } # state makes it cloneable
327 bless \&recredef, "Recursive::Redefinition"; eval "sub recredef{}"
328 }, 'recursive sub redefinition');
331 leak(2, 0, sub { local *_; $_[1]=1; &re::regname },
332 'passing sparse array to xsub via ampersand call');
335 eleak(2, 0, '"${<<END}"
336 ', 'unterminated here-doc in quotes in multiline eval');
337 eleak(2, 0, '"${<<END
338 }"', 'unterminated here-doc in multiline quotes in eval');
339 leak(2, 0, sub { eval { do './op/svleak.pl' } },
340 'unterminated here-doc in file');
341 eleak(2, 0, 'tr/9-0//');
342 eleak(2, 0, 'tr/a-z-0//');
343 eleak(2, 0, 'no warnings; nonexistent_function 33838',
344 'bareword followed by number');
345 eleak(2, 0, '//dd;'x20, '"too many errors" when parsing m// flags');
346 eleak(2, 0, 's///dd;'x20, '"too many errors" when parsing s/// flags');
347 eleak(2, 0, 'no warnings; 2 2;BEGIN{}',
348 'BEGIN block after syntax error');
350 local %INC; # in case Errno is already loaded
351 eleak(2, 0, 'no warnings; 2@!{',
352 'implicit "use Errno" after syntax error');
354 eleak(2, 0, "\"\$\0\356\"", 'qq containing $ <null> something');
355 eleak(2, 0, 'END OF TERMS AND CONDITIONS', 'END followed by words');
356 eleak(2, 0, "+ + +;qq|\\N{a}|"x10,'qq"\N{a}" after errors');
357 eleak(2, 0, "qq|\\N{%}|", 'qq"\N{%}" (invalid charname)');
358 eleak(2, 0, "qq|\\N{au}|;", 'qq"\N{invalid}"');
359 eleak(2, 0, "qq|\\c|;"x10, '"too many errors" from qq"\c"');
360 eleak(2, 0, "qq|\\o|;"x10, '"too many errors" from qq"\o"');
361 eleak(2, 0, "qq|\\x{|;"x10, '"too many errors" from qq"\x{"');
362 eleak(2, 0, "qq|\\N|;"x10, '"too many errors" from qq"\N"');
363 eleak(2, 0, "qq|\\N{|;"x10, '"too many errors" from qq"\N{"');
364 eleak(2, 0, "qq|\\N{U+GETG}|;"x10,'"too many errors" from qq"\N{U+JUNK}"');
367 # [perl #114764] Attributes leak scalars
368 leak(2, 0, sub { eval 'my $x : shared' }, 'my $x :shared used to leak');
370 eleak(2, 0, 'ref: 1', 'labels');
372 # Tied hash iteration was leaking if the hash was freed before itera-
375 sub TIEHASH { bless [] }
383 }, 'tied hash iteration does not leak');
385 package explosive_scalar {
386 sub TIESCALAR { my $self = shift; bless [undef, {@_}], $self }
387 sub FETCH { die 'FETCH' if $_[0][1]{FETCH}; $_[0][0] }
388 sub STORE { die 'STORE' if $_[0][1]{STORE}; $_[0][0] = $_[1] }
390 tie my $die_on_fetch, 'explosive_scalar', FETCH => 1;
392 # List assignment was leaking when assigning explosive scalars to
395 eval {%a = ($die_on_fetch, 0)}; # key
396 eval {%a = (0, $die_on_fetch)}; # value
397 eval {%a = ($die_on_fetch, $die_on_fetch)}; # both
398 eval {%a = ($die_on_fetch)}; # key, odd elements
399 }, 'hash assignment does not leak');
401 eval {@a = ($die_on_fetch)};
402 eval {($die_on_fetch, $b) = ($b, $die_on_fetch)};
404 tie $die_on_fetch, 'explosive_scalar', FETCH => 1;
405 }, 'array assignment does not leak');
409 sub TIEHASH { bless [] }
410 sub STORE { $_[0][0]{$_[1]} = $_[2] }
411 sub FETCH { die if $explosive; $_[0][0]{$_[1]} }
412 sub FIRSTKEY { keys %{$_[0][0]}; each %{$_[0][0]} }
413 sub NEXTKEY { each %{$_[0][0]} }
418 $hhtie::explosive = 0;
421 $hhtie::explosive = 1;
425 }, 'hint-hash copying does not leak');
427 package explosive_array {
428 sub TIEARRAY { bless [[], {}], $_[0] }
429 sub FETCH { die if $_[0]->[1]{FETCH}; $_[0]->[0][$_[1]] }
430 sub FETCHSIZE { die if $_[0]->[1]{FETCHSIZE}; scalar @{ $_[0]->[0] } }
431 sub STORE { die if $_[0]->[1]{STORE}; $_[0]->[0][$_[1]] = $_[2] }
432 sub CLEAR { die if $_[0]->[1]{CLEAR}; @{$_[0]->[0]} = () }
433 sub EXTEND { die if $_[0]->[1]{EXTEND}; return }
434 sub explode { my $self = shift; $self->[1] = {@_} }
438 tie my @a, 'explosive_array';
439 tied(@a)->explode( STORE => 1 );
442 }, 'explosive array assignment does not leak');
446 eval { warn $die_on_fetch };
447 }, 'explosive warn argument');
450 my $foo = sub { return $die_on_fetch };
451 my $res = eval { $foo->() };
452 my @res = eval { $foo->() };
453 }, 'function returning explosive does not leak');
456 my $res = eval { {$die_on_fetch, 0} };
457 $res = eval { {0, $die_on_fetch} };
458 }, 'building anon hash with explosives does not leak');
461 my $res = eval { [$die_on_fetch] };
462 }, 'building anon array with explosives does not leak');
466 eval { push @a, $die_on_fetch };
467 }, 'pushing exploding scalar does not leak');
470 eval { push @-, '' };
471 }, 'pushing onto read-only array does not leak');
474 # Run-time regexp code blocks
477 my @tests = ('[(?{})]','(?{})');
481 }, "/ \$x/ where \$x is $t does not leak");
484 }, "/(?{})\$x/ where \$x is $t does not leak");
490 use warnings FATAL => 'all';
493 eval { printf uNopened 42 };
494 }, 'printfing to bad handle under fatal warnings does not leak');
495 open my $fh, ">", \my $buf;
497 eval { printf $fh chr 2455 };
498 }, 'wide fatal warning does not make printf leak');
503 leak(2,0,sub{eval{require untohunothu}}, 'requiring nonexistent module');
506 use constant const_av_xsub_leaked => 1 .. 3;
507 leak(5, 0, sub { scalar &const_av_xsub_leaked }, "const_av_sub in scalar context");
509 # check that OP_MULTIDEREF doesn't leak when compiled and then freed
511 eleak(2, 0, <<'EOF', 'OP_MULTIDEREF');
514 my ($x, @a, %h, $r, $k, $i);
515 $x = $a[0]{foo}{$k}{$i};
516 $x = $h[0]{foo}{$k}{$i};
517 $x = $r->[0]{foo}{$k}{$i};
518 $x = $mdr::a[0]{foo}{$mdr::k}{$mdr::i};
519 $x = $mdr::h[0]{foo}{$mdr::k}{$mdr::i};
520 $x = $mdr::r->[0]{foo}{$mdr::k}{$mdr::i};
523 # un-localizing a tied (or generally magic) item could leak if the things
524 # called by mg_set() died
529 sub TIESCALAR { bless [] }
532 sub STORE { die if $do_die; }
541 eval { my $x = f(); };
544 ::leak(5,0, \&g, "MG_SET");
547 # check that @_ isn't leaked when dieing while goto'ing a new sub
551 sub TIEARRAY { bless [] }
553 sub STORE { die if $_[0][0]; $_[0][0] = 1 }
555 sub f { eval { g() } }
564 ::leak(5, 0, \&f, q{goto shouldn't leak @_});
567 # [perl #128313] POSIX warnings shouldn't leak
569 no warnings 'experimental';
573 sub f { $a =~ /[^.]+$b/; }
574 ::leak(2, 0, \&f, q{use re 'strict' shouldn't leak warning strings});
577 # check that B::RHE->HASH does not leak
582 my $op = B::svref_2object(\&foo)->ROOT->first;
583 sub lk { { my $d = $op->hints_hash->HASH } }
584 ::leak(3, 0, \&lk, q!B::RHE->HASH shoudln't leak!);
588 # dying while compiling a regex with codeblocks imported from an embedded
593 my $r = qr/(?{ 1; })/;
597 ::leak(2, 0, \&codeblocks, q{leaking embedded qr codeblocks});
601 # Perl_reg_named_buff_fetch() leaks an AV when called with an RE
602 # with no named captures
605 re::regname("foo", 1);
607 ::leak(2, 0, \&named, "Perl_reg_named_buff_fetch() on no-name RE");
611 sub N_leak { eval 'tr//\N{}-0/' }
612 ::leak(2, 0, \&N_leak, "a bad \\N{} in a range leaks");
615 leak 2,0,\&XS::APItest::PerlIO_stderr,'T_INOUT in default typemap';
616 leak 2,0,\&XS::APItest::PerlIO_stdin, 'T_IN in default typemap';
617 leak 2,0,\&XS::APItest::PerlIO_stdout,'T_OUT in default typemap';
619 skip "for now; crashes";
620 leak 2,1,sub{XS::APItest::PerlIO_exportFILE(*STDIN,"");0},
621 'T_STDIO in default typemap';
625 my %rh= ( qr/^foo/ => 1);
626 sub Regex_Key_Leak { my ($r)= keys %rh; "foo"=~$r; }
627 leak 2, 0, \&Regex_Key_Leak,"RT #132892 - regex patterns should not leak";
632 fresh_perl_is(<<'PERL', "ok", {}, "check goto core sub doesn't leak");
633 # done this way to avoid overloads for all of svleak.t
636 *CORE::GLOBAL::open = sub (*;$@) {
643 open(my $fh, '<', 'TEST');
644 my $sv = B::svref_2object($fh);
645 print $sv->REFCNT == 1 ? "ok" : "not ok";