#!/bin/bash

# Copyright (c) 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 that annocheck detects the use of -fexceptions via --test-threads

TEST_NAME=threads
. $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 -g"

start_test

# Part 1: Compile WITH -fexceptions

COMMAND="$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS -fexceptions $srcdir/hello2.c"
$COMMAND > $G_OUT 2>&1
if [ $? != 0 ];
then
    echo " $TEST_NAME: SKIP: unable to compile test file with -fexceptions"
    echo " $TEST_NAME: command: $COMMAND"
    cat $G_OUT
    end_test
    exit $EXIT_TEST_SKIPPED
fi

SKIPS="--skip-all --test-threads --suppress-version-warnings"
A_COMMAND="$ANNOCHECK hello2.o --verbose $SKIPS"

$A_COMMAND > $A_OUT
grep -q -e"PASS: threads test" $A_OUT
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: annocheck did not PASS for object compiled with -fexceptions"
    echo " $TEST_NAME: compile command: $COMMAND"
    echo " $TEST_NAME: annocheck command: $A_COMMAND"
    echo " $TEST_NAME: annocheck output:"
    cat $A_OUT
    end_test
    exit $EXIT_TEST_FAILED
fi

echo " $TEST_NAME: PASS: annocheck PASSed an object compiled with -fexceptions"

#-------------------------------------------------------------------

# Part 2: Compile WITHOUT -fexceptions
COMMAND="$GCC -fplugin=$PLUGIN $PLUGIN_OPTS $OPTS -fno-exceptions $srcdir/hello2.c"
$COMMAND > $G_OUT 2>&1
if [ $? != 0 ];
then
    echo " $TEST_NAME: SKIP: unable to compile test file with -fno-exceptions"
    echo " $TEST_NAME: command: $COMMAND"
    cat $G_OUT
    end_test
    exit $EXIT_TEST_SKIPPED
fi

$A_COMMAND > $A_OUT
grep -q -e"FAIL: threads test" $A_OUT
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: annocheck did not FAIL for object compiled without -fexceptions"
    echo " $TEST_NAME: compile command: $COMMAND"
    echo " $TEST_NAME: annocheck command: $A_COMMAND"
    echo " $TEST_NAME: annocheck output:"
    cat $A_OUT
    end_test
    exit $EXIT_TEST_FAILED
fi

echo " $TEST_NAME: PASS: annocheck FAILed an object compiled without -fexceptions"

end_test
