Re: [PATCH] pinctrl:sunplus: Add check for kmalloc

From: Dan Carpenter
Date: Thu May 25 2023 - 15:52:14 EST


On Tue, May 23, 2023 at 10:05:49PM +0200, Christophe JAILLET wrote:
> Le 23/05/2023 à 21:37, andy.shevchenko@xxxxxxxxx a écrit :
> > Tue, May 23, 2023 at 05:39:51PM +0000, Wells Lu 呂芳騰 kirjoitti:
> > > > > Fix Smatch static checker warning:
> > > > > potential null dereference 'configs'. (kmalloc returns null)
> >
> > ...
> >
> > > > > configs = kmalloc(sizeof(*configs), GFP_KERNEL);
> > > > > + if (!configs)
> > > >
> > > > > + return -ENOMEM;
> > > >
> > > > "Fixing" by adding a memory leak is not probably a good approach.
> > >
> > > Do you mean I need to free all memory which are allocated in this subroutine before
> > > return -ENOMEM?
> >
> > This is my understanding of the code. But as I said... (see below)
> >
> > ...
> >
> > > > > configs = kmalloc(sizeof(*configs), GFP_KERNEL);
> > > > > + if (!configs)
> > > > > + return -ENOMEM;
> > > >
> > > > Ditto.
> >
> > ...
> >
> > > > It might be that I'm mistaken. In this case please add an explanation why in the commit
> > > > message.
> >
> > ^^^
> >
>
> Hmmm, not so sure.
>
> Should be looked at more carefully, but
> dt_to_map_one_config (in /drivers/pinctrl/devicetree.c)
> .dt_node_to_map
> --> sppctl_dt_node_to_map
>
> Should dt_to_map_one_config() fail, pinctrl_dt_free_maps() is called
> (see https://elixir.bootlin.com/linux/v6.4-rc1/source/drivers/pinctrl/devicetree.c#L281)

Thanks for this call tree, I don't have this file enabled in my build
so it's not easy for me to find how sppctl_dt_node_to_map() was called.

drivers/pinctrl/devicetree.c
160 dev_err(p->dev, "pctldev %s doesn't support DT\n",
161 dev_name(pctldev->dev));
162 return -ENODEV;
163 }
164 ret = ops->dt_node_to_map(pctldev, np_config, &map, &num_maps);
^^^^
"map" isn't stored anywhere so it will be leaked. I guess kmemleak
already figured this out.

165 if (ret < 0)
166 return ret;
167 else if (num_maps == 0) {
168 /*

>
> pinctrl_dt_free_maps() calls dt_free_map(), which calls .dt_free_map, so
> pinctrl_utils_free_map()
> (see https://elixir.bootlin.com/linux/v6.4-rc1/source/drivers/pinctrl/sunplus/sppctl.c#L978)
>
> Finally the needed kfree seem to be called from here.
> (see https://elixir.bootlin.com/linux/v6.4-rc1/source/drivers/pinctrl/pinctrl-utils.c#L119)
>
>
> *This should obviously be double checked*, but looks safe to me.
>
>
> BUT, in the same function, the of_get_parent() should be undone in case of
> error, as done at the end of the function, in the normal path.
> This one seems to be missing, should a memory allocation error occur.
>

Yes. There are some missing calls to of_node_put(parent); in
sppctl_dt_node_to_map().

regards,
dan carpenter