Skip to content

Commit

Permalink
Add simple test of C/C++ hardening flags (#270)
Browse files Browse the repository at this point in the history
Signed-off-by: David A. Wheeler <[email protected]>
  • Loading branch information
david-a-wheeler authored Nov 3, 2023
1 parent 13d8fee commit 2a2991d
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
25 changes: 25 additions & 0 deletions docs/Compiler-Hardening-Guides/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Test C/C++ hardening flags

# Copyright Open Source Security Foundation (OpenSSF) and its contributors
# SPDX-License-Identifier: Apache-2.0 OR MIT

# Test hardening flags. You can set CC to the compiler to use. E.g.:
# make CC=clang
# make CC=/usr/local/Cellar/gcc/13.2.0/bin/gcc-13

# Extract the current hardening recommendations so we can test them.
# We use GNU make extensions $(shell ...) and ":=" to do this.
# Recent POSIX adds "!=" and "::=" but they are not yet universally supported,
# e.g., Apple MacOS only supplies an obsolete version of GNU Make.

CFLAGS_HARDENING := $(shell sed -e '1,/~~~~/d' -e '/~~~~/,$$d' -e 's/\\$$//' \
Compiler-Options-Hardening-Guide-for-C-and-C++.md )

# Could add architecture-specific flags, e.g.:
# -fcf-protection=full -mbranch-protection=standard

CFLAGS := $(CFLAGS_HARDENING) $(CFLAGS)

all: demo

demo: demo.c
27 changes: 27 additions & 0 deletions docs/Compiler-Hardening-Guides/demo.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Test C/C++ hardening flags

// Copyright Open Source Security Foundation (OpenSSF) and its contributors
// SPDX-License-Identifier: Apache-2.0 OR MIT

#include <stdio.h>

// Linux 5.10 solution:
#if __has_attribute(__fallthrough__)
# define fallthrough __attribute__((__fallthrough__))
#else
# define fallthrough do {} while (0) /* fallthrough */
#endif

int main(void) {
int c = 0;
switch (c) {
case 1:
printf("Hello\n");
fallthrough;
case 0:
printf("Goodbye\n");
fallthrough;
default:
printf("Default\n");
}
}

0 comments on commit 2a2991d

Please sign in to comment.