From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: Sadaf Ebrahimi <sadafebrahimi@google.com>
Date: Fri, 3 Jun 2022 03:40:21 +0000
Subject: [PATCH] Prevent integer overflow in function doProlog

Bug: http://b/221256678
Change-Id: I6fe381103f4eb287726d1ccb5bfec99db160ffe4
(cherry picked from commit 257f1d3777240016d3ccd74a61cd7d0e0efcaae3)
Merged-In: I6fe381103f4eb287726d1ccb5bfec99db160ffe4
---
 lib/xmlparse.c | 20 +++++++++++++-------
 1 file changed, 13 insertions(+), 7 deletions(-)

diff --git a/lib/xmlparse.c b/lib/xmlparse.c
index 91f50034..0e57538a 100644
--- a/lib/xmlparse.c
+++ b/lib/xmlparse.c
@@ -4671,23 +4671,29 @@ doProlog(XML_Parser parser,
       if (dtd->in_eldecl) {
         ELEMENT_TYPE *el;
         const XML_Char *name;
-        int nameLen;
-        const char *nxt = (quant == XML_CQUANT_NONE
-                           ? next
-                           : next - enc->minBytesPerChar);
+        size_t nameLen;
+        const char *nxt
+            = (quant == XML_CQUANT_NONE ? next : next - enc->minBytesPerChar);
         int myindex = nextScaffoldPart(parser);
         if (myindex < 0)
           return XML_ERROR_NO_MEMORY;
         dtd->scaffold[myindex].type = XML_CTYPE_NAME;
         dtd->scaffold[myindex].quant = quant;
         el = getElementType(parser, enc, s, nxt);
-        if (!el)
+        if (! el)
           return XML_ERROR_NO_MEMORY;
         name = el->name;
         dtd->scaffold[myindex].name = name;
         nameLen = 0;
-        for (; name[nameLen++]; );
-        dtd->contentStringLen +=  nameLen;
+        for (; name[nameLen++];)
+          ;
+
+        /* Detect and prevent integer overflow */
+        if (nameLen > UINT_MAX - dtd->contentStringLen) {
+          return XML_ERROR_NO_MEMORY;
+        }
+
+        dtd->contentStringLen += (unsigned)nameLen;
         if (elementDeclHandler)
           handleDefault = XML_FALSE;
       }
