Perl / perl5

🐪 The Perl programming language
https://dev.perl.org/perl5/
Other
1.85k stars 527 forks source link

fix refcount on cloned constant state subs #22158

Closed iabyn closed 3 weeks ago

iabyn commented 3 weeks ago

Perl was doing this:

$ perl -e'sub { CORE::state sub FOO () { 42 } }'
Attempt to free unreferenced scalar: ...
$

This warning was in particular now showing up on stderr on bleed builds: ever since the recent addition of similar code to Deparse.t with v5.39.9-33-g4a55343c55.

When a sub is made constant, it is converted into an XS sub, and the IV(42) SV is stored in the CV's CvXSUBANY(cv).any_sv field.

But state subs (even const ones) get cloned if wrapped within an outer anon sub and then that outer sub gets cloned. And it turns out that when a const state sub is cloned, the ref count of that const SV wasn't being incremented.

The fix is trivial. But there were two possible ways to fix it. The approach I chose was to fix the cloning code so that it increments on CvCONST(cv) being true in addition to on CvREFCOUNTED_ANYSV(cv) being true.

The other approach (and arguably more logically correct) would be to set the CVf_REFCOUNTED_ANYSV flag on const subs too, but this involves modifying the code in multiple places, e.g. newMYSUB(), newATTRSUB_x(), newCONSTSUB_flags(), and makes it more likely that CPAN XS code out there which cargo-cults similar code would also need fixing. So my fix is simpler, more robust, but less satisfying.

Note that before 5.36.0, the failing code example above would segfault rather than warn.

iabyn commented 3 weeks ago

Now in as v5.39.9-66-g17535c984a.