Skip to content

Commit ce5aaea

Browse files
committed
Fix oversight in handling of modifiedCols since f245236
Commit f245236 fixed a memory leak by moving the modifiedCols bitmap into the per-row memory context. In the case of AFTER UPDATE triggers, the bitmap is however referenced from an event kept until the end of the query, resulting in a use-after-free bug. Fixed by copying the bitmap into the AfterTriggerEvents memory context, which is the one where we keep the trigger events. There's only one place that needs to do the copy, but the memory context may not exist yet. Doing that in a separate function seems more readable. Report by Alexander Pyhalov, fix by me. Backpatch to 13, where the bitmap was added to the event by commit 71d60e2. Reported-by: Alexander Pyhalov Backpatch-through: 13 Discussion: https://postgr.es/m/acddb17c89b0d6cb940eaeda18c08bbe@postgrespro.ru
1 parent 98640f9 commit ce5aaea

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

src/backend/commands/trigger.c

+32-1
Original file line numberDiff line numberDiff line change
@@ -3976,6 +3976,37 @@ afterTriggerCheckState(AfterTriggerShared evtshared)
39763976
return ((evtshared->ats_event & AFTER_TRIGGER_INITDEFERRED) != 0);
39773977
}
39783978

3979+
/* ----------
3980+
* afterTriggerCopyBitmap()
3981+
*
3982+
* Copy bitmap into AfterTriggerEvents memory context, which is where the after
3983+
* trigger events are kept.
3984+
* ----------
3985+
*/
3986+
static Bitmapset *
3987+
afterTriggerCopyBitmap(Bitmapset *src)
3988+
{
3989+
Bitmapset *dst;
3990+
MemoryContext oldcxt;
3991+
3992+
if (src == NULL)
3993+
return NULL;
3994+
3995+
/* Create event context if we didn't already */
3996+
if (afterTriggers.event_cxt == NULL)
3997+
afterTriggers.event_cxt =
3998+
AllocSetContextCreate(TopTransactionContext,
3999+
"AfterTriggerEvents",
4000+
ALLOCSET_DEFAULT_SIZES);
4001+
4002+
oldcxt = MemoryContextSwitchTo(afterTriggers.event_cxt);
4003+
4004+
dst = bms_copy(src);
4005+
4006+
MemoryContextSwitchTo(oldcxt);
4007+
4008+
return dst;
4009+
}
39794010

39804011
/* ----------
39814012
* afterTriggerAddEvent()
@@ -6387,7 +6418,7 @@ AfterTriggerSaveEvent(EState *estate, ResultRelInfo *relinfo,
63876418
new_shared.ats_table = transition_capture->tcs_private;
63886419
else
63896420
new_shared.ats_table = NULL;
6390-
new_shared.ats_modifiedcols = modifiedCols;
6421+
new_shared.ats_modifiedcols = afterTriggerCopyBitmap(modifiedCols);
63916422

63926423
afterTriggerAddEvent(&afterTriggers.query_stack[afterTriggers.query_depth].events,
63936424
&new_event, &new_shared);

0 commit comments

Comments
 (0)