Skip to content

Commit c50596c

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 e46f6a0 commit c50596c

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

src/backend/commands/prepare.c

+11-7
Original file line numberDiff line numberDiff line change
@@ -234,6 +234,17 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause,
234234
cplan = GetCachedPlan(entry->plansource, paramLI, false);
235235
plan_list = cplan->stmt_list;
236236

237+
/*
238+
* DO NOT add any logic that could possibly throw an error between
239+
* GetCachedPlan and PortalDefineQuery, or you'll leak the plan refcount.
240+
*/
241+
PortalDefineQuery(portal,
242+
NULL,
243+
query_string,
244+
entry->plansource->commandTag,
245+
plan_list,
246+
cplan);
247+
237248
/*
238249
* For CREATE TABLE ... AS EXECUTE, we must verify that the prepared
239250
* statement is one that produces tuples. Currently we insist that it be
@@ -279,13 +290,6 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause,
279290
count = FETCH_ALL;
280291
}
281292

282-
PortalDefineQuery(portal,
283-
NULL,
284-
query_string,
285-
entry->plansource->commandTag,
286-
plan_list,
287-
cplan);
288-
289293
/*
290294
* Run the portal as appropriate.
291295
*/

0 commit comments

Comments
 (0)