Ted Unangst <t...@tedunangst.com> wrote:

> Theo Buehler wrote:
> > According to our documentation and all the standards I checked,
> > snprintf() returns a negative value on error, not necessarily -1. 
> > This confused me quite a bit recently so I suggest to adjust the
> > example code as follows:
> 
> I don't know. I guess it's technially correct, but there's theory and
> practice, and I don't think anybody will ever return -2 here. Everything in
> base is written to check for -1.
> 
> In read.2 and write.2, we specially say that -1 is the correct value to check.
> It would be nice if the rules were consistent. (To that end, I'd consider it a
> standards bug that snprintf is underspecified. It should say -1.)

Yep.

I dug into my email archives of July 1998.  Chris Torek, Casper Dik and
I worked to convince everyone of the 4.4lite2 approach of returning "bytes
desired", and -1 only for the obscure errno-delivering cases.  Since errno
is returned, the interface should return -1 (precisely).

There are many thousands of lines of code checking for -1 (precisely),
and not checking for other negative numbers.  Any library which returns
a different negative value will break many security-sensitive prorams.

Please don't change our manual page.  If anything, reach out to ANSI and
POSIX and ask them to seperate description of snprintf from fprintf,
and indicate snprintf returns precisely -1 in this circumstance.

> > 
> > Index: lib/libc/stdio/printf.3
> > ===================================================================
> > RCS file: /var/cvs/src/lib/libc/stdio/printf.3,v
> > retrieving revision 1.79
> > diff -u -p -r1.79 printf.3
> > --- lib/libc/stdio/printf.3 16 Jan 2019 12:55:49 -0000      1.79
> > +++ lib/libc/stdio/printf.3 18 Jan 2019 17:29:54 -0000
> > @@ -876,7 +876,7 @@ for later interpolation by
> >  Be sure to use the proper secure idiom:
> >  .Bd -literal -offset indent
> >  int ret = snprintf(buffer, sizeof(buffer), "%s", string);
> > -if (ret == -1 || ret >= sizeof(buffer))
> > +if (ret < 0 || ret >= sizeof(buffer))
> >     goto toolong;
> >  .Ed
> >  .Pp

Reply via email to