https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124005
Bug ID: 124005
Summary: -fsanitize=undefined has different behavior depending
on the optimization flags
Product: gcc
Version: 14.2.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: sanitizer
Assignee: unassigned at gcc dot gnu.org
Reporter: Adam.Banasiak at dolby dot com
CC: dodji at gcc dot gnu.org, dvyukov at gcc dot gnu.org,
jakub at gcc dot gnu.org, kcc at gcc dot gnu.org
Target Milestone: ---
Created attachment 63610
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=63610&action=edit
Minimal reproduction
The attached piece of code produces a warning when compiled with
-fsanitize=undefined and optimization enabled (-O1, -O2 or -O3). But when
compiled with different optimization flags (-O0, -Og, -Oz, -Os) it compiles
without any warnings.
>From what I've learned from the documentation, optimization level should have
no impact on that.
I've noticed this issue first when working on Ubuntu 24.04 with g++ 14.2.0:
```
adam @ Linux ~/test/gcc [15:36:49]
└─ $ ▶ cat main.cpp
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
void reproduction(const char *format, va_list args)
{
va_list argscp;
va_copy(argscp, args);
auto size = static_cast<size_t>(1 + vsnprintf(nullptr, 0, format, argscp));
va_end(argscp);
char *buf = (char *)malloc(size);
if (buf != nullptr)
{
vsnprintf(buf, size, format, args);
printf("%lu",size);
free(buf);
}
}
int main()
{
return 0;
}
adam @ Linux ~/test/gcc [15:36:53]
└─ $ ▶ g++ -O0 -fsanitize=undefined main.cpp -o main_o0
adam @ Linux ~/test/gcc [15:36:57]
└─ $ ▶ g++ -O1 -fsanitize=undefined main.cpp -o main_o1
In file included from /usr/include/stdio.h:980,
from /usr/include/c++/14/cstdio:42,
from main.cpp:2:
In function ‘int vsnprintf(char*, size_t, const char*, __va_list_tag*)’,
inlined from ‘void reproduction(const char*, __va_list_tag*)’ at
main.cpp:9:50:
/usr/include/x86_64-linux-gnu/bits/stdio2.h:68:36: warning: null format string
[-Wformat-truncation=]
68 | return __builtin___vsnprintf_chk (__s, __n, __USE_FORTIFY_LEVEL - 1,
| ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
69 | __glibc_objsize (__s), __fmt,
__ap);
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
adam @ Linux ~/test/gcc [15:37:00]
└─ $ ▶ g++ --version
g++ (Ubuntu 14.2.0-4ubuntu2~24.04) 14.2.0
Copyright (C) 2024 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
```
Later on, I've checked it also on the Compiler Explorer (you can find it here:
https://godbolt.org/z/Kb1nPovWr) and noticed the same behaviour on the
different versions of gcc (starting from 10.1 up to the trunk version). Older
versions has the same behaviour, no mather what's the optimization level is.