Re: [PATCH] sysfs: Add sysfs_emit to replace sprintf to PAGE_SIZE buffers.

From: Joe Perches
Date: Sat Aug 29 2020 - 03:21:05 EST


On Sat, 2020-08-29 at 09:59 +0300, Denis Efremov wrote:
> Hi,
>
> On 8/29/20 1:52 AM, Joe Perches wrote:
> > sprintf does not know the PAGE_SIZE maximum of the temporary buffer
> > used for outputting sysfs content requests and it's possible to
> > overrun the buffer length.
> >
> > Add a generic sysfs_emit mechanism that knows that the size of the
> > temporary buffer and ensures that no overrun is done.
> >
> > Signed-off-by: Joe Perches <joe@xxxxxxxxxxx>
> > --- rK
>
> It could be a good idea to update the docs to, i.e.:
> https://www.kernel.org/doc/html/latest/filesystems/sysfs.html

Yes, thanks.

I have the below already, but Greg makes a sensible point
about the generic use of sysfs_emit for single values
which is ~95% of the actual uses, so likely there will be
two functions. Given the multiple thousand instances,
using 2 functions would be smaller overall object code
as well.

Perhaps:

sysfs_emit (for single value output)
sysfs_emit_at (or sysfs_emit_pos ? or some better name?)

int sysfs_emit(char *buf, const char *fmt, ...)
int sysfs_emit_at(char *buf, int pos, const char *fmt, ...)

or maybe use

int sysfs_emit_pos(char *buf, char *pos, const char *fmt, ...)

The multiple use emit_at with int as the 2nd parameter would
make the direct return easier than the char * which needs a
subtraction.

six of this/half dozen of that...

cheers...

---

Anyway, this will need updating, likely with better examples.

diff --git a/Documentation/filesystems/sysfs.rst b/Documentation/filesystems/sysfs.rst
index ab0f7795792b..13c7a86fa6c8 100644
--- a/Documentation/filesystems/sysfs.rst
+++ b/Documentation/filesystems/sysfs.rst
@@ -242,12 +242,9 @@ Other notes:
is 4096.

- show() methods should return the number of bytes printed into the
- buffer. This is the return value of scnprintf().
+ buffer. This is the return value of sysfs_emit().

-- show() must not use snprintf() when formatting the value to be
- returned to user space. If you can guarantee that an overflow
- will never happen you can use sprintf() otherwise you must use
- scnprintf().
+- show() methods should only use sysfs_emit to format output.