Re: [PATCH] fix memory leak in ramoops_init

From: Kees Cook
Date: Fri Sep 28 2018 - 18:18:26 EST


In the future, please use scripts/get_maintainer.pl to find your To/Cc list. :)

On Mon, Sep 17, 2018 at 2:15 AM, nixiaoming <nixiaoming@xxxxxxxxxx> wrote:
> 1, memory leak in ramoops_register_dummy.
> dummy_data = kzalloc(sizeof(*dummy_data), GFP_KERNEL);
> but no free when platform_device_register_data return fail

Yup, that's a problem.

> 2, if kzalloc(sizeof(*dummy_data), GFP_KERNEL) return NULL,
> but platform_driver_register(&ramoops_driver) return 0
> kfree(NULL) in ramoops_exit
> so, add return val for ramoops_register_dummy, and check it in ramoops_init

The kfree(NULL) isn't a problem, but a NULL platform_data implies
device tree data is expected, so it'll just confuse things. However,
since the dummy platform data is optional, there's no need to plumb
the return value back up. Either it gets set up correctly, or there is
a pr_info() about why it has been ignored.

> 3, memory leak in ramoops_init.
> miss platform_device_unregister(dummy) and kfree(dummy_data)
> when platform_driver_register(&ramoops_driver) return fail

Agreed.

> Signed-off-by: nixiaoming <nixiaoming@xxxxxxxxxx>
> ---
> fs/pstore/ram.c | 22 +++++++++++++++++-----
> 1 file changed, 17 insertions(+), 5 deletions(-)
>
> diff --git a/fs/pstore/ram.c b/fs/pstore/ram.c
> index bd9812e..331b600 100644
> --- a/fs/pstore/ram.c
> +++ b/fs/pstore/ram.c
> @@ -604,17 +604,17 @@ static struct platform_driver ramoops_driver = {
> },
> };
>
> -static void ramoops_register_dummy(void)
> +static int ramoops_register_dummy(void)

Another bug is that this should actually be __init (it's only called
by an __init).

> {
> if (!mem_size)
> - return;
> + return -EINVAL;
>
> pr_info("using module parameters\n");
>
> dummy_data = kzalloc(sizeof(*dummy_data), GFP_KERNEL);
> if (!dummy_data) {
> pr_info("could not allocate pdata\n");
> - return;
> + return -ENOMEM;
> }
>
> dummy_data->mem_size = mem_size;
> @@ -636,13 +636,25 @@ static void ramoops_register_dummy(void)
> if (IS_ERR(dummy)) {
> pr_info("could not create platform device: %ld\n",
> PTR_ERR(dummy));
> + kfree(dummy_data);
> + return PTR_ERR(dummy);
> }
> + return 0;
> }
>
> static int __init ramoops_init(void)
> {
> - ramoops_register_dummy();
> - return platform_driver_register(&ramoops_driver);
> + int ret = ramoops_register_dummy();
> +
> + if (ret != 0)
> + return ret;
> +
> + ret = platform_driver_register(&ramoops_driver);
> + if (ret != 0) {
> + platform_device_unregister(dummy);
> + kfree(dummy_data);
> + }
> + return ret;
> }
> postcore_initcall(ramoops_init);
>
> --
> 1.9.0
>

I'll send an updated patch with a similar fix...

-Kees

--
Kees Cook
Pixel Security