]> git.kaiwu.me - nginx.git/commit
Perl: introduced reference counting for perl scalars
authorMaxim Dounin <mdounin@mdounin.ru>
Fri, 26 Jun 2026 19:23:28 +0000 (22:23 +0300)
committerSergey Kandaurov <s.kandaurov@f5.com>
Wed, 15 Jul 2026 10:06:50 +0000 (14:06 +0400)
commitd9b7669666c8acaf9ec109ce6c2f16011a5a3762
tree91dc53e5d1f1637efcda239780cfcd6e163337ba
parenta6a942fd6a7e18cc168a4c0281118d08181d668f
Perl: introduced reference counting for perl scalars

Perl scalars might have a limited lifetime, and using them without
appropriate reference counting is incorrect.  In particular, heap
use-after-free was observed in the following configuration (note the
"eval", which limits lifetime of the string being printed), which
demonstrates that the previously used SvREADONLY() optimizations are
incorrect:

    location / {
        perl 'sub {
            my $r = shift;
            $r->send_http_header;
            eval q!$r->print("it works")!;
            return OK;
        }';
    }

Similarly, errors were observed with handlers in $r->sleep() and
$r->has_request_body() when a handler comes from an eval, such as in
the following configuration:

    location / {
        perl 'sub {
            my $r = shift;
            $r->sleep(100, eval q!sub {
                my $r = shift;
                $r->send_http_header;
                $r->print("it works");
                return OK;
            }!);
            return OK;
        }';
    }

Accordingly, the SvREADONLY() optimization was removed in
ngx_http_perl_sv2str(), since it is expected to be used for small
strings, and using proper reference counting likely will be more costly
than just copying the string.  In $r->print(), $r->sleep(), and
$r->has_request_body() proper reference counting was implemented, with
decrement operations being performed by pool cleanup handlers.

As a positive side effect, $r->print() can now avoid copying any single
scalar, not just read-only scalars.

Reported by Evan Hellman,
https://github.com/freenginx/nginx/issues/26

Signed-off-by: Sergey Kandaurov <pluknet@nginx.com>
Origin: https://freenginx.org/hg/nginx/rev/7a3dbb7905ad
src/http/modules/perl/nginx.xs
src/http/modules/perl/ngx_http_perl_module.c
src/http/modules/perl/ngx_http_perl_module.h