From ae41cf9af5753bf3eacb81253f5d691cf49b78b0 Mon Sep 17 00:00:00 2001 From: Nick Wellnhofer Date: Sun, 15 Dec 2024 23:05:06 +0100 Subject: [PATCH] xinclude: Check reallocations for overflow --- xinclude.c | 45 ++++++++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 19 deletions(-) diff --git a/xinclude.c b/xinclude.c index 895631c2..9ea71905 100644 --- a/xinclude.c +++ b/xinclude.c @@ -28,6 +28,7 @@ #include "private/buf.h" #include "private/error.h" +#include "private/memory.h" #include "private/parser.h" #include "private/tree.h" #include "private/xinclude.h" @@ -562,14 +563,15 @@ xmlXIncludeAddNode(xmlXIncludeCtxtPtr ctxt, xmlNodePtr cur) { if (ctxt->incNr >= ctxt->incMax) { xmlXIncludeRefPtr *table; -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - size_t newSize = ctxt->incMax ? ctxt->incMax * 2 : 1; -#else - size_t newSize = ctxt->incMax ? ctxt->incMax * 2 : 4; -#endif + int newSize; - table = (xmlXIncludeRefPtr *) xmlRealloc(ctxt->incTab, - newSize * sizeof(ctxt->incTab[0])); + newSize = xmlGrowCapacity(ctxt->incMax, sizeof(table[0]), + 4, XML_MAX_ITEMS); + if (newSize < 0) { + xmlXIncludeErrMemory(ctxt); + goto error; + } + table = xmlRealloc(ctxt->incTab, newSize * sizeof(table[0])); if (table == NULL) { xmlXIncludeErrMemory(ctxt); goto error; @@ -1133,13 +1135,16 @@ xmlXIncludeLoadDoc(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) { /* Also cache NULL docs */ if (ctxt->urlNr >= ctxt->urlMax) { xmlXIncludeDoc *tmp; -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - size_t newSize = ctxt->urlMax ? ctxt->urlMax * 2 : 1; -#else - size_t newSize = ctxt->urlMax ? ctxt->urlMax * 2 : 8; -#endif + int newSize; - tmp = xmlRealloc(ctxt->urlTab, sizeof(xmlXIncludeDoc) * newSize); + newSize = xmlGrowCapacity(ctxt->urlMax, sizeof(tmp[0]), + 8, XML_MAX_ITEMS); + if (newSize < 0) { + xmlXIncludeErrMemory(ctxt); + xmlFreeDoc(doc); + goto error; + } + tmp = xmlRealloc(ctxt->urlTab, newSize * sizeof(tmp[0])); if (tmp == NULL) { xmlXIncludeErrMemory(ctxt); xmlFreeDoc(doc); @@ -1484,13 +1489,15 @@ xmlXIncludeLoadTxt(xmlXIncludeCtxtPtr ctxt, xmlXIncludeRefPtr ref) { if (ctxt->txtNr >= ctxt->txtMax) { xmlXIncludeTxt *tmp; -#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION - size_t newSize = ctxt->txtMax ? ctxt->txtMax * 2 : 1; -#else - size_t newSize = ctxt->txtMax ? ctxt->txtMax * 2 : 8; -#endif + int newSize; - tmp = xmlRealloc(ctxt->txtTab, sizeof(xmlXIncludeTxt) * newSize); + newSize = xmlGrowCapacity(ctxt->txtMax, sizeof(tmp[0]), + 8, XML_MAX_ITEMS); + if (newSize < 0) { + xmlXIncludeErrMemory(ctxt); + goto error; + } + tmp = xmlRealloc(ctxt->txtTab, newSize * sizeof(tmp[0])); if (tmp == NULL) { xmlXIncludeErrMemory(ctxt); goto error;