From: Tom Lane <tgl@sss.pgh.pa.us>
Date: Sat, 6 Jul 2019 15:25:37 +0000 (-0400)
Subject: In pg_log_generic(), be more paranoid about preserving errno.
X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=fb30c9c1c5c36989d6b93906986358cb96936d64;p=postgresql

In pg_log_generic(), be more paranoid about preserving errno.

This code failed to account for the possibility that malloc() would
change errno, resulting in wrong output for %m, not to mention the
possibility of message truncation.  Such a change is obviously
expected when malloc fails, but there's reason to fear that on some
platforms even a successful malloc call can modify errno.

Discussion: https://postgr.es/m/2576.1527382833@sss.pgh.pa.us
---

diff --git a/src/common/logging.c b/src/common/logging.c
index f247554a32..895da7150e 100644
--- a/src/common/logging.c
+++ b/src/common/logging.c
@@ -216,6 +216,8 @@ pg_log_generic_v(enum pg_log_level level, const char *pg_restrict fmt, va_list a
 
 	buf = pg_malloc_extended(required_len, MCXT_ALLOC_NO_OOM);
 
+	errno = save_errno;			/* malloc might change errno */
+
 	if (!buf)
 	{
 		/* memory trouble, just print what we can and get out of here */