From 68909d22bb58f2b11f53f423787bb2afa1f59c8a Mon Sep 17 00:00:00 2001
From: Tofig Aliev <t.aliev@postgrespro.ru>
Date: Tue, 21 Jul 2026 14:38:24 +0700
Subject: [PATCH] Add cleanup parsing contexts for pg_hba and pg_ident files.

Add proper cleanup for parsing contexts. Without this cleanup,
calling load_hba() or load_ident() in background processes
can cause undefined behavior.

Co-authored-by: Kirill Lukyanov <k.lukyanov@postgrespro.ru>
---
 src/backend/libpq/hba.c           | 27 +++++++++++++++++++++++----
 src/backend/postmaster/bgworker.c |  2 ++
 2 files changed, 25 insertions(+), 4 deletions(-)

diff --git a/src/backend/libpq/hba.c b/src/backend/libpq/hba.c
index d47eab2cba0..4f75abd3195 100644
--- a/src/backend/libpq/hba.c
+++ b/src/backend/libpq/hba.c
@@ -2437,6 +2437,26 @@ check_hba(Port *port)
 	port->hba = hba;
 }
 
+void
+DestroyParsedHbaContext(void)
+{
+	if (parsed_hba_context != NULL)
+	{
+		MemoryContextDelete(parsed_hba_context);
+		parsed_hba_context = NULL;
+	}
+}
+
+void
+DestroyParsedIdentContext(void)
+{
+	if (parsed_ident_context != NULL)
+	{
+		MemoryContextDelete(parsed_ident_context);
+		parsed_ident_context = NULL;
+	}
+}
+
 /*
  * Read the config file and create a List of HbaLine records for the contents.
  *
@@ -2531,8 +2551,8 @@ load_hba(void)
 	}
 
 	/* Loaded new file successfully, replace the one we use */
-	if (parsed_hba_context != NULL)
-		MemoryContextDelete(parsed_hba_context);
+	DestroyParsedHbaContext();
+
 	parsed_hba_context = hbacxt;
 	parsed_hba_lines = new_parsed_lines;
 
@@ -2912,8 +2932,7 @@ load_ident(void)
 	}
 
 	/* Loaded new file successfully, replace the one we use */
-	if (parsed_ident_context != NULL)
-		MemoryContextDelete(parsed_ident_context);
+	DestroyParsedIdentContext();
 
 	parsed_ident_context = ident_context;
 	parsed_ident_lines = new_parsed_lines;
diff --git a/src/backend/postmaster/bgworker.c b/src/backend/postmaster/bgworker.c
index f2cffce3ff6..84655427d76 100644
--- a/src/backend/postmaster/bgworker.c
+++ b/src/backend/postmaster/bgworker.c
@@ -756,6 +756,8 @@ BackgroundWorkerMain(const void *startup_data, size_t startup_data_len)
 	 */
 	if (PostmasterContext)
 	{
+		DestroyParsedHbaContext();
+		DestroyParsedIdentContext();
 		MemoryContextDelete(PostmasterContext);
 		PostmasterContext = NULL;
 	}
-- 
2.51.0

