#!/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.

rm -f hello.o hello2.o hello3.o libhello.so objcopy-test.exe objcopy-merged.exe

GCC=${GCC:-gcc}
OBJCOPY=${OBJCOPY:-objcopy}
ANNOCHECK=${ANNOCHECK:-../annocheck/annocheck}
PLUGIN=${PLUGIN:-../gcc-plugin/.libs/annobin.so}

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

$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

# Run annocheck, but only enable the LTO test.

$ANNOCHECK -v --ignore-gaps --skip-all --test-optimization objcopy-merged.exe | grep -e "PASS: Compiled with sufficient optimization"
