]> git.ipfire.org Git - thirdparty/postgresql.git/commit
Create infrastructure to reliably prevent leakage of PGresults.
authorTom Lane <tgl@sss.pgh.pa.us>
Fri, 25 Jul 2025 20:30:00 +0000 (16:30 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Fri, 25 Jul 2025 20:30:00 +0000 (16:30 -0400)
commit7d8f5957792421ec3bb9d1b9b6ca25d689d974b7
tree495a988503ec584f527ab2a0860178cedf5720a5
parent5457ea46d181f8b8dbe1ae482720b23bff4029de
Create infrastructure to reliably prevent leakage of PGresults.

Commit 232d8caea fixed a case where postgres_fdw could lose track
of a PGresult object, resulting in a process-lifespan memory leak.
But I have little faith that there aren't other potential PGresult
leakages, now or in future, in the backend modules that use libpq.
Therefore, this patch proposes infrastructure that makes all
PGresults returned from libpq act as though they are palloc'd
in the CurrentMemoryContext (with the option to relocate them to
another context later).  This should greatly reduce the risk of
careless leaks, and it also permits removal of a bunch of code
that attempted to prevent such leaks via PG_TRY blocks.

This patch adds infrastructure that wraps each PGresult in a
"libpqsrv_PGresult" that provides a memory context reset callback
to PQclear the PGresult.  Code using this abstraction is inherently
memory-safe to the same extent as we are accustomed to in most backend
code.  Furthermore, we add some macros that automatically redirect
calls of the libpq functions concerned with PGresults to use this
infrastructure, so that almost no source-code changes are needed to
wheel this infrastructure into place in all the backend code that
uses libpq.

Perhaps in future we could create similar infrastructure for
PGconn objects, but there seems less need for that.

This patch just creates the infrastructure and makes relevant code
use it, including reverting 232d8caea in favor of this mechanism.
A good deal of follow-on simplification is possible now that we don't
have to be so cautious about freeing PGresults, but I'll put that in
a separate patch.

Author: Tom Lane <tgl@sss.pgh.pa.us>
Reviewed-by: Matheus Alcantara <matheusssilv97@gmail.com>
Discussion: https://postgr.es/m/2976982.1748049023@sss.pgh.pa.us
contrib/postgres_fdw/postgres_fdw.c
contrib/postgres_fdw/postgres_fdw.h
src/backend/utils/mmgr/mcxt.c
src/include/libpq/libpq-be-fe-helpers.h
src/include/libpq/libpq-be-fe.h [new file with mode: 0644]
src/include/utils/palloc.h
src/tools/pgindent/typedefs.list