#!/bin/bash

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

# Mimics how glibc builds C sources without annotation.

TEST_NAME=atexit
. $srcdir/common.sh

# Use the same command line options that normal spec file will use,
# *except* that we disable the use of the annobin plugin, since GLIBC
# is built without the plugin.

OPTS="$(rpm --eval '%undefine _annotated_build %build_cflags %build_ldflags')"

# The rpm macros may not be available, so if necessary use our own

if ! [[ $OPTS == *"redhat-hardened-cc1"* ]];
then
    echo " $TEST_NAME: using built-in option selection"
    OPTS="-fno-lto -O2 -g -Wl,-z,now -pie -fPIE -Wall"
fi

# Make sure that we use the magic option to generate an assembler note.
OPTS+=" -Wa,--generate-missing-build-notes=yes"

# For debugging purposes we also generate a linker map.
OPTS+=" -Wl,-Map,atexit.map"

start_test

$GCC $OPTS $srcdir/atexit.c -o $EXE

if [ $? != 0 ];
then
    OPTS="-flto -O2 -g -Wl,-z,now -pie -fPIE"
    $GCC $OPTS $srcdir/atexit.c -o $EXE >$G_OUT 2>&1
    if [ $? != 0 ];
    then
	# FIXME: Should this be a FAIL ?
	echo " $TEST_NAME: SKIP: Could not compile source files"
	cat $G_OUT
	end_test
	exit $EXIT_TEST_SKIPPED
    fi
    echo " $TEST_NAME: SKIP: Assembler does not support --generate-missing-build-notes, skipping test"
    end_test
    exit $EXIT_TEST_SKIPPED
fi

# Strip the executable.  Just for fun.  Or rather in order to test how glibc treats its binaries.
STRIP_EXE=atexit.strip
$STRIP -g -o $STRIP_EXE $EXE

# Run annocheck - do not skip the LTO test

SKIPS="--skip-cf-protection --skip-property-note --skip-stack-realign --skip-entry --skip-dynamic-tags --skip-not-dynamic-tags --skip-branch-protection --skip-not-branch-protection --suppress-version-warnings --skip-fortify --skip-warnings"

COMMAND="$ANNOCHECK $STRIP_EXE $SKIPS --ignore-gaps"
$COMMAND > $A_OUT
grep -q -e"PASS" $A_OUT
if [ $? != 0 ];
then
    echo " $TEST_NAME: FAIL: generating assembler notes did not hide lack of GCC notes"
    echo " $TEST_NAME: annocheck command: $COMMAND"
    cat $A_OUT
    uuencode $STRIP_EXE $STRIP_EXE
    end_test
    exit $EXIT_TEST_FAILED
fi

echo " $TEST_NAME: PASS: generating assembler notes hid a lack of GCC notes"

end_test
