[packages/expat] Rel 2.
arekm
arekm at pld-linux.org
Thu Oct 29 09:38:26 CET 2026
commit a4dacc455672630eafb7bf1bca21ad827382c7b7
Author: Arkadiusz Miśkiewicz <arekm at maven.pl>
Date: Thu Oct 29 09:34:05 2026 +0100
Rel 2.
Fixes CVE-2026-118370, CVE-2026-117610, CVE-2026-115506,
CVE-2026-113351.
CVE-2026-113351.patch | 327 +++++++
CVE-2026-115506.patch | 2307 +++++++++++++++++++++++++++++++++++++++++++++++++
CVE-2026-117610.patch | 110 +++
CVE-2026-118370.patch | 79 ++
expat.spec | 18 +-
5 files changed, 2840 insertions(+), 1 deletion(-)
---
diff --git a/expat.spec b/expat.spec
index ddd42bb..0543b23 100644
--- a/expat.spec
+++ b/expat.spec
@@ -1,6 +1,7 @@
#
# Conditional build:
%bcond_without static_libs # static library
+%bcond_without tests # unit tests
Summary: XML 1.0 parser
Summary(es.UTF-8): Parser de XML 1.0
@@ -10,12 +11,16 @@ Summary(ru.UTF-8): Переносимая библиотека разбора XM
Summary(uk.UTF-8): Переносима бібліотека розбору XML (expat)
Name: expat
Version: 2.9.0
-Release: 1
+Release: 2
Epoch: 1
License: MIT
Group: Applications/Publishing/XML
Source0: https://downloads.sourceforge.net/expat/%{name}-%{version}.tar.xz
# Source0-md5: fa5ea2bb996c624133368a87206d72af
+Patch0: CVE-2026-113351.patch
+Patch1: CVE-2026-117610.patch
+Patch2: CVE-2026-118370.patch
+Patch3: CVE-2026-115506.patch
URL: http://www.libexpat.org/
BuildRequires: autoconf >= 2.69
BuildRequires: automake >= 1:1.13
@@ -134,6 +139,10 @@ Programy narzędziowe do biblioteki Expat:
%prep
%setup -q
+%patch -P0 -p2
+%patch -P1 -p2
+%patch -P2 -p2
+%patch -P3 -p2
%build
%{__libtoolize}
@@ -148,12 +157,19 @@ Programy narzędziowe do biblioteki Expat:
%{!?with_static_libs:--disable-static}
%{__make}
+%if %{with tests}
+%{__make} check
+%endif
+
%install
rm -rf $RPM_BUILD_ROOT
%{__make} install \
DESTDIR=$RPM_BUILD_ROOT
+# packaged as %doc
+%{__rm} -r $RPM_BUILD_ROOT%{_docdir}/%{name}
+
install -d $RPM_BUILD_ROOT%{_aclocaldir}
install -d $RPM_BUILD_ROOT%{_examplesdir}/%{name}-%{version}
diff --git a/CVE-2026-113351.patch b/CVE-2026-113351.patch
new file mode 100644
index 0000000..afcecb6
--- /dev/null
+++ b/CVE-2026-113351.patch
@@ -0,0 +1,327 @@
+https://github.com/libexpat/libexpat/pull/1431 (merged as d8f31e647a4d)
+From ba431e267e751bfd0ed8bb608d21b0b1b52bd604 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 17 Oct 2026 20:59:13 +0200
+Subject: [PATCH 1/6] lib: Document the idea behind the
+ `parser->m_protocolEncodingName` check
+
+---
+ expat/lib/xmlparse.c | 3 +++
+ 1 file changed, 3 insertions(+)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index ab2d4f1ed2..aee6b58133 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -1630,6 +1630,9 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
+ parser->m_protocolEncodingName = NULL;
+ parserInit(parser, encodingName);
+ dtdReset(parser->m_dtd, parser);
++
++ // NOTE: This effectively checks for `copyString` having failed during the
++ // call to `parserInit` above
+ if (encodingName && ! parser->m_protocolEncodingName) {
+ parser->m_errorCode = XML_ERROR_NO_MEMORY;
+ return XML_FALSE;
+
+From 16b6b2d583f8de3fe204f5ce3c2a6b9f1e2b4cd7 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 17 Oct 2026 20:43:01 +0200
+Subject: [PATCH 2/6] lib: Extract variable `bytesAllocated`
+
+---
+ expat/lib/xmlparse.c | 6 ++++--
+ 1 file changed, 4 insertions(+), 2 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index aee6b58133..e0a8e60077 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -865,11 +865,13 @@ expat_heap_increase_tolerable(XML_Parser rootParser, size_t increase,
+ size_t newTotal = 0;
+ bool tolerable = true;
+
++ const size_t bytesAllocated = rootParser->m_alloc_tracker.bytesAllocated;
++
+ // Detect integer overflow
+- if (SIZE_MAX - rootParser->m_alloc_tracker.bytesAllocated < increase) {
++ if (SIZE_MAX - bytesAllocated < increase) {
+ tolerable = false;
+ } else {
+- newTotal = rootParser->m_alloc_tracker.bytesAllocated + increase;
++ newTotal = bytesAllocated + increase;
+
+ if (newTotal >= rootParser->m_alloc_tracker.activationThresholdBytes) {
+ assert(newTotal > 0);
+
+From a6cf8a6944b6c6d81e74c4cd95faa29132e67aa3 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 17 Oct 2026 20:51:49 +0200
+Subject: [PATCH 3/6] lib: Offset allocation tracking at `XML_ParserReset` time
+
+.. to enforce the same rules to later parses as to the first
+---
+ expat/lib/xmlparse.c | 17 ++++++++++++++++-
+ 1 file changed, 16 insertions(+), 1 deletion(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index e0a8e60077..83e1dafeda 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -467,6 +467,7 @@ typedef struct accounting {
+ typedef struct MALLOC_TRACKER {
+ size_t bytesAllocated;
+ size_t peakBytesAllocated; // updated live only for debug level >=2
++ size_t bytesAllocatedWhenLastReset;
+ unsigned long debugLevel;
+ float maximumAmplificationFactor; // >=1.0
+ XmlBigCount activationThresholdBytes;
+@@ -865,7 +866,16 @@ expat_heap_increase_tolerable(XML_Parser rootParser, size_t increase,
+ size_t newTotal = 0;
+ bool tolerable = true;
+
+- const size_t bytesAllocated = rootParser->m_alloc_tracker.bytesAllocated;
++ // The idea is to subtract the amount of memory that was already
++ // allocated the last time that `XML_ParserReset` was called for
++ // this parser, the memory use of one document could skew the
++ // memory statso of the next document.
++ const size_t bytesAllocated
++ = (rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset
++ > rootParser->m_alloc_tracker.bytesAllocated)
++ ? 0
++ : (rootParser->m_alloc_tracker.bytesAllocated
++ - rootParser->m_alloc_tracker.bytesAllocatedWhenLastReset);
+
+ // Detect integer overflow
+ if (SIZE_MAX - bytesAllocated < increase) {
+@@ -1633,6 +1643,11 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
+ parserInit(parser, encodingName);
+ dtdReset(parser->m_dtd, parser);
+
++#if XML_GE == 1
++ parser->m_alloc_tracker.bytesAllocatedWhenLastReset
++ = parser->m_alloc_tracker.bytesAllocated;
++#endif
++
+ // NOTE: This effectively checks for `copyString` having failed during the
+ // call to `parserInit` above
+ if (encodingName && ! parser->m_protocolEncodingName) {
+
+From c400537c2df393161946d60bedbdc2c3a7e971ef Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 19 Oct 2026 17:55:36 +0200
+Subject: [PATCH 4/6] tests/alloc_tests.c: Cover `XML_ParserReset` alloc
+ tracker neutrality
+
+---
+ expat/tests/alloc_tests.c | 42 +++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 42 insertions(+)
+
+diff --git a/expat/tests/alloc_tests.c b/expat/tests/alloc_tests.c
+index 690039bc9e..9bda6b5928 100644
+--- a/expat/tests/alloc_tests.c
++++ b/expat/tests/alloc_tests.c
+@@ -2330,6 +2330,47 @@ START_TEST(test_alloc_tracker_api_float_round_trip) {
+ }
+ END_TEST
+
++START_TEST(test_alloc_tracker_reset_neutrality) {
++ // Speed up the test, chunk size expected to not matter in this test
++ if (g_chunkSize != 0)
++ return;
++
++ XML_Parser parser = XML_ParserCreate(NULL);
++
++ const char *const small = "<hello/>";
++
++ // Create a document that drives `parser->m_alloc_tracker.bytesAllocated`
++ // towards the activation threshold
++#if XML_GE == 1
++ const size_t bigSizeBytes
++ = (size_t)(1.1f * EXPAT_ALLOC_TRACKER_ACTIVATION_THRESHOLD_DEFAULT);
++ const char *const before = "<doc a='";
++ const char *const after = "'/>";
++ char *const big = malloc(bigSizeBytes);
++ assert_true(big != NULL);
++ memset(big, 'X', bigSizeBytes);
++ memcpy(big, before, strlen(before)); // without zero terminator
++ strcpy(big + (bigSizeBytes - strlen(after) - 1),
++ after); // with zero terminator
++ assert_true(strlen(big) == bigSizeBytes - 1); // self-test
++
++ assert_true(
++ _XML_Parse_SINGLE_BYTES(parser, big, strlen(big), /*isFinal=*/XML_TRUE)
++ == XML_STATUS_OK);
++
++ free(big);
++#endif // XML_GE == 1
++
++ XML_ParserReset(parser, NULL);
++
++ assert_true(_XML_Parse_SINGLE_BYTES(parser, small, strlen(small),
++ /*isFinal=*/XML_TRUE)
++ == XML_STATUS_OK);
++
++ XML_ParserFree(parser);
++}
++END_TEST
++
+ START_TEST(test_mem_api_cycle) {
+ XML_Parser parser = XML_ParserCreate(NULL);
+
+@@ -2445,6 +2486,7 @@ make_alloc_test_case(Suite *s) {
+ tcase_add_test__if_xml_ge(tc_alloc, test_alloc_tracker_getbuffer_unlimited);
+ tcase_add_test__if_xml_ge(tc_alloc, test_alloc_tracker_api);
+ tcase_add_test__if_xml_ge(tc_alloc, test_alloc_tracker_api_float_round_trip);
++ tcase_add_test__if_xml_ge(tc_alloc, test_alloc_tracker_reset_neutrality);
+
+ tcase_add_test(tc_alloc, test_mem_api_cycle);
+ tcase_add_test__if_xml_ge(tc_alloc, test_mem_api_unlimited);
+
+From 8b722a1453b8179dbda9876df2af4ce62e34b00c Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 19 Oct 2026 19:17:06 +0200
+Subject: [PATCH 5/6] lib: Stop `XML_ParserReset` from resetting accounting
+ settings
+
+.. and debugging levels
+---
+ expat/lib/xmlparse.c | 36 +++++++++++++++++++++++-------------
+ 1 file changed, 23 insertions(+), 13 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index 83e1dafeda..f12b7d31ad 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -616,7 +616,8 @@ static XML_Parser parserCreate(const XML_Char *encodingName,
+ const XML_Char *nameSep, DTD *dtd,
+ XML_Parser parentParser);
+
+-static void parserInit(XML_Parser parser, const XML_Char *encodingName);
++static void parserInit(XML_Parser parser, const XML_Char *encodingName,
++ bool isReset);
+
+ #if XML_GE == 1
+ static float accountingGetCurrentAmplification(XML_Parser rootParser);
+@@ -1461,7 +1462,7 @@ parserCreate(const XML_Char *encodingName,
+
+ poolInit(&parser->m_tempPool, parser);
+ poolInit(&parser->m_temp2Pool, parser);
+- parserInit(parser, encodingName);
++ parserInit(parser, encodingName, /*isReset=*/false);
+
+ if (encodingName && ! parser->m_protocolEncodingName) {
+ if (dtd) {
+@@ -1488,7 +1489,7 @@ parserCreate(const XML_Char *encodingName,
+ }
+
+ static void
+-parserInit(XML_Parser parser, const XML_Char *encodingName) {
++parserInit(XML_Parser parser, const XML_Char *encodingName, bool isReset) {
+ parser->m_processor = prologInitProcessor;
+ XmlPrologStateInit(&parser->m_prologState);
+ if (encodingName != NULL) {
+@@ -1569,15 +1570,24 @@ parserInit(XML_Parser parser, const XML_Char *encodingName) {
+ parser->m_hash_secret_salt_set = XML_FALSE;
+
+ #if XML_GE == 1
+- memset(&parser->m_accounting, 0, sizeof(ACCOUNTING));
+- parser->m_accounting.debugLevel = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u);
+- parser->m_accounting.maximumAmplificationFactor
+- = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;
+- parser->m_accounting.activationThresholdBytes
+- = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;
+-
+- memset(&parser->m_entity_stats, 0, sizeof(ENTITY_STATS));
+- parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u);
++ parser->m_accounting.countBytesDirect = 0;
++ parser->m_accounting.countBytesIndirect = 0;
++ if (! isReset) {
++ parser->m_accounting.debugLevel
++ = getDebugLevel("EXPAT_ACCOUNTING_DEBUG", 0u);
++ parser->m_accounting.maximumAmplificationFactor
++ = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_MAXIMUM_AMPLIFICATION_DEFAULT;
++ parser->m_accounting.activationThresholdBytes
++ = EXPAT_BILLION_LAUGHS_ATTACK_PROTECTION_ACTIVATION_THRESHOLD_DEFAULT;
++ }
++
++ parser->m_entity_stats.countEverOpened = 0;
++ parser->m_entity_stats.currentDepth = 0;
++ parser->m_entity_stats.maximumDepthSeen = 0;
++ if (! isReset)
++ parser->m_entity_stats.debugLevel = getDebugLevel("EXPAT_ENTITY_DEBUG", 0u);
++#else
++ UNUSED_P(isReset);
+ #endif
+ }
+
+@@ -1640,7 +1650,7 @@ XML_ParserReset(XML_Parser parser, const XML_Char *encodingName) {
+ poolClear(&parser->m_temp2Pool);
+ FREE(parser, (void *)parser->m_protocolEncodingName);
+ parser->m_protocolEncodingName = NULL;
+- parserInit(parser, encodingName);
++ parserInit(parser, encodingName, /*isReset=*/true);
+ dtdReset(parser->m_dtd, parser);
+
+ #if XML_GE == 1
+
+From f74501d61e09341a8a2899c65a03a5bbb1fa4535 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 19 Oct 2026 18:35:15 +0200
+Subject: [PATCH 6/6] tests/acc_tests.c: Cover `XML_ParserReset` accounting
+ neutrality
+
+---
+ expat/tests/acc_tests.c | 32 ++++++++++++++++++++++++++++++++
+ 1 file changed, 32 insertions(+)
+
+diff --git a/expat/tests/acc_tests.c b/expat/tests/acc_tests.c
+index 5e2f0f0731..17de2c5fc8 100644
+--- a/expat/tests/acc_tests.c
++++ b/expat/tests/acc_tests.c
+@@ -475,6 +475,37 @@ START_TEST(test_amplification_isolated_external_parser) {
+ }
+ END_TEST
+
++START_TEST(test_amplification_reset_neutrality) {
++ // Speed up the test, chunk size expected to not matter in this test
++ if (g_chunkSize != 0)
++ return;
++
++ const char *const doc
++ = "<!DOCTYPE r [<!ENTITY e 'general entity'>]><r>&e;</r>";
++ XML_Parser parser = XML_ParserCreate(NULL);
++ assert_true(XML_SetPropertyDouble(
++ parser, XML_PROP_BILLION_LAUGHS_MAXIMUM_AMPLIFICATION, 1.0)
++ == XML_PROP_ERROR_NONE);
++ assert_true(XML_SetPropertyUInt64(
++ parser, XML_PROP_BILLION_LAUGHS_ACTIVATION_THRESHOLD, 0)
++ == XML_PROP_ERROR_NONE);
++
++ assert_true(_XML_Parse_SINGLE_BYTES(parser, doc, (int)strlen(doc),
++ /*isFinal=*/XML_TRUE)
++ == XML_STATUS_ERROR);
++ assert_true(XML_GetErrorCode(parser) == XML_ERROR_AMPLIFICATION_LIMIT_BREACH);
++
++ assert_true(XML_ParserReset(parser, NULL) == XML_STATUS_OK);
++
++ assert_true(_XML_Parse_SINGLE_BYTES(parser, doc, (int)strlen(doc),
++ /*isFinal=*/XML_TRUE)
++ == XML_STATUS_ERROR);
++ assert_true(XML_GetErrorCode(parser) == XML_ERROR_AMPLIFICATION_LIMIT_BREACH);
++
++ XML_ParserFree(parser);
++}
++END_TEST
++
+ #endif // XML_GE == 1
+
+ void
+@@ -491,6 +522,7 @@ make_accounting_test_case(Suite *s) {
+ tcase_add_test(tc_accounting, test_helper_unsigned_char_to_printable);
+ tcase_add_test__ifdef_xml_dtd(tc_accounting,
+ test_amplification_isolated_external_parser);
++ tcase_add_test(tc_accounting, test_amplification_reset_neutrality);
+ #else
+ UNUSED_P(s);
+ #endif /* XML_GE == 1 */
diff --git a/CVE-2026-115506.patch b/CVE-2026-115506.patch
new file mode 100644
index 0000000..9df6372
--- /dev/null
+++ b/CVE-2026-115506.patch
@@ -0,0 +1,2307 @@
+CVE-2026-115506: billion laughs protection detected amplification too late.
+https://github.com/libexpat/libexpat/pull/1433 (fix), plus its follow-ups
+https://github.com/libexpat/libexpat/pull/1436 (debug output)
+https://github.com/libexpat/libexpat/pull/1439 (CDATA/comment/PI regression, issue #1438)
+https://github.com/libexpat/libexpat/pull/1442 (tests)
+Prerequisites from 2.10.0 development: d545081f6a90, da504c0c1110 (#1417),
+b34f62d59354, b068d5a0a228 (#1415).
+
+From d545081f6a90792208e0d274888a352e2e5d894d Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Tue, 6 Oct 2026 19:37:45 +0200
+Subject: [PATCH] lib: Migrate `ENTITY.textLen` and `.processed` from `int` to
+ `size_t`
+
+---
+ expat/lib/xmlparse.c | 24 +++++++++++-------------
+ 1 file changed, 11 insertions(+), 13 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -312,8 +312,8 @@ typedef struct tag {
+ typedef struct {
+ const XML_Char *name;
+ const XML_Char *textPtr;
+- int textLen; /* length in XML_Chars */
+- int processed; /* # of processed bytes - when suspended */
++ size_t textLen; /* length in XML_Chars */
++ size_t processed; /* # of processed bytes - when suspended */
+ const XML_Char *systemId;
+ const XML_Char *base;
+ const XML_Char *publicId;
+@@ -5980,8 +5980,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ return XML_ERROR_NO_MEMORY;
+ }
+ parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
+- parser->m_declEntity->textLen
+- = (int)(poolLength(&dtd->entityValuePool));
++ parser->m_declEntity->textLen = poolLength(&dtd->entityValuePool);
+ poolFinish(&dtd->entityValuePool);
+ if (parser->m_entityDeclHandler) {
+ *eventEndPP = s;
+@@ -5989,7 +5988,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ parser->m_entityDeclHandler(
+ parser->m_handlerArg, parser->m_declEntity->name,
+ parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
+- parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
++ (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
+ afterHandler(parser);
+ handleDefault = XML_FALSE;
+ }
+@@ -6012,7 +6011,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ parser->m_entityDeclHandler(
+ parser->m_handlerArg, parser->m_declEntity->name,
+ parser->m_declEntity->is_param, parser->m_declEntity->textPtr,
+- parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
++ (int)parser->m_declEntity->textLen, parser->m_curBase, 0, 0, 0);
+ afterHandler(parser);
+ handleDefault = XML_FALSE;
+ }
+@@ -6826,7 +6825,7 @@ internalEntityProcessor(XML_Parser parser, const char *s, const char *end,
+ && (parser->m_parsingStatus.parsing == XML_SUSPENDED
+ || (parser->m_parsingStatus.parsing == XML_PARSING
+ && parser->m_reenter))) {
+- entity->processed = (int)(next - (const char *)entity->textPtr);
++ entity->processed = next - (const char *)entity->textPtr;
+ return result;
+ }
+
+@@ -6907,8 +6906,7 @@ storeAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
+ // processed. A XML_SUSPENDED check here is not required as
+ // appendAttributeValue will never suspend the parser.
+ if (nextInEntity < textEnd) {
+- entity->processed
+- = (int)(nextInEntity - (const char *)entity->textPtr);
++ entity->processed = nextInEntity - (const char *)entity->textPtr;
+ continue;
+ }
+ assert(nextInEntity == textEnd);
+@@ -7368,8 +7366,7 @@ callStoreEntityValue(XML_Parser parser, const ENCODING *enc,
+ // processed. A XML_SUSPENDED check here is not required as
+ // appendAttributeValue will never suspend the parser.
+ if (textEnd != nextInEntity) {
+- entity->processed
+- = (int)(nextInEntity - (const char *)entity->textPtr);
++ entity->processed = nextInEntity - (const char *)entity->textPtr;
+ continue;
+ }
+
+@@ -7430,7 +7427,7 @@ storeSelfEntityValue(XML_Parser parser, ENTITY *entity) {
+ return XML_ERROR_NO_MEMORY;
+ }
+ entity->textPtr = poolStart(pool);
+- entity->textLen = (int)(poolLength(pool));
++ entity->textLen = poolLength(pool);
+ poolFinish(pool);
+
+ return XML_ERROR_NONE;
+@@ -9147,7 +9144,8 @@ entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity,
+
+ fprintf(
+ stderr,
+- "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s length %d (xmlparse.c:%d)\n",
++ "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s length " EXPAT_FMT_SIZE_T(
++ "") " (xmlparse.c:%d)\n",
+ (void *)rootParser, rootParser->m_entity_stats.countEverOpened,
+ rootParser->m_entity_stats.currentDepth,
+ rootParser->m_entity_stats.maximumDepthSeen, indentDepth * 2, "",
+
+From da504c0c111086072172431c76867800673fbc34 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Tue, 6 Oct 2026 19:44:52 +0200
+Subject: [PATCH] lib: Migrate parameter `n` of function `poolCopyStringN` to
+ `size_t`
+
+---
+ expat/lib/xmlparse.c | 4 ++--
+ 1 file changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -598,7 +598,7 @@ static const XML_Char *poolCopyString(STRING_POOL *pool, const XML_Char *s);
+ static const XML_Char *poolCopyStringNoFinish(STRING_POOL *pool,
+ const XML_Char *s);
+ static const XML_Char *poolCopyStringN(STRING_POOL *pool, const XML_Char *s,
+- int n);
++ size_t n);
+ static const XML_Char *poolAppendString(STRING_POOL *pool, const XML_Char *s);
+
+ static int nextScaffoldPart(XML_Parser parser);
+@@ -8526,7 +8526,7 @@ poolCopyStringNoFinish(STRING_POOL *pool, const XML_Char *s) {
+ }
+
+ static const XML_Char *
+-poolCopyStringN(STRING_POOL *pool, const XML_Char *s, int n) {
++poolCopyStringN(STRING_POOL *pool, const XML_Char *s, size_t n) {
+ if (! pool->ptr && ! poolGrow(pool)) {
+ /* The following line is unreachable given the current usage of
+ * poolCopyStringN(). Currently it is called from exactly one
+
+From b34f62d5935495f61ef3d9d40779ca0ca7b432b2 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Tue, 6 Oct 2026 16:44:44 +0200
+Subject: [PATCH] lib: Stop delaying `callStoreEntityValue` error handling
+
+The delay is unexpected, and does not seem needed.
+
+The `const` is added to protect another upcoming pull request
+from writing into `result`, by accident.
+---
+ expat/lib/xmlparse.c | 8 +++++---
+ 1 file changed, 5 insertions(+), 3 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -5971,9 +5971,13 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ #if XML_GE == 1
+ // This will store the given replacement text in
+ // parser->m_declEntity->textPtr.
+- enum XML_Error result = callStoreEntityValue(
++ const enum XML_Error result = callStoreEntityValue(
+ parser, enc, s + enc->minBytesPerChar, next - enc->minBytesPerChar,
+ XML_ACCOUNT_NONE);
++ if (result != XML_ERROR_NONE) {
++ poolDiscard(&dtd->entityValuePool);
++ return result;
++ }
+ if (parser->m_declEntity) {
+ /* Detect and prevent signed integer overflow */
+ if ((size_t)poolLength(&dtd->entityValuePool) > (size_t)INT_MAX) {
+@@ -5994,8 +5998,6 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ }
+ } else
+ poolDiscard(&dtd->entityValuePool);
+- if (result != XML_ERROR_NONE)
+- return result;
+ #else
+ // This will store "&entity123;" in parser->m_declEntity->textPtr
+ // to end up as "&entity123;" in the handler.
+
+From b068d5a0a228029bb4aac50dc3f343971634f25e Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Thu, 8 Oct 2026 13:03:52 +0200
+Subject: [PATCH] lib: Add missing call to `poolDiscard` to function `doProlog`
+
+.. after the call to `callStoreEntityValue`.
+Follow-up to commit 30c2fc179ce5d2b1b1bae30bbe0dfddeac894e13.
+---
+ expat/lib/xmlparse.c | 1 +
+ 1 file changed, 1 insertion(+)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -5981,6 +5981,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ if (parser->m_declEntity) {
+ /* Detect and prevent signed integer overflow */
+ if ((size_t)poolLength(&dtd->entityValuePool) > (size_t)INT_MAX) {
++ poolDiscard(&dtd->entityValuePool);
+ return XML_ERROR_NO_MEMORY;
+ }
+ parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
+
+From 041b6cd115cde31a28375abc6e96e83ddab400fe Mon Sep 17 00:00:00 2001
+From: Shani Yosef <shani.yosef at echo.ai>
+Date: Sun, 10 May 2026 17:50:21 +0300
+Subject: [PATCH] Move definition of type XmlBigCount up to ease upcoming
+ changes
+
+Co-authored-by: Sebastian Pipping <sebastian at pipping.org>
+---
+ expat/lib/xmlparse.c | 3 ++-
+ 1 file changed, 2 insertions(+), 1 deletion(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -309,6 +309,8 @@ typedef struct tag {
+ BINDING *bindings;
+ } TAG;
+
++typedef unsigned long long XmlBigCount;
++
+ typedef struct {
+ const XML_Char *name;
+ const XML_Char *textPtr;
+@@ -455,7 +457,6 @@ enum XML_Account {
+ };
+
+ #if XML_GE == 1
+-typedef unsigned long long XmlBigCount;
+ typedef struct accounting {
+ XmlBigCount countBytesDirect;
+ XmlBigCount countBytesIndirect;
+
+From d89d67e0d7f0917b0a65ec8bb54fc8d66c1049d2 Mon Sep 17 00:00:00 2001
+From: Shani Yosef <shani.yosef at echo.ai>
+Date: Mon, 11 May 2026 11:43:28 +0300
+Subject: [PATCH] Add extraBytes parameter to accountingGetCurrentAmplification
+
+This prepares the function for reuse in processEntity, where we need
+to compute the projected amplification factor including not yet expanded
+bytes. Existing callers pass 0 to preserve current behavior.
+
+Co-authored-by: Sebastian Pipping <sebastian at pipping.org>
+---
+ expat/lib/xmlparse.c | 15 +++++++++------
+ 1 file changed, 9 insertions(+), 6 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -621,7 +621,8 @@ static void parserInit(XML_Parser parser, const XML_Char *encodingName,
+ bool isReset);
+
+ #if XML_GE == 1
+-static float accountingGetCurrentAmplification(XML_Parser rootParser);
++static float accountingGetCurrentAmplification(XML_Parser rootParser,
++ XmlBigCount extraBytes);
+ static void accountingReportStats(XML_Parser originParser, const char *epilog);
+ static void accountingOnAbort(XML_Parser originParser);
+ static void accountingReportDiff(XML_Parser rootParser,
+@@ -8975,18 +8976,20 @@ copyString(const XML_Char *s, XML_Parser parser) {
+ #if XML_GE == 1
+
+ static float
+-accountingGetCurrentAmplification(XML_Parser rootParser) {
++accountingGetCurrentAmplification(XML_Parser rootParser,
++ XmlBigCount extraBytes) {
+ // 1.........1.........12 => 22
+ const size_t lenOfShortestInclude = sizeof("<!ENTITY a SYSTEM 'b'>") - 1;
+ const XmlBigCount countBytesOutput
+ = rootParser->m_accounting.countBytesDirect
+- + rootParser->m_accounting.countBytesIndirect;
++ + rootParser->m_accounting.countBytesIndirect + extraBytes;
+ const float amplificationFactor
+ = rootParser->m_accounting.countBytesDirect
+ ? ((float)countBytesOutput
+ / (float)(rootParser->m_accounting.countBytesDirect))
+ : ((float)(lenOfShortestInclude
+- + rootParser->m_accounting.countBytesIndirect)
++ + rootParser->m_accounting.countBytesIndirect
++ + extraBytes)
+ / (float)lenOfShortestInclude);
+ assert(! rootParser->m_parentParser);
+ return amplificationFactor;
+@@ -9002,7 +9005,7 @@ accountingReportStats(XML_Parser originParser, const char *epilog) {
+ }
+
+ const float amplificationFactor
+- = accountingGetCurrentAmplification(rootParser);
++ = accountingGetCurrentAmplification(rootParser, 0);
+ fprintf(stderr,
+ "expat: Accounting(%p): Direct " EXPAT_FMT_ULL(
+ "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s",
+@@ -9093,7 +9096,7 @@ accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
+ = rootParser->m_accounting.countBytesDirect
+ + rootParser->m_accounting.countBytesIndirect;
+ const float amplificationFactor
+- = accountingGetCurrentAmplification(rootParser);
++ = accountingGetCurrentAmplification(rootParser, 0);
+ const XML_Bool tolerated
+ = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes)
+ || (amplificationFactor
+
+From eb525ded2da77214926e20af9ad8b260e073df5c Mon Sep 17 00:00:00 2001
+From: Shani Yosef <shani.yosef at echo.ai>
+Date: Tue, 25 Aug 2026 11:45:04 +0300
+Subject: [PATCH] Precompute entity expanded sizes to detect amplification
+ attacks early
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+The existing billion laughs protection must process the full entity
+expansion before the amplification ratio exceeds the limit. With a
+large DTD (~12 MB), this allows ~47 seconds of CPU time before
+rejection. Precomputing each entity's fully expanded size on first
+expansion enables instant rejection at entity expansion time.
+
+Forward references (an entity referencing one declared later) are
+resolved lazily, the first time an entity is expanded, using an
+iterative, stack-based depth-first search over the entity reference
+graph; this keeps resolution linear in the total replacement-text size
+and avoids unbounded recursion. A dedicated ENTITY flag marks entities
+currently on the search stack, so reference cycles are detected without
+overloading the entity->open recursion guard.
+
+If an entity's expanded size overflows XmlBigCount, parsing is aborted
+immediately with XML_ERROR_AMPLIFICATION_LIMIT_BREACH rather than
+pinning the size to a sentinel value; such an entity could never expand
+within the limit anyway.
+
+Co-authored-by: Sebastian Pipping <sebastian at pipping.org>
+Co-authored-by: Berkay Eren Ürün <berkay.ueruen at siemens.com>
+---
+ expat/lib/xmlparse.c | 442 +++++++++++++++++++++++++++++++++++++++----
+ 1 file changed, 403 insertions(+), 39 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -327,6 +327,16 @@ typedef struct {
+ entities are processed and closed */
+ bool is_param;
+ bool is_internal; /* true if declared in internal subset outside PE */
++#if XML_GE == 1
++ /* Indirect accounting bytes charged when this entity is expanded: 1 per text
++ character, plus each reference's "&name;"/"%name;" token length and its own
++ expansion. Matches XML_ACCOUNT_ENTITY_EXPANSION, so it is not the
++ replacement-text size. 0 means "not computed yet" (an empty entity is 0
++ too, told apart by textLen == 0). */
++ XmlBigCount expandedSize;
++ bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first
++ search stack; used for cycle detection */
++#endif /* XML_GE == 1 */
+ } ENTITY;
+
+ typedef struct {
+@@ -480,6 +490,14 @@ typedef struct entity_stats {
+ unsigned int maximumDepthSeen;
+ unsigned long debugLevel;
+ } ENTITY_STATS;
++
++/* One pending entity-analysis task on the explicit stack used by
++ resolveEntityClosureExpandedSize's depth-first search over the entity
++ reference graph. */
++typedef struct {
++ ENTITY *entity; /* entity currently being scanned */
++ const XML_Char *pos; /* cursor position into the entity's replacement text */
++} ENTITY_ANALYSIS_TASK;
+ #endif /* XML_GE == 1 */
+
+ typedef enum XML_Error Processor(XML_Parser parser, const char *start,
+@@ -562,6 +580,9 @@ static enum XML_Error callStoreEntityValue(XML_Parser parser,
+ const ENCODING *enc,
+ const char *start, const char *end,
+ enum XML_Account account);
++static enum XML_Error resolveEntityClosureExpandedSize(XML_Parser parser,
++ HASH_TABLE *table,
++ ENTITY *root);
+ #else
+ static enum XML_Error storeSelfEntityValue(XML_Parser parser, ENTITY *entity);
+ #endif
+@@ -622,9 +643,12 @@ static void parserInit(XML_Parser parser, const XML_Char *encodingName,
+
+ #if XML_GE == 1
+ static float accountingGetCurrentAmplification(XML_Parser rootParser,
+- XmlBigCount extraBytes);
+-static void accountingReportStats(XML_Parser originParser, const char *epilog);
+-static void accountingOnAbort(XML_Parser originParser);
++ XmlBigCount extraIndirectBytes);
++static void accountingReportStats(XML_Parser originParser, const char *epilog,
++ XmlBigCount extraIndirectBytes,
++ int sourceLine);
++static void accountingOnAbort(XML_Parser originParser,
++ XmlBigCount extraIndirectBytes, int sourceLine);
+ static void accountingReportDiff(XML_Parser rootParser,
+ unsigned int levelsAwayFromRootParser,
+ const char *before, const char *after,
+@@ -634,6 +658,9 @@ static XML_Bool accountingDiffTolerated(XML_Parser originParser, int tok,
+ const char *before, const char *after,
+ int source_line,
+ enum XML_Account account);
++static XML_Bool
++accountingCurrentAmplificationTolerated(XML_Parser rootParser,
++ XmlBigCount extraIndirectBytes);
+
+ static void entityTrackingReportStats(XML_Parser parser, ENTITY *entity,
+ const char *action, int sourceLine);
+@@ -3506,7 +3533,7 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start,
+ #if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, start, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #endif /* XML_GE == 1 */
+@@ -3640,7 +3667,7 @@ doContent(XML_Parser parser, int startTagLevel, const ENCODING *enc,
+ : next;
+ if (! accountingDiffTolerated(parser, tok, s, accountAfter, __LINE__,
+ account)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #endif
+@@ -4913,7 +4940,7 @@ doCdataSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
+ int tok = XmlCdataSectionTok(enc, s, end, &next);
+ #if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #else
+@@ -5085,7 +5112,7 @@ doIgnoreSection(XML_Parser parser, const ENCODING *enc, const char **startPtr,
+ # if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ # endif
+@@ -5177,7 +5204,7 @@ processXmlDecl(XML_Parser parser, int isGeneralTextEntity, const char *s,
+ #if XML_GE == 1
+ if (! accountingDiffTolerated(parser, XML_TOK_XML_DECL, s, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #endif
+@@ -5398,7 +5425,7 @@ entityValueInitProcessor(XML_Parser parser, const char *s, const char *end,
+ # if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ # endif
+@@ -5451,7 +5478,7 @@ externalParEntProcessor(XML_Parser parser, const char *s, const char *end,
+ else if (tok == XML_TOK_BOM) {
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+
+@@ -5630,7 +5657,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ break;
+ default:
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__, account)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ }
+@@ -5793,7 +5820,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ handleDefault = XML_FALSE;
+ }
+ break;
+- case XML_ROLE_INSTANCE_START:
++ case XML_ROLE_INSTANCE_START: {
+ #ifdef XML_DTD
+ /* if there is no DOCTYPE declaration then now is the
+ last chance to read the foreign DTD
+@@ -5837,6 +5864,7 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ #endif /* XML_DTD */
+ parser->m_processor = contentProcessor;
+ return contentProcessor(parser, s, end, nextPtr);
++ }
+ case XML_ROLE_ATTLIST_ELEMENT_NAME:
+ parser->m_declElementType = getElementType(parser, enc, s, next);
+ if (! parser->m_declElementType)
+@@ -6661,7 +6689,7 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end,
+ #if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, s, next, __LINE__,
+ XML_ACCOUNT_DIRECT)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #endif
+@@ -6728,6 +6756,278 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end,
+ }
+ }
+
++#if XML_GE == 1
++// Checks `name` for being a predefined entity (i.e. one of "amp", "apos", "gt",
++// "lt", "quot"). Similar in implementation to function
++// `PREFIX(predefinedEntityName)` but operating on an `XML_Char` string with an
++// explicit length, instead. Returns
++// ASCII_AMP/ASCII_APOS/ASCII_GT/ASCII_LT/ASCII_QUOT for a match or 0 for no
++// match.
++static int
++isPredefinedEntityName(const XML_Char *name, size_t nameLen) {
++ switch (nameLen) {
++ case 2:
++ // Wanted: "lt" or "gt"
++ if (name[1] != XML_T(ASCII_t))
++ break;
++ switch (name[0]) {
++ case XML_T(ASCII_l):
++ return ASCII_LT;
++ case XML_T(ASCII_g):
++ return ASCII_GT;
++ }
++ break;
++ case 3:
++ // Wanted: "amp"
++ if (name[0] == XML_T(ASCII_a) && name[1] == XML_T(ASCII_m)
++ && name[2] == XML_T(ASCII_p))
++ return ASCII_AMP;
++ break;
++ case 4:
++ // Wanted: "apos" or "quot"
++ switch (name[0]) {
++ case XML_T(ASCII_a):
++ if (name[1] == XML_T(ASCII_p) && name[2] == XML_T(ASCII_o)
++ && name[3] == XML_T(ASCII_s))
++ return ASCII_APOS;
++ break;
++ case XML_T(ASCII_q):
++ if (name[1] == XML_T(ASCII_u) && name[2] == XML_T(ASCII_o)
++ && name[3] == XML_T(ASCII_t))
++ return ASCII_QUOT;
++ break;
++ }
++ }
++ return 0;
++}
++
++/* How a scanEntityText call ended. */
++enum EntityScanResult {
++ ENTITY_SCAN_COMPLETE, /* reached end of text; *expandedSize is final */
++ ENTITY_SCAN_BLOCKED, /* stopped at a defined entity whose expanded
++ size has not been computed yet; *blockerOut
++ names the entity whose size to compute
++ first */
++ ENTITY_SCAN_OVERFLOW /* the expanded size would exceed XmlBigCount;
++ callers must abort parsing */
++};
++
++/* Scan `entity`'s body, starting at `*posPtr`, accumulating the expanded
++ size into `*expandedSize`.
++
++ Return value: how the scan ended, see enum EntityScanResult.
++
++ *blockerOut (out, set only for ENTITY_SCAN_BLOCKED):
++ The non-empty entity the scan stopped at because its expanded size
++ has not been computed yet. The caller computes that size first and
++ calls again with *posPtr unchanged to resume.
++ The pointer is borrowed from the entity hash table (via lookup), not
++ a new allocation, so it must not be freed.
++
++ *posPtr (in/out, scan cursor):
++ Advanced to end-of-text on a complete scan, or parked at the
++ offending reference otherwise, so a follow-up call resumes from
++ the same position. Not meaningful after ENTITY_SCAN_OVERFLOW.
++
++ *expandedSize (in/out, expanded-byte accumulator):
++ The expanded size of this one `entity` (its text plus the expandedSize
++ of entities it references), not a total across all entities. Not
++ meaningful after ENTITY_SCAN_OVERFLOW; the overflowing value is never
++ stored anywhere. */
++static enum EntityScanResult
++scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
++ XmlBigCount *expandedSize, ENTITY **blockerOut) {
++ *blockerOut = NULL;
++ const XML_Char refChar = entity->is_param ? XML_T('%') : XML_T('&');
++ HASH_TABLE *const refTable
++# ifdef XML_DTD
++ = entity->is_param ? &parser->m_dtd->paramEntities
++ : &parser->m_dtd->generalEntities;
++# else
++ = &parser->m_dtd->generalEntities;
++# endif
++
++ const XML_Char *pos = *posPtr;
++ const XML_Char *const end = entity->textPtr + entity->textLen;
++
++ while (pos < end) {
++ if (*pos != refChar) {
++ // Detect and avoid integer overflow
++ if (*expandedSize == (XmlBigCount)(-1))
++ return ENTITY_SCAN_OVERFLOW;
++ (*expandedSize)++;
++ pos++;
++ continue;
++ }
++
++ const XML_Char *nameStart = pos + 1;
++ const XML_Char *nameEnd = nameStart;
++ while (nameEnd < end && *nameEnd != XML_T(';'))
++ nameEnd++;
++
++ if (nameEnd >= end) {
++ /* Unterminated reference at end of text: treat the trailing
++ bytes as literal characters. */
++ XmlBigCount addend = (XmlBigCount)(end - pos);
++ // Detect and avoid integer overflow
++ if (*expandedSize > (XmlBigCount)(-1) - addend)
++ return ENTITY_SCAN_OVERFLOW;
++ *expandedSize += addend;
++ *posPtr = end;
++ return ENTITY_SCAN_COMPLETE;
++ }
++
++ const size_t nameLen = (size_t)(nameEnd - nameStart);
++
++ /* At runtime the whole "&name;"/"%name;" token is re-scanned and charged to
++ the indirect accounting, then its expansion is charged separately; so
++ every reference below counts this token length plus its expansion. */
++ const XmlBigCount refTokenLen
++ = (XmlBigCount)(/*sigil*/ 1 + nameLen + /*semicolon*/ 1);
++
++ ENTITY *refEntity
++ = (ENTITY *)lookupWithLength(parser, refTable, nameStart, nameLen, 0);
++
++ XmlBigCount addend = 0;
++ if (! refEntity) {
++ /* Predefined entities (amp/lt/gt/quot/apos) are general-only, hence the
++ `! entity->is_param` guard, and expand to a single character. */
++ if (! entity->is_param && isPredefinedEntityName(nameStart, nameLen)) {
++ addend = refTokenLen + 1;
++ } else {
++ /* Undefined entity: expands to nothing, so only the token. */
++ addend = refTokenLen;
++ }
++ } else if (refEntity->beingAnalyzed) {
++ /* Cycle: refEntity is already on the depth-first search stack, so its
++ expandedSize is not final yet; charge just the token. Do not fail the
++ parse here: per XML 1.0r4,
++ "A parsed entity MUST NOT contain a recursive reference to
++ itself, either directly or indirectly", but also "Only parsed
++ entities that are referenced directly or indirectly within the
++ document are required to be well-formed" - so a declared-but-
++ never-expanded cycle must be accepted; if the cycle is actually
++ expanded, the runtime recursive-ref check reports
++ XML_ERROR_RECURSIVE_ENTITY_REF. */
++ addend = refTokenLen;
++ } else if (refEntity->textLen > 0 && refEntity->expandedSize == 0) {
++ /* Non-empty entity whose expanded size has not been computed yet;
++ report refEntity as a blocker so the caller can compute its size
++ first. */
++ *posPtr = pos;
++ *blockerOut = refEntity;
++ return ENTITY_SCAN_BLOCKED;
++ } else if (refEntity->expandedSize > 0) {
++ /* refEntity is fully resolved: expandedSize holds its final expanded
++ size (a non-zero value is never a partial here - the only entity that
++ briefly holds a partial is one currently on the resolve stack, which
++ is caught by the beingAnalyzed branch above). Add the token plus that
++ expansion. */
++ if (refEntity->expandedSize > (XmlBigCount)(-1) - refTokenLen)
++ return ENTITY_SCAN_OVERFLOW;
++ addend = refTokenLen + refEntity->expandedSize;
++ } else {
++ /* Empty entity (textLen == 0): expands to nothing, so only the token. */
++ addend = refTokenLen;
++ }
++
++ // Detect and avoid integer overflow
++ if (*expandedSize > (XmlBigCount)(-1) - addend)
++ return ENTITY_SCAN_OVERFLOW;
++ *expandedSize += addend;
++ pos = nameEnd + 1;
++ }
++
++ /* Loop only exits here with pos == end (a complete scan). */
++ assert(pos == end);
++ *posPtr = end;
++ return ENTITY_SCAN_COMPLETE;
++}
++
++/* Resolve expandedSize using an iterative depth-first search over the
++ reference graph. Each entity is scanned at most twice (once on push,
++ once after its blocker resolves), so the total work is O(N + T) where
++ N is the number of entities and T is the sum of all entities' textLen.
++ `entity->beingAnalyzed` marks the entities currently on the stack for
++ cycle detection; it is cleared again on pop.
++ Returns XML_ERROR_NO_MEMORY if the stack cannot be allocated, and
++ XML_ERROR_AMPLIFICATION_LIMIT_BREACH if an entity's expanded size
++ overflows XmlBigCount. */
++static enum XML_Error
++resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
++ ENTITY *root) {
++ if (root == NULL || root->expandedSize != 0 || root->textPtr == NULL
++ || root->textLen == 0)
++ return XML_ERROR_NONE;
++
++ if (table->used == 0)
++ return XML_ERROR_NONE;
++
++ // Detect and avoid integer overflow
++ if (table->used > SIZE_MAX / sizeof(ENTITY_ANALYSIS_TASK))
++ return XML_ERROR_NO_MEMORY;
++
++ ENTITY_ANALYSIS_TASK *stack
++ = MALLOC(parser, sizeof(ENTITY_ANALYSIS_TASK) * table->used);
++ if (stack == NULL)
++ return XML_ERROR_NO_MEMORY;
++
++ size_t top = 0;
++ stack[top].entity = root;
++ stack[top].pos = root->textPtr;
++ root->beingAnalyzed = XML_TRUE;
++ top++;
++
++ while (top > 0) {
++ ENTITY_ANALYSIS_TASK *task = &stack[top - 1];
++ ENTITY *e = task->entity;
++ XmlBigCount sizeSoFar = e->expandedSize;
++ ENTITY *blocker = NULL;
++ const enum EntityScanResult scanResult
++ = scanEntityText(parser, e, &task->pos, &sizeSoFar, &blocker);
++
++ switch (scanResult) {
++ case ENTITY_SCAN_OVERFLOW:
++ /* Abort parsing right away; the beingAnalyzed marks still set on
++ the stacked entities do not matter once the parse is dead. */
++ FREE(parser, stack);
++ /* expandedSize overflowed; pass SIZE_MAX (unrepresentable size). */
++ accountingOnAbort(parser, SIZE_MAX, __LINE__);
++ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
++
++ case ENTITY_SCAN_COMPLETE:
++ e->expandedSize = sizeSoFar;
++ e->beingAnalyzed = XML_FALSE;
++ top--;
++ break;
++
++ case ENTITY_SCAN_BLOCKED:
++ /* Save the size accumulated so far; together with task->pos it is
++ the state that lets the scan resume once the blocker's size has
++ been computed. This is the one place where expandedSize briefly
++ holds neither 0 nor the final size - only while the entity is
++ on the stack, where the beingAnalyzed check in scanEntityText
++ keeps every other reader away from the intermediate value. */
++ e->expandedSize = sizeSoFar;
++
++ /* Push the blocker. A blocker's expanded size is always still
++ uncomputed and it is never already on the stack, so each entity
++ is pushed at most once and top <= table->used. */
++ assert(! blocker->beingAnalyzed);
++ assert(top < table->used);
++ stack[top].entity = blocker;
++ stack[top].pos = blocker->textPtr;
++ blocker->beingAnalyzed = XML_TRUE;
++ top++;
++ break;
++ }
++ }
++
++ FREE(parser, stack);
++ return XML_ERROR_NONE;
++}
++#endif /* XML_GE == 1 */
++
+ static enum XML_Error
+ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl,
+ enum EntityType type) {
+@@ -6756,6 +7056,37 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl,
+ /* LCOV_EXCL_STOP */
+ }
+
++#if XML_GE == 1
++ // Compute entity size assuming immediate access
++ if (entity->textLen > 0 && entity->expandedSize == 0) {
++ HASH_TABLE *const table
++# ifdef XML_DTD
++ = entity->is_param ? &parser->m_dtd->paramEntities
++ : &parser->m_dtd->generalEntities;
++# else
++ = &parser->m_dtd->generalEntities;
++# endif
++ const enum XML_Error result
++ = resolveEntityClosureExpandedSize(parser, table, entity);
++ if (result != XML_ERROR_NONE)
++ return result;
++ }
++
++ /* Reject an amplification attack before acquiring openEntity, so a rejected
++ entity leaks nothing and leaves entity state untouched. */
++ if (entity->expandedSize > 0) {
++ const XML_Parser rootParser = getRootParserOf(parser, NULL);
++ /* Overflow of expandedSize aborts parsing during resolution
++ (on first expansion), so the stored value here is always exact. */
++ const XmlBigCount expandedBytes = entity->expandedSize;
++ if (accountingCurrentAmplificationTolerated(rootParser, expandedBytes)
++ != XML_TRUE) {
++ accountingOnAbort(rootParser, expandedBytes, __LINE__);
++ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
++ }
++ }
++#endif /* XML_GE == 1 */
++
+ if (*freeEntityList) {
+ openEntity = *freeEntityList;
+ *freeEntityList = openEntity->next;
+@@ -6768,7 +7099,7 @@ processEntity(XML_Parser parser, ENTITY *entity, bool betweenDecl,
+ entity->hasMore = true;
+ #if XML_GE == 1
+ entityTrackingOnOpen(parser, entity, __LINE__);
+-#endif
++#endif /* XML_GE == 1 */
+ entity->processed = 0;
+ openEntity->next = *openEntityList;
+ *openEntityList = openEntity;
+@@ -6970,7 +7301,7 @@ appendAttributeValue(XML_Parser parser, const ENCODING *enc, XML_Bool isCdata,
+ int tok = XmlAttributeValueTok(enc, ptr, end, &next);
+ #if XML_GE == 1
+ if (! accountingDiffTolerated(parser, tok, ptr, next, __LINE__, account)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ }
+ #endif
+@@ -7186,7 +7517,7 @@ storeEntityValue(XML_Parser parser, const ENCODING *enc,
+
+ if (! accountingDiffTolerated(parser, tok, entityTextPtr, next, __LINE__,
+ account)) {
+- accountingOnAbort(parser);
++ accountingOnAbort(parser, 0, __LINE__);
+ result = XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+ goto endEntityValue;
+ }
+@@ -8977,26 +9308,26 @@ copyString(const XML_Char *s, XML_Parser parser) {
+
+ static float
+ accountingGetCurrentAmplification(XML_Parser rootParser,
+- XmlBigCount extraBytes) {
++ XmlBigCount extraIndirectBytes) {
+ // 1.........1.........12 => 22
+ const size_t lenOfShortestInclude = sizeof("<!ENTITY a SYSTEM 'b'>") - 1;
+- const XmlBigCount countBytesOutput
+- = rootParser->m_accounting.countBytesDirect
+- + rootParser->m_accounting.countBytesIndirect + extraBytes;
++ /* Add as floats: u64 counts (max ~1.8e19) are far below FLT_MAX, so the sum
++ is always finite and cannot wrap the way an unsigned integer add could. */
++ const float indirect = (float)rootParser->m_accounting.countBytesIndirect
++ + (float)extraIndirectBytes;
+ const float amplificationFactor
+ = rootParser->m_accounting.countBytesDirect
+- ? ((float)countBytesOutput
++ ? (((float)rootParser->m_accounting.countBytesDirect + indirect)
+ / (float)(rootParser->m_accounting.countBytesDirect))
+- : ((float)(lenOfShortestInclude
+- + rootParser->m_accounting.countBytesIndirect
+- + extraBytes)
++ : (((float)lenOfShortestInclude + indirect)
+ / (float)lenOfShortestInclude);
+ assert(! rootParser->m_parentParser);
+ return amplificationFactor;
+ }
+
+ static void
+-accountingReportStats(XML_Parser originParser, const char *epilog) {
++accountingReportStats(XML_Parser originParser, const char *epilog,
++ XmlBigCount extraIndirectBytes, int sourceLine) {
+ const XML_Parser rootParser = getRootParserOf(originParser, NULL);
+ assert(! rootParser->m_parentParser);
+
+@@ -9004,19 +9335,33 @@ accountingReportStats(XML_Parser originParser, const char *epilog) {
+ return;
+ }
+
++ /* On an early abort the amplifying bytes have not been charged to the
++ indirect counter yet; fold extraIndirectBytes in (with overflow detection)
++ so the reported byte count and amplification reflect what was detected. */
++ const XmlBigCount indirect = rootParser->m_accounting.countBytesIndirect;
++ const XmlBigCount indirectWithExtra
++ = (extraIndirectBytes > (XmlBigCount)(-1) - indirect)
++ ? (XmlBigCount)(-1)
++ : indirect + extraIndirectBytes;
+ const float amplificationFactor
+- = accountingGetCurrentAmplification(rootParser, 0);
++ = accountingGetCurrentAmplification(rootParser, extraIndirectBytes);
+ fprintf(stderr,
+ "expat: Accounting(%p): Direct " EXPAT_FMT_ULL(
+ "10") ", indirect " EXPAT_FMT_ULL("10") ", amplification %8.2f%s",
+ (void *)rootParser, rootParser->m_accounting.countBytesDirect,
+- rootParser->m_accounting.countBytesIndirect,
+- (double)amplificationFactor, epilog);
++ indirectWithExtra, (double)amplificationFactor, epilog);
++ /* An abort has no accountingReportDiff before it, so append the originating
++ source line here to show which rejection site these stats belong to. */
++ if (sourceLine > 0) {
++ fprintf(stderr, " (xmlparse.c:%d)\n", sourceLine);
++ }
+ }
+
+ static void
+-accountingOnAbort(XML_Parser originParser) {
+- accountingReportStats(originParser, " ABORTING\n");
++accountingOnAbort(XML_Parser originParser, XmlBigCount extraIndirectBytes,
++ int sourceLine) {
++ accountingReportStats(originParser, " ABORTING", extraIndirectBytes,
++ sourceLine);
+ }
+
+ static void
+@@ -9056,6 +9401,32 @@ accountingReportDiff(XML_Parser rootParser,
+ fprintf(stderr, "\"\n");
+ }
+
++static XML_Bool
++accountingCurrentAmplificationTolerated(XML_Parser rootParser,
++ XmlBigCount extraIndirectBytes) {
++ assert(! rootParser->m_parentParser);
++
++ const XmlBigCount countBytesOutput
++ = rootParser->m_accounting.countBytesDirect
++ + rootParser->m_accounting.countBytesIndirect;
++ /* Overflow check: extraIndirectBytes can be SIZE_MAX, which would otherwise
++ wrap the unsigned total around to a small value and wrongly report the
++ output as tolerated. */
++ const XmlBigCount countBytesOutputWithExtra
++ = (extraIndirectBytes > (XmlBigCount)(-1) - countBytesOutput)
++ ? (XmlBigCount)(-1)
++ : countBytesOutput + extraIndirectBytes;
++ const float amplificationFactor
++ = accountingGetCurrentAmplification(rootParser, extraIndirectBytes);
++ const XML_Bool tolerated
++ = (countBytesOutputWithExtra
++ < rootParser->m_accounting.activationThresholdBytes)
++ || (amplificationFactor
++ <= rootParser->m_accounting.maximumAmplificationFactor);
++
++ return tolerated;
++}
++
+ static XML_Bool
+ accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
+ const char *after, int source_line,
+@@ -9092,18 +9463,11 @@ accountingDiffTolerated(XML_Parser originParser, int tok, const char *before,
+ return XML_FALSE;
+ *additionTarget += bytesMore;
+
+- const XmlBigCount countBytesOutput
+- = rootParser->m_accounting.countBytesDirect
+- + rootParser->m_accounting.countBytesIndirect;
+- const float amplificationFactor
+- = accountingGetCurrentAmplification(rootParser, 0);
+ const XML_Bool tolerated
+- = (countBytesOutput < rootParser->m_accounting.activationThresholdBytes)
+- || (amplificationFactor
+- <= rootParser->m_accounting.maximumAmplificationFactor);
++ = accountingCurrentAmplificationTolerated(rootParser, 0);
+
+ if (rootParser->m_accounting.debugLevel >= 2u) {
+- accountingReportStats(rootParser, "");
++ accountingReportStats(rootParser, "", 0, 0);
+ accountingReportDiff(rootParser, levelsAwayFromRootParser, before, after,
+ bytesMore, source_line, account);
+ }
+
+From 711a9b2d9fcae0dc622b3d7edb73b0ad3026c942 Mon Sep 17 00:00:00 2001
+From: Shani Yosef <shani.yosef at echo.ai>
+Date: Sun, 6 Sep 2026 10:59:02 +0300
+Subject: [PATCH] Extend entity debug output with scanning progress
+MIME-Version: 1.0
+Content-Type: text/plain; charset=UTF-8
+Content-Transfer-Encoding: 8bit
+
+- Migrate entity scan position from analysis task to entity structure
+- Wrap calls to scanEntityText by two calls to entityTrackingReportStats
+- Extend entityTrackingReportStats for entity scanning details
+- Document that the space at the end of "OPEN " length-matches "CLOSE"
+- Make scanEntityText support blockerOut==NULL to simplify invocation
+
+Co-authored-by: Sebastian Pipping <sebastian at pipping.org>
+Co-authored-by: Berkay Eren Ürün <berkay.ueruen at siemens.com>
+---
+ expat/lib/xmlparse.c | 97 ++++++++++++++++++++++++++++++++++----------
+ 1 file changed, 75 insertions(+), 22 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -336,7 +336,11 @@ typedef struct {
+ XmlBigCount expandedSize;
+ bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first
+ search stack; used for cycle detection */
+-#endif /* XML_GE == 1 */
++ const XML_Char
++ *scanPtr; /* cursor position into the entity's replacement text; NULL when
++ `textPtr` is NULL, else a pointer into the entity value,
++ ranging from `.textPtr` to `.textPtr + .textLen`. */
++#endif /* XML_GE == 1 */
+ } ENTITY;
+
+ typedef struct {
+@@ -495,8 +499,7 @@ typedef struct entity_stats {
+ resolveEntityClosureExpandedSize's depth-first search over the entity
+ reference graph. */
+ typedef struct {
+- ENTITY *entity; /* entity currently being scanned */
+- const XML_Char *pos; /* cursor position into the entity's replacement text */
++ ENTITY *entity; /* entity currently being scanned */
+ } ENTITY_ANALYSIS_TASK;
+ #endif /* XML_GE == 1 */
+
+@@ -668,6 +671,10 @@ static void entityTrackingOnOpen(XML_Parser parser, ENTITY *entity,
+ int sourceLine);
+ static void entityTrackingOnClose(XML_Parser parser, ENTITY *entity,
+ int sourceLine);
++static void entityTrackingOnScanStart(XML_Parser parser, ENTITY *entity,
++ int sourceLine);
++static void entityTrackingOnScanStop(XML_Parser parser, ENTITY *entity,
++ int sourceLine);
+ #endif /* XML_GE == 1 */
+
+ static XML_Parser getRootParserOf(XML_Parser parser,
+@@ -6014,8 +6021,10 @@ doProlog(XML_Parser parser, const ENCODING *enc, const char *s, const char *end,
+ poolDiscard(&dtd->entityValuePool);
+ return XML_ERROR_NO_MEMORY;
+ }
+- parser->m_declEntity->textPtr = poolStart(&dtd->entityValuePool);
++ const XML_Char *const valueStart = poolStart(&dtd->entityValuePool);
++ parser->m_declEntity->textPtr = valueStart;
+ parser->m_declEntity->textLen = poolLength(&dtd->entityValuePool);
++ parser->m_declEntity->scanPtr = valueStart;
+ poolFinish(&dtd->entityValuePool);
+ if (parser->m_entityDeclHandler) {
+ *eventEndPP = s;
+@@ -6837,7 +6846,8 @@ enum EntityScanResult {
+ static enum EntityScanResult
+ scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
+ XmlBigCount *expandedSize, ENTITY **blockerOut) {
+- *blockerOut = NULL;
++ if (blockerOut != NULL)
++ *blockerOut = NULL;
+ const XML_Char refChar = entity->is_param ? XML_T('%') : XML_T('&');
+ HASH_TABLE *const refTable
+ # ifdef XML_DTD
+@@ -6915,7 +6925,8 @@ scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
+ report refEntity as a blocker so the caller can compute its size
+ first. */
+ *posPtr = pos;
+- *blockerOut = refEntity;
++ if (blockerOut != NULL)
++ *blockerOut = refEntity;
+ return ENTITY_SCAN_BLOCKED;
+ } else if (refEntity->expandedSize > 0) {
+ /* refEntity is fully resolved: expandedSize holds its final expanded
+@@ -6974,7 +6985,6 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+
+ size_t top = 0;
+ stack[top].entity = root;
+- stack[top].pos = root->textPtr;
+ root->beingAnalyzed = XML_TRUE;
+ top++;
+
+@@ -6983,8 +6993,27 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+ ENTITY *e = task->entity;
+ XmlBigCount sizeSoFar = e->expandedSize;
+ ENTITY *blocker = NULL;
++
++ entityTrackingOnScanStart(parser, e, __LINE__);
++
+ const enum EntityScanResult scanResult
+- = scanEntityText(parser, e, &task->pos, &sizeSoFar, &blocker);
++ = scanEntityText(parser, e, &e->scanPtr, &sizeSoFar, &blocker);
++ switch (scanResult) {
++ case ENTITY_SCAN_COMPLETE:
++ case ENTITY_SCAN_BLOCKED:
++ /* Save the size accumulated so far; together with task->pos it is
++ the state that lets the scan resume once the blocker's size has
++ been computed. This is the one place where expandedSize briefly
++ holds neither 0 nor the final size - only while the entity is
++ on the stack, where the beingAnalyzed check in scanEntityText
++ keeps every other reader away from the intermediate value. */
++ e->expandedSize = sizeSoFar;
++ break;
++ default:
++ break;
++ }
++
++ entityTrackingOnScanStop(parser, e, __LINE__);
+
+ switch (scanResult) {
+ case ENTITY_SCAN_OVERFLOW:
+@@ -6996,27 +7025,17 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+ return XML_ERROR_AMPLIFICATION_LIMIT_BREACH;
+
+ case ENTITY_SCAN_COMPLETE:
+- e->expandedSize = sizeSoFar;
+ e->beingAnalyzed = XML_FALSE;
+ top--;
+ break;
+
+ case ENTITY_SCAN_BLOCKED:
+- /* Save the size accumulated so far; together with task->pos it is
+- the state that lets the scan resume once the blocker's size has
+- been computed. This is the one place where expandedSize briefly
+- holds neither 0 nor the final size - only while the entity is
+- on the stack, where the beingAnalyzed check in scanEntityText
+- keeps every other reader away from the intermediate value. */
+- e->expandedSize = sizeSoFar;
+-
+ /* Push the blocker. A blocker's expanded size is always still
+ uncomputed and it is never already on the stack, so each entity
+ is pushed at most once and top <= table->used. */
+ assert(! blocker->beingAnalyzed);
+ assert(top < table->used);
+ stack[top].entity = blocker;
+- stack[top].pos = blocker->textPtr;
+ blocker->beingAnalyzed = XML_TRUE;
+ top++;
+ break;
+@@ -7762,7 +7781,8 @@ storeSelfEntityValue(XML_Parser parser, ENTITY *entity) {
+ poolDiscard(pool);
+ return XML_ERROR_NO_MEMORY;
+ }
+- entity->textPtr = poolStart(pool);
++ const XML_Char *const valueStart = poolStart(pool);
++ entity->textPtr = valueStart;
+ entity->textLen = poolLength(pool);
+ poolFinish(pool);
+
+@@ -8540,6 +8560,9 @@ copyEntityTable(XML_Parser oldParser, HASH_TABLE *newTable,
+ return 0;
+ newE->textPtr = tem;
+ newE->textLen = oldE->textLen;
++#if XML_GE == 1
++ newE->scanPtr = tem;
++#endif /* XML_GE == 1 */
+ }
+ if (oldE->notation) {
+ const XML_Char *tem = poolCopyString(newPool, oldE->notation);
+@@ -9513,15 +9536,21 @@ entityTrackingReportStats(XML_Parser rootParser, ENTITY *entity,
+ = limitingNeeded ? (maxLimitedDepth - /* make space for ellipis */ 2)
+ : candidateIndentDepth;
+
++ const ptrdiff_t scannedLength
++ = EXPAT_SAFE_PTR_DIFF(entity->scanPtr, entity->textPtr);
++ const char *const confidenceMarker
++ = ((size_t)scannedLength == entity->textLen) ? "!" : "?";
++
+ fprintf(
+ stderr,
+- "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s length " EXPAT_FMT_SIZE_T(
+- "") " (xmlparse.c:%d)\n",
++ "expat: Entities(%p): Count %9u, depth %2u/%2u %*s%s%s%s; %s scanned " EXPAT_FMT_PTRDIFF_T(
++ "") "/" EXPAT_FMT_SIZE_T("") ", expanded " EXPAT_FMT_ULL("") "%s (xmlparse.c:%d)\n",
+ (void *)rootParser, rootParser->m_entity_stats.countEverOpened,
+ rootParser->m_entity_stats.currentDepth,
+ rootParser->m_entity_stats.maximumDepthSeen, indentDepth * 2, "",
+ ellipisOrEmpty, entity->is_param ? "%" : "&", entityName, action,
+- entity->textLen, sourceLine);
++ scannedLength, entity->textLen, entity->expandedSize, confidenceMarker,
++ sourceLine);
+ }
+
+ static void
+@@ -9536,6 +9565,7 @@ entityTrackingOnOpen(XML_Parser originParser, ENTITY *entity, int sourceLine) {
+ rootParser->m_entity_stats.maximumDepthSeen++;
+ }
+
++ // NOTE: The space at the end of "OPEN " is for length alignment with "CLOSE"
+ entityTrackingReportStats(rootParser, entity, "OPEN ", sourceLine);
+ }
+
+@@ -9548,6 +9578,29 @@ entityTrackingOnClose(XML_Parser originParser, ENTITY *entity, int sourceLine) {
+ rootParser->m_entity_stats.currentDepth--;
+ }
+
++static void
++entityTrackingOnScanStart(XML_Parser originParser, ENTITY *entity,
++ int sourceLine) {
++ const XML_Parser rootParser = getRootParserOf(originParser, NULL);
++ assert(! rootParser->m_parentParser);
++
++ rootParser->m_entity_stats.currentDepth += 1;
++ entityTrackingReportStats(rootParser, entity, "START", sourceLine);
++ rootParser->m_entity_stats.currentDepth -= 1;
++}
++
++static void
++entityTrackingOnScanStop(XML_Parser originParser, ENTITY *entity,
++ int sourceLine) {
++ const XML_Parser rootParser = getRootParserOf(originParser, NULL);
++ assert(! rootParser->m_parentParser);
++
++ rootParser->m_entity_stats.currentDepth += 1;
++ // NOTE: The space at the end of "STOP " is for length alignment with "START"
++ entityTrackingReportStats(rootParser, entity, "STOP ", sourceLine);
++ rootParser->m_entity_stats.currentDepth -= 1;
++}
++
+ #endif /* XML_GE == 1 */
+
+ static XML_Parser
+
+From e877b48378d781bd63c3817037d2f2678a610bb3 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Fri, 23 Oct 2026 16:50:26 +0200
+Subject: [PATCH] lib: Indent `EXPAT_ENTIY_DEBUG` output during entity scanning
+
+---
+ expat/lib/xmlparse.c | 18 ++++++++++++++----
+ 1 file changed, 14 insertions(+), 4 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -6983,10 +6983,18 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+ if (stack == NULL)
+ return XML_ERROR_NO_MEMORY;
+
++ const XML_Parser rootParser = getRootParserOf(parser, NULL);
++ assert(! rootParser->m_parentParser);
++
+ size_t top = 0;
+ stack[top].entity = root;
+ root->beingAnalyzed = XML_TRUE;
+ top++;
++ rootParser->m_entity_stats.currentDepth++;
++ if (rootParser->m_entity_stats.currentDepth
++ > rootParser->m_entity_stats.maximumDepthSeen) {
++ rootParser->m_entity_stats.maximumDepthSeen++;
++ }
+
+ while (top > 0) {
+ ENTITY_ANALYSIS_TASK *task = &stack[top - 1];
+@@ -7027,6 +7035,7 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+ case ENTITY_SCAN_COMPLETE:
+ e->beingAnalyzed = XML_FALSE;
+ top--;
++ rootParser->m_entity_stats.currentDepth--;
+ break;
+
+ case ENTITY_SCAN_BLOCKED:
+@@ -7038,6 +7047,11 @@ resolveEntityClosureExpandedSize(XML_Parser parser, HASH_TABLE *table,
+ stack[top].entity = blocker;
+ blocker->beingAnalyzed = XML_TRUE;
+ top++;
++ rootParser->m_entity_stats.currentDepth++;
++ if (rootParser->m_entity_stats.currentDepth
++ > rootParser->m_entity_stats.maximumDepthSeen) {
++ rootParser->m_entity_stats.maximumDepthSeen++;
++ }
+ break;
+ }
+ }
+@@ -9584,9 +9598,7 @@ entityTrackingOnScanStart(XML_Parser originParser, ENTITY *entity,
+ const XML_Parser rootParser = getRootParserOf(originParser, NULL);
+ assert(! rootParser->m_parentParser);
+
+- rootParser->m_entity_stats.currentDepth += 1;
+ entityTrackingReportStats(rootParser, entity, "START", sourceLine);
+- rootParser->m_entity_stats.currentDepth -= 1;
+ }
+
+ static void
+@@ -9595,10 +9607,8 @@ entityTrackingOnScanStop(XML_Parser originParser, ENTITY *entity,
+ const XML_Parser rootParser = getRootParserOf(originParser, NULL);
+ assert(! rootParser->m_parentParser);
+
+- rootParser->m_entity_stats.currentDepth += 1;
+ // NOTE: The space at the end of "STOP " is for length alignment with "START"
+ entityTrackingReportStats(rootParser, entity, "STOP ", sourceLine);
+- rootParser->m_entity_stats.currentDepth -= 1;
+ }
+
+ #endif /* XML_GE == 1 */
+
+From 2daec6ab382e0e75210d367dd6958319994df9ce Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Fri, 23 Oct 2026 23:29:06 +0200
+Subject: [PATCH] lib: Implement `strnstr` for `XML_Char`
+
+---
+ expat/lib/xcs.c | 21 +++++++++++++++++++++
+ expat/lib/xcs.h | 3 +++
+ expat/tests/xcs_tests.c | 23 +++++++++++++++++++++++
+ 3 files changed, 47 insertions(+)
+
+diff --git a/expat/lib/xcs.c b/expat/lib/xcs.c
+--- a/expat/lib/xcs.c
++++ b/expat/lib/xcs.c
+@@ -88,3 +88,24 @@ xcsncmp(const XML_Char *a, const XML_Char *b, size_t len) {
+ return strncmp(a, b, len);
+ #endif
+ }
++
++// A port of `strnstr(3bsd)` to `XML_Char`
++const XML_Char *
++xcsnstr(const XML_Char *haystack, const XML_Char *needle, size_t maxLen) {
++ // NOTE: We are not calling `xcsnlen(haystack, maxLen)` because
++ // `haystack` could be long and `xcsnlen` could be used in a loop
++ // and we need to avoid quadratic runtime behavior.
++ if (! *needle)
++ return haystack; // i.e. empty needle is always a match
++ const size_t needleLen = xcslen(needle);
++ if (needleLen > maxLen)
++ return NULL;
++ const size_t maxTries = (maxLen - needleLen) + 1;
++ for (size_t i = 0; i < maxTries && haystack[i]; i++) {
++ if (haystack[i] == needle[0]
++ && xcsncmp(haystack + i, needle, needleLen) == 0) {
++ return haystack + i;
++ }
++ }
++ return NULL;
++}
+diff --git a/expat/lib/xcs.h b/expat/lib/xcs.h
+--- a/expat/lib/xcs.h
++++ b/expat/lib/xcs.h
+@@ -41,4 +41,7 @@ extern size_t xcslen(const XML_Char *s);
+ extern int xcscmp(const XML_Char *a, const XML_Char *b);
+ extern int xcsncmp(const XML_Char *a, const XML_Char *b, size_t len);
+
++extern const XML_Char *xcsnstr(const XML_Char *haystack, const XML_Char *needle,
++ size_t maxLen);
++
+ #endif // ! defined(EXPAT_XCS_H)
+diff --git a/expat/tests/xcs_tests.c b/expat/tests/xcs_tests.c
+--- a/expat/tests/xcs_tests.c
++++ b/expat/tests/xcs_tests.c
+@@ -76,6 +76,28 @@ START_TEST(test_xcs_ncmp) {
+ }
+ END_TEST
+
++START_TEST(test_xcs_nstr) {
++ if (g_chunkSize != 0)
++ return;
++
++ const XML_Char haystack[] = {ASCII_h, ASCII_a, ASCII_y, ASCII_s, ASCII_t,
++ ASCII_a, ASCII_c, ASCII_k, '\0'};
++ const XML_Char hay[] = {ASCII_h, ASCII_a, ASCII_y, '\0'};
++ const XML_Char stack[] = {ASCII_s, ASCII_t, ASCII_a, ASCII_c, ASCII_k, '\0'};
++ const XML_Char other[] = {ASCII_o, ASCII_t, ASCII_h, ASCII_e, ASCII_r, '\0'};
++
++ assert_true(xcsnstr(haystack, haystack, xcslen(haystack)) == haystack);
++ assert_true(xcsnstr(haystack, hay, xcslen(haystack)) == haystack);
++ assert_true(xcsnstr(haystack, hay, xcslen(hay)) == haystack);
++ assert_true(xcsnstr(haystack, hay, xcslen(hay) - 1) == NULL);
++ assert_true(xcsnstr(haystack, stack, xcslen(haystack))
++ == haystack + xcslen(hay));
++ assert_true(xcsnstr(haystack, other, xcslen(haystack)) == NULL);
++ assert_true(xcsnstr(haystack, empty, xcslen(haystack)) == haystack);
++ assert_true(xcsnstr(hay, haystack, xcslen(hay)) == NULL);
++}
++END_TEST
++
+ void
+ make_xcs_test_case(Suite *s) {
+ TCase *const tc_xcs = tcase_create("xcs tests");
+@@ -83,4 +105,5 @@ make_xcs_test_case(Suite *s) {
+ tcase_add_test(tc_xcs, test_xcs_len);
+ tcase_add_test(tc_xcs, test_xcs_cmp);
+ tcase_add_test(tc_xcs, test_xcs_ncmp);
++ tcase_add_test(tc_xcs, test_xcs_nstr);
+ }
+
+From 5619228015f818d3161f57446ed5ba7ab6f67154 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Fri, 23 Oct 2026 23:35:51 +0200
+Subject: [PATCH] lib: Take CDATA sections, comments and PI into account with
+ entity scanning
+
+---
+ expat/lib/ascii.h | 1 +
+ expat/lib/xmlparse.c | 124 +++++++++++++++++++++++++++++++++++++++++++
+ 2 files changed, 125 insertions(+)
+
+diff --git a/expat/lib/ascii.h b/expat/lib/ascii.h
+--- a/expat/lib/ascii.h
++++ b/expat/lib/ascii.h
+@@ -113,6 +113,7 @@
+ #define ASCII_LT 0x3C
+ #define ASCII_EQUALS 0x3D
+ #define ASCII_GT 0x3E
++#define ASCII_QUEST 0x3F
+ #define ASCII_LSQB 0x5B
+ #define ASCII_RSQB 0x5D
+ #define ASCII_UNDERSCORE 0x5F
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -6821,6 +6821,65 @@ enum EntityScanResult {
+ callers must abort parsing */
+ };
+
++static const XML_Char cdataOpen[]
++ = {ASCII_LT, ASCII_EXCL, ASCII_LSQB, ASCII_C, ASCII_D,
++ ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB, '\0'}; // i.e. "<![CDATA["
++static const XML_Char cdataClose[]
++ = {ASCII_RSQB, ASCII_RSQB, ASCII_GT, '\0'}; // e.i. "]]>"
++static const XML_Char commentOpen[]
++ = {ASCII_LT, ASCII_EXCL, ASCII_MINUS, ASCII_MINUS, '\0'}; // i.e. "<!--"
++static const XML_Char commentClose[]
++ = {ASCII_MINUS, ASCII_MINUS, ASCII_GT, '\0'}; // i.e. "-->"
++static const XML_Char piClose[] = {ASCII_QUEST, ASCII_GT, '\0'}; // i.e. "?>"
++
++static const size_t cdataOpenLen = sizeof(cdataOpen) / sizeof(cdataOpen[0]) - 1;
++static const size_t cdataCloseLen
++ = sizeof(cdataClose) / sizeof(cdataClose[0]) - 1;
++static const size_t commentOpenLen
++ = sizeof(commentOpen) / sizeof(commentOpen[0]) - 1;
++static const size_t commentCloseLen
++ = sizeof(commentClose) / sizeof(commentClose[0]) - 1;
++static const size_t piCloseLen = sizeof(piClose) / sizeof(piClose[0]) - 1;
++
++// Checks the string starting at `pos` for starting a CDATA section, a comment
++// or processing instructions. Returns
++// XML_TOK_CDATA_SECT_OPEN/XML_TOK_COMMENT/XML_TOK_PI for a match or
++// XML_TOK_INVALID (=0) for no match. Only in the success case, the length
++// of the token is written to `*openTextLen`.
++static int
++isCDataCommentOrPIStart(const XML_Char *pos, size_t maxLen,
++ size_t *openTextLen) {
++ assert(pos != NULL);
++ assert(openTextLen != NULL);
++
++ if (maxLen < 2)
++ return XML_TOK_INVALID;
++
++ if (pos[0] != XML_T(ASCII_LT))
++ return XML_TOK_INVALID;
++
++ if (pos[1] == XML_T(ASCII_QUEST)) {
++ *openTextLen = 2;
++ return XML_TOK_PI;
++ }
++
++ if (pos[1] != XML_T(ASCII_EXCL))
++ return XML_TOK_INVALID;
++
++ if (maxLen >= cdataOpenLen && xcsncmp(pos, cdataOpen, cdataOpenLen) == 0) {
++ *openTextLen = cdataOpenLen;
++ return XML_TOK_CDATA_SECT_OPEN;
++ }
++
++ if (maxLen >= commentOpenLen
++ && xcsncmp(pos, commentOpen, commentOpenLen) == 0) {
++ *openTextLen = commentOpenLen;
++ return XML_TOK_COMMENT;
++ }
++
++ return XML_TOK_INVALID;
++}
++
+ /* Scan `entity`'s body, starting at `*posPtr`, accumulating the expanded
+ size into `*expandedSize`.
+
+@@ -6861,6 +6920,71 @@ scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
+ const XML_Char *const end = entity->textPtr + entity->textLen;
+
+ while (pos < end) {
++ // Detect and skip CDATA/comment/PI sections
++ // because entities have no effect in these places
++ if (*pos == XML_T('<')) {
++ // Detect CDATA/comment/PI section start
++ size_t openTextLen = 0;
++ const int tok = isCDataCommentOrPIStart(pos, end - pos, &openTextLen);
++ if (tok != XML_TOK_INVALID) {
++ assert(openTextLen != 0);
++
++ // Detect and avoid integer overflow
++ if (openTextLen > (XmlBigCount)(-1) - *expandedSize)
++ return ENTITY_SCAN_OVERFLOW;
++
++ *expandedSize += openTextLen;
++ pos += openTextLen;
++
++ // Detect CDATA/comment/PI section end
++ const XML_Char *closeText = NULL;
++ size_t closeLen = 0;
++
++ switch (tok) {
++ case XML_TOK_CDATA_SECT_OPEN:
++ closeText = cdataClose;
++ closeLen = cdataCloseLen;
++ break;
++ case XML_TOK_COMMENT:
++ closeText = commentClose;
++ closeLen = commentCloseLen;
++ break;
++ case XML_TOK_PI:
++ closeText = piClose;
++ closeLen = piCloseLen;
++ break;
++ default:
++ assert(0 && "never gets here");
++ break;
++ }
++
++ const size_t remainderLen = end - pos;
++ const XML_Char *const closeStart
++ = xcsnstr(pos, closeText, remainderLen);
++ if (closeStart == NULL) {
++ // The CDATA/comment/PI section is NOT terminated
++ if (remainderLen > (XmlBigCount)(-1) - *expandedSize)
++ return ENTITY_SCAN_OVERFLOW;
++ *expandedSize += remainderLen;
++ *posPtr = end;
++ return ENTITY_SCAN_COMPLETE;
++ }
++
++ // The CDATA/comment/PI section is NOT terminated
++ const size_t skippedLen = closeStart + closeLen - pos;
++
++ // Detect and avoid integer overflow
++ if (skippedLen > (XmlBigCount)(-1) - *expandedSize)
++ return ENTITY_SCAN_OVERFLOW;
++
++ *expandedSize += skippedLen;
++ pos += skippedLen;
++
++ continue;
++ }
++ }
++
++ // Detect an entity reference
+ if (*pos != refChar) {
+ // Detect and avoid integer overflow
+ if (*expandedSize == (XmlBigCount)(-1))
+
+From 15df55ca8828ff2a79a8f625e716b029a1e40be2 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 24 Oct 2026 21:50:56 +0200
+Subject: [PATCH] lib: Move internal type `XmlBigCount` to `internal.h` for
+ reuse
+
+---
+ expat/lib/internal.h | 2 ++
+ expat/lib/xmlparse.c | 2 --
+ 2 files changed, 2 insertions(+), 2 deletions(-)
+
+diff --git a/expat/lib/internal.h b/expat/lib/internal.h
+--- a/expat/lib/internal.h
++++ b/expat/lib/internal.h
+@@ -127,6 +127,8 @@ union expat_align {
+
+ # include "expat.h" // so we can use type XML_Parser below
+
++typedef unsigned long long XmlBigCount;
++
+ void _INTERNAL_trim_to_complete_utf8_characters(const char *from,
+ const char **fromLimRef);
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -309,8 +309,6 @@ typedef struct tag {
+ BINDING *bindings;
+ } TAG;
+
+-typedef unsigned long long XmlBigCount;
+-
+ typedef struct {
+ const XML_Char *name;
+ const XML_Char *textPtr;
+
+From 4f40b909780b881e348da6d2a1dc09cffb2f377c Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 24 Oct 2026 21:00:03 +0200
+Subject: [PATCH] lib: Extract new header `entities.h` to improve testability
+
+---
+ expat/lib/Makefile.am | 1 +
+ expat/lib/entities.h | 99 +++++++++++++++++++++++++++++++++++++++++++
+ expat/lib/xmlparse.c | 50 ++--------------------
+ 3 files changed, 104 insertions(+), 46 deletions(-)
+ create mode 100644 expat/lib/entities.h
+
+diff --git a/expat/lib/Makefile.am b/expat/lib/Makefile.am
+--- a/expat/lib/Makefile.am
++++ b/expat/lib/Makefile.am
+@@ -113,6 +113,7 @@ uninstall-local:
+ EXTRA_DIST = \
+ ascii.h \
+ asciitab.h \
++ entities.h \
+ expat_external.h \
+ expat.h \
+ fallthrough.h \
+diff --git a/expat/lib/entities.h b/expat/lib/entities.h
+new file mode 100644
+--- /dev/null
++++ b/expat/lib/entities.h
+@@ -0,0 +1,99 @@
++/* Internal helpers related to entities
++ __ __ _
++ ___\ \/ /_ __ __ _| |_
++ / _ \\ /| '_ \ / _` | __|
++ | __// \| |_) | (_| | |_
++ \___/_/\_\ .__/ \__,_|\__|
++ |_| XML parser
++
++ Copyright (c) 2026 Sebastian Pipping <sebastian at pipping.org>
++ Licensed under the MIT license:
++
++ Permission is hereby granted, free of charge, to any person obtaining
++ a copy of this software and associated documentation files (the
++ "Software"), to deal in the Software without restriction, including
++ without limitation the rights to use, copy, modify, merge, publish,
++ distribute, sublicense, and/or sell copies of the Software, and to permit
++ persons to whom the Software is furnished to do so, subject to the
++ following conditions:
++
++ The above copyright notice and this permission notice shall be included
++ in all copies or substantial portions of the Software.
++
++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
++ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
++ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
++ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
++ USE OR OTHER DEALINGS IN THE SOFTWARE.
++
++ SPDX-License-Identifier: MIT
++*/
++
++#if ! defined(EXPAT_ENTITIES_H)
++# define EXPAT_ENTITIES_H 1
++
++# include "expat_config.h" // for XML_GE
++# include "expat_external.h" // for XML_Char
++# include "internal.h" // for XML_NONTESTING_STATIC
++# include <stdbool.h> // for size_t
++# include <stddef.h> // for size_t
++
++typedef struct {
++ const XML_Char *name;
++ const XML_Char *textPtr;
++ size_t textLen; /* length in XML_Chars */
++ size_t processed; /* # of processed bytes - when suspended */
++ const XML_Char *systemId;
++ const XML_Char *base;
++ const XML_Char *publicId;
++ const XML_Char *notation;
++ bool open;
++ bool hasMore; /* true if entity has not been completely processed */
++ /* An entity can be open while being already completely processed (!hasMore).
++ The reason is the delayed closing of entities until their inner
++ entities are processed and closed */
++ bool is_param;
++ bool is_internal; /* true if declared in internal subset outside PE */
++# if XML_GE == 1
++ /* Indirect accounting bytes charged when this entity is expanded: 1 per text
++ character, plus each reference's "&name;"/"%name;" token length and its own
++ expansion. Matches XML_ACCOUNT_ENTITY_EXPANSION, so it is not the
++ replacement-text size. 0 means "not computed yet" (an empty entity is 0
++ too, told apart by textLen == 0). */
++ XmlBigCount expandedSize;
++ bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first
++ search stack; used for cycle detection */
++ const XML_Char
++ *scanPtr; /* cursor position into the entity's replacement text; NULL when
++ `textPtr` is NULL, else a pointer into the entity value,
++ ranging from `.textPtr` to `.textPtr + .textLen`. */
++# endif /* XML_GE == 1 */
++} ENTITY;
++
++# if XML_GE == 1
++/* How a scanEntityText call ended. */
++enum EntityScanResult {
++ ENTITY_SCAN_COMPLETE, /* reached end of text; *expandedSize is final */
++ ENTITY_SCAN_BLOCKED, /* stopped at a defined entity whose expanded
++ size has not been computed yet; *blockerOut
++ names the entity whose size to compute
++ first */
++ ENTITY_SCAN_OVERFLOW /* the expanded size would exceed XmlBigCount;
++ callers must abort parsing */
++};
++
++XML_NONTESTING_STATIC int isCDataCommentOrPIStart(const XML_Char *pos,
++ size_t maxLen,
++ size_t *openTextLen);
++
++XML_NONTESTING_STATIC int isPredefinedEntityName(const XML_Char *name,
++ size_t nameLen);
++
++XML_NONTESTING_STATIC enum EntityScanResult
++scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
++ XmlBigCount *expandedSize, ENTITY **blockerOut);
++# endif /* XML_GE == 1 */
++
++#endif // ! defined(EXPAT_ENTITIES_H)
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -232,6 +232,7 @@ typedef char ICHAR;
+
+ #include "internal.h"
+ #include "hash_table.h"
++#include "entities.h"
+ #include "xmltok.h"
+ #include "xmlrole.h"
+
+@@ -309,38 +310,6 @@ typedef struct tag {
+ BINDING *bindings;
+ } TAG;
+
+-typedef struct {
+- const XML_Char *name;
+- const XML_Char *textPtr;
+- size_t textLen; /* length in XML_Chars */
+- size_t processed; /* # of processed bytes - when suspended */
+- const XML_Char *systemId;
+- const XML_Char *base;
+- const XML_Char *publicId;
+- const XML_Char *notation;
+- bool open;
+- bool hasMore; /* true if entity has not been completely processed */
+- /* An entity can be open while being already completely processed (!hasMore).
+- The reason is the delayed closing of entities until their inner
+- entities are processed and closed */
+- bool is_param;
+- bool is_internal; /* true if declared in internal subset outside PE */
+-#if XML_GE == 1
+- /* Indirect accounting bytes charged when this entity is expanded: 1 per text
+- character, plus each reference's "&name;"/"%name;" token length and its own
+- expansion. Matches XML_ACCOUNT_ENTITY_EXPANSION, so it is not the
+- replacement-text size. 0 means "not computed yet" (an empty entity is 0
+- too, told apart by textLen == 0). */
+- XmlBigCount expandedSize;
+- bool beingAnalyzed; /* on the resolveEntityClosureExpandedSize depth-first
+- search stack; used for cycle detection */
+- const XML_Char
+- *scanPtr; /* cursor position into the entity's replacement text; NULL when
+- `textPtr` is NULL, else a pointer into the entity value,
+- ranging from `.textPtr` to `.textPtr + .textLen`. */
+-#endif /* XML_GE == 1 */
+-} ENTITY;
+-
+ typedef struct {
+ enum XML_Content_Type type;
+ enum XML_Content_Quant quant;
+@@ -6770,7 +6739,7 @@ epilogProcessor(XML_Parser parser, const char *s, const char *end,
+ // explicit length, instead. Returns
+ // ASCII_AMP/ASCII_APOS/ASCII_GT/ASCII_LT/ASCII_QUOT for a match or 0 for no
+ // match.
+-static int
++XML_NONTESTING_STATIC int
+ isPredefinedEntityName(const XML_Char *name, size_t nameLen) {
+ switch (nameLen) {
+ case 2:
+@@ -6808,17 +6777,6 @@ isPredefinedEntityName(const XML_Char *name, size_t nameLen) {
+ return 0;
+ }
+
+-/* How a scanEntityText call ended. */
+-enum EntityScanResult {
+- ENTITY_SCAN_COMPLETE, /* reached end of text; *expandedSize is final */
+- ENTITY_SCAN_BLOCKED, /* stopped at a defined entity whose expanded
+- size has not been computed yet; *blockerOut
+- names the entity whose size to compute
+- first */
+- ENTITY_SCAN_OVERFLOW /* the expanded size would exceed XmlBigCount;
+- callers must abort parsing */
+-};
+-
+ static const XML_Char cdataOpen[]
+ = {ASCII_LT, ASCII_EXCL, ASCII_LSQB, ASCII_C, ASCII_D,
+ ASCII_A, ASCII_T, ASCII_A, ASCII_LSQB, '\0'}; // i.e. "<![CDATA["
+@@ -6844,7 +6802,7 @@ static const size_t piCloseLen = sizeof(piClose) / sizeof(piClose[0]) - 1;
+ // XML_TOK_CDATA_SECT_OPEN/XML_TOK_COMMENT/XML_TOK_PI for a match or
+ // XML_TOK_INVALID (=0) for no match. Only in the success case, the length
+ // of the token is written to `*openTextLen`.
+-static int
++XML_NONTESTING_STATIC int
+ isCDataCommentOrPIStart(const XML_Char *pos, size_t maxLen,
+ size_t *openTextLen) {
+ assert(pos != NULL);
+@@ -6900,7 +6858,7 @@ isCDataCommentOrPIStart(const XML_Char *pos, size_t maxLen,
+ of entities it references), not a total across all entities. Not
+ meaningful after ENTITY_SCAN_OVERFLOW; the overflowing value is never
+ stored anywhere. */
+-static enum EntityScanResult
++XML_NONTESTING_STATIC enum EntityScanResult
+ scanEntityText(XML_Parser parser, ENTITY *entity, const XML_Char **posPtr,
+ XmlBigCount *expandedSize, ENTITY **blockerOut) {
+ if (blockerOut != NULL)
+
+From 7aa6179fc93c472c84e0e781f147147ef0501341 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 24 Oct 2026 21:07:59 +0200
+Subject: [PATCH] tests: Introduce empty test suite dedicated to internal
+ entities testing
+
+---
+ expat/CMakeLists.txt | 1 +
+ expat/tests/Makefile.am | 2 ++
+ expat/tests/entities_tests.c | 40 +++++++++++++++++++++++++++++++++++
+ expat/tests/entities_tests.h | 41 ++++++++++++++++++++++++++++++++++++
+ expat/tests/runtests.c | 2 ++
+ 5 files changed, 86 insertions(+)
+ create mode 100644 expat/tests/entities_tests.c
+ create mode 100644 expat/tests/entities_tests.h
+
+diff --git a/expat/CMakeLists.txt b/expat/CMakeLists.txt
+--- a/expat/CMakeLists.txt
++++ b/expat/CMakeLists.txt
+@@ -728,6 +728,7 @@ if(EXPAT_BUILD_TESTS)
+ tests/dummy.c
+ tests/handlers.c
+ tests/hash_tests.c
++ tests/entities_tests.c
+ tests/memcheck.c
+ tests/minicheck.c
+ tests/misc_tests.c
+diff --git a/expat/tests/Makefile.am b/expat/tests/Makefile.am
+--- a/expat/tests/Makefile.am
++++ b/expat/tests/Makefile.am
+@@ -50,6 +50,7 @@ runtests_SOURCES = \
+ dummy.c \
+ handlers.c \
+ hash_tests.c \
++ entities_tests.c \
+ memcheck.c \
+ minicheck.c \
+ misc_tests.c \
+@@ -73,6 +74,7 @@ EXTRA_DIST = \
+ dummy.h \
+ handlers.h \
+ hash_tests.h \
++ entities_tests.h \
+ memcheck.h \
+ minicheck.h \
+ misc_tests.h \
+diff --git a/expat/tests/entities_tests.c b/expat/tests/entities_tests.c
+new file mode 100644
+--- /dev/null
++++ b/expat/tests/entities_tests.c
+@@ -0,0 +1,40 @@
++/* Unit tests related to internal handling of entities
++__ __ _
++ ___\ \/ /_ __ __ _| |_
++ / _ \\ /| '_ \ / _` | __|
++ | __// \| |_) | (_| | |_
++ \___/_/\_\ .__/ \__,_|\__|
++ |_| XML parser
++
++ Copyright (c) 2026 Sebastian Pipping <sebastian at pipping.org>
++ Licensed under the MIT license:
++
++ Permission is hereby granted, free of charge, to any person obtaining
++ a copy of this software and associated documentation files (the
++ "Software"), to deal in the Software without restriction, including
++ without limitation the rights to use, copy, modify, merge, publish,
++ distribute, sublicense, and/or sell copies of the Software, and to permit
++ persons to whom the Software is furnished to do so, subject to the
++ following conditions:
++
++ The above copyright notice and this permission notice shall be included
++ in all copies or substantial portions of the Software.
++
++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
++ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
++ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
++ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
++ USE OR OTHER DEALINGS IN THE SOFTWARE.
++
++ SPDX-License-Identifier: MIT
++*/
++
++#include "entities_tests.h"
++
++void
++make_entities_test_case(Suite *s) {
++ TCase *const tc_entities = tcase_create("entities tests");
++ suite_add_tcase(s, tc_entities);
++}
+diff --git a/expat/tests/entities_tests.h b/expat/tests/entities_tests.h
+new file mode 100644
+--- /dev/null
++++ b/expat/tests/entities_tests.h
+@@ -0,0 +1,41 @@
++/* Unit tests related to internal handling of entities
++__ __ _
++ ___\ \/ /_ __ __ _| |_
++ / _ \\ /| '_ \ / _` | __|
++ | __// \| |_) | (_| | |_
++ \___/_/\_\ .__/ \__,_|\__|
++ |_| XML parser
++
++ Copyright (c) 2026 Sebastian Pipping <sebastian at pipping.org>
++ Licensed under the MIT license:
++
++ Permission is hereby granted, free of charge, to any person obtaining
++ a copy of this software and associated documentation files (the
++ "Software"), to deal in the Software without restriction, including
++ without limitation the rights to use, copy, modify, merge, publish,
++ distribute, sublicense, and/or sell copies of the Software, and to permit
++ persons to whom the Software is furnished to do so, subject to the
++ following conditions:
++
++ The above copyright notice and this permission notice shall be included
++ in all copies or substantial portions of the Software.
++
++ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
++ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
++ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
++ NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
++ DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
++ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
++ USE OR OTHER DEALINGS IN THE SOFTWARE.
++
++ SPDX-License-Identifier: MIT
++*/
++
++#ifndef XML_ENTITIES_TESTS_H
++#define XML_ENTITIES_TESTS_H
++
++#include "minicheck.h"
++
++extern void make_entities_test_case(Suite *s);
++
++#endif /* XML_ENTITIES_TESTS_H */
+diff --git a/expat/tests/runtests.c b/expat/tests/runtests.c
+--- a/expat/tests/runtests.c
++++ b/expat/tests/runtests.c
+@@ -57,6 +57,7 @@
+ #include "acc_tests.h"
+ #include "alloc_tests.h"
+ #include "basic_tests.h"
++#include "entities_tests.h"
+ #include "hash_tests.h"
+ #include "misc_tests.h"
+ #include "ns_tests.h"
+@@ -75,6 +76,7 @@ make_suite(void) {
+ #endif
+ make_alloc_test_case(s);
+ make_basic_test_case(s);
++ make_entities_test_case(s);
+ make_hash_test_case(s);
+ make_miscellaneous_test_case(s);
+ make_namespace_test_case(s);
+
+From facd124e8dc8f1a0c039dda1c51a87bb3d398353 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 26 Oct 2026 12:57:32 +0100
+Subject: [PATCH] tests: Implement helper `xcsdup_str` for reuse
+
+---
+ expat/tests/common.c | 12 ++++++++++++
+ expat/tests/common.h | 2 ++
+ 2 files changed, 14 insertions(+)
+
+diff --git a/expat/tests/common.c b/expat/tests/common.c
+--- a/expat/tests/common.c
++++ b/expat/tests/common.c
+@@ -339,3 +339,15 @@ portable_strndup(const char *s, size_t n) {
+
+ return buffer;
+ }
++
++XML_Char *
++xcsdup_str(const char *s) {
++ const size_t len = strlen(s);
++ XML_Char *const buf = calloc(len + /*terminator*/ 1, sizeof(XML_Char));
++ if (! buf)
++ return NULL;
++ XML_Char *t = buf;
++ while (*s)
++ *t++ = *s++;
++ return buf;
++}
+diff --git a/expat/tests/common.h b/expat/tests/common.h
+--- a/expat/tests/common.h
++++ b/expat/tests/common.h
+@@ -140,4 +140,6 @@ extern void *duff_reallocator(void *ptr, size_t size);
+
+ extern char *portable_strndup(const char *s, size_t n);
+
++extern XML_Char *xcsdup_str(const char *s);
++
+ #endif /* XML_COMMON_H */
+
+From 81fb672878502c70b0526c5b39fd8498f13adf34 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Sat, 24 Oct 2026 21:27:20 +0200
+Subject: [PATCH] tests: Briefly cover function `isCDataCommentOrPIStart`
+
+---
+ expat/tests/entities_tests.c | 51 ++++++++++++++++++++++++++++++++++++
+ 1 file changed, 51 insertions(+)
+
+diff --git a/expat/tests/entities_tests.c b/expat/tests/entities_tests.c
+--- a/expat/tests/entities_tests.c
++++ b/expat/tests/entities_tests.c
+@@ -32,9 +32,60 @@ __ __ _
+ */
+
+ #include "entities_tests.h"
++#include "expat_config.h" // for XML_GE
++
++#include "ascii.h" // for ASCII_*
++#include "common.h" // for g_chunkSize, xcsdup_str
++#include "entities.h" // for isCDataCommentOrPIStart
++#include "xmltok.h" // for XML_TOK_*
++#include "xcs.h" // for xcslen
++
++START_TEST(test_is_cdata_comment_or_pi_start) {
++ // Speed up the test, chunk size expected to not matter in this test
++ if (g_chunkSize != 0)
++ return;
++
++ XML_Char *const cdataOpen = xcsdup_str("<![CDATA[");
++ XML_Char *const commentOpen = xcsdup_str("<!--");
++ XML_Char *const piOpen = xcsdup_str("<?");
++
++#if XML_GE == 1
++ const size_t expectedCdataOpenLen = xcslen(cdataOpen);
++ const size_t expectedCommentOpenLen = xcslen(commentOpen);
++ const size_t expectedPiOpenLen = xcslen(piOpen);
++
++ size_t actualCdataOpenLen = 0;
++ assert_true(isCDataCommentOrPIStart(cdataOpen, expectedCdataOpenLen,
++ &actualCdataOpenLen)
++ == XML_TOK_CDATA_SECT_OPEN);
++ assert_true(actualCdataOpenLen == expectedCdataOpenLen);
++
++ size_t actualCommentOpenLen = 0;
++ assert_true(isCDataCommentOrPIStart(commentOpen, expectedCommentOpenLen,
++ &actualCommentOpenLen)
++ == XML_TOK_COMMENT);
++ assert_true(actualCommentOpenLen == expectedCommentOpenLen);
++
++ size_t actualPiOpenLen = 0;
++ assert_true(
++ isCDataCommentOrPIStart(piOpen, expectedPiOpenLen, &actualPiOpenLen)
++ == XML_TOK_PI);
++ assert_true(actualCdataOpenLen == expectedCdataOpenLen);
++
++ size_t dummy = 0;
++ assert_true(isCDataCommentOrPIStart(piOpen, 0, &dummy) == XML_TOK_INVALID);
++ assert_true(isCDataCommentOrPIStart(piOpen, 1, &dummy) == XML_TOK_INVALID);
++#endif // XML_GE == 1
++
++ free(cdataOpen);
++ free(commentOpen);
++ free(piOpen);
++}
++END_TEST
+
+ void
+ make_entities_test_case(Suite *s) {
+ TCase *const tc_entities = tcase_create("entities tests");
+ suite_add_tcase(s, tc_entities);
++ tcase_add_test(tc_entities, test_is_cdata_comment_or_pi_start);
+ }
+
+From e05732b8c77ff1bb40d3e0b19bec61a4e7bb4967 Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 26 Oct 2026 12:24:34 +0100
+Subject: [PATCH] tests: Briefly cover function `isPredefinedEntityName`
+
+---
+ expat/tests/entities_tests.c | 35 ++++++++++++++++++++++++++++++++++-
+ 1 file changed, 34 insertions(+), 1 deletion(-)
+
+diff --git a/expat/tests/entities_tests.c b/expat/tests/entities_tests.c
+--- a/expat/tests/entities_tests.c
++++ b/expat/tests/entities_tests.c
+@@ -36,10 +36,14 @@ __ __ _
+
+ #include "ascii.h" // for ASCII_*
+ #include "common.h" // for g_chunkSize, xcsdup_str
+-#include "entities.h" // for isCDataCommentOrPIStart
++#include "entities.h" // for isCDataCommentOrPIStart, isPredefinedEntityName
+ #include "xmltok.h" // for XML_TOK_*
+ #include "xcs.h" // for xcslen
+
++static void
++assert_entity_expanded_size_equals(XML_Parser parser, const char *text,
++ XmlBigCount expectedExpandedSize);
++
+ START_TEST(test_is_cdata_comment_or_pi_start) {
+ // Speed up the test, chunk size expected to not matter in this test
+ if (g_chunkSize != 0)
+@@ -83,9 +87,38 @@ START_TEST(test_is_cdata_comment_or_pi_start) {
+ }
+ END_TEST
+
++static void
++assert_predefined_entity_name_match(const char *text, int expectedCharacter) {
++ XML_Char *const xcsText = xcsdup_str(text);
++ assert_true(xcsText != NULL);
++
++#if XML_GE == 1
++ assert_true(isPredefinedEntityName(xcsText, xcslen(xcsText))
++ == expectedCharacter);
++#else
++ UNUSED_P(expectedCharacter);
++#endif // XML_GE == 1
++
++ free(xcsText);
++}
++
++START_TEST(test_is_predefined_entity_name) {
++ // Speed up the test, chunk size expected to not matter in this test
++ if (g_chunkSize != 0)
++ return;
++
++ assert_predefined_entity_name_match("amp", ASCII_AMP);
++ assert_predefined_entity_name_match("apos", ASCII_APOS);
++ assert_predefined_entity_name_match("gt", ASCII_GT);
++ assert_predefined_entity_name_match("lt", ASCII_LT);
++ assert_predefined_entity_name_match("quot", ASCII_QUOT);
++}
++END_TEST
++
+ void
+ make_entities_test_case(Suite *s) {
+ TCase *const tc_entities = tcase_create("entities tests");
+ suite_add_tcase(s, tc_entities);
+ tcase_add_test(tc_entities, test_is_cdata_comment_or_pi_start);
++ tcase_add_test(tc_entities, test_is_predefined_entity_name);
+ }
+
+From 35ec9d99718bed72643adff25d2b7155f278fa8f Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 26 Oct 2026 13:48:03 +0100
+Subject: [PATCH] tests: Briefly cover function `scanEntityText`
+
+---
+ expat/tests/entities_tests.c | 124 ++++++++++++++++++++++++++++++++++-
+ 1 file changed, 123 insertions(+), 1 deletion(-)
+
+diff --git a/expat/tests/entities_tests.c b/expat/tests/entities_tests.c
+--- a/expat/tests/entities_tests.c
++++ b/expat/tests/entities_tests.c
+@@ -36,14 +36,21 @@ __ __ _
+
+ #include "ascii.h" // for ASCII_*
+ #include "common.h" // for g_chunkSize, xcsdup_str
+-#include "entities.h" // for isCDataCommentOrPIStart, isPredefinedEntityName
++#include "entities.h" // for isCDataCommentOrPIStart, isPredefinedEntityName, ..
+ #include "xmltok.h" // for XML_TOK_*
+ #include "xcs.h" // for xcslen
+
++#include <string.h> // for strlen
++
+ static void
+ assert_entity_expanded_size_equals(XML_Parser parser, const char *text,
+ XmlBigCount expectedExpandedSize);
+
++static void assert_predefined_entity_name_match(const char *text,
++ int expectedCharacter);
++
++static ENTITY *createGeneralEntityWithText(const char *text);
++
+ START_TEST(test_is_cdata_comment_or_pi_start) {
+ // Speed up the test, chunk size expected to not matter in this test
+ if (g_chunkSize != 0)
+@@ -115,10 +122,125 @@ START_TEST(test_is_predefined_entity_name) {
+ }
+ END_TEST
+
++static ENTITY *
++createGeneralEntityWithText(const char *text) {
++ assert_true(text != NULL);
++
++ ENTITY *const entity = calloc(1, sizeof(ENTITY));
++ assert_true(entity != NULL);
++
++ entity->textPtr = xcsdup_str(text);
++ assert_true(entity->textPtr != NULL);
++
++ entity->textLen = xcslen(entity->textPtr);
++
++#if XML_GE == 1
++ entity->scanPtr = entity->textPtr;
++#endif // XML_GE == 1
++
++ return entity;
++}
++
++static void
++assert_entity_expanded_size_equals(XML_Parser parser, const char *text,
++ XmlBigCount expectedExpandedSize) {
++ // Turn `text` into a general entity with that text
++ ENTITY *const entity = createGeneralEntityWithText(text);
++
++#if XML_GE == 1
++ XmlBigCount actualExpandedSize = 0;
++ assert_true(scanEntityText(parser, entity, &entity->scanPtr,
++ &actualExpandedSize, NULL)
++ == ENTITY_SCAN_COMPLETE);
++ assert_true(entity->scanPtr == entity->textPtr + entity->textLen);
++ assert_true(actualExpandedSize == expectedExpandedSize);
++#else
++ UNUSED_P(parser);
++ UNUSED_P(expectedExpandedSize);
++#endif // XML_GE == 1
++
++ free((XML_Char *)entity->textPtr);
++ free(entity);
++}
++
++START_TEST(test_scan_entity_text) {
++ // Speed up the test, chunk size expected to not matter in this test
++ if (g_chunkSize != 0)
++ return;
++
++ const char *const doc = "<!DOCTYPE doc[\n"
++ " <!ENTITY ten '123456789a'>\n"
++ "]>\n"
++ "<doc/>";
++ XML_Parser parser = XML_ParserCreate(NULL);
++ assert_true(parser != NULL);
++ assert_true(_XML_Parse_SINGLE_BYTES(parser, doc, (int)strlen(doc),
++ /*isFinal=*/XML_TRUE)
++ == XML_STATUS_OK);
++
++ assert_entity_expanded_size_equals(parser, "", 0);
++ assert_entity_expanded_size_equals(parser, "123", 3);
++ assert_entity_expanded_size_equals(parser, "&'><"",
++ strlen("&'><"") + 5);
++ assert_entity_expanded_size_equals(parser, "&undefined;",
++ strlen("&undefined;"));
++
++ // Extract entity "ten" and set its `.expandedSize` so that we can scan text
++ // that refers to "&ten;" without blocking
++#if XML_GE == 1
++ ENTITY *entityTen = NULL;
++#endif
++ {
++ ENTITY *const entityReferencingTen
++ = createGeneralEntityWithText("referencing &ten;");
++ assert_true(entityReferencingTen != NULL);
++
++#if XML_GE == 1
++ assert_true(scanEntityText(parser, entityReferencingTen,
++ &entityReferencingTen->scanPtr,
++ &entityReferencingTen->expandedSize, &entityTen)
++ == ENTITY_SCAN_BLOCKED);
++ assert_true(entityTen != NULL);
++ assert_true(entityReferencingTen->expandedSize == strlen("referencing "));
++ assert_true(entityReferencingTen->scanPtr
++ == entityReferencingTen->textPtr
++ + entityReferencingTen->expandedSize);
++ XML_Char *const ten = xcsdup_str("ten");
++ assert_true(xcscmp(entityTen->name, ten) == 0);
++ free(ten);
++
++ entityTen->expandedSize = 10; // which makes it stop being a blocker
++#endif // XML_GE == 1
++
++ free((XML_Char *)entityReferencingTen->textPtr);
++ free(entityReferencingTen);
++ }
++
++ assert_entity_expanded_size_equals(parser, "&ten;",
++ strlen("&ten;") + strlen("123456789a"));
++ assert_entity_expanded_size_equals(
++ parser, "[&ten;&ten;|&ten;]",
++ 3 * (strlen("&ten;") + strlen("123456789a")) + strlen("[|]"));
++
++ // Cases where no entities should be recognized
++ assert_entity_expanded_size_equals(
++ parser, "<![CDATA[&ten;]]><!--&ten;--><?php &ten;?>",
++ strlen("<![CDATA[&ten;]]><!--&ten;--><?php &ten;?>"));
++ assert_entity_expanded_size_equals(parser, "<![CDATA[&ten;",
++ strlen("<![CDATA[&ten;"));
++ assert_entity_expanded_size_equals(parser, "<!--&ten;", strlen("<!--&ten;"));
++ assert_entity_expanded_size_equals(parser, "<?php &ten;",
++ strlen("<?php &ten;"));
++
++ XML_ParserFree(parser);
++}
++END_TEST
++
+ void
+ make_entities_test_case(Suite *s) {
+ TCase *const tc_entities = tcase_create("entities tests");
+ suite_add_tcase(s, tc_entities);
+ tcase_add_test(tc_entities, test_is_cdata_comment_or_pi_start);
+ tcase_add_test(tc_entities, test_is_predefined_entity_name);
++ tcase_add_test(tc_entities, test_scan_entity_text);
+ }
diff --git a/CVE-2026-117610.patch b/CVE-2026-117610.patch
new file mode 100644
index 0000000..b98d0c4
--- /dev/null
+++ b/CVE-2026-117610.patch
@@ -0,0 +1,110 @@
+https://github.com/libexpat/libexpat/pull/1444 (unmerged when taken)
+Test adjusted: 2.9.0 lacks the xcsdup_str helper and test_misc_start_doctype_decl_handler_reset.
+From 7b0d50e4b1d16fafd55876260701e04279a7489d Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 26 Oct 2026 17:39:32 +0100
+Subject: [PATCH 1/2] lib: Fix initial non-final empty subparser call with a
+ handler
+
+---
+ expat/lib/xmlparse.c | 5 +++++
+ 1 file changed, 5 insertions(+)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index a04ffde07..d2edf9a13 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -3537,6 +3537,11 @@ externalEntityInitProcessor2(XML_Parser parser, const char *start,
+ }
+ parser->m_eventPtr = start;
+ return XML_ERROR_PARTIAL_CHAR;
++ case XML_TOK_NONE:
++ if (! parser->m_parsingStatus.finalBuffer) {
++ *endPtr = start;
++ }
++ return XML_ERROR_NONE;
+ }
+ parser->m_processor = externalEntityInitProcessor3;
+ return externalEntityInitProcessor3(parser, start, end, endPtr);
+
+From 9bb7a7a45d5325eae5ec8bed13157f7e65d0bfea Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Mon, 26 Oct 2026 17:17:57 +0100
+Subject: [PATCH 2/2] tests: Add a test for a initial non-final empty subparser
+ parse
+
+.. with a handler call
+---
+ expat/tests/misc_tests.c | 63 ++++++++++++++++++++++++++++++++++++++++
+ 1 file changed, 63 insertions(+)
+
+diff --git a/expat/tests/misc_tests.c b/expat/tests/misc_tests.c
+index 5d87c92b8..6bfde9b9b 100644
+--- a/expat/tests/misc_tests.c
++++ b/expat/tests/misc_tests.c
+@@ -1064,6 +1064,60 @@ START_TEST(test_misc_start_doctype_decl_handler_reset) {
+ }
+ END_TEST
+
++static void
++comparingPiHandler(void *userData, const XML_Char *target,
++ const XML_Char *data) {
++ UNUSED_P(userData);
++
++ assert_true(xcscmp(target, XCS("target")) == 0);
++ assert_true(xcscmp(data, XCS("data")) == 0);
++}
++
++static int XMLCALL
++piParsingExternalEntityHandler(XML_Parser parent, const XML_Char *context,
++ const XML_Char *base, const XML_Char *systemId,
++ const XML_Char *publicId) {
++ UNUSED_P(base);
++ UNUSED_P(systemId);
++ UNUSED_P(publicId);
++
++ const char *const doc = "<?target data?>";
++
++ XML_Parser subParser = XML_ExternalEntityParserCreate(parent, context, NULL);
++ assert_true(subParser != NULL);
++
++ // NOTE: Related test "test_empty_ext_param_entity_in_value" could be of
++ // interest
++ assert_true(_XML_Parse_SINGLE_BYTES(subParser, "", 0, /*isFinal=*/XML_FALSE)
++ == XML_STATUS_OK);
++ assert_true(_XML_Parse_SINGLE_BYTES(subParser, doc, (int)strlen(doc),
++ /*isFinal=*/XML_TRUE)
++ == XML_STATUS_OK);
++
++ XML_ParserFree(subParser);
++
++ return XML_STATUS_OK;
++}
++
++START_TEST(test_misc_empty_nonfinal_subparser_parse) {
++ const char *const doc = "<!DOCTYPE root [\n"
++ " <!ENTITY ext SYSTEM 'external.dtd'>\n"
++ "]>\n"
++ "<root>&ext;</root>\n";
++
++ XML_Parser parser = XML_ParserCreate(NULL);
++ assert_true(parser != NULL);
++
++ XML_SetProcessingInstructionHandler(parser, comparingPiHandler);
++ XML_SetExternalEntityRefHandler(parser, piParsingExternalEntityHandler);
++
++ assert_true(_XML_Parse_SINGLE_BYTES(parser, doc, (int)strlen(doc),
++ /*isFinal=*/XML_TRUE));
++
++ XML_ParserFree(parser);
++}
++END_TEST
++
+ void
+ make_miscellaneous_test_case(Suite *s) {
+ TCase *tc_misc = tcase_create("miscellaneous tests");
+@@ -1064,3 +1118,4 @@ make_miscellaneous_test_case(Suite *s) {
+ tcase_add_test(tc_misc, test_misc_input_2gb);
+ tcase_add_test(tc_misc, test_misc_low_surrogate_mozilla_bug_2053153);
++ tcase_add_test(tc_misc, test_misc_empty_nonfinal_subparser_parse);
+ }
diff --git a/CVE-2026-118370.patch b/CVE-2026-118370.patch
new file mode 100644
index 0000000..b08e15f
--- /dev/null
+++ b/CVE-2026-118370.patch
@@ -0,0 +1,79 @@
+https://github.com/libexpat/libexpat/pull/1450 (unmerged when taken)
+From 621cb2c78b253ee023a86bc91d6ddb048481c04c Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Tue, 27 Oct 2026 17:57:19 +0100
+Subject: [PATCH 1/2] lib: Protect `nPrefixes` in `storeAtts` from signed
+ integer overflow
+
+.. by migrating to `size_t`
+---
+ expat/lib/xmlparse.c | 2 +-
+ 1 file changed, 1 insertion(+), 1 deletion(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index a04ffde07..84a1fc135 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -4170,7 +4170,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
+ DTD *const dtd = parser->m_dtd; /* save one level of indirection */
+ int attIndex = 0;
+ XML_Char *uri;
+- int nPrefixes = 0;
++ size_t nPrefixes = 0;
+ BINDING *binding;
+ const XML_Char *localPart;
+
+
+From 1bac53c4fc460a03cd9860f39501c7979f6750ae Mon Sep 17 00:00:00 2001
+From: Sebastian Pipping <sebastian at pipping.org>
+Date: Tue, 27 Oct 2026 15:20:33 +0100
+Subject: [PATCH 2/2] lib: Protect `attIndex` in `storeAtts` from signed
+ integer overflow
+
+.. by migrating to `size_t`
+---
+ expat/lib/xmlparse.c | 15 ++++++++++-----
+ 1 file changed, 10 insertions(+), 5 deletions(-)
+
+diff --git a/expat/lib/xmlparse.c b/expat/lib/xmlparse.c
+index 84a1fc135..14b4b0013 100644
+--- a/expat/lib/xmlparse.c
++++ b/expat/lib/xmlparse.c
+@@ -4168,7 +4168,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
+ TAG_NAME *tagNamePtr, BINDING **bindingsPtr,
+ enum XML_Account account) {
+ DTD *const dtd = parser->m_dtd; /* save one level of indirection */
+- int attIndex = 0;
++ size_t attIndex = 0;
+ XML_Char *uri;
+ size_t nPrefixes = 0;
+ BINDING *binding;
+@@ -4311,11 +4311,16 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
+ }
+
+ /* set-up for XML_GetSpecifiedAttributeCount and XML_GetIdAttributeIndex */
+- parser->m_nSpecifiedAtts = attIndex;
++ // Detect and reject integer overflow
++ if (attIndex > INT_MAX)
++ return XML_ERROR_NO_MEMORY;
++ parser->m_nSpecifiedAtts = (int)attIndex;
+ if (elementType->idAtt && (elementType->idAtt->name)[-1]) {
+- for (int i = 0; i < attIndex; i += 2)
++ for (size_t i = 0; i < attIndex; i += 2)
+ if (appAtts[i] == elementType->idAtt->name) {
+- parser->m_idAttIndex = i;
++ if (i > INT_MAX)
++ return XML_ERROR_NO_MEMORY;
++ parser->m_idAttIndex = (int)i;
+ break;
+ }
+ } else
+@@ -4348,7 +4353,7 @@ storeAtts(XML_Parser parser, const ENCODING *enc, const char *attStr,
+
+ /* expand prefixed attribute names, check for duplicates,
+ and clear flags that say whether attributes were specified */
+- int i = 0;
++ size_t i = 0;
+ if (nPrefixes) {
+ unsigned int j; /* hash table index */
+ unsigned long version = parser->m_nsAttsVersion;
================================================================
---- gitweb:
http://git.pld-linux.org/gitweb.cgi/packages/expat.git/commitdiff/a4dacc455672630eafb7bf1bca21ad827382c7b7
More information about the pld-cvs-commit
mailing list