#!/bin/bash

# Copyright (c) 2017-2021 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=objcopy
. $srcdir/common.sh

PLUGIN_OPTS="-fplugin-arg-annobin-no-attach"
OPTS="-g -c -O2 -fpie"

start_test

$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS $srcdir/hello.c
$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS $srcdir/hello2.c
$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS $srcdir/hello3.c
$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $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 \
    -flto \
    -pie \
  hello.o hello2.o hello3.o -L. -lhello -o objcopy-test.exe

# Run objcopy to merge the notes

$OBJCOPY --merge-notes objcopy-test.exe objcopy-merged.exe
if [ $? != 0 ];
then
    $OBJCOPY objcopy-test.exe objcopy-merged.exe
    if [ $? != 0 ];
    then
	echo "objcopy-test: FAIL: could not copy test executable"
	exit 1
    fi
    echo "objcopy-test: objcopy does not support --merge-notes, skipping test"
    end_test
    exit 0
fi


# Run annocheck, but only enable the LTO test.

$ANNOCHECK -v --ignore-gaps --skip-all --test-optimization objcopy-merged.exe > objcopy-test.out
grep -e "PASS: optimization test" objcopy-test.out
if [ $? != 0 ];
then
    echo "objcopy-test: FAIL: did not confirm sufficient optimization"
    cat objcopy-test.out
    exit 1
fi

end_test
