Prevent crash when calling pgstat functions with unregistered stats kind

From: Bertrand Drouvot <bertranddrouvot(dot)pg(at)gmail(dot)com>
To: pgsql-hackers(at)lists(dot)postgresql(dot)org
Cc: Michael Paquier <michael(at)paquier(dot)xyz>
Subject: Prevent crash when calling pgstat functions with unregistered stats kind
Date: 2026-07-01 07:19:49
Message-ID: akS/ldidWeqG1FWk@bdtpg
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi hackers,

While reviewing [1], I got segfault(s) because I created a custom statistics
extension that I forgot to add to shared_preload_libraries. Then using one of
its function produced:

"
Core was generated by `postgres: postgres postgres [local] SELECT '.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 pgstat_init_entry (kind=kind(at)entry=24, shhashent=shhashent(at)entry=0x73f6c341a740) at pgstat_shmem.c:335
335 chunk = dsa_allocate_extended(pgStatLocal.dsa,
"

Indeed, if a custom statistics extension is loaded via CREATE EXTENSION without
being listed in shared_preload_libraries, its _PG_init() skips the call to
pgstat_register_kind(). The SQL functions are still created, and calling them
invokes pgstat functions with a kind that was never registered.

pgstat_get_kind_info() returns NULL in this case. The existing code only
checked this via Assert() in some paths, so non-assert builds would dereference
NULL and segfault.

The attached patch adds runtime checks in all public-facing pgstat functions that
accept a PgStat_Kind and dereference the returned kind info:

- pgstat_prep_pending_entry()
- pgstat_fetch_entry()
- pgstat_reset()
- pgstat_reset_of_kind()
- pgstat_have_entry()
- pgstat_snapshot_fixed()
- pgstat_init_entry()
- pgstat_reset_entry()

Each now raises ERROR with ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE when
the kind is not known or registered.

[1]: https://postgr.es/m/akSi2txzLZWQL31Q%40bdtpg

Regards,

--
Bertrand Drouvot
PostgreSQL Contributors Team
RDS Open Source Databases
Amazon Web Services: https://aws.amazon.com

Attachment Content-Type Size
v1-0001-Prevent-crash-when-calling-pgstat-functions-with-.patch text/x-diff 6.6 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message cca5507 2026-07-01 07:21:06 Re: Handle concurrent drop when doing whole database vacuum
Previous Message Dilip Kumar 2026-07-01 07:14:53 Re: Proposal: Conflict log history table for Logical Replication