Bug 11672 - gcc 7 format-truncation off by one with O2
Summary: gcc 7 format-truncation off by one with O2
Status: RESOLVED FIXED
Alias: None
Product: OE-Core
Classification: Build System, Metadata & Runtime
Component: devtools / tool chain (show other bugs)
Version: unspecified
Hardware: x86 Multiple
: Medium+ normal
Target Milestone: 2.5 M4
Assignee: Khem Raj
QA Contact:
URL:
Whiteboard:
Depends on:
Blocks:
 
Reported: 2017-06-15 18:41 UTC by Mark
Modified: 2018-05-10 08:01 UTC (History)
5 users (show)

See Also:
OS type for building Yocto: ---
Type of Regression: ---
Verified:
Documentation change: No (bug/feature does not impact docs)


Attachments
example C file (1.27 KB, text/x-csrc)
2017-06-15 18:41 UTC, Mark
no flags Details

Note You need to log in before you can comment on or make changes to this bug.
Description Mark 2017-06-15 18:41:11 UTC
Created attachment 3823 [details]
example C file

If you have a program such as
---
#include <stdio.h>

int main(int argc, char **argv)
{
  int i = 0;
  char buffer[100];

  for(i=0; i <= 999; i++)
    snprintf(buffer, 5, "-%d", i);

  return 0;
}
---

and build it with something like:
x86_64-overc-linux-gcc --sysroot=/home/mark/build/overc/tmp/work/core2-64-overc-linux/lxc/2.0.8-r0/recipe-sysroot -Wall -Werror -m64 -march=core2 -mtune=core2 -msse3 -mfpmath=sse -fPIC -DPIC -O2 -c range.c -o range

where x86_64-overc-linux-gcc --version
x86_64-overc-linux-gcc (GCC) 7.1.0

You will get
---
range.c: In function 'main':
range.c:10:25: error: 'snprintf' output may be truncated before the last format character [-Werror=format-truncation=]
     snprintf(buffer, 5, "-%d", i);
                         ^~~~~
range.c:10:5: note: 'snprintf' output between 3 and 6 bytes into a destination of size 5
     snprintf(buffer, 5, "-%d", i);
     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
cc1: all warnings being treated as errors
---

NOTE that to my surprise the check is not using the type size (which would be 12 -- 10 chars in an int, plus sign, plus null). It is in fact using the loop logic to determine range but incorrectly using 1000 even though the loop stops at 999.

Attached is a more extensive example which can be played with.
Comment 1 Mark 2017-06-15 18:48:03 UTC
This seems to be reported to gcc already as

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

NOTE they even note the issue in LXC which is where I ran into this.
Comment 2 Khem Raj 2017-08-16 16:26:08 UTC
This missed the 7.2 gcc release. I dont see it getting fixed by 2.4 release. Therefore moving it to 2.5
Comment 3 Richard Purdie 2018-05-10 08:01:50 UTC
We now have gcc 7.3 everywhere including the stable branches which resolves this.