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