Skip to content

Commit ca4c676

Browse files
committed
pg_stat_statements: fetch stmt location/length before it disappears.
When executing a utility statement, we must fetch everything we need out of the PlannedStmt data structure before calling standard_ProcessUtility. In certain cases (possibly only ROLLBACK in extended query protocol), that data structure will get freed during command execution. The situation is probably often harmless in production builds, but in debug builds we intentionally overwrite the freed memory with garbage, leading to picking up garbage values of statement location and length, typically causing an assertion failure later in pg_stat_statements. In non-debug builds, if something did go wrong it would likely lead to storing garbage for the query string. Report and fix by zhaoqigui (with cosmetic adjustments by me). It's an old problem, so back-patch to all supported versions. Discussion: https://postgr.es/m/17663-a344fd0675f92128@postgresql.org Discussion: https://postgr.es/m/1667307420050.56657@hundsun.com
1 parent 51c24d9 commit ca4c676

File tree

1 file changed

+11
-2
lines changed

1 file changed

+11
-2
lines changed

contrib/pg_stat_statements/pg_stat_statements.c

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -966,6 +966,8 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
966966
DestReceiver *dest, char *completionTag)
967967
{
968968
Node *parsetree = pstmt->utilityStmt;
969+
int saved_stmt_location = pstmt->stmt_location;
970+
int saved_stmt_len = pstmt->stmt_len;
969971

970972
/*
971973
* If it's an EXECUTE statement, we don't track it and don't increment the
@@ -1015,6 +1017,13 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
10151017
}
10161018
PG_END_TRY();
10171019

1020+
/*
1021+
* CAUTION: do not access the *pstmt data structure again below here.
1022+
* If it was a ROLLBACK or similar, that data structure may have been
1023+
* freed. We must copy everything we still need into local variables,
1024+
* which we did above.
1025+
*/
1026+
10181027
INSTR_TIME_SET_CURRENT(duration);
10191028
INSTR_TIME_SUBTRACT(duration, start);
10201029

@@ -1053,8 +1062,8 @@ pgss_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
10531062

10541063
pgss_store(queryString,
10551064
0, /* signal that it's a utility stmt */
1056-
pstmt->stmt_location,
1057-
pstmt->stmt_len,
1065+
saved_stmt_location,
1066+
saved_stmt_len,
10581067
INSTR_TIME_GET_MILLISEC(duration),
10591068
rows,
10601069
&bufusage,

0 commit comments

Comments
 (0)