]> git.ipfire.org Git - thirdparty/postgresql.git/commit
Fix memory leakage in postgres_fdw's DirectModify code path.
authorTom Lane <tgl@sss.pgh.pa.us>
Fri, 30 May 2025 17:45:41 +0000 (13:45 -0400)
committerTom Lane <tgl@sss.pgh.pa.us>
Fri, 30 May 2025 17:45:41 +0000 (13:45 -0400)
commit3c31594f55cd210bbee4e2ac92c2610b8c260f2c
tree4e34aa0498b2270991a0ed5f70684fcc946cf245
parent39b1d190714a11f98cb35916a7ceb1a998e24062
Fix memory leakage in postgres_fdw's DirectModify code path.

postgres_fdw tries to use PG_TRY blocks to ensure that it will
eventually free the PGresult created by the remote modify command.
However, it's fundamentally impossible for this scheme to work
reliably when there's RETURNING data, because the query could fail
in between invocations of postgres_fdw's DirectModify methods.
There is at least one instance of exactly this situation in the
regression tests, and the ensuing session-lifespan leak is visible
under Valgrind.

We can improve matters by using a memory context reset callback
attached to the ExecutorState context.  That ensures that the
PGresult will be freed when the ExecutorState context is torn
down, even if control never reaches postgresEndDirectModify.

I have little faith that there aren't other potential PGresult
leakages in the backend modules that use libpq.  So I think it'd
be a good idea to apply this concept universally by creating
infrastructure that attaches a reset callback to every PGresult
generated in the backend.  However, that seems too invasive for
v18 at this point, let alone the back branches.  So for the
moment, apply this narrow fix that just makes DirectModify safe.
I have a patch in the queue for the more general idea, but it
will have to wait for v19.

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
Backpatch-through: 13
contrib/postgres_fdw/postgres_fdw.c