Re: [PATCH v3] node: put_device after failing to device_register
From: Johan Hovold
Date: Tue Jun 21 2022 - 08:03:42 EST
On Tue, Jun 21, 2022 at 06:17:22PM +0800, 智宋 wrote:
> > On Jun 20, 2022, at 21:55, Johan Hovold <johan@xxxxxxxxxx> wrote:
> > That's a pretty obvious use-after-free you just added here. You can't
> > access dev after you've just freed it.
> >
> > The name is freed along with the rest of the struct device so you need
> > to remove the second explicit free. And you should rename the label too.
> >
> >> free:
> >> kfree(access_node);
> >
> > But here's another use after free... The put_device() call you added
> > will have freed access_node by calling node_access_release().
> dev_set_name() allocates new space to dev->name and assigns the address of space to dev->name if it allocates successfully. But if we fail to allocate space, there isn’t any new space for dev->name. Therefore, there’s no need for calling kfree_const(dev->kobj.name) in dev_set_name()’s error handling.
Note that your mails are being rejected by the mailing list since they
include HTML. Can you see if you can fix your mail client to send as
text instead?
That may fix lack line breaks too (break lines at 72 columns or so).
> If we fail to do device_register(dev), we just need to put_device(dev) which will do free access_node, kobj.name and other cleanup.
>
> Maybe the code is:
>
> --- a/drivers/base/node.c
> +++ b/drivers/base/node.c
> @@ -144,21 +144,19 @@ static struct node_access_nodes *node_init_node_access(struct node *node,
> dev->parent = &node->dev;
> dev->release = node_access_release;
> dev->groups = node_access_node_groups;
> - if (dev_set_name(dev, "access%u", access))
> - goto free;
> + if (dev_set_name(dev, "access%u", access)) {
> + kfree(access_node);
> + return NULL;
> + }
>
> - if (device_register(dev))
> - goto free_name;
> + if (device_register(dev)) {
> + put_device(dev);
> + return NULL;
> + }
>
> pm_runtime_no_callbacks(dev);
> list_add_tail(&access_node->list_node, &node->access_list);
> return access_node;
> -free_name:
> - put_device(dev);
> - kfree_const(dev->kobj.name);
> -free:
> - kfree(access_node);
> - return NULL;
> }
The above fix looks correct now.
> Thanks for your patience. :)
You're welcome. Thanks for finding and fixing the bug.
Johan