On Wed, 11 Mar 2020 23:09:14 +0100, Dave Chinner wrote: > > On Wed, Mar 11, 2020 at 10:35:52AM +0100, Takashi Iwai wrote: > > Since snprintf() returns the would-be-output size instead of the > > actual output size, the succeeding calls may go beyond the given > > buffer limit. Fix it by replacing with scnprintf(). > > > > Signed-off-by: Takashi Iwai <tiwai@xxxxxxx> > > --- > > fs/xfs/xfs_stats.c | 10 +++++----- > > 1 file changed, 5 insertions(+), 5 deletions(-) > > what about all the other calls to snprintf() in fs/xfs/xfs_sysfs.c > and fs/xfs/xfs_error.c that return the "would be written" length to > their callers? i.e. we can return a length longer than the buffer > provided to the callers... > > Aren't they all broken, too? The one in xfs_error.c is a oneshot call for a sysfs output with PAGE_SIZE limit, so it's obviously safe. OTOH, using snprintf() makes no sense as it doesn't return the right value if it really exceeds, so it should be either simplified to sprintf() or use scnprintf() to align both the truncation and the return value. > A quick survey of random snprintf() calls shows there's an abundance > of callers that do not check the return value of snprintf for > overflow when outputting stuff to proc/sysfs files. This seems like > a case of "snprintf() considered harmful, s/snprintf/scnprintf/ > kernel wide, remove snprintf()"... Yeah, snprintf() is a hard-to-use function if you evaluate the return value. I've submitted many similar patches like this matching a pattern like pos += snprintf(buf + pos, limit - pos, ...) which is a higher risk of breakage than a single shot call. We may consider flagging snprintf() to be harmful, but I guess it wasn't done at the time scnprintf() was introduced just because there are too many callers of snprintf(). And some code actually needs the size that would be output for catching the overflow explicitly (hence warning or resizing after that). Practically seen, the recent kernel snprintf() already protects the negative length with WARN(). But it's error-prone and would hit other issue if you access to the buffer position by other than snprintf(), so please see my patch just as a precaution. thanks, Takashi