Skip to content

Commit 9cf1632

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 c0a7587 commit 9cf1632

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
@@ -246,6 +246,17 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause,
246246
cplan = GetCachedPlan(entry->plansource, paramLI, false, NULL);
247247
plan_list = cplan->stmt_list;
248248

249+
/*
250+
* DO NOT add any logic that could possibly throw an error between
251+
* GetCachedPlan and PortalDefineQuery, or you'll leak the plan refcount.
252+
*/
253+
PortalDefineQuery(portal,
254+
NULL,
255+
query_string,
256+
entry->plansource->commandTag,
257+
plan_list,
258+
cplan);
259+
249260
/*
250261
* For CREATE TABLE ... AS EXECUTE, we must verify that the prepared
251262
* statement is one that produces tuples. Currently we insist that it be
@@ -289,13 +300,6 @@ ExecuteQuery(ExecuteStmt *stmt, IntoClause *intoClause,
289300
count = FETCH_ALL;
290301
}
291302

292-
PortalDefineQuery(portal,
293-
NULL,
294-
query_string,
295-
entry->plansource->commandTag,
296-
plan_list,
297-
cplan);
298-
299303
/*
300304
* Run the portal as appropriate.
301305
*/

0 commit comments

Comments
 (0)