Skip to content

Commit 131ea3e

Browse files
committed
Fix plancache refcount leak after error in ExecuteQuery.
When stuffing a plan from the plancache into a Portal, one is not supposed to risk throwing an error between GetCachedPlan and PortalDefineQuery; if that happens, the plan refcount incremented by GetCachedPlan will be leaked. I managed to break this rule while refactoring code in 9dbf2b7. There is no visible consequence other than some memory leakage, and since nobody is very likely to trigger the relevant error conditions many times in a row, it's not surprising we haven't noticed. Nonetheless, it's a bug, so rearrange the order of operations to remove the hazard. Noted on the way to looking for a better fix for bug #17053. This mistake is pretty old, so back-patch to all supported branches.
1 parent 99cea49 commit 131ea3e

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/backend/commands/prepare.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,17 @@ ExecuteQuery(ParseState *pstate,
233233
cplan = GetCachedPlan(entry->plansource, paramLI, NULL, NULL);
234234
plan_list = cplan->stmt_list;
235235

236+
/*
237+
* DO NOT add any logic that could possibly throw an error between
238+
* GetCachedPlan and PortalDefineQuery, or you'll leak the plan refcount.
239+
*/
240+
PortalDefineQuery(portal,
241+
NULL,
242+
query_string,
243+
entry->plansource->commandTag,
244+
plan_list,
245+
cplan);
246+
236247
/*
237248
* For CREATE TABLE ... AS EXECUTE, we must verify that the prepared
238249
* statement is one that produces tuples. Currently we insist that it be
@@ -276,13 +287,6 @@ ExecuteQuery(ParseState *pstate,
276287
count = FETCH_ALL;
277288
}
278289

279-
PortalDefineQuery(portal,
280-
NULL,
281-
query_string,
282-
entry->plansource->commandTag,
283-
plan_list,
284-
cplan);
285-
286290
/*
287291
* Run the portal as appropriate.
288292
*/

0 commit comments

Comments
 (0)