From d6c55de1f99a9028540516316b95321a7b12a540 Mon Sep 17 00:00:00 2001 From: Tom Lane Date: Wed, 26 Sep 2018 13:31:56 -0400 Subject: Implement %m in src/port/snprintf.c, and teach elog.c to rely on that. I started out with the idea that we needed to detect use of %m format specs in contexts other than elog/ereport calls, because we couldn't rely on that working in *printf calls. But a better answer is to fix things so that it does work. Now that we're using snprintf.c all the time, we can implement %m in that and we've fixed the problem. This requires also adjusting our various printf-wrapping functions so that they ensure "errno" is preserved when they call snprintf.c. Remove elog.c's handmade implementation of %m, and let it rely on snprintf to support the feature. That should provide some performance gain, though I've not attempted to measure it. There are a lot of places where we could now simplify 'printf("%s", strerror(errno))' into 'printf("%m")', but I'm not in any big hurry to make that happen. Patch by me, reviewed by Michael Paquier Discussion: https://postgr.es/m/2975.1526862605@sss.pgh.pa.us --- src/common/psprintf.c | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src/common/psprintf.c') diff --git a/src/common/psprintf.c b/src/common/psprintf.c index 04465a18e69..2cf100f0954 100644 --- a/src/common/psprintf.c +++ b/src/common/psprintf.c @@ -45,6 +45,7 @@ char * psprintf(const char *fmt,...) { + int save_errno = errno; size_t len = 128; /* initial assumption about buffer size */ for (;;) @@ -60,6 +61,7 @@ psprintf(const char *fmt,...) result = (char *) palloc(len); /* Try to format the data. */ + errno = save_errno; va_start(args, fmt); newlen = pvsnprintf(result, len, fmt, args); va_end(args); @@ -89,6 +91,9 @@ psprintf(const char *fmt,...) * Other error cases do not return, but exit via elog(ERROR) or exit(). * Hence, this shouldn't be used inside libpq. * + * Caution: callers must be sure to preserve their entry-time errno + * when looping, in case the fmt contains "%m". + * * Note that the semantics of the return value are not exactly C99's. * First, we don't promise that the estimated buffer size is exactly right; * callers must be prepared to loop multiple times to get the right size. -- cgit v1.2.3