Re: [PATCH] block/rnbd-clt: fix overlapping snprintf arguments

From: Jinpu Wang
Date: Wed Mar 24 2021 - 06:35:14 EST


On Tue, Mar 23, 2021 at 1:55 PM Arnd Bergmann <arnd@xxxxxxxxxx> wrote:
>
> From: Arnd Bergmann <arnd@xxxxxxxx>
>
> The -Wrestrict warning (disabled by default) points out undefined
> behavior calling snprintf():
>
> drivers/block/rnbd/rnbd-clt-sysfs.c: In function 'rnbd_clt_get_path_name':
> drivers/block/rnbd/rnbd-clt-sysfs.c:486:8: error: 'snprintf' argument 4 overlaps destination object 'buf' [-Werror=restrict]
> 486 | ret = snprintf(buf, len, "%s@%s", buf, dev->sess->sessname);
> | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> drivers/block/rnbd/rnbd-clt-sysfs.c:472:67: note: destination object referenced by 'restrict'-qualified argument 1 was declared here
> 472 | static int rnbd_clt_get_path_name(struct rnbd_clt_dev *dev, char *buf,
> | ~~~~~~^~~
>
> This can be simplified by using a single snprintf() to print the
> whole buffer, avoiding the undefined behavior.
>
> Fixes: 91f4acb2801c ("block/rnbd-clt: support mapping two devices with the same name from different servers")
> Signed-off-by: Arnd Bergmann <arnd@xxxxxxxx>
> ---
> drivers/block/rnbd/rnbd-clt-sysfs.c | 6 +-----
> 1 file changed, 1 insertion(+), 5 deletions(-)
>
> diff --git a/drivers/block/rnbd/rnbd-clt-sysfs.c b/drivers/block/rnbd/rnbd-clt-sysfs.c
> index d4aa6bfc9555..38251b749664 100644
> --- a/drivers/block/rnbd/rnbd-clt-sysfs.c
> +++ b/drivers/block/rnbd/rnbd-clt-sysfs.c
> @@ -479,11 +479,7 @@ static int rnbd_clt_get_path_name(struct rnbd_clt_dev *dev, char *buf,
> while ((s = strchr(pathname, '/')))
> s[0] = '!';
>
> - ret = snprintf(buf, len, "%s", pathname);
> - if (ret >= len)
> - return -ENAMETOOLONG;
> -
> - ret = snprintf(buf, len, "%s@%s", buf, dev->sess->sessname);
> + ret = snprintf(buf, len, "%s@%s", pathname, dev->sess->sessname);
> if (ret >= len)
> return -ENAMETOOLONG;
>
> --
> 2.29.2
>
Thanks Arnd, We have a same patch will send out soon as part of a
bigger patchset.