pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedFix unsafe coding in ResourceOwnerReleaseAll()
7+ messages / 3 participants
[nested] [flat]
Commits from this thread:
2026-06-22 ef01ca6dbc ac6a58a700 011eedcdc3 Fix unsafe order of operations in ResourceOwnerReleaseAll().
* Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-06-22 19:45 Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 7+ messages in thread
From: Tom Lane @ 2026-06-22 19:45 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org; +Cc: Heikki Linnakangas <hlinnaka@iki.fi>
I wondered why the example shown in [1] led to a double-free crash
rather than a clean failure. On investigation, the problem is that
ResourceOwnerReleaseAll() calls the resource kind's ReleaseResource
method before deleting the resource from the owner, rather than
afterwards as the code in ResourceOwnerReleaseAllOfKind() does.
So if we throw an error inside ReleaseResource, the subsequent abort
cleanup comes back and does resource owner cleanup again, and we
try to delete the item again. Kaboom.
The attached patch converts the bug example into a clean failure,
even with the recent bug fix in pgcrypto undone:
regression=# SELECT encrypt_iv(
repeat('A', 1073741308)::bytea,
decode('00112233445566778899aabbccddeeff', 'hex'),
decode('000102030405060708090a0b0c0d0e0f', 'hex'),
'aes'
);
ERROR: invalid memory alloc request size 1073741824
WARNING: AbortTransaction while in ABORT state
ERROR: ResourceOwnerForget called for pgcrypto OpenSSL cipher handle after release started
regression=#
Of course, this might lead to leaking the resource we wished to free.
But that's better than crashing, or at least that's the value judgment
we made long ago in the original ResourceOwner code.
regards, tom lane
[1] https://www.postgresql.org/message-id/19527-6e7686960c6dce78%40postgresql.org
Attachments:
make-ResourceOwnerReleaseAll-safer.patch (text/x-diff, 1.4K) download
diff --git a/src/backend/utils/resowner/resowner.c b/src/backend/utils/resowner/resowner.c
index 06e1121c5ff..03d2f5a0334 100644
--- a/src/backend/utils/resowner/resowner.c
+++ b/src/backend/utils/resowner/resowner.c
@@ -347,6 +347,7 @@ ResourceOwnerReleaseAll(ResourceOwner owner, ResourceReleasePhase phase,
{
ResourceElem *items;
uint32 nitems;
+ bool using_arr;
/*
* ResourceOwnerSort must've been called already. All the resources are
@@ -358,12 +359,14 @@ ResourceOwnerReleaseAll(ResourceOwner owner, ResourceReleasePhase phase,
{
items = owner->arr;
nitems = owner->narr;
+ using_arr = true;
}
else
{
Assert(owner->narr == 0);
items = owner->hash;
nitems = owner->nhash;
+ using_arr = false;
}
/*
@@ -392,13 +395,20 @@ ResourceOwnerReleaseAll(ResourceOwner owner, ResourceReleasePhase phase,
elog(WARNING, "resource was not closed: %s", res_str);
pfree(res_str);
}
- kind->ReleaseResource(value);
+
+ /*
+ * Update stored count to forget the item before calling its
+ * ReleaseResource method. This avoids double-free crashes in case an
+ * error gets thrown within ReleaseResource.
+ */
nitems--;
+ if (using_arr)
+ owner->narr = nitems;
+ else
+ owner->nhash = nitems;
+
+ kind->ReleaseResource(value);
}
- if (owner->nhash == 0)
- owner->narr = nitems;
- else
- owner->nhash = nitems;
}
=
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-06-25 04:49 Rahila Syed <rahilasyed90@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 7+ messages in thread
From: Rahila Syed @ 2026-06-25 04:49 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers@lists.postgresql.org, Heikki Linnakangas <hlinnaka@iki.fi>
Hi Tom,
Thank you for proposing this change.
>
> Of course, this might lead to leaking the resource we wished to free.
> But that's better than crashing, or at least that's the value judgment
> we made long ago in the original ResourceOwner code.
>
Another approach would be to remove the resource from the resource
owner's list directly within the ResourceRelease callbacks, just
before the resource is released.
This makes the fix specific to a resource type rather than applying it
across all resource types. This would be similar to how it's done in
ReleaseCatCacheWithOwner.
That said, the patch looks good because it makes the code consistent
with ResourceOwnerReleaseAllOfKind() and avoids the crash.
Unrelated to the patch but I noticed a typo in the ERROR message in
ResourceOwnerReleaseAllOfKind(). If we
want a check similar to ResourceOwnerForget in this function, we
should edit the ERROR message with the correct
function name.
I can propose a patch for this in a separate thread, if you'd prefer.
The error message is as follows:
> void
> ResourceOwnerReleaseAllOfKind(ResourceOwner owner, const ResourceOwnerDesc *kind)
> {
> /* Mustn't call this after we have already started releasing resources. */
> if (owner->releasing)
> elog(ERROR, "ResourceOwnerForget called for %s after release started", kind->name);
Thank you,
Rahila Syed
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-06-25 05:15 Tom Lane <tgl@sss.pgh.pa.us>
parent: Rahila Syed <rahilasyed90@gmail.com>
0 siblings, 1 reply; 7+ messages in thread
From: Tom Lane @ 2026-06-25 05:15 UTC (permalink / raw)
To: Rahila Syed <rahilasyed90@gmail.com>; +Cc: pgsql-hackers@lists.postgresql.org, Heikki Linnakangas <hlinnaka@iki.fi>
Rahila Syed <rahilasyed90@gmail.com> writes:
> Unrelated to the patch but I noticed a typo in the ERROR message in
> ResourceOwnerReleaseAllOfKind().
>> /* Mustn't call this after we have already started releasing resources. */
>> if (owner->releasing)
>> elog(ERROR, "ResourceOwnerForget called for %s after release started", kind->name);
Hmm, that definitely looks like a message that was transposed from
someplace else without much thought. It might be worth tracing the
git history to see how it got to be like that.
More: unless I'm missing something, ResourceOwnerReleaseAllOfKind
is called only from plancache.c's ReleaseAllPlanCacheRefsInOwner,
which is called only in some very random-looking ways in plpgsql.
I wonder whether there's not a bigger cleanup project indicated here.
When I posted before, I thought that ResourceOwnerReleaseAllOfKind had
a direct lineage to the old ResourceOwner code, but now I'm thinking
maybe it shouldn't exist at all. Why should plpgsql be taking special
care for particular kinds of resource entries, and why should it
suppose that it owns all instances of that kind within that resowner?
regards, tom lane
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-08-12 08:27 Rahila Syed <rahilasyed90@gmail.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 7+ messages in thread
From: Rahila Syed @ 2026-08-12 08:27 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers@lists.postgresql.org, Heikki Linnakangas <hlinnaka@iki.fi>
Hi,
>
> More: unless I'm missing something, ResourceOwnerReleaseAllOfKind
> is called only from plancache.c's ReleaseAllPlanCacheRefsInOwner,
> which is called only in some very random-looking ways in plpgsql.
> I wonder whether there's not a bigger cleanup project indicated here.
> When I posted before, I thought that ResourceOwnerReleaseAllOfKind had
> a direct lineage to the old ResourceOwner code, but now I'm thinking
> maybe it shouldn't exist at all. Why should plpgsql be taking special
> care for particular kinds of resource entries, and why should it
> suppose that it owns all instances of that kind within that resowner?
>
I agree that ResourceOwnerReleaseAllOfKind can be removed
After digging into the resource owner code, it looks like a reason for
having the ResourceOwnerReleaseAllOfKind variant is to allow releasing
all of an owner's resources without going through the three-phase
release mechanism that ResourceOwnerRelease normally enforces
(BEFORE_LOCKS -> LOCKS -> AFTER_LOCKS). That phase ordering isn't
needed if a resource owner only ever holds one kind of resource and
has no children holding other kinds.
The resource owners that ResourceOwnerReleaseAllOfKind is actually
called on (plpgsql's procedure-lifespan owner, the DO-block
simple-expression owner, and the shared simple-expression owner) are
all created specifically to retain resources across transaction
COMMIT/ROLLBACK boundaries. In practice they only ever hold plan-cache
refcounts, so a three-phase release is not required for them. These
owners are deleted immediately after the ResourceOwnerReleaseAllOfKind
call, which shows the intent at each call site is "release everything
this owner holds," rather than to "release only resources of this one
kind."
I tested this by replacing all four call sites with three explicit
ResourceOwnerRelease() calls (one per phase) instead of the single
ResourceOwnerReleaseAllOfKind() call. This passes the plpgsql tests
and the regression suite without crashes or assertion failures. (patch
attached).
The drawback with this approach is that it takes three calls to
release the owners.
Since plan-cache refs are registered at RESOURCE_RELEASE_AFTER_LOCKS,
the BEFORE_LOCKS and LOCKS calls are no-ops for these owners, but are
still required to satisfy ResourceOwnerRelease's internal
phase-ordering assertions.
One possible refactoring: pass a flag to ResourceOwnerRelease (or
ResourceOwnerReleaseAll) indicating it does not need to respect phase
ordering and can just release everything the owner holds in one pass.
That would let a caller drain a standalone, single-kind owner in one
call instead of three.
If we had that, I don't think we would need
ResourceOwnerReleaseAllOfKind — unless a future use case requires
releasing resources of one particular kind from an owner that contains
different kinds of resources or has children holding different kinds
of resources belonging to different phases.
Removing ResourceOwnerReleaseAllOfKind will also help get rid of one
of the flags
"releasing" or "sorted" in ResourceOwnerData.
Thank you,
Rahila Syed
Attachments:
0001-Replace-ReleaseAllPlanCacheRefsInOwner-calls-with-ex.patch (application/octet-stream, 4.4K) download
From f86de31f76790df40a0072dea65f79fe67adc338 Mon Sep 17 00:00:00 2001
From: rahila <rahilasyed.90@gmail.com>
Date: Wed, 12 Aug 2026 15:57:59 +0800
Subject: [PATCH] Replace ReleaseAllPlanCacheRefsInOwner calls with explicit
ResourceOwnerRelease phases in plpgsql
plpgsql keeps three detached ResourceOwners (the procedure-lifespan
owner used for top-level CALLs, the DO-block simple-expression owner,
and the shared simple-expression owner) that must survive internal
COMMIT/ROLLBACK inside a procedure or DO block. Each of them only
ever accumulates plan-cache refcounts, so they were drained via
ResourceOwnerReleaseAllOfKind() in ReleaseAllPlanCacheRefsInOwner()
before being deleted or reset.
This replaces those four call sites with direct calls to the public
ResourceOwnerRelease(), once per release phase (BEFORE_LOCKS, LOCKS,
AFTER_LOCKS), so the same plan-cache refcounts are released without
going through the single-kind function.
isCommit is passed as false at each call site. ResourceOwnerRelease()
overloads isCommit as the "print leak warnings" flag for resources
still remembered when a phase runs; since these owners are expected to
be holding a live plan-cache reference at this point (that is the
resource being intentionally released here, not a leak), isCommit=true
makes every one of these releases emit a spurious "resource was not
closed" WARNING, which is visible to clients and breaks the plpgsql
regression tests' expected output. isCommit=false suppresses that
warning path.
"make check" in src/pl/plpgsql and the full regression suite both pass
with no crashes or assertion failures.
---
src/pl/plpgsql/src/pl_exec.c | 6 +++++-
src/pl/plpgsql/src/pl_handler.c | 12 +++++++++---
2 files changed, 14 insertions(+), 4 deletions(-)
diff --git a/src/pl/plpgsql/src/pl_exec.c b/src/pl/plpgsql/src/pl_exec.c
index 341beb496b..a328d5199d 100644
--- a/src/pl/plpgsql/src/pl_exec.c
+++ b/src/pl/plpgsql/src/pl_exec.c
@@ -8838,7 +8838,11 @@ plpgsql_xact_cb(XactEvent event, void *arg)
FreeExecutorState(shared_simple_eval_estate);
shared_simple_eval_estate = NULL;
if (shared_simple_eval_resowner)
- ReleaseAllPlanCacheRefsInOwner(shared_simple_eval_resowner);
+ {
+ ResourceOwnerRelease(shared_simple_eval_resowner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true);
+ ResourceOwnerRelease(shared_simple_eval_resowner, RESOURCE_RELEASE_LOCKS, false, true);
+ ResourceOwnerRelease(shared_simple_eval_resowner, RESOURCE_RELEASE_AFTER_LOCKS, false, true);
+ }
shared_simple_eval_resowner = NULL;
}
else if (event == XACT_EVENT_ABORT ||
diff --git a/src/pl/plpgsql/src/pl_handler.c b/src/pl/plpgsql/src/pl_handler.c
index 3055c3db5d..0404f1b26a 100644
--- a/src/pl/plpgsql/src/pl_handler.c
+++ b/src/pl/plpgsql/src/pl_handler.c
@@ -289,7 +289,9 @@ plpgsql_call_handler(PG_FUNCTION_ARGS)
/* Be sure to release the procedure resowner if any */
if (procedure_resowner)
{
- ReleaseAllPlanCacheRefsInOwner(procedure_resowner);
+ ResourceOwnerRelease(procedure_resowner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true);
+ ResourceOwnerRelease(procedure_resowner, RESOURCE_RELEASE_LOCKS, false, true);
+ ResourceOwnerRelease(procedure_resowner, RESOURCE_RELEASE_AFTER_LOCKS, false, true);
ResourceOwnerDelete(procedure_resowner);
}
}
@@ -393,7 +395,9 @@ plpgsql_inline_handler(PG_FUNCTION_ARGS)
/* Clean up the private EState and resowner */
FreeExecutorState(simple_eval_estate);
- ReleaseAllPlanCacheRefsInOwner(simple_eval_resowner);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_LOCKS, false, true);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_AFTER_LOCKS, false, true);
ResourceOwnerDelete(simple_eval_resowner);
/* Function should now have no remaining use-counts ... */
@@ -410,7 +414,9 @@ plpgsql_inline_handler(PG_FUNCTION_ARGS)
/* Clean up the private EState and resowner */
FreeExecutorState(simple_eval_estate);
- ReleaseAllPlanCacheRefsInOwner(simple_eval_resowner);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_BEFORE_LOCKS, false, true);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_LOCKS, false, true);
+ ResourceOwnerRelease(simple_eval_resowner, RESOURCE_RELEASE_AFTER_LOCKS, false, true);
ResourceOwnerDelete(simple_eval_resowner);
/* Function should now have no remaining use-counts ... */
--
2.39.5 (Apple Git-154)
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-08-13 12:34 Heikki Linnakangas <hlinnaka@iki.fi>
parent: Rahila Syed <rahilasyed90@gmail.com>
0 siblings, 1 reply; 7+ messages in thread
From: Heikki Linnakangas @ 2026-08-13 12:34 UTC (permalink / raw)
To: Rahila Syed <rahilasyed90@gmail.com>; Tom Lane <tgl@sss.pgh.pa.us>; +Cc: pgsql-hackers@lists.postgresql.org
On 12/08/2026 11:27, Rahila Syed wrote:
>> More: unless I'm missing something, ResourceOwnerReleaseAllOfKind
>> is called only from plancache.c's ReleaseAllPlanCacheRefsInOwner,
>> which is called only in some very random-looking ways in plpgsql.
>> I wonder whether there's not a bigger cleanup project indicated here.
>> When I posted before, I thought that ResourceOwnerReleaseAllOfKind had
>> a direct lineage to the old ResourceOwner code, but now I'm thinking
>> maybe it shouldn't exist at all. Why should plpgsql be taking special
>> care for particular kinds of resource entries, and why should it
>> suppose that it owns all instances of that kind within that resowner?
>
> I agree that ResourceOwnerReleaseAllOfKind can be removed
>
> After digging into the resource owner code, it looks like a reason for
> having the ResourceOwnerReleaseAllOfKind variant is to allow releasing
> all of an owner's resources without going through the three-phase
> release mechanism that ResourceOwnerRelease normally enforces
> (BEFORE_LOCKS -> LOCKS -> AFTER_LOCKS). That phase ordering isn't
> needed if a resource owner only ever holds one kind of resource and
> has no children holding other kinds.
>
> The resource owners that ResourceOwnerReleaseAllOfKind is actually
> called on (plpgsql's procedure-lifespan owner, the DO-block
> simple-expression owner, and the shared simple-expression owner) are
> all created specifically to retain resources across transaction
> COMMIT/ROLLBACK boundaries. In practice they only ever hold plan-cache
> refcounts, so a three-phase release is not required for them. These
> owners are deleted immediately after the ResourceOwnerReleaseAllOfKind
> call, which shows the intent at each call site is "release everything
> this owner holds," rather than to "release only resources of this one
> kind."
>
> I tested this by replacing all four call sites with three explicit
> ResourceOwnerRelease() calls (one per phase) instead of the single
> ResourceOwnerReleaseAllOfKind() call. This passes the plpgsql tests
> and the regression suite without crashes or assertion failures. (patch
> attached).
> The drawback with this approach is that it takes three calls to
> release the owners.
> Since plan-cache refs are registered at RESOURCE_RELEASE_AFTER_LOCKS,
> the BEFORE_LOCKS and LOCKS calls are no-ops for these owners, but are
> still required to satisfy ResourceOwnerRelease's internal
> phase-ordering assertions.
>
> One possible refactoring: pass a flag to ResourceOwnerRelease (or
> ResourceOwnerReleaseAll) indicating it does not need to respect phase
> ordering and can just release everything the owner holds in one pass.
> That would let a caller drain a standalone, single-kind owner in one
> call instead of three.
+1 for having a function that just releases all resources in a resource
owner in one call. I don't think it's performance critical so it could
just call ResourceOwnerRelease() three times.
ReleaseAuxProcessResources() could make use of it too.
> If we had that, I don't think we would need
> ResourceOwnerReleaseAllOfKind — unless a future use case requires
> releasing resources of one particular kind from an owner that contains
> different kinds of resources or has children holding different kinds
> of resources belonging to different phases.
+1 for removing it. I hope we don't need it in the future, it feels like
a ugly wart in the first place.
> Removing ResourceOwnerReleaseAllOfKind will also help get rid of one
> of the flags "releasing" or "sorted" in ResourceOwnerData.
You still need those flags when you release in phases. I don't see us
getting rid of the three phases in the usual transaction-scoped resource
owners any time soon, even if some resource owners don't need them.
- Heikki
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-08-27 17:52 Rahila Syed <rahilasyed90@gmail.com>
parent: Heikki Linnakangas <hlinnaka@iki.fi>
0 siblings, 1 reply; 7+ messages in thread
From: Rahila Syed @ 2026-08-27 17:52 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org
Hi,
> +1 for having a function that just releases all resources in a resource
> owner in one call. I don't think it's performance critical so it could
> just call ResourceOwnerRelease() three times.
> ReleaseAuxProcessResources() could make use of it too.
>
Thank you for the feedback. I am working on a patch for this and will
post it soon.
>
> > Removing ResourceOwnerReleaseAllOfKind will also help get rid of one
> > of the flags "releasing" or "sorted" in ResourceOwnerData.
>
> You still need those flags when you release in phases. I don't see us
> getting rid of the three phases in the usual transaction-scoped resource
> owners any time soon, even if some resource owners don't need them.
>
We do need one of these flags, but not both, for phased release to work.
I don't see any occurrence of these flags where one is true and the
other is false
except for the ResourceOwnerReleaseAllOfKind() function.
Both flags are set simultaneously when entering the release phase.
The following comment in ResourceOwnerData also shows that we have
separate flags only
due to the ResourceOwnerReleaseAllOfKind() function.
* We have separate flags because
* ResourceOwnerReleaseAllOfKind() temporarily sets 'releasing' without
* sorting the arrays.
Thank you,
Rahila Syed
^ permalink raw reply [nested|flat] 7+ messages in thread
* Re: Fix unsafe coding in ResourceOwnerReleaseAll()
@ 2026-09-11 09:05 Rahila Syed <rahilasyed90@gmail.com>
parent: Rahila Syed <rahilasyed90@gmail.com>
0 siblings, 0 replies; 7+ messages in thread
From: Rahila Syed @ 2026-09-11 09:05 UTC (permalink / raw)
To: Heikki Linnakangas <hlinnaka@iki.fi>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers@lists.postgresql.org
Hi,
> Hi,
>
> > +1 for having a function that just releases all resources in a resource
> > owner in one call. I don't think it's performance critical so it could
> > just call ResourceOwnerRelease() three times.
> > ReleaseAuxProcessResources() could make use of it too.
> >
>
> Thank you for the feedback. I am working on a patch for this and will
> post it soon.
>
While I agree that calling ResourceOwnerRelease() three times results
in a patch with minimal changes to existing logic, I think it is worth avoiding
the unneces calls to simplify the code.
Hence, I added another phase to the ResourceReleasePhase which
bypasses the phased release in the existing
ResourceOwnerRelease function. This allows us to maintain the existing function
signature for both phased and non-phased resource release.
This is similar to what NoLock does in the case of LOCKMODE.
A separate thread for this discussion with a patch has been started
here [1] as it
has branched off from the original proposal in this thread.
[1] https://www.postgresql.org/message-id/CAH2L28vVo-Q3Jf%2BP4huRKxjnbF%2B2t7OdDh3ZGMxL88hiWezd%3DA%40ma...
Thank you,
Rahila Syed
^ permalink raw reply [nested|flat] 7+ messages in thread
end of thread, other threads:[~2026-09-11 09:05 UTC | newest]
Thread overview: 7+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-06-22 19:45 Fix unsafe coding in ResourceOwnerReleaseAll() Tom Lane <tgl@sss.pgh.pa.us>
2026-06-25 04:49 ` Rahila Syed <rahilasyed90@gmail.com>
2026-06-25 05:15 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-08-12 08:27 ` Rahila Syed <rahilasyed90@gmail.com>
2026-08-13 12:34 ` Heikki Linnakangas <hlinnaka@iki.fi>
2026-08-27 17:52 ` Rahila Syed <rahilasyed90@gmail.com>
2026-09-11 09:05 ` Rahila Syed <rahilasyed90@gmail.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox