#!/usr/bin/make -f

BUILD_TREE=../build-tree

WRAPPED_CC=$(BUILD_TREE)/hardened-cc
WRAPPED_CXX=$(BUILD_TREE)/hardened-c++
WRAPPED_LD=$(BUILD_TREE)/hardened-ld

# It seems that GCC_EXEC_PREFIX does not behave the same across all
# architectures, so we need to pass the -B flag instead.
CC=$(WRAPPED_CC) -B $(BUILD_TREE)/

WRAPPERS=$(WRAPPED_CC) $(WRAPPED_LD) $(WRAPPED_CXX)


SYMLINKED_LD=$(BUILD_TREE)/ld

HELLO=hello.c

TEST_REQS=$(HELLO) $(WRAPPERS) $(SYMLINKED_LD)

export HARDENING_USE_USR_BIN=1
export DEB_BUILD_HARDENING=1
export DEB_BUILD_HARDENING_DEBUG=1

TESTS=\
	syntax.stamp \
	$(BUILD_TREE)/test-stock \
	$(BUILD_TREE)/test-compiled \
	$(SYMLINKED_LD) \
	$(BUILD_TREE)/test-linked \
	$(BUILD_TREE)/test-fPIC-direct \
	$(BUILD_TREE)/test-fPIC

check: $(TESTS)

clean:
	rm -f $(TESTS)

syntax.stamp: $(WRAPPERS)
	# Test basic perl syntax
	for script in $(WRAPPERS); do perl -c $$script; done
	touch $@

##########
# Compilation and linking results tests

$(BUILD_TREE)/test-stock: $(HELLO) $(WRAPPERS)
	# Compiler and linker options disabled.
	DEB_BUILD_HARDENING=0 $(CC) -o $@ $<
	readelf -l $@
	$@

$(BUILD_TREE)/test-compiled: $(HELLO) $(WRAPPERS)
	# Compiler options enabled. (linker is system-default)
	$(CC) -o $@ $<
	readelf -l $@
	# Run twice to show off PIE, if available in kernel
	$@
	$@

$(SYMLINKED_LD): $(WRAPPED_LD)
	# Enable symlink for ld to trick gcc into doing wrapped linking
	(cd $(BUILD_TREE) && ln -s hardened-ld ld)

$(BUILD_TREE)/test-linked: $(TEST_REQS)
	# Compiler and linker options enabled.
	$(CC) -o $@ $<
	readelf -l $@
	# Run twice to show off PIE, if available in kernel
	$@
	$@


##########
# Compiler arg calling style tests

# cmake likes to pass -fPIC to everything, which broke pre-1.10 wrappers
$(BUILD_TREE)/test-fPIC-direct: $(TEST_REQS)
	# Build directly with -fPIC already defined
	$(CC) -fPIC -o $@ $<
	$@

$(BUILD_TREE)/test-fPIC.o: $(TEST_REQS)
	# Build .o with -fPIC already defined
	$(CC) -fPIC -o $@ -c $<

$(BUILD_TREE)/test-fPIC: $(BUILD_TREE)/test-fPIC.o $(TEST_REQS)
	# Link .o with -fPIC already defined
	$(CC) -fPIC -o $@ $<
	$@
