From 391565147e7501b84289d3ec84bf499df63134fd Mon Sep 17 00:00:00 2001 From: Eric Biggers Date: Tue, 6 Feb 2024 22:26:50 -0800 Subject: [PATCH] xmlproc: fix buffer enlargement logic This fixes a heap buffer overflow caught by the xmlproc fuzzer. --- include/wimlib/compiler.h | 4 ++++ src/xmlproc.c | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/include/wimlib/compiler.h b/include/wimlib/compiler.h index 2f712545..77cd27f8 100644 --- a/include/wimlib/compiler.h +++ b/include/wimlib/compiler.h @@ -122,6 +122,10 @@ #undef MAX #define MAX(a, b) max((a), (b)) +/* Get the maximum of three variables, without multiple evaluation. */ +#undef max3 +#define max3(a, b, c) max(max((a), (b)), (c)) + /* Swap the values of two variables, without multiple evaluation. */ #ifndef swap # define swap(a, b) ({ typeof(a) _a = (a); (a) = (b); (b) = _a; }) diff --git a/src/xmlproc.c b/src/xmlproc.c index 6e1d2c16..8ce193e9 100644 --- a/src/xmlproc.c +++ b/src/xmlproc.c @@ -665,7 +665,8 @@ static void xml_write(struct xml_out_buf *buf, const tchar *str, size_t len) { if (buf->count + len + 1 > buf->capacity) { - size_t new_capacity = max(buf->capacity * 2, 4096); + size_t new_capacity = max3(buf->count + len + 1, + buf->capacity * 2, 4096); tchar *new_buf = REALLOC(buf->buf, new_capacity * sizeof(str[0])); if (!new_buf) { -- 2.43.0