Comment 0 for bug 1770676

Revision history for this message
Scott Emmons (lscotte) wrote : gcc optimizer bug

Note: Package gcc-7 selected, but this affects other gcc versions.

While investigating why cronolog was no longer changing a log symlink in bionic, I discovered a bug in gcc (reproducable in 7.3.0-16ubuntu3 in bionic and 5.4.0-6ubuntu1~16.04.9 in xenial) for code compiled with -O2. I have created a simple testcase to reproduce the problem, which is attached.

You can reproduce the problem with the following:

# ====
set -x
echo "First, we compile and run without optimization:"
gcc -o testcase testcase.c && ./testcase

echo "Then, we compile and run with optimization:"
gcc -O2 -o testcase testcase.c && ./testcase
# ====

Which outputs:
+ echo 'First, we compile and run without optimization:'
First, we compile and run without optimization:
+ gcc -o testcase testcase.c
+ ./testcase
foo in func() is NULL (expected)
foo in func() is NULL (expected)
foo in main() is NULL (expected)
foo in main() is NULL (expected)
+ echo 'Then, we compile and run with optimization:'
Then, we compile and run with optimization:
+ gcc -O2 -o testcase testcase.c
+ ./testcase
foo in func() is NULL (expected)
foo in func() is not NULL (NOT EXPECTED!)
foo in main() is NULL (expected)
foo in main() is NULL (expected)

The problem occurs after calling:

  stat(foo, &stat_buf);

Where foo is a NULL pointer. After the return from this function, foo will no longer be NULL when the code is compiled with optimization. (You can argue calling stat with a NULL pointer is bad behavior, however this code has been in cronolog, working fine when compiled with -O2, for years).

I can reproduce this easily on multiple systems, bionic with "gcc (Ubuntu 7.3.0-16ubuntu3) 7.3.0" and xenial with "gcc (Ubuntu 5.4.0-6ubuntu1~16.04.9) 5.4.0 20160609".

I could not initially reproduce the cronolog testcase in xenial, leading me to some suspicion that it may be related to retpoline or other recent compiler changes - and in fact after recompiling cronolog on xenial I can reproduce the issue there as well.