[PATCH v4 1/4] PCI: of: avoid allocations in of_pci_prop_compatible()
From: Alex Elder
Date: Fri Sep 04 2026 - 10:07:55 EST
Three compatible strings are formatted in of_pci_prop_compatible().
Their sizes are known in advance, and the largest is 16 bytes.
Rather than dynamically allocating the space for those strings, just
set aside a buffer on the stack large enough to hold all three.
This avoids a problem that Sashiko pointed out, where an allocation
failure would cause subsequent crash because strlen() is called
unconditionally in of_changeset_add_prop_string_array().
Reported-by: Sashiko <sashiko-bot@xxxxxxxxxx>
Link: https://lore.kernel.org/sashiko-reviews/a647bd56-7dc8-4fec-9d96-834622054cdf@xxxxxxxxxxxx
Signed-off-by: Alex Elder <elder@xxxxxxxxxxxx>
---
v4: - Added this fix to the beginning of the series
drivers/pci/of_property.c | 31 ++++++++++++++++++++-----------
1 file changed, 20 insertions(+), 11 deletions(-)
diff --git a/drivers/pci/of_property.c b/drivers/pci/of_property.c
index 75a358f73e694..a0632f932b5c6 100644
--- a/drivers/pci/of_property.c
+++ b/drivers/pci/of_property.c
@@ -324,27 +324,36 @@ static int of_pci_prop_intr_map(struct pci_dev *pdev, struct of_changeset *ocs,
return ret;
}
+/* The three compatible property strings have max sizes 12+1, 15+1, and 13+1 */
+#define PROP_SIZE 16 /* Max size of each compatible string */
static int of_pci_prop_compatible(struct pci_dev *pdev,
struct of_changeset *ocs,
struct device_node *np)
{
const char *compat_strs[PROP_COMPAT_NUM] = { 0 };
+ char buf[PROP_COMPAT_NUM * PROP_SIZE] = { };
+ char bufp = buf;
int i, ret;
- compat_strs[PROP_COMPAT_PCI_VVVV_DDDD] =
- kasprintf(GFP_KERNEL, "pci%x,%x", pdev->vendor, pdev->device);
- compat_strs[PROP_COMPAT_PCICLASS_CCSSPP] =
- kasprintf(GFP_KERNEL, "pciclass,%06x", pdev->class);
- compat_strs[PROP_COMPAT_PCICLASS_CCSS] =
- kasprintf(GFP_KERNEL, "pciclass,%04x", pdev->class >> 8);
+ ret = snprintf(bufp, PROP_SIZE, "pci%x,%x", pdev->vendor, pdev->device);
+ if (ret >= PROP_SIZE)
+ return -EINVAL;
+ compat_strs[PROP_COMPAT_PCI_VVVV_DDDD] = bufp;
+ bufp += ret + 1;
- ret = of_changeset_add_prop_string_array(ocs, np, "compatible",
- compat_strs, PROP_COMPAT_NUM);
- for (i = 0; i < PROP_COMPAT_NUM; i++)
- kfree(compat_strs[i]);
+ ret = snprintf(bufp, PROP_SIZE, "pciclass,%06x", pdev->class);
+ if (ret >= PROP_SIZE)
+ return -EINVAL;
+ compat_strs[PROP_COMPAT_PCICLASS_CCSSPP] = bufp;
+ bufp += ret + 1;
- return ret;
+ ret = snprintf(bufp, PROP_SIZE, "pciclass,%04x", pdev->class >> 8);
+ compat_strs[PROP_COMPAT_PCICLASS_CCSS] = bufp;
+
+ return of_changeset_add_prop_string_array(ocs, np, "compatible",
+ compat_strs, PROP_COMPAT_NUM);
}
+#undef PROP_SIZE
int of_pci_add_properties(struct pci_dev *pdev, struct of_changeset *ocs,
struct device_node *np)
--
2.53.0