From 01382dc4ad1d5f7448755a01daf28404dfdb1406 Mon Sep 17 00:00:00 2001 From: Marian Buschsieweke Date: Thu, 10 Jan 2019 15:07:35 +0100 Subject: [PATCH] makefiles: Add -fwrapv to CFLAGS This commit makes overflow of signed integers to behave as expected by at 90% of the C developers, even though overflow of signed integers are strictly undefined behavior. Note: Please do not add code relying on a specific behavior for the overflow of signed integers, even though `-fwrpav` will make that code work. This is intended to mitigate the risk of bugs in overflow checks being exploited, not to encourage adding new bugs. See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=30475 for details and see http://c-faq.com/misc/intovf.html on how to implement overflow checks properly. --- makefiles/cflags.inc.mk | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/makefiles/cflags.inc.mk b/makefiles/cflags.inc.mk index 10f3751a68..0fb5fcc512 100644 --- a/makefiles/cflags.inc.mk +++ b/makefiles/cflags.inc.mk @@ -19,6 +19,22 @@ ifneq ($(CC_NOCOLOR),1) OPTIONAL_CFLAGS += -fdiagnostics-color endif +# Force the C compiler to not ignore signed integer overflows +# Background: In practise signed integers overflow consistently and wrap +# around to the lowest number. But this is undefined behaviour. +# Branches that rely on this undefined behaviour will be silently +# optimized out. For details, have a look at +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=30475 +# Note: Please do not add new code that relies on this undefined +# behaviour, even though this flag makes your code work. There are +# safe ways to check for signed integer overflow. +CFLAGS += -fwrapv +# Enable warnings for code relying on signed integers to overflow correctly +# (see above for details). +# Note: This warning is sadly not reliable, thus -fwrapv cannot be +# dropped in favor of this +CFLAGS += -Wstrict-overflow + # Fast-out on old style function definitions. # They cause unreadable error compiler errors on missing semicolons. # Worse yet they hide errors by accepting wildcard argument types.