From 4ce2abf6f656b3e78ad40e33191a8b42561c10b0 Mon Sep 17 00:00:00 2001
From: David Kilzer <ddkilzer@apple.com>
Date: Sun, 29 May 2022 09:46:00 -0700
Subject: [PATCH 299/300] Fix missing NUL terminators in xmlBuf and xmlBuffer
 functions

* buf.c:
(xmlBufAddLen):
- Change check for remaining space to account for the NUL
  terminator.  When adding a length exactly equal to the number
  of unused bytes, a NUL terminator was not written.
(xmlBufResize):
- Set `buf->use` and NUL terminator when allocating a new
  buffer.
* tree.c:
(xmlBufferResize):
- Set `buf->use` and NUL terminator when allocating a new
  buffer.
(xmlBufferAddHead):
- Set NUL terminator before returning early when shifting
  contents.

Reference:https://github.com/GNOME/libxml2/commit/4ce2abf6f656b3e78ad40e33191a8b42561c10b0
Conflict:NA
---
 buf.c  | 9 ++++-----
 tree.c | 3 +++
 2 files changed, 7 insertions(+), 5 deletions(-)

diff --git a/buf.c b/buf.c
index f896826..da765f6 100644
--- a/buf.c
+++ b/buf.c
@@ -613,14 +613,11 @@ xmlBufAddLen(xmlBufPtr buf, size_t len) {
     if ((buf == NULL) || (buf->error))
         return(-1);
     CHECK_COMPAT(buf)
-    if (len > (buf->size - buf->use))
+    if (len >= (buf->size - buf->use))
         return(-1);
     buf->use += len;
+    buf->content[buf->use] = 0;
     UPDATE_COMPAT(buf)
-    if (buf->size > buf->use)
-        buf->content[buf->use] = 0;
-    else
-        return(-1);
     return(0);
 }
 
@@ -821,6 +818,8 @@ xmlBufResize(xmlBufPtr buf, size_t size)
     } else {
 	if (buf->content == NULL) {
 	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
+	    buf->use = 0;
+	    rebuf[buf->use] = 0;
 	} else if (buf->size - buf->use < 100) {
 	    rebuf = (xmlChar *) xmlRealloc(buf->content, newSize);
         } else {
diff --git a/tree.c b/tree.c
index 3dff195..e275671 100644
--- a/tree.c
+++ b/tree.c
@@ -7529,6 +7529,8 @@ xmlBufferResize(xmlBufferPtr buf, unsigned int size)
     } else {
 	if (buf->content == NULL) {
 	    rebuf = (xmlChar *) xmlMallocAtomic(newSize);
+	    buf->use = 0;
+	    rebuf[buf->use] = 0;
 	} else if (buf->size - buf->use < 100) {
 	    rebuf = (xmlChar *) xmlRealloc(buf->content, newSize);
         } else {
@@ -7657,6 +7659,7 @@ xmlBufferAddHead(xmlBufferPtr buf, const xmlChar *str, int len) {
             memmove(&buf->content[0], str, len);
 	    buf->use += len;
 	    buf->size += len;
+            buf->content[buf->use] = 0;
 	    return(0);
 	}
     }
-- 
2.27.0


