From 0f1a78411a195c1c51cabb158ca1b58858a12d99 Mon Sep 17 00:00:00 2001
From: Ian Ilyasov <ianilyasov@outlook.com>
Date: Tue, 29 Oct 2024 17:59:29 +0300
Subject: [PATCH] fix possible SIGSEGV situations on rubbish
 pg_control

uint32 for WalSegSz is crucial as xlog_seg_size in pg_control.h
is also uint32 and there could be situation when WalSegSz gets
a negative value and pg_controldata triggers FPE (division by zero):

((0x100000000UL) / (WalSegSz)) can turn into zero in

XLogFileName(xlogfilename, ControlFile->checkPointCopy.ThisTimeLineID,
				 segno, WalSegSz);

because if WalSegSz is -1 then by arithmetic rules in C we get
0x100000000UL / 0xFFFFFFFFFFFFFFFFUL == 0.
---
 src/bin/pg_controldata/pg_controldata.c | 28 ++++++++++++++++++++-----
 1 file changed, 23 insertions(+), 5 deletions(-)

diff --git a/src/bin/pg_controldata/pg_controldata.c b/src/bin/pg_controldata/pg_controldata.c
index e73639df744..1b7cbb03167 100644
--- a/src/bin/pg_controldata/pg_controldata.c
+++ b/src/bin/pg_controldata/pg_controldata.c
@@ -97,6 +97,7 @@ main(int argc, char *argv[])
 	bool		crc_ok;
 	char	   *DataDir = NULL;
 	time_t		time_tmp;
+	struct tm  *tm_tmp;
 	char		pgctime_str[128];
 	char		ckpttime_str[128];
 	char		mock_auth_nonce_str[MOCK_AUTH_NONCE_LEN * 2 + 1];
@@ -105,7 +106,7 @@ main(int argc, char *argv[])
 	char		xlogfilename[MAXFNAMELEN];
 	int			c;
 	int			i;
-	int			WalSegSz;
+	uint32			WalSegSz;
 
 	pg_logging_init(argv[0]);
 	set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_controldata"));
@@ -177,10 +178,10 @@ main(int argc, char *argv[])
 	if (!IsValidWalSegSize(WalSegSz))
 	{
 		printf(_("WARNING: invalid WAL segment size\n"));
-		printf(ngettext("The WAL segment size stored in the file, %d byte, is not a power of two\n"
+		printf(ngettext("The WAL segment size stored in the file, %u byte, is not a power of two\n"
 						"between 1 MB and 1 GB.  The file is corrupt and the results below are\n"
 						"untrustworthy.\n\n",
-						"The WAL segment size stored in the file, %d bytes, is not a power of two\n"
+						"The WAL segment size stored in the file, %u bytes, is not a power of two\n"
 						"between 1 MB and 1 GB.  The file is corrupt and the results below are\n"
 						"untrustworthy.\n\n",
 						WalSegSz),
@@ -197,11 +198,28 @@ main(int argc, char *argv[])
 	 * about %c
 	 */
 	time_tmp = (time_t) ControlFile->time;
+	tm_tmp = localtime(&time_tmp);
+
+	if (tm_tmp == NULL)
+	{
+		pg_log_error("timestamp is corrupted");
+		exit(1);
+	}
+
 	strftime(pgctime_str, sizeof(pgctime_str), strftime_fmt,
-			 localtime(&time_tmp));
+			 tm_tmp);
+
 	time_tmp = (time_t) ControlFile->checkPointCopy.time;
+	tm_tmp = localtime(&time_tmp);
+
+	if (tm_tmp == NULL)
+	{
+		pg_log_error("timestamp is corrupted");
+		exit(1);
+	}
+
 	strftime(ckpttime_str, sizeof(ckpttime_str), strftime_fmt,
-			 localtime(&time_tmp));
+			 tm_tmp);
 
 	/*
 	 * Calculate name of the WAL file containing the latest checkpoint's REDO
-- 
2.39.5

