From 5eaca7af9a228ac5a675877362ca3be382e11431 Mon Sep 17 00:00:00 2001
From: Onur Tirtir <onurcantirtir@gmail.com>
Date: Tue, 31 Jan 2023 15:40:49 +0300
Subject: [PATCH v1] Report the query string that caused a memory error

If we run multiple queries under Valgrind, it becomes quite hard to
understand which query caused a memory error by looking into the stack
traces that Valgrind reported.

For this reason, this patch introduces some changes to
exec_simple_query() to report the queries that cause memory errors. At
the high-level:
* We compare number of memory errors reported by Valgrind before and
  after this query-run by using VALGRIND_COUNT_ERRORS macro provided in
  valgrind.h.
* If the query caused a memory error, then we report this query to
  Valgrind log file (right after the relevant stack trace) by using
  VALGRIND_PRINTF macro provided in valgrind.h.
---
 src/backend/tcop/postgres.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/tcop/postgres.c b/src/backend/tcop/postgres.c
index 470b734e9e..e0032165ae 100644
--- a/src/backend/tcop/postgres.c
+++ b/src/backend/tcop/postgres.c
@@ -73,6 +73,9 @@
 #include "utils/snapmgr.h"
 #include "utils/timeout.h"
 #include "utils/timestamp.h"
+#ifdef USE_VALGRIND
+#include <valgrind/valgrind.h>
+#endif
 
 /* ----------------
  *		global variables
@@ -986,6 +989,9 @@ exec_simple_query(const char *query_string)
 	bool		was_logged = false;
 	bool		use_implicit_block;
 	char		msec_str[32];
+#ifdef USE_VALGRIND
+	unsigned	valgrind_errors_before_query = VALGRIND_COUNT_ERRORS;
+#endif
 
 	/*
 	 * Report query to various monitoring facilities.
@@ -1343,6 +1349,15 @@ exec_simple_query(const char *query_string)
 	TRACE_POSTGRESQL_QUERY_DONE(query_string);
 
 	debug_query_string = NULL;
+
+#ifdef USE_VALGRIND
+	if (VALGRIND_COUNT_ERRORS > valgrind_errors_before_query)
+	{
+		VALGRIND_PRINTF("The query for which valgrind reported a "
+						"memory error was: %s\n",
+						query_string);
+	}
+#endif
 }
 
 /*
-- 
2.25.1

