[Bug c/83586] [8 regression] Invalid -Wformat-truncation on stdio2.h

msebor at gcc dot gnu.org gcc-bugzilla@gcc.gnu.org
Tue Jan 2 19:27:00 GMT 2018


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

Martin Sebor <msebor at gcc dot gnu.org> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|UNCONFIRMED                 |WAITING
   Last reconfirmed|                            |2018-01-02
                 CC|                            |msebor at gcc dot gnu.org
     Ever confirmed|0                           |1

--- Comment #1 from Martin Sebor <msebor at gcc dot gnu.org> ---
The -Wformat-truncation warning relies on optimization to detect sizes and
ranges of sprintf arguments.  As optimizations improve the warning will detect
more instances of possible overflows.

I don't know what the source code looks like (we ask for a preprocessing
translation unit to reproduce errors) but the text of the warning suggests that
snprintf is being called to format a string of an unknown length stored in an
array of 128 chars into a buffer that has at most 126 bytes of space left,
allowing for the function to truncate the directive's output.  Below is a test
case that reproduces a similar warning with GCC 8.  GCC 7 doesn't diagnose it
because of bug 79538.  The solution to avoid the warning is to either a)
provide a buffer of sufficient size, or b) constrain the length of the string
argument to the %s directive to avoid the possible truncation, or c) handle the
truncation by using the snprintf return value to take some action (something
GCC doesn't optimize away).

Please either confirm whether this is what's going on in LinuxGamepad.cpp or
provide a preprocessing translation unit of the file that reproduces the
warning so it can be analyzed.

$ cat d.c && gcc -O2 -S -Wall -Wextra d.c
void f (char *d, unsigned long x)
{
  extern char a[128];

  x >>= 4;

  __builtin_snprintf (d, 128, "%lx %s", x, a);
}
d.c: In function ‘f’:
d.c:7:36: warning: ‘%s’ directive output may be truncated writing up to 127
bytes into a region of size between 112 and 126 [-Wformat-truncation=]
   __builtin_snprintf (d, 128, "%lx %s", x, a);
                                    ^~      ~
d.c:7:3: note: ‘__builtin_snprintf’ output between 3 and 144 bytes into a
destination of size 128
   __builtin_snprintf (d, 128, "%lx %s", x, a);
   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


More information about the Gcc-bugs mailing list