Re: [Cocci] [PATCH] usb: atm: don't use snprintf() for sysfs attrs

From: Joe Perches
Date: Thu Aug 27 2020 - 18:45:24 EST


On Thu, 2020-08-27 at 15:20 -0700, Kees Cook wrote:
> On Fri, Aug 28, 2020 at 12:01:34AM +0300, Denis Efremov wrote:
> > Just FYI, I've send an addition to the device_attr_show.cocci script[1] to turn
> > simple cases of snprintf (e.g. "%i") to sprintf. Looks like many developers would
> > like it more than changing snprintf to scnprintf. As for me, I don't like the idea
> > of automated altering of the original logic from bounded snprint to unbouded one
> > with sprintf.
>
> Agreed. This just makes me cringe. If the API design declares that when
> a show() callback starts, buf has been allocated with PAGE_SIZE bytes,
> then that's how the logic should proceed, and it should be using
> scnprintf...
>
> show(...) {
> size_t remaining = PAGE_SIZE;
>
> ...
> remaining -= scnprintf(buf, remaining, "fmt", var args ...);
> remaining -= scnprintf(buf, remaining, "fmt", var args ...);
> remaining -= scnprintf(buf, remaining, "fmt", var args ...);
>
> return PAGE_SIZE - remaining;
> }

It seems likely that coccinelle could do those transform
with any of sprintf/snprintf/scnprint too.

Though my bikeshed would use a single function and have
that function know the maximum output size

Something like:

With single line use:

return sysfs_emit(buf, buf, fmt, ...) - buf;

and multi-line use:

char *pos = buf;

pos = sysfs_emit(buf, pos, fmt1, ...);
pos = sysfs_emit(buf, pos, fmt2, ...);
...

return pos - buf;