Makefile: Test for warning flags before using them

Test for warning flags that older gcc versions don't support
and only use them if supported.

BUG=none
TEST=vboot builds with gcc 4.9, ensured with manual tests that the
test_ccflag operator works correctly.

Change-Id: I14c8cbe9a687981f195d481f744db12d8877a3e0
Signed-off-by: Patrick Georgi <pgeorgi@google.com>
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/vboot_reference/+/2550799
Reviewed-by: Julius Werner <jwerner@chromium.org>
Tested-by: Patrick Georgi <pgeorgi@chromium.org>
Commit-Queue: Patrick Georgi <pgeorgi@chromium.org>
diff --git a/Makefile b/Makefile
index 3a30c16..5de9f57 100644
--- a/Makefile
+++ b/Makefile
@@ -128,9 +128,9 @@
 FIRMWARE_FLAGS := -nostdinc -ffreestanding -fno-builtin -fno-stack-protector
 COMMON_FLAGS := -pipe ${WERROR} -Wall -Wstrict-prototypes -Wtype-limits \
 	-Wundef -Wmissing-prototypes -Wno-trigraphs -Wredundant-decls -Wshadow \
-	-Wwrite-strings -Wstrict-aliasing -Wdate-time -Wno-unknown-warning \
-	-Wno-address-of-packed-member -ffunction-sections -fdata-sections \
-	-Wimplicit-fallthrough -Wformat -Wno-format-security ${DEBUG_FLAGS}
+	-Wwrite-strings -Wstrict-aliasing -Wdate-time \
+	-ffunction-sections -fdata-sections \
+	-Wformat -Wno-format-security ${DEBUG_FLAGS}
 
 # FIRMWARE_ARCH is defined if compiling for a firmware target
 # (coreboot or depthcharge).
@@ -153,6 +153,21 @@
 CFLAGS += -DCHROMEOS_ENVIRONMENT ${COMMON_FLAGS}
 endif
 
+CFLAGS += -std=gnu11
+
+# test_ccflag
+# $(1): compiler flags to test
+# $(2): code to insert into test snippet
+# returns: $(1) if compiler was successful, empty string otherwise
+test_ccflag = $(shell \
+	printf "$(2)\nvoid _start(void) {}\n" | \
+	$(CC) -nostdlib -Werror $(1) -xc -c - -o /dev/null \
+	>/dev/null 2>&1 && echo "$(1)")
+
+COMMON_FLAGS += $(call test_ccflag,-Wimplicit-fallthrough)
+COMMON_FLAGS += $(call test_ccflag,-Wno-address-of-packed-member)
+COMMON_FLAGS += $(call test_ccflag,-Wno-unknown-warning)
+
 # Needs -Wl because LD is actually set to CC by default.
 LDFLAGS += -Wl,--gc-sections
 
@@ -247,8 +262,14 @@
 CFLAGS += -fPIE
 endif
 
-# These are required to access large disks and files on 32-bit systems.
-CFLAGS += -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64
+CFLAGS += -D_GNU_SOURCE
+
+# This is required to access large disks and files on 32-bit systems,
+# but if the environment doesn't support it, at least compile support
+# for what is possible.
+# Pass through cflags_use_64bits to evaluate it only once, here.
+cflags_use_64bits := $(call test_ccflag,-D_FILE_OFFSET_BITS=64,\#include <fts.h>)
+CFLAGS += $(cflags_use_64bits)
 
 # Code coverage
 ifneq (${COV},)