Subject: Re: CVS commit: src/sys
To: Simon J. Gerraty <sjg@crufty.net>
From: Andrew Brown <atatat@atatdot.net>
List: tech-kern
Date: 04/25/2004 02:35:59
On Sat, Apr 24, 2004 at 09:49:12PM -0700, Simon J. Gerraty wrote:
>>>I'd rather pay the expense of such a check than having memory
>>>corrupted.
>
>>	if 2nd arg to snprintf() is smaller than required space, snprintf()
>>	would leave truncated string as a result.
>
>Sure, but as previously noted, snprintf in that case, still returns the
>amount of space _required_ which makes usage like:
>
>cp += snprintf(...)
>
>very dangerous - which is a shame since its logically appealing.
>The solution I mentioned of using an snprintf wrapper that returns 0
>in the truncation case - or better yet for the kernel - panic'd
>would allow 
>
>cp += safe_snprintf(...)
>
>to be used freely without littering the entire kernel with if's and/or 
>#ifdef's.

if this is the solution to avoiding sprinkling if's and/or #ifdef's,
wouldn't returning the "number of bytes consumed" instead of zero be
more "useful"?

isn't that what the consumer of snprintf() in that (ie, the proposed
"safe") context really expects?  since they're not checking for
overflow anyway (or else they'd be using snprintf() properly), just
give them something that fits what they seem to be doing?

eg:

#define safe_snprintf(b, s, ...) \
	({int _x = snprintf((b), (s), __VA_ARGS__); \
	 if (_x > (s)) _x = (s); \
	 _x;})

sorry...dunno how to do that without "gcc extensions".

-- 
|-----< "CODE WARRIOR" >-----|
codewarrior@daemon.org             * "ah!  i see you have the internet
twofsonet@graffiti.com (Andrew Brown)                that goes *ping*!"
werdna@squooshy.com       * "information is power -- share the wealth."