From dae5afa7a7e1a2f3c5ecdb8cf1c62d996860973b Mon Sep 17 00:00:00 2001
From: Joshua Shanks <jjshanks@gmail.com>
Date: Sat, 1 Nov 2025 14:22:42 -0700
Subject: [PATCH] Add error message for out-of-memory in passwordFromFile()

      When memory allocation fails while reading the password file,
      now reports a proper error message instead of silently returning NULL.

      To enable proper error reporting, added PGconn *conn parameter to
      passwordFromFile() function, following the pattern used by all other
      out-of-memory handlers in fe-connect.c which use libpq_append_conn_error().

      Addresses XXX comment in fe-connect.c at line 8064.
---
 src/interfaces/libpq/fe-connect.c | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/src/interfaces/libpq/fe-connect.c b/src/interfaces/libpq/fe-connect.c
index a3d12931fff..4f619f64275 100644
--- a/src/interfaces/libpq/fe-connect.c
+++ b/src/interfaces/libpq/fe-connect.c
@@ -501,8 +501,9 @@ static int	parseServiceFile(const char *serviceFile,
 							 PQExpBuffer errorMessage,
 							 bool *group_found);
 static char *pwdfMatchesString(char *buf, const char *token);
-static char *passwordFromFile(const char *hostname, const char *port, const char *dbname,
-							  const char *username, const char *pgpassfile);
+static char *passwordFromFile(PGconn *conn, const char *hostname, const char *port,
+							  const char *dbname, const char *username,
+							  const char *pgpassfile);
 static void pgpassfileWarning(PGconn *conn);
 static void default_threadlock(int acquire);
 static bool sslVerifyProtocolVersion(const char *version);
@@ -1459,7 +1460,8 @@ pqConnectOptions2(PGconn *conn)
 					pwhost = conn->connhost[i].hostaddr;
 
 				conn->connhost[i].password =
-					passwordFromFile(pwhost,
+					passwordFromFile(conn,
+									 pwhost,
 									 conn->connhost[i].port,
 									 conn->dbName,
 									 conn->pguser,
@@ -7944,8 +7946,9 @@ pwdfMatchesString(char *buf, const char *token)
 
 /* Get a password from the password file. Return value is malloc'd. */
 static char *
-passwordFromFile(const char *hostname, const char *port, const char *dbname,
-				 const char *username, const char *pgpassfile)
+passwordFromFile(PGconn *conn, const char *hostname, const char *port,
+				 const char *dbname, const char *username,
+				 const char *pgpassfile)
 {
 	FILE	   *fp;
 #ifndef WIN32
@@ -8058,7 +8061,7 @@ passwordFromFile(const char *hostname, const char *port, const char *dbname,
 
 				if (!ret)
 				{
-					/* Out of memory. XXX: an error message would be nice. */
+					libpq_append_conn_error(conn, "out of memory");
 					return NULL;
 				}
 
-- 
2.34.1

