Skip to content

Commit b09caec

Browse files
committed
Fix potential memory leakage from HandleParallelMessages().
HandleParallelMessages leaked memory into the caller's context. Since it's called from ProcessInterrupts, there is basically zero certainty as to what CurrentMemoryContext is, which means we could be leaking into long-lived contexts. Over the processing of many worker messages that would grow to be a problem. Things could be even worse than just a leak, if we happened to service the interrupt while ErrorContext is current: elog.c thinks it can reset that on its own whim, possibly yanking storage out from under HandleParallelMessages. Give HandleParallelMessages its own dedicated context instead, which we can reset during each call to ensure there's no accumulation of wasted memory. Discussion: <16610.1472222135@sss.pgh.pa.us>
1 parent 51b5008 commit b09caec

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/backend/access/transam/parallel.c

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,9 @@ void
627627
HandleParallelMessages(void)
628628
{
629629
dlist_iter iter;
630+
MemoryContext oldcontext;
631+
632+
static MemoryContext hpm_context = NULL;
630633

631634
/*
632635
* This is invoked from ProcessInterrupts(), and since some of the
@@ -637,6 +640,23 @@ HandleParallelMessages(void)
637640
*/
638641
HOLD_INTERRUPTS();
639642

643+
/*
644+
* Moreover, CurrentMemoryContext might be pointing almost anywhere. We
645+
* don't want to risk leaking data into long-lived contexts, so let's do
646+
* our work here in a private context that we can reset on each use.
647+
*/
648+
if (hpm_context == NULL) /* first time through? */
649+
hpm_context = AllocSetContextCreate(TopMemoryContext,
650+
"HandleParallelMessages context",
651+
ALLOCSET_DEFAULT_MINSIZE,
652+
ALLOCSET_DEFAULT_INITSIZE,
653+
ALLOCSET_DEFAULT_MAXSIZE);
654+
else
655+
MemoryContextReset(hpm_context);
656+
657+
oldcontext = MemoryContextSwitchTo(hpm_context);
658+
659+
/* OK to process messages. Reset the flag saying there are more to do. */
640660
ParallelMessagePending = false;
641661

642662
dlist_foreach(iter, &pcxt_list)
@@ -683,6 +703,11 @@ HandleParallelMessages(void)
683703
}
684704
}
685705

706+
MemoryContextSwitchTo(oldcontext);
707+
708+
/* Might as well clear the context on our way out */
709+
MemoryContextReset(hpm_context);
710+
686711
RESUME_INTERRUPTS();
687712
}
688713

0 commit comments

Comments
 (0)