From 1d4f5d24ac3976012ab1f5b811385e7b00caaecf Mon Sep 17 00:00:00 2001
From: Nick Wellnhofer <wellnhofer@aevum.de>
Date: Tue, 13 Sep 2022 16:40:31 +0200
Subject: [PATCH] schemas: Fix null-pointer-deref in
 xmlSchemaCheckCOSSTDerivedOK

Found by OSS-Fuzz.

Reference:https://github.com/GNOME/libxml2/commit/1d4f5d24ac3976012ab1f5b811385e7b00caaecf
Conflict:NA

---
 result/schemas/oss-fuzz-51295_0_0.err |  2 ++
 test/schemas/oss-fuzz-51295_0.xml     |  1 +
 test/schemas/oss-fuzz-51295_0.xsd     |  4 ++++
 xmlschemas.c                          | 15 +++++++++++++--
 4 files changed, 20 insertions(+), 2 deletions(-)
 create mode 100644 result/schemas/oss-fuzz-51295_0_0.err
 create mode 100644 test/schemas/oss-fuzz-51295_0.xml
 create mode 100644 test/schemas/oss-fuzz-51295_0.xsd

diff --git a/result/schemas/oss-fuzz-51295_0_0.err b/result/schemas/oss-fuzz-51295_0_0.err
new file mode 100644
index 00000000..1e89524f
--- /dev/null
+++ b/result/schemas/oss-fuzz-51295_0_0.err
@@ -0,0 +1,2 @@
+./test/schemas/oss-fuzz-51295_0.xsd:2: element element: Schemas parser error : element decl. 'e': The element declaration 'e' defines a circular substitution group to element declaration 'e'.
+./test/schemas/oss-fuzz-51295_0.xsd:2: element element: Schemas parser error : element decl. 'e': The element declaration 'e' defines a circular substitution group to element declaration 'e'.
diff --git a/test/schemas/oss-fuzz-51295_0.xml b/test/schemas/oss-fuzz-51295_0.xml
new file mode 100644
index 00000000..10a7e703
--- /dev/null
+++ b/test/schemas/oss-fuzz-51295_0.xml
@@ -0,0 +1 @@
+<e/>
diff --git a/test/schemas/oss-fuzz-51295_0.xsd b/test/schemas/oss-fuzz-51295_0.xsd
new file mode 100644
index 00000000..fde96af5
--- /dev/null
+++ b/test/schemas/oss-fuzz-51295_0.xsd
@@ -0,0 +1,4 @@
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+    <xs:element name="e" substitutionGroup="e"/>
+    <xs:element name="t" substitutionGroup="e" type='xs:decimal'/>
+</xs:schema>
diff --git a/xmlschemas.c b/xmlschemas.c
index ade10f78..de6ea2b0 100644
--- a/xmlschemas.c
+++ b/xmlschemas.c
@@ -13348,8 +13348,19 @@ xmlSchemaResolveElementReferences(xmlSchemaElementPtr elemDecl,
 	    * declaration `resolved` to by the `actual value`
 	    * of the substitutionGroup [attribute], if present"
 	    */
-	    if (elemDecl->subtypes == NULL)
-		elemDecl->subtypes = substHead->subtypes;
+	    if (elemDecl->subtypes == NULL) {
+                if (substHead->subtypes == NULL) {
+                    /*
+                     * This can happen with self-referencing substitution
+                     * groups. The cycle will be detected later, but we have
+                     * to set subtypes to avoid null-pointer dereferences.
+                     */
+	            elemDecl->subtypes = xmlSchemaGetBuiltInType(
+                            XML_SCHEMAS_ANYTYPE);
+                } else {
+		    elemDecl->subtypes = substHead->subtypes;
+                }
+            }
 	}
     }
     /*
-- 
2.27.0

