#!/bin/bash

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

rm -f hello.o hello2.o function-sections-test.exe unused_code.o unused_code.i unused_code.s fred.map

GCC=gcc
READELF=readelf
PLUGIN=../plugin/.libs/annobin.so

OPTS="-c -O2 -D_FORTIFY_SOURCE=2 -fPIE -fstack-protector-strong -D_GLIBCXX_ASSERTIONS -fstack-clash-protection"
EXTRA_OPTS="-fcf-protection -mstackrealign"

$GCC -fplugin=$PLUGIN -g $OPTS $EXTRA_OPTS  $srcdir/hello_hard.c 
if [ $? != 0 ];
then
    echo "Compiler might not support -fcf-protection, retrying without it"
    EXTRA_OPTS="-mstackrealign"
    $GCC -fplugin=$PLUGIN -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 -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 -g $OPTS $EXTRA_OPTS $srcdir/hello_hard.c 
	    if [ $? != 0 ];
	    then
		echo "Failed :-("
		exit 1
	    fi
	fi
    fi
fi


$GCC -fplugin=$PLUGIN $OPTS $EXTRA_OPTS -ffunction-sections $srcdir/unused_code.c \

$GCC -fplugin=$PLUGIN $OPTS $EXTRA_OPTS $srcdir/hello.c 

$GCC -fplugin=$PLUGIN $OPTS $EXTRA_OPTS -ffunction-sections $srcdir/hello2.c 

$GCC -pie \
     -Wl,-z,now,-z,relro \
     -Wl,--gc-sections -Wl,--print-gc-sections \
     -Wl,-Map,fred.map \
     -Wl,--orphan-handling=warn \
 hello.o unused_code.o hello2.o -o function-sections-test.exe

# Note - currently unused_func_1 and unused_func_2 will not be
# garbage collected.  The duplicate of the linkonce_func_1
# function however will be discarded.  This is because the linker
# sees the relocations in the gnu build notes section against
# the unused functions, and since they are not in a section
# group together, it presumes that the relocations must be
# satisified.
#
# To solve this problem the annobin plugin will have to create
# a section group containing both the code and the notes.  In
# fact strictly speaking GCC should be doing this, and annobin
# should just be adding the notes to the section group.


# FIXME - we should check that the notes were parsed correctly...
# FIXME - we should check for gaps.
../annocheck/annocheck --ignore-gaps function-sections-test.exe
