#!/bin/bash

# Copyright (c) 2017-2026 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 -fplugin-arg-annobin-note-format=note"
OPTS="-g -c -O2 -fPIE -D_GLIBCXX_ASSERTIONS -fstack-clash-protection"

start_test

EXE=objcopy-test.exe
$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 $EXE > $G_OUT 2>&1
if [ $? != 0 ];
then
    echo " $TEST_NAME: SKIP: could not compile test executable"
    cat $G_OUT
    end_test
    exit $EXIT_TEST_SKIPPED
fi

# Run objcopy to merge the notes

MERGED_EXE=objcopy-merged.exe
$OBJCOPY --merge-notes $EXE $MERGED_EXE
if [ $? != 0 ];
then
    $OBJCOPY $EXE $MERGED_EXE > $G_OUT 2>&1
    if [ $? != 0 ];
    then
	echo " $TEST_NAME: FAIL: could not copy test executable"
	cat $G_OUT
	end_test
	exit $EXIT_TEST_FAILED
    fi
    echo " $TEST_NAME: SKIP: objcopy does not support --merge-notes"
    end_test
    exit $EXIT_TEST_SKIPPED
fi

# Run annocheck, but only enable the optimization test.
$ANNOCHECK -v --ignore-gaps --skip-all --test-optimization $MERGED_EXE --suppress-version-warnings > $A_OUT
grep -q -e"PASS: optimization test" $A_OUT
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: did not confirm sufficient optimization"
    cat $A_OUT
    end_test
    exit $EXIT_TEST_FAILED
fi

echo " $TEST_NAME: PASS: annocheck was able to correctly detect a problem even though the binary had been copied and the notes merged"

end_test
