From be80954688c406122b560161192cc1d2e64e3757 Mon Sep 17 00:00:00 2001
From: Andreas Seltenreich <seltenreich@gmx.de>
Date: Mon, 5 Dec 2016 20:46:28 +0100
Subject: [PATCH] Fix potential crash on ReScanGather.

Initialize gatherstate->nextreader to 0 in order to prevent a crash
when ReScanGather gets less workers than the original scan, leading to
nextreader pointing outside the readers[nworkers] array.
---
 src/backend/executor/nodeGather.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/src/backend/executor/nodeGather.c b/src/backend/executor/nodeGather.c
index 880ca62..2bdf223 100644
--- a/src/backend/executor/nodeGather.c
+++ b/src/backend/executor/nodeGather.c
@@ -173,6 +173,7 @@ ExecGather(GatherState *node)
 			if (pcxt->nworkers_launched > 0)
 			{
 				node->nreaders = 0;
+				node->nextreader = 0;
 				node->reader =
 					palloc(pcxt->nworkers_launched * sizeof(TupleQueueReader *));
 
@@ -335,6 +336,7 @@ gather_readnext(GatherState *gatherstate)
 		CHECK_FOR_INTERRUPTS();
 
 		/* Attempt to read a tuple, but don't block if none is available. */
+		Assert(gatherstate->nextreader < gatherstate->nreaders);
 		reader = gatherstate->reader[gatherstate->nextreader];
 		tup = TupleQueueReaderNext(reader, true, &readerdone);
 
-- 
2.10.2

