This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug middle-end/49905] Better sanity checking on sprintf src & dest to produce warning for dodgy code ?


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

--- Comment #17 from Martin Sebor <msebor at gcc dot gnu.org> ---
I have tweaked the patch to print the following for the test case in comment
#13:

xyz.c: In function ‘f’:
xyz.c:10:46: warning: ‘%+03d’ directive output may be truncated between ‘3’ and
‘9’ bytes into a region of size ‘6’ [-Wformat-length=]
     __builtin_snprintf (zone, ZONE_LEN + 1, "%+03d%02d",
                                              ^
xyz.c:10:46: note: directive argument determined to be in the range
[‘-35791394’, ‘35791394’]
xyz.c:10:5: note: destination region size is ‘6’ bytes, minimum required ‘6’,
maximum ‘12’

The computation to determine the range of bytes on output is less
straightforward than might be expected when the argument is determined to be in
a range whose bounds have different signs and different magnitudes.  The
checker then has to decide which of the bounds to use as the maximum (the
minimum is zero).  For instance, if the argument is in range [-3, 123], the
relevant upper bound is 123 for %i but -3 for %u.  This is because formatting a
value in this range results in between 1 and 3 bytes on output for %i, but in
as many as 10 bytes for %u given 32-bit ints (-3 formats as "4294967293"). 
This may not be completely intuitive but I hope the new note helps make it
clearer.  For the %u case with [-3, 123], it results in:

warning: ‘%u’ directive output may be truncated between ‘1’ and ‘10’ bytes into
a region of size ‘3’ [-Wformat-length=]
     __builtin_snprintf (d, sizeof d, "%u", x);
                                       ^
note: directive argument determined to be in the range [‘-3’, ‘123’]

It still assumes the user will figure out that it's the lower end of the range
that results in the maximum of 10 bytes.  I'm not sure how to help with that
without cluttering the output with too much verbiage and possibly making some
cases seem more complicated than they are.

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]