[Bug rtl-optimization/87096] "Optimised" snprintf is not POSIX conformant

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Wed Dec 12 19:46:00 GMT 2018


https://gcc.gnu.org/bugzilla/show_bug.cgi?id=87096

--- Comment #8 from Martin Sebor <msebor at gcc dot gnu.org> ---
The POSIX requirement prevents buffer overflow when the size of the destination
is incorrectly computed.  I realize it's common practice to ignore snprintf 
return value, but defensively written code should check it.  The return value
can safely be ignored only when the function can neither fail nor truncate (in
the latter case sprintf is just as safe).  Otherwise, the return value should
be tested and either the failure or the more likely truncation should be
handled somehow.  The -Wstringop-truncation warning is based on this premise.

GCC can mitigate some of the buffer overflow cases when it can determine the
size of the destination on its own, but that's only possible in a subset of
cases.

That said, I'm not sure how to proceed here.  I see three ways forward:

1) disable the folding in this case and call the library function
2) suspend this until C/POSIX have resolved the conflict
3) fold the call to -1 and set errno to EOVERFLOW

I have a trivial patch to do (1) but my testing shows that while Solaris 11
implements the POSIX requirement AIX and Glibc don't, so it won't solve the
conformance/portability problem.  (2) is the easy way out for now, until C and
POSIX have either converged or decided not to.  (3) is out of scope for GCC 9.

>From your comments, Rich, it's not clear to me what you are arguing for.  It
sounds like you don't agree with the POSIX requirement but also disapprove of
the GCC optimization.


More information about the Gcc-bugs mailing list