[CVE-2022-43680] Fix overeager DTD destruction (fixes #649)

Bug: http://b/255449293
Test: TreeHugger
Change-Id: I15ba529c07a6b868484bd5972be154c07cd97cc6
(cherry picked from commit 03836568ec3e5a4051e54bf39568656d07f5a3dd)
Merged-In: I15ba529c07a6b868484bd5972be154c07cd97cc6
diff --git a/lib/xmlparse.c b/lib/xmlparse.c
index 7db28d0..7e98191 100644
--- a/lib/xmlparse.c
+++ b/lib/xmlparse.c
@@ -1066,6 +1066,14 @@
   parserInit(parser, encodingName);
 
   if (encodingName && ! parser->m_protocolEncodingName) {
+    if (dtd) {
+      // We need to stop the upcoming call to XML_ParserFree from happily
+      // destroying parser->m_dtd because the DTD is shared with the parent
+      // parser and the only guard that keeps XML_ParserFree from destroying
+      // parser->m_dtd is parser->m_isParamEntity but it will be set to
+      // XML_TRUE only later in XML_ExternalEntityParserCreate (or not at all).
+      parser->m_dtd = NULL;
+    }
     XML_ParserFree(parser);
     return NULL;
   }