1From 767ae50bc9e94a35bfede3af291cf0060893db0f Mon Sep 17 00:00:00 2001
2From: Nick Wellnhofer <wellnhofer@aevum.de>
3Date: Sun, 5 Mar 2023 14:11:24 +0100
4Subject: [PATCH] malloc-fail: Fix null deref after
5 xmlSchemaItemList{Add,Insert}
6
7Found with libFuzzer, see #344.
8
9Reference:https://github.com/GNOME/libxml2/commit/767ae50bc9e94a35bfede3af291cf0060893db0f
10Conflict:NA
11---
12 xmlschemas.c | 44 ++++++++++++++++----------------------------
13 1 file changed, 16 insertions(+), 28 deletions(-)
14
15diff --git a/xmlschemas.c b/xmlschemas.c
16index 46cbe0f..d2f8bf1 100644
17--- a/xmlschemas.c
18+++ b/xmlschemas.c
19@@ -3417,23 +3417,17 @@ xmlSchemaItemListClear(xmlSchemaItemListPtr list)
20 static int
21 xmlSchemaItemListAdd(xmlSchemaItemListPtr list, void *item)
22 {
23-    if (list->items == NULL) {
24-	list->items = (void **) xmlMalloc(
25-	    20 * sizeof(void *));
26-	if (list->items == NULL) {
27-	    xmlSchemaPErrMemory(NULL, "allocating new item list", NULL);
28-	    return(-1);
29-	}
30-	list->sizeItems = 20;
31-    } else if (list->sizeItems <= list->nbItems) {
32-	list->sizeItems *= 2;
33-	list->items = (void **) xmlRealloc(list->items,
34-	    list->sizeItems * sizeof(void *));
35-	if (list->items == NULL) {
36+    if (list->sizeItems <= list->nbItems) {
37+        void **tmp;
38+        size_t newSize = list->sizeItems == 0 ? 20 : list->sizeItems * 2;
39+
40+	tmp = (void **) xmlRealloc(list->items, newSize * sizeof(void *));
41+	if (tmp == NULL) {
42 	    xmlSchemaPErrMemory(NULL, "growing item list", NULL);
43-	    list->sizeItems = 0;
44 	    return(-1);
45 	}
46+        list->items = tmp;
47+	list->sizeItems = newSize;
48     }
49     list->items[list->nbItems++] = item;
50     return(0);
51@@ -3474,23 +3468,17 @@ xmlSchemaItemListAddSize(xmlSchemaItemListPtr list,
52 static int
53 xmlSchemaItemListInsert(xmlSchemaItemListPtr list, void *item, int idx)
54 {
55-    if (list->items == NULL) {
56-	list->items = (void **) xmlMalloc(
57-	    20 * sizeof(void *));
58-	if (list->items == NULL) {
59-	    xmlSchemaPErrMemory(NULL, "allocating new item list", NULL);
60-	    return(-1);
61-	}
62-	list->sizeItems = 20;
63-    } else if (list->sizeItems <= list->nbItems) {
64-	list->sizeItems *= 2;
65-	list->items = (void **) xmlRealloc(list->items,
66-	    list->sizeItems * sizeof(void *));
67-	if (list->items == NULL) {
68+    if (list->sizeItems <= list->nbItems) {
69+        void **tmp;
70+        size_t newSize = list->sizeItems == 0 ? 20 : list->sizeItems * 2;
71+
72+	tmp = (void **) xmlRealloc(list->items, newSize * sizeof(void *));
73+	if (tmp == NULL) {
74 	    xmlSchemaPErrMemory(NULL, "growing item list", NULL);
75-	    list->sizeItems = 0;
76 	    return(-1);
77 	}
78+        list->items = tmp;
79+	list->sizeItems = newSize;
80     }
81     /*
82     * Just append if the index is greater/equal than the item count.
83-- 
842.27.0
85
86