#!/bin/bash

# Copyright (c) 2021-2022 Red Hat.
#
# This is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 3, or (at your
# option) any later version.
#
# It is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# See BZ 2010675

set +x
echo START

TEST_NAME=fortify
. $srcdir/common.sh

# Use the same command line options that normal spec file will use,
# *except* that we disable the use of the annobin plugin, since this
# will pick up the one in the system directory, not the one just built"

OPTS="$(rpm --eval '%undefine _annotated_build %build_cflags %build_ldflags')"

# The rpm macros may not be available, so if necessary use our own

if ! [[ $OPTS == *"redhat-hardened-cc1"* ]];
then
    echo " $TEST_NAME: using built-in option selection instead"
    OPTS="-O2 -fexceptions -g -grecord-gcc-switches -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fPIE -fstack-protector-strong -fasynchronous-unwind-tables -fstack-clash-protection -Wl,-z,relro -Wl,--as-needed  -Wl,-z,now -pie"
fi

# Now add in our newly built plugin.
OPTS+=" -fplugin=$PLUGIN"

# For debugging purposes, generate a linker map as well.
OPTS+=" -Wl,-Map,fortify-test.map"

# Next, turn off fortification."
OPTS+=" -Wp,-U_FORTIFY_SOURCE"

# And because LTO obscures fortification, turn that off too.
OPTS+=" -fno-lto"

start_test

# Use atexit.c rather than main.c as it is bigger.
COMMAND="$GCC $OPTS $srcdir/atexit.c -o fortify-test.exe"
$COMMAND
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: unable to compile test file"
    echo " $TEST_NAME: command: $COMMAND"
    end_test
    exit 1
fi

# Run annocheck

SKIPS="--skip-all --test-fortify"
A_COMMAND="$ANNOCHECK fortify-test.exe $SKIPS"
$A_COMMAND > fortify-test.out
grep -e "Overall: FAIL" fortify-test.out
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: compiling with -D_FORTIFY_SOURCE=2 still produces an executable that passes annocheck"
    echo " $TEST_NAME: compile command: $COMMAND"
    echo " $TEST_NAME: annocheck command: $A_COMMAND"
    echo " $TEST_NAME: annocheck output (with verbose enabled):"
    $A_COMMAND --verbose
    uuencode fortify-test.exe fortify-test.exe
    uuencode fortify-test.map fortify-test.map
    end_test
    exit 1
fi

end_test
