2022-07-04 13:20:34

by Jianglei Nie

[permalink] [raw]
Subject: [PATCH] peci: fix potential memory leak in devm_adev_add()

devm_adev_add() allocates a memory chunk for "adev" and "adev->name"
with adev_alloc(). When auxiliary_device_add() fails, the function calls
auxiliary_device_uninit(), which doesn't release the allocated "adev"
and "adev->name", thus leading to a memory leak bug.

We should call adev_release() instead of auxiliary_device_uninit() to
release the "adev" and "adev->name".

Signed-off-by: Jianglei Nie <[email protected]>
---
drivers/peci/cpu.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/drivers/peci/cpu.c b/drivers/peci/cpu.c
index 68eb61c65d34..de865997ccde 100644
--- a/drivers/peci/cpu.c
+++ b/drivers/peci/cpu.c
@@ -248,7 +248,7 @@ static int devm_adev_add(struct device *dev, int idx)

ret = auxiliary_device_add(adev);
if (ret) {
- auxiliary_device_uninit(adev);
+ adev_release(&adev->dev);
return ret;
}

--
2.25.1


2022-07-05 10:25:22

by Winiarska, Iwona

[permalink] [raw]
Subject: Re: [PATCH] peci: fix potential memory leak in devm_adev_add()

On Mon, 2022-07-04 at 20:59 +0800, Jianglei Nie wrote:
> devm_adev_add() allocates a memory chunk for "adev" and "adev->name"
> with adev_alloc(). When auxiliary_device_add() fails, the function calls
> auxiliary_device_uninit(), which doesn't release the allocated "adev"
> and "adev->name", thus leading to a memory leak bug.
>
> We should call adev_release() instead of auxiliary_device_uninit() to
> release the "adev" and "adev->name".
>
> Signed-off-by: Jianglei Nie <[email protected]>
> ---
>  drivers/peci/cpu.c | 2 +-
>  1 file changed, 1 insertion(+), 1 deletion(-)
>
> diff --git a/drivers/peci/cpu.c b/drivers/peci/cpu.c
> index 68eb61c65d34..de865997ccde 100644
> --- a/drivers/peci/cpu.c
> +++ b/drivers/peci/cpu.c
> @@ -248,7 +248,7 @@ static int devm_adev_add(struct device *dev, int idx)
>  
>         ret = auxiliary_device_add(adev);
>         if (ret) {
> -               auxiliary_device_uninit(adev);
> +               adev_release(&adev->dev);
>                 return ret;
>         }
>  

When we call auxiliary_device_uninit() the .release callback (adev_release())
will be triggered, so there's no memory leak here.

But thank you for pointing to this - it made me realize that we have a bug in
adev_release(), because we call auxiliary_device_uninit() there, which will
cause a use-after-free with refcount underflow in this case.

I'd appreciate if you could review it:
https://lore.kernel.org/lkml/[email protected]/

Thanks
-Iwona