Use improved vsnprintf calling logic in more places.

When we are using a C99-compliant vsnprintf implementation (which should be
most places, these days) it is worth the trouble to make use of its report
of how large the buffer needs to be to succeed.  This patch adjusts
stringinfo.c and some miscellaneous usages in pg_dump to do that, relying
on the logic recently added in libpgcommon's psprintf.c.  Since these
places want to know the number of bytes written once we succeed, modify the
API of pvsnprintf() to report that.

There remains near-duplicate logic in pqexpbuffer.c, but since that code
is in libpq, psprintf.c's approach of exit()-on-error isn't appropriate
for use there.  Also note that I didn't bother touching the multitude
of places that call (v)snprintf without any attempt to provide a resizable
buffer.

Release-note-worthy incompatibility: the API of appendStringInfoVA()
changed.  If there's any third-party code that's calling that directly,
it will need tweaking along the same lines as in this patch.

David Rowley and Tom Lane
This commit is contained in:
Tom Lane 2013-10-24 21:43:57 -04:00
parent 98c50656ca
commit 3147acd63e
8 changed files with 153 additions and 137 deletions

View File

@ -80,18 +80,18 @@ appendStringInfo(StringInfo str, const char *fmt,...)
for (;;) for (;;)
{ {
va_list args; va_list args;
bool success; int needed;
/* Try to format the data. */ /* Try to format the data. */
va_start(args, fmt); va_start(args, fmt);
success = appendStringInfoVA(str, fmt, args); needed = appendStringInfoVA(str, fmt, args);
va_end(args); va_end(args);
if (success) if (needed == 0)
break; break; /* success */
/* Double the buffer size and try again. */ /* Increase the buffer size and try again. */
enlargeStringInfo(str, str->maxlen); enlargeStringInfo(str, needed);
} }
} }
@ -100,59 +100,51 @@ appendStringInfo(StringInfo str, const char *fmt,...)
* *
* Attempt to format text data under the control of fmt (an sprintf-style * Attempt to format text data under the control of fmt (an sprintf-style
* format string) and append it to whatever is already in str. If successful * format string) and append it to whatever is already in str. If successful
* return true; if not (because there's not enough space), return false * return zero; if not (because there's not enough space), return an estimate
* without modifying str. Typically the caller would enlarge str and retry * of the space needed, without modifying str. Typically the caller should
* on false return --- see appendStringInfo for standard usage pattern. * pass the return value to enlargeStringInfo() before trying again; see
* appendStringInfo for standard usage pattern.
* *
* XXX This API is ugly, but there seems no alternative given the C spec's * XXX This API is ugly, but there seems no alternative given the C spec's
* restrictions on what can portably be done with va_list arguments: you have * restrictions on what can portably be done with va_list arguments: you have
* to redo va_start before you can rescan the argument list, and we can't do * to redo va_start before you can rescan the argument list, and we can't do
* that from here. * that from here.
*/ */
bool int
appendStringInfoVA(StringInfo str, const char *fmt, va_list args) appendStringInfoVA(StringInfo str, const char *fmt, va_list args)
{ {
int avail, int avail;
nprinted; size_t nprinted;
Assert(str != NULL); Assert(str != NULL);
/* /*
* If there's hardly any space, don't bother trying, just fail to make the * If there's hardly any space, don't bother trying, just fail to make the
* caller enlarge the buffer first. * caller enlarge the buffer first. We have to guess at how much to
* enlarge, since we're skipping the formatting work.
*/ */
avail = str->maxlen - str->len - 1; avail = str->maxlen - str->len;
if (avail < 16) if (avail < 16)
return false; return 32;
/* nprinted = pvsnprintf(str->data + str->len, (size_t) avail, fmt, args);
* Assert check here is to catch buggy vsnprintf that overruns the
* specified buffer length. Solaris 7 in 64-bit mode is an example of a
* platform with such a bug.
*/
#ifdef USE_ASSERT_CHECKING
str->data[str->maxlen - 1] = '\0';
#endif
nprinted = vsnprintf(str->data + str->len, avail, fmt, args); if (nprinted < (size_t) avail)
Assert(str->data[str->maxlen - 1] == '\0');
/*
* Note: some versions of vsnprintf return the number of chars actually
* stored, but at least one returns -1 on failure. Be conservative about
* believing whether the print worked.
*/
if (nprinted >= 0 && nprinted < avail - 1)
{ {
/* Success. Note nprinted does not include trailing null. */ /* Success. Note nprinted does not include trailing null. */
str->len += nprinted; str->len += (int) nprinted;
return true; return 0;
} }
/* Restore the trailing null so that str is unmodified. */ /* Restore the trailing null so that str is unmodified. */
str->data[str->len] = '\0'; str->data[str->len] = '\0';
return false;
/*
* Return pvsnprintf's estimate of the space needed. (Although this is
* given as a size_t, we know it will fit in int because it's not more
* than MaxAllocSize.)
*/
return (int) nprinted;
} }
/* /*

View File

@ -715,13 +715,13 @@ errcode_for_socket_access(void)
for (;;) \ for (;;) \
{ \ { \
va_list args; \ va_list args; \
bool success; \ int needed; \
va_start(args, fmt); \ va_start(args, fmt); \
success = appendStringInfoVA(&buf, fmtbuf, args); \ needed = appendStringInfoVA(&buf, fmtbuf, args); \
va_end(args); \ va_end(args); \
if (success) \ if (needed == 0) \
break; \ break; \
enlargeStringInfo(&buf, buf.maxlen); \ enlargeStringInfo(&buf, needed); \
} \ } \
/* Done with expanded fmt */ \ /* Done with expanded fmt */ \
pfree(fmtbuf); \ pfree(fmtbuf); \
@ -758,13 +758,13 @@ errcode_for_socket_access(void)
for (;;) \ for (;;) \
{ \ { \
va_list args; \ va_list args; \
bool success; \ int needed; \
va_start(args, n); \ va_start(args, n); \
success = appendStringInfoVA(&buf, fmtbuf, args); \ needed = appendStringInfoVA(&buf, fmtbuf, args); \
va_end(args); \ va_end(args); \
if (success) \ if (needed == 0) \
break; \ break; \
enlargeStringInfo(&buf, buf.maxlen); \ enlargeStringInfo(&buf, needed); \
} \ } \
/* Done with expanded fmt */ \ /* Done with expanded fmt */ \
pfree(fmtbuf); \ pfree(fmtbuf); \

View File

@ -1183,29 +1183,33 @@ archputs(const char *s, Archive *AH)
int int
archprintf(Archive *AH, const char *fmt,...) archprintf(Archive *AH, const char *fmt,...)
{ {
char *p = NULL; char *p;
va_list ap; size_t len = 128; /* initial assumption about buffer size */
int bSize = strlen(fmt) + 256; size_t cnt;
int cnt = -1;
/* for (;;)
* This is paranoid: deal with the possibility that vsnprintf is willing
* to ignore trailing null or returns > 0 even if string does not fit. It
* may be the case that it returns cnt = bufsize
*/
while (cnt < 0 || cnt >= (bSize - 1))
{ {
if (p != NULL) va_list args;
free(p);
bSize *= 2; /* Allocate work buffer. */
p = (char *) pg_malloc(bSize); p = (char *) pg_malloc(len);
va_start(ap, fmt);
cnt = vsnprintf(p, bSize, fmt, ap); /* Try to format the data. */
va_end(ap); va_start(args, fmt);
cnt = pvsnprintf(p, len, fmt, args);
va_end(args);
if (cnt < len)
break; /* success */
/* Release buffer and loop around to try again with larger len. */
free(p);
len = cnt;
} }
WriteData(AH, p, cnt); WriteData(AH, p, cnt);
free(p); free(p);
return cnt; return (int) cnt;
} }
@ -1312,29 +1316,33 @@ RestoreOutput(ArchiveHandle *AH, OutputContext savedContext)
int int
ahprintf(ArchiveHandle *AH, const char *fmt,...) ahprintf(ArchiveHandle *AH, const char *fmt,...)
{ {
char *p = NULL; char *p;
va_list ap; size_t len = 128; /* initial assumption about buffer size */
int bSize = strlen(fmt) + 256; /* Usually enough */ size_t cnt;
int cnt = -1;
/* for (;;)
* This is paranoid: deal with the possibility that vsnprintf is willing
* to ignore trailing null or returns > 0 even if string does not fit. It
* may be the case that it returns cnt = bufsize.
*/
while (cnt < 0 || cnt >= (bSize - 1))
{ {
if (p != NULL) va_list args;
free(p);
bSize *= 2; /* Allocate work buffer. */
p = (char *) pg_malloc(bSize); p = (char *) pg_malloc(len);
va_start(ap, fmt);
cnt = vsnprintf(p, bSize, fmt, ap); /* Try to format the data. */
va_end(ap); va_start(args, fmt);
cnt = pvsnprintf(p, len, fmt, args);
va_end(args);
if (cnt < len)
break; /* success */
/* Release buffer and loop around to try again with larger len. */
free(p);
len = cnt;
} }
ahwrite(p, 1, cnt, AH); ahwrite(p, 1, cnt, AH);
free(p); free(p);
return cnt; return (int) cnt;
} }
void void

View File

@ -996,33 +996,33 @@ _EndBlobs(ArchiveHandle *AH, TocEntry *te)
static int static int
tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...) tarPrintf(ArchiveHandle *AH, TAR_MEMBER *th, const char *fmt,...)
{ {
char *p = NULL; char *p;
va_list ap; size_t len = 128; /* initial assumption about buffer size */
size_t bSize = strlen(fmt) + 256; /* Should be enough */ size_t cnt;
int cnt = -1;
/* for (;;)
* This is paranoid: deal with the possibility that vsnprintf is willing
* to ignore trailing null
*/
/*
* or returns > 0 even if string does not fit. It may be the case that it
* returns cnt = bufsize
*/
while (cnt < 0 || cnt >= (bSize - 1))
{ {
if (p != NULL) va_list args;
free(p);
bSize *= 2; /* Allocate work buffer. */
p = (char *) pg_malloc(bSize); p = (char *) pg_malloc(len);
va_start(ap, fmt);
cnt = vsnprintf(p, bSize, fmt, ap); /* Try to format the data. */
va_end(ap); va_start(args, fmt);
cnt = pvsnprintf(p, len, fmt, args);
va_end(args);
if (cnt < len)
break; /* success */
/* Release buffer and loop around to try again with larger len. */
free(p);
len = cnt;
} }
cnt = tarWrite(p, cnt, th); cnt = tarWrite(p, cnt, th);
free(p); free(p);
return cnt; return (int) cnt;
} }
bool bool

View File

@ -23,10 +23,6 @@
#include "utils/memutils.h" #include "utils/memutils.h"
static size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 0)));
/* /*
* psprintf * psprintf
* *
@ -48,6 +44,7 @@ psprintf(const char *fmt,...)
{ {
char *result; char *result;
va_list args; va_list args;
size_t newlen;
/* /*
* Allocate result buffer. Note that in frontend this maps to malloc * Allocate result buffer. Note that in frontend this maps to malloc
@ -57,14 +54,15 @@ psprintf(const char *fmt,...)
/* Try to format the data. */ /* Try to format the data. */
va_start(args, fmt); va_start(args, fmt);
len = pvsnprintf(result, len, fmt, args); newlen = pvsnprintf(result, len, fmt, args);
va_end(args); va_end(args);
if (len == 0) if (newlen < len)
return result; /* success */ return result; /* success */
/* Release buffer and loop around to try again with larger len. */ /* Release buffer and loop around to try again with larger len. */
pfree(result); pfree(result);
len = newlen;
} }
} }
@ -72,19 +70,30 @@ psprintf(const char *fmt,...)
* pvsnprintf * pvsnprintf
* *
* Attempt to format text data under the control of fmt (an sprintf-style * Attempt to format text data under the control of fmt (an sprintf-style
* format string) and insert it into buf (which has length len). * format string) and insert it into buf (which has length len, len > 0).
* *
* If successful, return zero. If there's not enough space in buf, return * If successful, return the number of bytes emitted, not counting the
* an estimate of the buffer size needed to succeed (this *must* be more * trailing zero byte. This will always be strictly less than len.
* than "len", else psprintf might loop infinitely).
* Other error cases do not return.
* *
* XXX This API is ugly, but there seems no alternative given the C spec's * If there's not enough space in buf, return an estimate of the buffer size
* restrictions on what can portably be done with va_list arguments: you have * needed to succeed (this *must* be more than the given len, else callers
* to redo va_start before you can rescan the argument list, and we can't do * might loop infinitely).
* that from here. *
* Other error cases do not return, but exit via elog(ERROR) or exit().
* Hence, this shouldn't be used inside libpq.
*
* This function exists mainly to centralize our workarounds for
* non-C99-compliant vsnprintf implementations. Generally, any call that
* pays any attention to the return value should go through here rather
* than calling snprintf or vsnprintf directly.
*
* 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.
* Second, we return the recommended buffer size, not one less than that;
* this lets overflow concerns be handled here rather than in the callers.
*/ */
static size_t size_t
pvsnprintf(char *buf, size_t len, const char *fmt, va_list args) pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
{ {
int nprinted; int nprinted;
@ -129,15 +138,15 @@ pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
if (nprinted >= 0 && (size_t) nprinted < len - 1) if (nprinted >= 0 && (size_t) nprinted < len - 1)
{ {
/* Success. Note nprinted does not include trailing null. */ /* Success. Note nprinted does not include trailing null. */
return 0; return (size_t) nprinted;
} }
if (nprinted >= 0 && (size_t) nprinted > len) if (nprinted >= 0 && (size_t) nprinted > len)
{ {
/* /*
* This appears to be a C99-compliant vsnprintf, so believe its * This appears to be a C99-compliant vsnprintf, so believe its
* estimate of the required space. (If it's wrong, this code will * estimate of the required space. (If it's wrong, the logic will
* still work, but may loop multiple times.) Note that the space * still work, but we may loop multiple times.) Note that the space
* needed should be only nprinted+1 bytes, but we'd better allocate * needed should be only nprinted+1 bytes, but we'd better allocate
* one more than that so that the test above will succeed next time. * one more than that so that the test above will succeed next time.
* *
@ -150,14 +159,15 @@ pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
/* /*
* Buffer overrun, and we don't know how much space is needed. Estimate * Buffer overrun, and we don't know how much space is needed. Estimate
* twice the previous buffer size. If this would overflow, choke. We use * twice the previous buffer size, but not more than MaxAllocSize; if we
* a palloc-oriented overflow limit even when in frontend. * are already at MaxAllocSize, choke. Note we use this palloc-oriented
* overflow limit even when in frontend.
*/ */
if (len > MaxAllocSize / 2) if (len >= MaxAllocSize)
{ {
#ifndef FRONTEND #ifndef FRONTEND
ereport(ERROR, ereport(ERROR,
(errcode(ERRCODE_OUT_OF_MEMORY), (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("out of memory"))); errmsg("out of memory")));
#else #else
fprintf(stderr, _("out of memory\n")); fprintf(stderr, _("out of memory\n"));
@ -165,5 +175,8 @@ pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
#endif #endif
} }
if (len >= MaxAllocSize / 2)
return MaxAllocSize;
return len * 2; return len * 2;
} }

View File

@ -101,11 +101,12 @@ __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
* appendStringInfoVA * appendStringInfoVA
* Attempt to format text data under the control of fmt (an sprintf-style * Attempt to format text data under the control of fmt (an sprintf-style
* format string) and append it to whatever is already in str. If successful * format string) and append it to whatever is already in str. If successful
* return true; if not (because there's not enough space), return false * return zero; if not (because there's not enough space), return an estimate
* without modifying str. Typically the caller would enlarge str and retry * of the space needed, without modifying str. Typically the caller should
* on false return --- see appendStringInfo for standard usage pattern. * pass the return value to enlargeStringInfo() before trying again; see
* appendStringInfo for standard usage pattern.
*/ */
extern bool extern int
appendStringInfoVA(StringInfo str, const char *fmt, va_list args) appendStringInfoVA(StringInfo str, const char *fmt, va_list args)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 0))); __attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 0)));

View File

@ -98,14 +98,16 @@ extern char *MemoryContextStrdup(MemoryContext context, const char *string);
extern char *pstrdup(const char *in); extern char *pstrdup(const char *in);
extern char *pnstrdup(const char *in, Size len); extern char *pnstrdup(const char *in, Size len);
/* sprintf into a palloc'd buffer */
extern char *psprintf(const char *fmt,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
/* basic memory allocation functions */ /* basic memory allocation functions */
extern void *palloc(Size size); extern void *palloc(Size size);
extern void *palloc0(Size size); extern void *palloc0(Size size);
extern void pfree(void *pointer); extern void pfree(void *pointer);
extern void *repalloc(void *pointer, Size size); extern void *repalloc(void *pointer, Size size);
/* sprintf into a palloc'd buffer --- these are in psprintf.c */
extern char *psprintf(const char *fmt,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
extern size_t pvsnprintf(char *buf, size_t len, const char *fmt, va_list args)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 3, 0)));
#endif /* PALLOC_H */ #endif /* PALLOC_H */

View File

@ -70,14 +70,14 @@ PLy_elog(int elevel, const char *fmt,...)
for (;;) for (;;)
{ {
va_list ap; va_list ap;
bool success; int needed;
va_start(ap, fmt); va_start(ap, fmt);
success = appendStringInfoVA(&emsg, dgettext(TEXTDOMAIN, fmt), ap); needed = appendStringInfoVA(&emsg, dgettext(TEXTDOMAIN, fmt), ap);
va_end(ap); va_end(ap);
if (success) if (needed == 0)
break; break;
enlargeStringInfo(&emsg, emsg.maxlen); enlargeStringInfo(&emsg, needed);
} }
primary = emsg.data; primary = emsg.data;