Re: [PATCH] pds_core: Fix possible double free in error handling path

From: Nelson, Shannon
Date: Fri Mar 01 2024 - 12:56:04 EST


On 2/29/2024 6:23 PM, hyper wrote:


Please specify the networking tree in your patch subject, something like [PATCH net] in this case.


When auxiliary_device_add() returns error and then calls
auxiliary_device_uninit(), Callback function pdsc_auxbus_dev_release
calls kfree(padev) to free memory. We shouldn't call kfree(padev)
again in the error handling path.

Fix this by returning error directly after calling
auxiliary_device_uninit().

Fixes: 4569cce43bc6 ("pds_core: add auxiliary_bus devices")
Signed-off-by: hyper <hyperlyzcs@xxxxxxxxx>
---
drivers/net/ethernet/amd/pds_core/auxbus.c | 2 ++
1 file changed, 2 insertions(+)

diff --git a/drivers/net/ethernet/amd/pds_core/auxbus.c b/drivers/net/ethernet/amd/pds_core/auxbus.c
index 11c23a7f3172..d6eedd78d5cc 100644
--- a/drivers/net/ethernet/amd/pds_core/auxbus.c
+++ b/drivers/net/ethernet/amd/pds_core/auxbus.c
@@ -174,6 +174,8 @@ static struct pds_auxiliary_dev *pdsc_auxbus_dev_register(struct pdsc *cf,

err_out_uninit:
auxiliary_device_uninit(aux_dev);
+ return ERR_PTR(err);
+
err_out:
kfree(padev);
return ERR_PTR(err);
--
2.36.1


Yes, I think you've got the right idea here, and this is probably a reasonable solution.

However, usually the error handling exit code stacks on itself, but here it becomes two separate independent chunks - a slightly different pattern. Since these are both very short bits I'd be tempted to "enhance" that independence by putting the error handling back to where the errors happened, something like

diff --git a/drivers/net/ethernet/amd/pds_core/auxbus.c b/drivers/net/ethernet/amd/pds_core/auxbus.c
index a3c79848a69a..2babea110991 100644
--- a/drivers/net/ethernet/amd/pds_core/auxbus.c
+++ b/drivers/net/ethernet/amd/pds_core/auxbus.c
@@ -160,23 +160,19 @@ static struct pds_auxiliary_dev *pdsc_auxbus_dev_register(struct pdsc *cf,
if (err < 0) {
dev_warn(cf->dev, "auxiliary_device_init of %s failed: %pe\n",
name, ERR_PTR(err));
- goto err_out;
+ kfree(padev);
+ return ERR_PTR(err);
}

err = auxiliary_device_add(aux_dev);
if (err) {
dev_warn(cf->dev, "auxiliary_device_add of %s failed: %pe\n",
name, ERR_PTR(err));
- goto err_out_uninit;
+ auxiliary_device_uninit(aux_dev);
+ return ERR_PTR(err);
}

return padev;
-
-err_out_uninit:
- auxiliary_device_uninit(aux_dev);
-err_out:
- kfree(padev);
- return ERR_PTR(err);
}

Some might disagree. I like this a little better, but I could go either way.

Thoughts?

sln