#!/bin/bash
# CUSTOM_BUILD_HARDENED
# GCC package build script (written by volkerdi@slackware.com)
#
# Copyright 2003, 2004  Slackware Linux, Inc., Concord, California, USA
# Copyright 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026  Patrick J. Volkerding, Sebeka, MN, USA
# Copyright 2026 ANNE Media amos@anne.media
# All rights reserved.
#
# Redistribution and use of this script, with or without modification, is
# permitted provided that the following conditions are met:
#
# 1. Redistributions of this script must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
#
#  THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
#  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
#  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO
#  EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
#  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
#  OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
#  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
#  ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# AM·OS override reduced language set (c,c++,lto), no bootstrap, no multilib,
# full host+target hardening baked in. Managed in /repo/overrides/.

cd $(dirname $0) ; CWD=$(pwd)

PKGNAM=gcc
SRCVER=${VERSION:-$(echo $PKGNAM-*.tar.?z | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
VERSION=$(echo $SRCVER | cut -f 1 -d _)
BUILD=${BUILD:-2}

# Which compilers do we want to build?
LANGS="c,c++,lto"

# How many jobs to run in parallel:
NUMJOBS=${NUMJOBS:-"-j 6"}

# Automatically determine the architecture we're building on:
if [ -z "$ARCH" ]; then
  case "$(uname -m)" in
    i?86) ARCH=i686 ;;
    arm*) readelf /usr/bin/file -A | grep -E -q "Tag_CPU.*[4,5]" && ARCH=arm || ARCH=armv7hl ;;
    *) ARCH=$(uname -m) ;;
  esac
  export ARCH
fi

# No multilib, ever, in this build.
MULTILIB="--disable-multilib"

# If the variable PRINT_PACKAGE_NAME is set, then this script will report what
# the name of the created package would be, and then exit.
if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "gcc-${VERSION}-$ARCH-${BUILD}.txz"
  echo "gcc-g++-${VERSION}-$ARCH-${BUILD}.txz"
  exit 0
fi

if [ "$ARCH" = "i686" ]; then
  SLKCFLAGS="${SLKCFLAGS:--O2 -march=pentium4 -mtune=generic}"
  LIBDIRSUFFIX=""
  LIB_ARCH=i386
elif [ "$ARCH" = "x86_64" ]; then
  SLKCFLAGS="${SLKCFLAGS:--O2 -march=x86-64 -mtune=generic -fPIC}"
  LIBDIRSUFFIX="64"
  LIB_ARCH=amd64
else
  SLKCFLAGS="${SLKCFLAGS:--O2}"
  LIBDIRSUFFIX=""
  LIB_ARCH=$ARCH
fi

case "$ARCH" in
    arm*) TARGET=$ARCH-slackware-linux-gnueabi ;;
    *)    TARGET=$ARCH-slackware-linux ;;
esac

# Temporary build location:
TMP=${TMP:-/tmp}

# Extract the source code:
cd $TMP
rm -rf gcc-$SRCVER
echo "Extracting $CWD/gcc-$SRCVER.tar.?z..."
tar xf $CWD/gcc-$SRCVER.tar.?z || exit 1

# This is the main DESTDIR target:
PKG1=$TMP/package-gcc
# gcc-g++ output:
PKG2=$TMP/package-gcc-g++

# Clear the build locations:
rm -rf $PKG1 $PKG2
mkdir -p $PKG1/usr/doc/gcc-$VERSION $PKG2/usr/doc/gcc-$VERSION

# Insert package descriptions:
mkdir -p $PKG1/install $PKG2/install
cat $CWD/slack-desc.gcc     > $PKG1/install/slack-desc
cat $CWD/slack-desc.gcc-g++ > $PKG2/install/slack-desc

cd gcc-$SRCVER || exit 1

# Apply any required patches:
for patch in $CWD/patches/*.patch $CWD/patches/*.diff ; do
  if [ -r "$patch" ]; then
    cat $patch | patch -p1 --verbose --backup --suffix=.orig || exit 1
  fi
done
for patch in $CWD/patches/*.patch.gz $CWD/patches/*.diff.gz ; do
  if [ -r "$patch" ]; then
    zcat $patch | patch -p1 --verbose --backup --suffix=.orig || exit 1
  fi
done

# ---- Remove hardcoded -fno-stack-protector from libgcc ----
#
# GCC 16 layers -fno-stack-protector on top of every user-controllable
# flag variable in libgcc/Makefile.in. Both LIBGCC2_CFLAGS and
# CRTSTUFF_CFLAGS already expand $(GCC_CFLAGS), which carries
# CFLAGS_FOR_TARGET and therefore -fstack-protector-strong, and the
# -fno- appears later in the expansion and cancels it. That is why
# libgcc_s.so.1 ships without a canary even though every other flag
# we pass (FORTIFY, CET, stack-clash, zero-init) does reach the
# libgcc object files.
#
# Upstream rationale for the flag (avoid a link dependency on the
# standalone libssp library) does not apply on a glibc system, where
# __stack_chk_fail lives in libc.so.6. Removing it lets the hardening
# flags we already pass reach libgcc.
#
# Both occurrences are patched:
#   LIBGCC2_CFLAGS  -> objects that end up in libgcc.a / libgcc_s.so.1
#   CRTSTUFF_CFLAGS -> crtbegin.o / crtend.o / crtbeginS.o / crtendS.o
# The crt files contain no stack buffers, so -fstack-protector-strong
# will not emit a canary in them; removing the -fno- override there is
# a no-op in the output, but keeps the file self-consistent.
if ! grep -q -- '-fbuilding-libgcc -fno-stack-protector ' libgcc/Makefile.in; then
    echo "ERROR: expected -fno-stack-protector pattern not found in libgcc/Makefile.in" >&2
    echo "       upstream layout may have changed; patch needs review" >&2
    exit 1
fi

sed -i 's/-fbuilding-libgcc -fno-stack-protector /-fbuilding-libgcc /g' libgcc/Makefile.in

if grep -q -- '-fbuilding-libgcc -fno-stack-protector' libgcc/Makefile.in; then
    echo "ERROR: failed to remove -fno-stack-protector from libgcc/Makefile.in" >&2
    exit 1
fi

echo ">>> Removed hardcoded -fno-stack-protector from libgcc/Makefile.in"



# Fix perms/owners:
chown -R root:root .
find . \
  \( -perm 777 -o -perm 775 -o -perm 754 \) \
  -exec chmod 755 {} \+ -o \
  \( -perm 664 \) \
  -exec chmod 644 {} \+

# Install docs:
mkdir -p $PKG1/usr/doc/gcc-$VERSION
cp -a \
  COPYING* ChangeLog* FAQ* INSTALL \
  LAST_UPDATED* MAINTAINERS* NEWS* \
  README* SECURITY* *.html \
$PKG1/usr/doc/gcc-$VERSION

if [ -r ChangeLog ]; then
  DOCSDIR=$PKG1/usr/doc/gcc-$VERSION
  cat ChangeLog | head -n 1000 > $DOCSDIR/ChangeLog
  touch -r ChangeLog $DOCSDIR/ChangeLog
fi
if [ -r NEWS ]; then
  DOCSDIR=$PKG1/usr/doc/gcc-$VERSION
  cat NEWS | head -n 1500 > $DOCSDIR/NEWS
  touch -r NEWS $DOCSDIR/NEWS
fi

mkdir -p $PKG1/usr/doc/gcc-${VERSION}/gcc
( cd gcc || exit 0
  cp -a \
    ABOUT* COPYING* DATESTAMP DEV-PHASE LANG* ONEWS README* SERVICE \
  $PKG1/usr/doc/gcc-$VERSION/gcc
  if [ -r ChangeLog ]; then
    cat ChangeLog | head -n 1000 > $PKG1/usr/doc/gcc-$VERSION/gcc/ChangeLog
    touch -r ChangeLog $PKG1/usr/doc/gcc-$VERSION/gcc/ChangeLog
  fi
)

mkdir -p $PKG1/usr/doc/gcc-${VERSION}/libgomp
( cd libgomp || exit 0
  if [ -r ChangeLog ]; then
    cat ChangeLog | head -n 1000 > $PKG1/usr/doc/gcc-$VERSION/libgomp/ChangeLog
    touch -r ChangeLog $PKG1/usr/doc/gcc-$VERSION/libgomp/ChangeLog
  fi
)

mkdir -p $PKG2/usr/doc/gcc-${VERSION}/libstdc++-v3
( cd libstdc++-v3 || exit 0
  cp -a \
    README* \
    doc/html/faq.html \
  $PKG2/usr/doc/gcc-$VERSION/libstdc++-v3
  if [ -r ChangeLog ]; then
    cat ChangeLog | head -n 1000 > $PKG2/usr/doc/gcc-$VERSION/libstdc++-v3/ChangeLog
    touch -r ChangeLog $PKG2/usr/doc/gcc-$VERSION/libstdc++-v3/ChangeLog
  fi
)

# build gcc
( mkdir gcc.build.lnx
  cd gcc.build.lnx

  if [ "$ARCH" = "x86_64" ]; then
    GCC_ARCHOPTS="--with-arch=x86-64"
  else
    GCC_ARCHOPTS="--with-arch=$ARCH"
  fi

  # ---- Hardening flags ---------------------------------------------------
  # Host side: compiler binaries themselves. Maximum set including
  # zero-init and call-used-regs zeroing. These are host tools, they
  # run once during a build and their performance is irrelevant.
  HOST_HARDEN="-fstack-protector-strong -D_FORTIFY_SOURCE=3 -fstack-clash-protection -fcf-protection=full -ftrivial-auto-var-init=zero -fzero-call-used-regs=all"

  # >>> CHANGED: Target side now also carries the full set.  Previously
  # >>> -ftrivial-auto-var-init and -fzero-call-used-regs were omitted
  # >>> from target libraries.  They are included here for maximum
  # >>> hardening.  If libgomp/libatomic/libitm fail to build, remove
  # >>> -fzero-call-used-regs=all from TARGET_HARDEN only. The other
  # >>> flags are safe for all target runtimes.
  TARGET_HARDEN="-fstack-protector-strong -D_FORTIFY_SOURCE=3 -fstack-clash-protection -fcf-protection=full -ftrivial-auto-var-init=zero -fzero-call-used-regs=all"

  # >>> ADDED: Linker-side hardening, applied to BOTH host and target.
  # >>> -Wl,-z,now        -> Full RELRO (BIND_NOW)
  # >>> -Wl,-z,relro      -> RELRO segment
  # >>> -Wl,-z,noexecstack -> NX stack
  # >>> -Wl,-z,separate-code -> Separate code/data segments
  # >>> -Wl,-z,ibt        -> IBT property note (needs -fcf-protection=full)
  # >>> -Wl,-z,shstk      -> SHSTK property note
  LDFLAGS_HARDEN="-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,separate-code -Wl,-z,ibt -Wl,-z,shstk"

  CFLAGS="$SLKCFLAGS $HOST_HARDEN" \
  CXXFLAGS="$SLKCFLAGS $HOST_HARDEN" \
  CFLAGS_FOR_TARGET="-O2 -march=x86-64 -mtune=generic $TARGET_HARDEN" \
  CXXFLAGS_FOR_TARGET="-O2 -march=x86-64 -mtune=generic $TARGET_HARDEN" \
  LDFLAGS="$LDFLAGS_HARDEN" \
  LDFLAGS_FOR_TARGET="$LDFLAGS_HARDEN" \
  ../configure --prefix=/usr \
     --libdir=/usr/lib$LIBDIRSUFFIX \
     --mandir=/usr/man \
     --infodir=/usr/info \
     --enable-shared \
     --disable-bootstrap \
     --enable-cet \
     --enable-cet-property \
     --enable-host-pie \
     --enable-host-bind-now \
     --enable-default-pie \
     --enable-default-ssp \
     --enable-linker-build-id \
     --with-linker-hash-style=gnu \
     --enable-languages=${LANGS} \
     --enable-threads=posix \
     --enable-checking=release \
     --with-system-zlib \
     --enable-libstdcxx-dual-abi \
     --with-default-libstdcxx-abi=new \
     --disable-libstdcxx-pch \
     --disable-libunwind-exceptions \
     --enable-__cxa_atexit \
     --disable-libssp \
     --enable-gnu-indirect-function \
     --enable-gnu-unique-object \
     --enable-plugin \
     --enable-lto \
     --disable-install-libiberty \
     --disable-werror \
     --with-gnu-ld \
     --with-isl \
     --verbose \
     --with-arch-directory=$LIB_ARCH \
     --disable-gtktest \
     --enable-clocale=gnu \
     $GCC_ARCHOPTS \
     $MULTILIB \
     --target=${TARGET} \
     --build=${TARGET} \
     --host=${TARGET} || exit 1

  # Single-stage build (no bootstrap).
  make $NUMJOBS all || exit 1
  make info || exit 1

  if [ ! -z $GCCCHECK ]; then
    make $NUMJOBS check || exit 1
  fi

  make install DESTDIR=$PKG1 || exit 1

  # Move gdb pretty printers to the correct place:
  mkdir -p $PKG1/usr/share/gdb/auto-load/usr/lib$LIBDIRSUFFIX
  mv $PKG1/usr/lib$LIBDIRSUFFIX/*-gdb.py \
    $PKG1/usr/share/gdb/auto-load/usr/lib$LIBDIRSUFFIX/

  # x86_64 + --disable-multilib: look for 32-bit gcc binaries in ./32.
  if [ "$ARCH" = "x86_64" -a "$MULTILIB" = "--disable-multilib" ]; then
    sed -i 's#;.\(:../lib !m64 m32;\)$#;32\1#' \
      $PKG1/usr/lib${LIBDIRSUFFIX}/gcc/${TARGET}/${VERSION}/specs
  fi

  make -i install-info DESTDIR=$PKG1 || exit 1

  chmod 755 $PKG1/usr/lib${LIBDIRSUFFIX}/libgcc_s.so.1

  ( cd $PKG1/usr/info ; rm dir ; gzip -9 * )
  ( cd $PKG1
    mkdir -p lib
    cd lib
    ln -sf /usr/bin/cpp .
  )

  ( cd $PKG1/usr/bin
    mv g++ g++-gcc-$VERSION
    mv gcc gcc-$VERSION
    ln -sf g++-gcc-$VERSION g++
    ln -sf gcc-$VERSION gcc
    ln -sf g++ c++
    ln -sf gcc cc
    ln -sf gcc-$VERSION ${TARGET}-cc
    ln -sf gcc-$VERSION ${TARGET}-gcc
    ln -sf gcc-$VERSION ${TARGET}-gcc-$VERSION
    ln -sf gcc-ar ${TARGET}-gcc-ar
    ln -sf gcc-nm ${TARGET}-gcc-nm
    ln -sf gcc-ranlib ${TARGET}-gcc-ranlib
    ln -sf g++-gcc-$VERSION ${TARGET}-c++
    ln -sf g++-gcc-$VERSION ${TARGET}-g++
    cat $CWD/c89.sh > c89
    cat $CWD/c99.sh > c99
    chmod 755 c89 c99
  )

  ( cd $PKG1/usr/man
    gzip -9 */*
    cd man1
    ln -sf g++.1.gz c++.1.gz
    ln -sf gcc.1.gz cc.1.gz
  )

) 2>&1 | tee gcc.build.log

# Don't ship any .la files:
find $PKG1 -name "*.la" -exec rm -f "{}" \;

# Strip bloated binaries and libraries:
( cd $PKG1
  find . -name "lib*so*" -exec strip --strip-unneeded "{}" \;
  find . -name "lib*so*" -exec patchelf --remove-rpath "{}" \;
  find . -name "lib*a" -exec strip -g "{}" \;
  strip --strip-unneeded usr/bin/* 2> /dev/null
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip --strip-unneeded 2> /dev/null
)

# ---- gcc-g++ split ---------------------------------------------------------
( cd $PKG2
  mkdir -p usr/bin
  mv $PKG1/usr/bin/*++* usr/bin
  mkdir -p usr/include
  mv $PKG1/usr/include/c++ usr/include
  mkdir -p usr/libexec/gcc/$TARGET/$VERSION
  mv $PKG1/usr/libexec/gcc/$TARGET/$VERSION/cc1plus usr/libexec/gcc/$TARGET/$VERSION/cc1plus
  mkdir -p usr/man/man1
  mv $PKG1/usr/man/man1/*++* usr/man/man1
  mkdir -p usr/share
  mv $PKG1/usr/share/gdb usr/share
  mkdir -p usr/share/gcc-$VERSION/python
  mv $PKG1/usr/share/gcc-$VERSION/python/libstdcxx usr/share/gcc-$VERSION/python
  # Libraries:
  mkdir -p usr/lib${LIBDIRSUFFIX}
  mv $PKG1/usr/lib${LIBDIRSUFFIX}/*++* usr/lib${LIBDIRSUFFIX}
)

# ---- Generate packages -----------------------------------------------------
( cd $PKG1
  /sbin/makepkg -l y -c n $TMP/gcc-${VERSION}-$ARCH-${BUILD}.txz )
( cd $PKG2
  /sbin/makepkg -l y -c n $TMP/gcc-g++-${VERSION}-$ARCH-${BUILD}.txz )

echo
echo "AM·OS GCC package build complete!"
echo
