#!/bin/bash

# Copyright (c) 2017-2020 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.

TEST_NAME=hardening
. $srcdir/common.sh

PLUGIN_OPTS="-fplugin-arg-annobin-no-attach"
OPTS="-c -O2 -D_FORTIFY_SOURCE=2 -fpie -Wall -fstack-protector-strong -D_GLIBCXX_ASSERTIONS -fstack-clash-protection"
EXTRA_OPTS="-fcf-protection -mstackrealign"

start_test

$GCC -fplugin=$PLUGIN $PLUGIN_OPTS -g $OPTS $EXTRA_OPTS hello_hard.o $srcdir/hello_hard.c
if [ $? != 0 ];
then
    echo "Compiler might not support -fcf-protection, retrying without it"
    EXTRA_OPTS="-mstackrealign"
    $GCC -fplugin=$PLUGIN $PLUGIN_OPTS -g $OPTS $EXTRA_OPTS -$srcdir/hello_hard.c
    if [ $? != 0 ];
    then
    echo "Compiler might not support -mstackrealign, retrying without it"
    EXTRA_OPTS="-fcf-protection"
    $GCC -fplugin=$PLUGIN $PLUGIN_OPTS -g $OPTS $EXTRA_OPTS $srcdir/hello_hard.c
    if [ $? != 0 ];
    then
        echo "Compiler might not support either -fcf-protection or -mstackrealign, retrying without both"
        EXTRA_OPTS=""
        $GCC -fplugin=$PLUGIN $PLUGIN_OPTS -g $OPTS $EXTRA_OPTS $srcdir/hello_hard.c
        if [ $? != 0 ];
        then
      echo "Failed :-("
      exit 1
        fi
    fi
    fi
fi

$GCC -fplugin=$PLUGIN $PLUGIN_OPTS -O3 $OPTS $EXTRA_OPTS $srcdir/hello2.c

$GCC -fplugin=$PLUGIN $PLUGIN_OPTS -g3 $OPTS $EXTRA_OPTS $srcdir/hello3.c

$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS $EXTRA_OPTS -shared $srcdir/hello_lib.c -o libhello.so

# Link without system files as these may not have been hardened.
$GCC -fplugin=$PLUGIN $PLUGIN_OPTS \
     -nostartfiles -nostdlib \
     -Wl,-e,0x0 \
     -Wl,--defsym=__stack_chk_fail=0 \
     -Wl,--defsym=__stack_chk_fail_local=0 \
     -Wl,--defsym=__stack_chk_guard=0 \
     -Wl,--defsym=__printf_chk=0 \
     -L . -pie \
     -Wl,-z,now,-z,relro \
 hello_hard.o hello2.o hello3.o -lhello -o hardening-test.exe

# $OBJCOPY --merge-notes hardening-test.exe hardening-test-merged.exe

# The s390 and PPC targets always create some gaps.  Have not found out why...
# The entry point test (on x86/x86_64) will fail with a MAYBE result because the entry point is 0...

$ANNOCHECK -v --ignore-gaps --skip-entry hardening-test.exe --enable-timing

end_test
