CRASH: use-after-free of function stats when a procedure rolls back its own CREATE

From: Jeevan Chalke <jeevan(dot)chalke(at)enterprisedb(dot)com>
To: PostgreSQL Hackers <pgsql-hackers(at)postgresql(dot)org>, PostgreSQL Hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org>
Subject: CRASH: use-after-free of function stats when a procedure rolls back its own CREATE
Date: 2026-12-03 12:52:30
Message-ID: CAM2+6=U182bLBUdABAW=pttFd9ph9aqEOptp-Fd=kJa_vegzrg@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi,

With track_functions enabled, a procedure that ROLLBACKs the CREATE of a
procedure that is still executing corrupts memory and can crash the server.

pgstat_init_function_usage() stores a pointer to the function's pending
stats entry in PgStat_FunctionCallUsage. If the ROLLBACK drops the stats
entry, the pending counters are pfree'd, and when the call returns
pgstat_end_function_usage() does fs->numcalls++ on the freed chunk.
numcalls is the first field, and the first 8 bytes of a freed AllocSet
chunk are the freelist link, so the link becomes 0x1 and a later allocation
from "PgStat Pending" crashes in AllocSetAlloc():

SET track_functions = 'pl';
CREATE PROCEDURE outer_p() LANGUAGE plpgsql AS $o$
BEGIN
EXECUTE $c$ CREATE PROCEDURE pg_temp.inner_p() LANGUAGE plpgsql AS
$b$
BEGIN ROLLBACK; END $b$ $c$;
CALL pg_temp.inner_p();
END $o$;
CREATE PROCEDURE q1() LANGUAGE plpgsql AS $$ BEGIN NULL; END $$;
CREATE PROCEDURE q2() LANGUAGE plpgsql AS $$ BEGIN NULL; END $$;
CALL outer_p();
CALL q1();
CALL q2(); -- SIGSEGV

The write goes into freed memory on all branches, but only corrupts the
freelist since v16.

The attached patch adds a backend-local counter, bumped whenever the
pending data of a function stats entry is freed. PgStat_FunctionCallUsage
records the counter and the function OID at call start; at call end, if the
counter changed, the entry is looked up again and the update is skipped
unless it is still the same one. The common case costs one integer
comparison.

It also adds a regression test to plpgsql_transaction, which crashes
without the fix.

I think this should be back-patched.

Comments...

Thanks

--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*

enterprisedb.com <https://www.enterprisedb.com>

Attachment Content-Type Size
v1-0001-Fix-use-after-free-of-function-stats-in-pgstat_en.patch application/octet-stream 8.7 KB

Browse pgsql-hackers by date

  From Date Subject
Previous Message Dave Sharpe 2026-12-03 12:51:37 Re: several cases of float and integer mixup