From 077df27eb1bdc2a3268f7596415fd91db76d29d4 Mon Sep 17 00:00:00 2001
From: Nick Wellnhofer <wellnhofer@aevum.de>
Date: Thu, 22 Dec 2022 15:22:01 +0100
Subject: [PATCH] parser: Fix integer overflow of input ID

Applies a patch from Chromium. Also stop incrementing input ID of
subcontexts. This isn't necessary.

Fixes #465.

Reference:https://github.com/GNOME/libxml2/commit/077df27eb1bdc2a3268f7596415fd91db76d29d4
Conflict:NA
---
 parser.c          | 8 ++------
 parserInternals.c | 7 ++++++-
 2 files changed, 8 insertions(+), 7 deletions(-)

diff --git a/parser.c b/parser.c
index 2207404..431851f 100644
--- a/parser.c
+++ b/parser.c
@@ -13337,7 +13337,7 @@ xmlParseBalancedChunkMemoryInternal(xmlParserCtxtPtr oldctxt,
 	ctxt->userData = ctxt;
     if (ctxt->dict != NULL) xmlDictFree(ctxt->dict);
     ctxt->dict = oldctxt->dict;
-    ctxt->input_id = oldctxt->input_id + 1;
+    ctxt->input_id = oldctxt->input_id;
     ctxt->str_xml = xmlDictLookup(ctxt->dict, BAD_CAST "xml", 3);
     ctxt->str_xmlns = xmlDictLookup(ctxt->dict, BAD_CAST "xmlns", 5);
     ctxt->str_xml_ns = xmlDictLookup(ctxt->dict, XML_XML_NAMESPACE, 36);
@@ -13968,11 +13968,7 @@ xmlCreateEntityParserCtxtInternal(const xmlChar *URL, const xmlChar *ID,
     if (pctx != NULL) {
         ctxt->options = pctx->options;
         ctxt->_private = pctx->_private;
-	/*
-	 * this is a subparser of pctx, so the input_id should be
-	 * incremented to distinguish from main entity
-	 */
-	ctxt->input_id = pctx->input_id + 1;
+	ctxt->input_id = pctx->input_id;
     }
 
     /* Don't read from stdin. */
diff --git a/parserInternals.c b/parserInternals.c
index ef18ccf..cee4cd9 100644
--- a/parserInternals.c
+++ b/parserInternals.c
@@ -1352,8 +1352,13 @@ xmlNewInputStream(xmlParserCtxtPtr ctxt) {
      * should not happen while parsing which is the situation where
      * the id is actually needed.
      */
-    if (ctxt != NULL)
+    if (ctxt != NULL) {
+        if (input->id >= INT_MAX) {
+            xmlErrMemory(ctxt, "Input ID overflow\n");
+            return(NULL);
+        }
         input->id = ctxt->input_id++;
+    }
 
     return(input);
 }
-- 
2.27.0

