printbuf: preserve self-append sources across growth

When the appended data points into the printbuf itself, growing the buffer may invalidate the source pointer before it is copied. Preserve the source offset across realloc and use memmove for internal overlap.
This commit is contained in:
Darren Carreras
2026-08-01 14:12:56 -04:00
parent 1bd2e4b3ef
commit 62bb838c57
3 changed files with 49 additions and 1 deletions
+12 -1
View File
@@ -28,6 +28,7 @@
#endif /* HAVE_STDARG_H */
#include "debug.h"
#include "json_inttypes.h"
#include "printbuf.h"
#include "snprintf_compat.h"
#include "vasprintf_compat.h"
@@ -96,6 +97,8 @@ static int printbuf_extend(struct printbuf *p, int min_size)
int printbuf_memappend(struct printbuf *p, const char *buf, int size)
{
int buf_offset = -1;
/* Prevent signed integer overflows with large buffers. */
if (size < 0 || size > INT_MAX - p->bpos - 1)
{
@@ -104,10 +107,18 @@ int printbuf_memappend(struct printbuf *p, const char *buf, int size)
}
if (p->size <= p->bpos + size + 1)
{
const uintptr_t buf_addr = (uintptr_t)(const void *)buf;
const uintptr_t p_buf_addr = (uintptr_t)(const void *)p->buf;
/* realloc() invalidates source pointers into the old buffer. */
if (buf_addr >= p_buf_addr && buf_addr - p_buf_addr < (uintptr_t)p->size)
buf_offset = (int)(buf_addr - p_buf_addr);
if (printbuf_extend(p, p->bpos + size + 1) < 0)
return -1;
if (buf_offset >= 0)
buf = p->buf + buf_offset;
}
memcpy(p->buf + p->bpos, buf, size);
memmove(p->buf + p->bpos, buf, size);
p->bpos += size;
p->buf[p->bpos] = '\0';
return size;