Re: [PATCH] lib: string_helpers: fix potential snprintf() output truncation

From: James Bottomley
Date: Tue Oct 22 2024 - 10:30:32 EST


On Tue, 2024-10-22 at 15:46 +0200, Rasmus Villemoes wrote:
[...]
> -       snprintf(buf, len, "%u%s %s", (u32)size,
> -                tmp, unit);
> +       if (j)
> +               snprintf(buf, len, "%u.%03u %s", (u32)size,
> remainder, unit);
> +       else
> +               snprintf(buf, len, "%u %s", (u32)size, unit);
>  }
>  EXPORT_SYMBOL(string_get_size);

Where are you getting this from? The current statement you'd be
replacing is

return snprintf(buf, len, "%u%s%s%s%s", (u32)size, tmp,
(units & STRING_UNITS_NO_SPACE) ? "" : " ",
unit,
(units & STRING_UNITS_NO_BYTES) ? "" : "B");

The use of a tmp buffer prevents that having to be repeated.

If we had a way of specifying "ignore argument" I suppose we could
switch the format string on J and then only have a single statement.

Regards,

James