From d7daf9fd967ad7fcd509e6355f12f824327f07a4 Mon Sep 17 00:00:00 2001
From: Nick Wellnhofer <wellnhofer@aevum.de>
Date: Tue, 14 Mar 2023 13:02:36 +0100
Subject: [PATCH] xmllint: Fix use-after-free with --maxmem

Fixes #498.

Reference:https://github.com/GNOME/libxml2/commit/d7daf9fd967ad7fcd509e6355f12f824327f07a4
Conflict:include/libxml/xmlmemory.h


---
 include/libxml/xmlmemory.h |  2 ++
 xmllint.c                  | 15 ++++++---------
 xmlmemory.c                | 21 +++++++++++++++++++++
 3 files changed, 29 insertions(+), 9 deletions(-)

diff --git a/include/libxml/xmlmemory.h b/include/libxml/xmlmemory.h
index 17e375a..0a5f3eb 100644
--- a/include/libxml/xmlmemory.h
+++ b/include/libxml/xmlmemory.h
@@ -137,6 +137,8 @@ XMLPUBFUN void XMLCALL
 /*
  * These are specific to the XML debug memory wrapper.
  */
+XMLPUBFUN size_t
+	xmlMemSize	(void *ptr);
 XMLPUBFUN int XMLCALL
 	xmlMemUsed	(void);
 XMLPUBFUN int XMLCALL
diff --git a/xmllint.c b/xmllint.c
index fd43893..a17aa07 100644
--- a/xmllint.c
+++ b/xmllint.c
@@ -358,17 +358,14 @@ myMallocFunc(size_t size)
 static void *
 myReallocFunc(void *mem, size_t size)
 {
-    void *ret;
+    size_t oldsize = xmlMemSize(mem);
 
-    ret = xmlMemRealloc(mem, size);
-    if (ret != NULL) {
-        if (xmlMemUsed() > maxmem) {
-            OOM();
-            xmlMemFree(ret);
-            return (NULL);
-        }
+    if (xmlMemUsed() + size - oldsize > (size_t) maxmem) {
+        OOM();
+        return (NULL);
     }
-    return (ret);
+
+    return (xmlMemRealloc(mem, size));
 }
 static char *
 myStrdupFunc(const char *str)
diff --git a/xmlmemory.c b/xmlmemory.c
index c51f49a..469fcfb 100644
--- a/xmlmemory.c
+++ b/xmlmemory.c
@@ -573,6 +573,27 @@ xmlMemoryStrdup(const char *str) {
     return(xmlMemStrdupLoc(str, "none", 0));
 }
 
+/**
+ * xmlMemSize:
+ * @ptr:  pointer to the memory allocation
+ *
+ * Returns the size of a memory allocation.
+ */
+
+size_t
+xmlMemSize(void *ptr) {
+    MEMHDR *p;
+
+    if (ptr == NULL)
+	return(0);
+
+    p = CLIENT_2_HDR(ptr);
+    if (p->mh_tag != MEMTAG)
+        return(0);
+
+    return(p->mh_size);
+}
+
 /**
  * xmlMemUsed:
  *
-- 
2.27.0

