diff options
author | Tom Lane <tgl@sss.pgh.pa.us> | 2021-10-01 11:10:12 -0400 |
---|---|---|
committer | Tom Lane <tgl@sss.pgh.pa.us> | 2021-10-01 11:10:12 -0400 |
commit | 7b5d4c29ed0262e537026cb3a85161d6cf98abcc (patch) | |
tree | c22377b3b39ed1955ac6b663d84d2c04a14b82ca /src/backend/utils/time/snapmgr.c | |
parent | 2d44dee0281a1abf0dcb1548c910fae067f1d34d (diff) | |
download | postgresql-7b5d4c29ed0262e537026cb3a85161d6cf98abcc.tar.gz postgresql-7b5d4c29ed0262e537026cb3a85161d6cf98abcc.zip |
Fix Portal snapshot tracking to handle subtransactions properly.
Commit 84f5c2908 forgot to consider the possibility that
EnsurePortalSnapshotExists could run inside a subtransaction with
lifespan shorter than the Portal's. In that case, the new active
snapshot would be popped at the end of the subtransaction, leaving
a dangling pointer in the Portal, with mayhem ensuing.
To fix, make sure the ActiveSnapshot stack entry is marked with
the same subtransaction nesting level as the associated Portal.
It's certainly safe to do so since we won't be here at all unless
the stack is empty; hence we can't create an out-of-order stack.
Let's also apply this logic in the case where PortalRunUtility
sets portalSnapshot, just to be sure that path can't cause similar
problems. It's slightly less clear that that path can't create
an out-of-order stack, so add an assertion guarding it.
Report and patch by Bertrand Drouvot (with kibitzing by me).
Back-patch to v11, like the previous commit.
Discussion: https://postgr.es/m/ff82b8c5-77f4-3fe7-6028-fcf3303e82dd@amazon.com
Diffstat (limited to 'src/backend/utils/time/snapmgr.c')
-rw-r--r-- | src/backend/utils/time/snapmgr.c | 17 |
1 files changed, 16 insertions, 1 deletions
diff --git a/src/backend/utils/time/snapmgr.c b/src/backend/utils/time/snapmgr.c index 2968c7f7b7d..dca1bc8afca 100644 --- a/src/backend/utils/time/snapmgr.c +++ b/src/backend/utils/time/snapmgr.c @@ -679,9 +679,24 @@ FreeSnapshot(Snapshot snapshot) void PushActiveSnapshot(Snapshot snap) { + PushActiveSnapshotWithLevel(snap, GetCurrentTransactionNestLevel()); +} + +/* + * PushActiveSnapshotWithLevel + * Set the given snapshot as the current active snapshot + * + * Same as PushActiveSnapshot except that caller can specify the + * transaction nesting level that "owns" the snapshot. This level + * must not be deeper than the current top of the snapshot stack. + */ +void +PushActiveSnapshotWithLevel(Snapshot snap, int snap_level) +{ ActiveSnapshotElt *newactive; Assert(snap != InvalidSnapshot); + Assert(ActiveSnapshot == NULL || snap_level >= ActiveSnapshot->as_level); newactive = MemoryContextAlloc(TopTransactionContext, sizeof(ActiveSnapshotElt)); @@ -695,7 +710,7 @@ PushActiveSnapshot(Snapshot snap) newactive->as_snap = snap; newactive->as_next = ActiveSnapshot; - newactive->as_level = GetCurrentTransactionNestLevel(); + newactive->as_level = snap_level; newactive->as_snap->active_count++; |