https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95673
Bug ID: 95673
Summary: Inconsistent optimization behavior when there is a
buffer overflow
Product: gcc
Version: 10.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: regression
Assignee: unassigned at gcc dot gnu.org
Reporter: dn2sp-dev at yahoo dot fr
Target Milestone: ---
Created attachment 48728
--> https://gcc.gnu.org/bugzilla/attachment.cgi?id=48728&action=edit
Example code
Hello,
I encountered a very strange behavior which i wanted to share with you. I'm not
sure if this is really a bug but the given example file shows a different
behavior in the code generated by -O0/1 and -O2/3.
First in this specific case there is an obvious buffer overflow. (char
data_read[sizeof(DATA)-1];) and this condition is required so the strange
behavior can be observed (if the buffer is not present, the generated code is
correct in both cases).
I also made a test with GCC8 and code behave the same with every -O level
unlike GCC10.
gcc -O0 -g -std=gnu99 test.c -o example; ./example
Output:
> strcmp(MAGIC, MAGIC) == 0
> Comparison is valid
gcc -O3 -g -std=gnu99 test.c -o example; ./example
Output:
> strcmp(MAGIC, MAGIC) == 0
> cmp value is: 0
> This code should not be reached
In the -O2/3 case, the generated assembly code does not include the conditional
jump corresponding to the if (cmp != 0) statement but includes the if ((ret =
fread(&data_read, sizeof(DATA), 1, fd)) != 1) statement.
│ 0x50eecallq 0x5050
│ 0x50f3cmp$0x1,%eax
│ 0x50f6jne0x5164
│ 0x50f8lea0xf08(%rip),%rdx#
0x6007
│ 0x50ffmov$0x6,%ecx
│ 0x5104mov%r12,%rsi
│ 0x5107mov%rdx,%rdi
│ 0x510arepz cmpsb %es:(%rdi),%ds:(%rsi)
│ 0x510cmov%r12,%rsi
│ 0x510flea0xef7(%rip),%rdi#
0x600d
│ 0x5116seta %bpl
│ 0x511asbb$0x0,%bpl
│ 0x511exor%eax,%eax
│ 0x5120movsbl %bpl,%ebp
│ 0x5124mov%ebp,%ecx
│ 0x5126callq 0x5070