#!/bin/bash
# CUSTOM_BUILD_HARDENED
# AM·OS hardened glibc build – pure 64-bit, maximum hardening.
# Managed in /repo/overrides/.
# CUSTOM_BUILD_NUMJOBS_PATCHED
# Copyright 2006, 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 pure 64-bit, configure-time hardening (CET, SSP strong,
# FORTIFY=3, bind-now) baked in. Managed in /repo/overrides/.
# nscd disabled: redundant on systemd-resolved / SSSD systems, removes a
# root-owned local-socket daemon from the attack surface.


export LDFLAGS="${LDFLAGS:-} -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack \
  -Wl,-z,separate-code -Wl,-z,ibt -Wl,-z,shstk -Wl,--as-needed -Wl,-O1"

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

PKGNAM=glibc
VERSION=${VERSION:-$(echo glibc-*.tar.xz | rev | cut -f 3- -d . | cut -f 1 -d - | rev)}
CHECKOUT=${CHECKOUT:-""}
BUILD=${BUILD:-7}

if [ -z "$ARCH" ]; then
  case "$( uname -m )" in
    i?86) export ARCH=i686 ;;
    arm*) export ARCH=arm ;;
       *) export ARCH=$( uname -m ) ;;
  esac
fi

if [ ! -z "${PRINT_PACKAGE_NAME}" ]; then
  echo "glibc-${VERSION}-$ARCH-${BUILD}.txz"
  echo "glibc-i18n-${VERSION}-$ARCH-${BUILD}.txz"
  echo "glibc-profile-${VERSION}-$ARCH-${BUILD}.txz"
  echo "aaa_glibc-solibs-${VERSION}-$ARCH-${BUILD}.txz"
  exit 0
fi

NUMJOBS=${NUMJOBS:-"-j 6"}

# Build flags – maximum hardening without breaking glibc internals.
# -fstack-clash-protection: protects against stack clash attacks.
# -fno-common: modern default, explicit for clarity.
# -fPIC: needed for shared libraries.
X86FLAGS32="${X86FLAGS32:--O3 -march=pentium4 -mtune=generic -mstackrealign -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer -fstack-clash-protection -fno-common}"
X86FLAGS64="${X86FLAGS64:--O3 -march=x86-64 -mtune=generic -fPIC -fstack-clash-protection -fno-common}"

case $ARCH  in
  i686)
    OPTIMIZ="${X86FLAGS32}"
    LIBDIRSUFFIX=""
    TARGET=${TARGET:-i686}
    ;;
  x86_64)
    OPTIMIZ="${X86FLAGS64}"
    LIBDIRSUFFIX="64"
    TARGET=${TARGET:-x86_64}
    TARGET32=${TARGET32:-i686}
    ;;
  *)
    OPTIMIZ="${OPTIMIZ:--O3 -fstack-clash-protection -fno-common}"
    LIBDIRSUFFIX=""
    TARGET=${TARGET:-"$ARCH"}
    ;;
esac

SLACKWARE_ARCH=$ARCH
unset ARCH

CVSVER=${VERSION}${CHECKOUT}

TMP=${TMP:-/tmp}
mkdir -p $TMP

apply_patches() {
  zcat $CWD/glibc.locale.no-archive.diff.gz | patch -p1 --verbose || exit 1
  zcat $CWD/glibc.ru_RU.CP1251.diff.gz | patch -p1 --verbose || exit 1
  zcat $CWD/glibc-2.32.en_US.no.am.pm.date.format.diff.gz | patch -p1 --verbose || exit 1
  for git_patch in $CWD/patches/*.patch.gz ; do
    zcat $git_patch | patch -p1 --verbose || exit 1
  done
}

export PKG=$TMP/package-glibc-incoming-tree
PGLIBC=$TMP/package-glibc
PSOLIBS=$TMP/package-aaa_glibc-solibs
PI18N=$TMP/package-glibc-i18n
PPROFILE=$TMP/package-glibc-profile
PDEBUG=$TMP/package-glibc-debug

for dir in $PKG $PGLIBC $PSOLIBS $PI18N $PPROFILE $PDEBUG ; do
  if [ -d $dir ]; then
    rm -rf $dir
  fi
  mkdir -p $dir
done
if [ -d $TMP/glibc-$VERSION ]; then
  rm -rf $TMP/glibc-$VERSION
fi

mkdir -p $PKG/lib${LIBDIRSUFFIX}
mkdir -p $PKG/sbin
mkdir -p $PKG/usr/bin
mkdir -p $PKG/usr/lib${LIBDIRSUFFIX}
mkdir -p $PKG/usr/sbin
mkdir -p $PKG/usr/include
mkdir -p $PKG/usr/doc
mkdir -p $PKG/usr/man
mkdir -p $PKG/usr/share

cd $TMP
rm -rf glibc-$CVSVER
echo "Extracting $CWD/glibc-$CVSVER.tar.?z..."
tar xf $CWD/glibc-$CVSVER.tar.xz \
  || tar xf $CWD/glibc-$CVSVER.tar.lz \
  || tar xf $CWD/glibc-$CVSVER.tar.gz
cd glibc-$CVSVER

apply_patches
if [ ! $? = 0 ]; then
  exit 1
fi

find . -type d -name CVS -exec rm -r {} \+ 2> /dev/null

# ----------------------------------------------------------------------
# Force -fstack-protector-all on the libmvec sincos wrappers.
#
# These functions pass the address of a scalar spill slot to libc's
# sincos(). -fstack-protector-strong does not instrument them because
# the address-taken local is a scalar, not an array. The write is
# bounded by sincos's contract, but the audit correctly flags the
# absence of a canary on a frame-address-escaping function. Force the
# canary on per-file rather than weaken the audit.
#
# glibc's build system consults CFLAGS-$(<F) (Makeconfig:1126), so a
# per-file CFLAGS-<basename> variable is picked up for both the plain
# and the multiarch-variant objects.
# ----------------------------------------------------------------------
echo ">>> sincos patch running in: $(pwd)"

SINCOS_MARKER="# AM·OS: force SSP-all on sincos wrappers"
SINCOS_MK="sysdeps/x86_64/fpu/multiarch/Makefile"

[ -f "$SINCOS_MK" ] || {
    echo "ERROR: $SINCOS_MK not found; glibc layout may have changed" >&2
    exit 1
}

SINCOS_FILES=$(find sysdeps/x86_64/fpu -name 'svml_*sincos*.c' -printf '%f\n' | sort -u)
SINCOS_COUNT=$(printf '%s\n' "$SINCOS_FILES" | grep -c .)

[ "$SINCOS_COUNT" -ge 6 ] || {
    echo "ERROR: expected >=6 sincos sources, found $SINCOS_COUNT" >&2
    echo "$SINCOS_FILES" >&2
    exit 1
}

if ! grep -qF "$SINCOS_MARKER" "$SINCOS_MK"; then
    {
        echo ""
        echo "$SINCOS_MARKER"
        printf '%s\n' "$SINCOS_FILES" | while read -r f; do
            [ -n "$f" ] && echo "CFLAGS-$f += -fstack-protector-all"
        done
    } >> "$SINCOS_MK"
    echo ">>> Forced -fstack-protector-all on $SINCOS_COUNT sincos source(s)"
    printf '%s\n' "$SINCOS_FILES" | sed 's/^/      /'
else
    echo ">>> sincos SSP patch already present; skipping"
fi

grep -qF "$SINCOS_MARKER" "$SINCOS_MK" || {
    echo "ERROR: sincos SSP patch did not land" >&2
    exit 1
}

chown -R root:root .
find . \
  \( -perm 777 -o -perm 775 -o -perm 711 -o -perm 555 -o -perm 511 \) \
  -exec chmod 755 {} \+ -o \
  \( -perm 666 -o -perm 664 -o -perm 600 -o -perm 444 -o -perm 440 -o -perm 400 \) \
  -exec chmod 644 {} \+

build_glibc() {
  # >>> CHANGED: -fstack-protector-strong and -fcf-protection=full are
  # >>> added to CFLAGS/CXXFLAGS directly. The --enable-stack-protector
  # >>> and --enable-cet configure options only apply to objects inside
  # >>> libc.so.6; the standalone utilities (getconf, XBS5_*, POSIX_V*)
  # >>> and libmvec are built by their own subdir Makefiles from the
  # >>> plain $(CFLAGS) and never saw the flag. Passing it here closes
  # >>> that gap.
  CFLAGS="-g $OPTIMIZ -fstack-protector-strong -fcf-protection=full" \
  CXXFLAGS="-g $OPTIMIZ -fstack-protector-strong -fcf-protection=full" \
  ../configure \
    --prefix=/usr \
    --libdir=/usr/lib${LIBDIRSUFFIX} \
    --enable-kernel=7.2.5 \
    --enable-cet \
    --disable-nscd \
    --enable-stack-protector=strong \
    --enable-fortify-source=3 \
    --enable-bind-now \
    --disable-werror \
    --enable-multi-arch \
    --with-headers=/usr/include \
    --enable-profile \
    --infodir=/usr/info \
    --mandir=/usr/man \
    --with-__thread \
    --without-cvs \
    $TARGET-slackware-linux || exit 1
  make $NUMJOBS || exit 1
  make $NUMJOBS install install_root=$PKG || exit 1
  make $NUMJOBS localedata/install-locales install_root=$PKG DESTDIR=$PKG || exit 1
}

mkdir build-glibc-$VERSION
cd build-glibc-$VERSION
echo "BUILDING DAS NPTL GLIBC"
build_glibc || exit 1

pushd $CWD
ARCH=$SLACKWARE_ARCH LIBDIRSUFFIX=$LIBDIRSUFFIX \
  SLKCFLAGS="$OPTIMIZ -D_FORTIFY_SOURCE=3" \
  ./libxcrypt.build || exit 1
popd

mkdir -p $PKG/bin
( cd $PKG/bin ; ln -sf /sbin/sln sln )

mkdir -p $PKG/usr/lib${LIBDIRSUFFIX}/debug
cp -a $PKG/lib${LIBDIRSUFFIX}/l*.so* $PKG/usr/lib${LIBDIRSUFFIX}/debug
cp -a $PKG/usr/lib${LIBDIRSUFFIX}/*.a $PKG/usr/lib${LIBDIRSUFFIX}/debug
( cd $PKG/usr/lib${LIBDIRSUFFIX}/debug ; rm -f *_p.* )

strip -g $PKG/usr/lib${LIBDIRSUFFIX}/lib*.a

rm -f $PKG/usr/include/rpcsvc/rquota.{h,x}

cd $TMP/glibc-$CVSVER

( mkdir -p $PKG/usr/doc/glibc-$VERSION
  cp -a \
    CONTRIBUTED-BY* COPYING* INSTALL* LICENSES* MAINTAINERS* NEWS* README* SECURITY* SHARED-FILES* \
    $PKG/usr/doc/glibc-$VERSION
)

if [ -r NEWS ]; then
  DOCSDIR=$(echo $PKG/usr/doc/glibc-$VERSION)
  cat NEWS | head -n 1000 > $DOCSDIR/NEWS
  touch -r NEWS $DOCSDIR/NEWS
fi

( cd $PKG
  find . | xargs file | grep "executable" | grep ELF | cut -f 1 -d : | xargs strip --strip-debug 2> /dev/null
  find . | xargs file | grep "shared object" | grep ELF | cut -f 1 -d : | xargs strip -g 2> /dev/null
)

find $PKG/usr/man -type f -exec gzip -9 {} \+
for i in $( find $PKG/usr/man -type l ) ; do
  ln -s $( readlink $i ).gz $i.gz
  rm $i
done

if [ -d $PKG/usr/info ]; then
  ( cd $PKG/usr/info
    rm -f dir
    gzip -9 *
  )
fi

rm -f $PKG/etc/ld.so.cache

( cd $PKG
  find . -name "*.orig" -exec rm {} \+
)

( cd $PKG/lib${LIBDIRSUFFIX}
  mkdir incoming
  mv *so* incoming
  cd incoming
  mv libcrypt* libmemusage.so libpcprofile.so ..
) || exit 1

######################
# Build the packages #
######################

# glibc-profile:
cd $PPROFILE
mkdir -p usr/lib${LIBDIRSUFFIX}
mv $PKG/usr/lib${LIBDIRSUFFIX}/lib*_p.a usr/lib${LIBDIRSUFFIX}
( cd usr/lib${LIBDIRSUFFIX} ; strip -g *.a )
mkdir install
cp -a $CWD/slack-desc.glibc-profile install/slack-desc
/sbin/makepkg -l y -c n $TMP/glibc-profile-${VERSION}-$SLACKWARE_ARCH-${BUILD}.txz

# glibc-debug (not shipped):
cd $PDEBUG
mkdir -p usr/lib${LIBDIRSUFFIX}
mv $PKG/usr/lib${LIBDIRSUFFIX}/debug usr/lib${LIBDIRSUFFIX}
mkdir install
cp -a $CWD/slack-desc.glibc-debug install/slack-desc

# glibc-i18n:
cd $PI18N
mkdir -p usr/share/{i18n,locale}
mv $PKG/usr/share/i18n/* usr/share/i18n
mv $PKG/usr/share/locale/* usr/share/locale
mkdir -p usr/lib${LIBDIRSUFFIX}/locale
mv $PKG/usr/lib${LIBDIRSUFFIX}/locale/* usr/lib${LIBDIRSUFFIX}/locale
cp -a usr/lib${LIBDIRSUFFIX}/locale/{C,en_US}* $PKG/usr/lib${LIBDIRSUFFIX}/locale
mkdir -p $PKG/usr/share/i18n/locales
cp -a usr/share/i18n/locales/{C,POSIX,en_US} $PKG/usr/share/i18n/locales
mkdir install
cp -a $CWD/slack-desc.glibc-i18n install/slack-desc
/sbin/makepkg -l y -c n $TMP/glibc-i18n-${VERSION}-$SLACKWARE_ARCH-${BUILD}.txz

# aaa_glibc-solibs:
cd $PSOLIBS
mkdir -p lib${LIBDIRSUFFIX}
cp -a $PKG/lib${LIBDIRSUFFIX}/* lib${LIBDIRSUFFIX}
mkdir -p usr
cp -a $PKG/usr/bin usr
mv usr/bin/ldd .
rm usr/bin/*
mv ldd usr/bin
mkdir -p usr/lib${LIBDIRSUFFIX}
cp -a $PKG/usr/lib${LIBDIRSUFFIX}/gconv usr/lib${LIBDIRSUFFIX}
mkdir -p usr/libexec
cp -a $PKG/usr/libexec/pt_chown usr/libexec
cp -a $PKG/sbin .
mv sbin/ldconfig .
rm sbin/*
mv ldconfig sbin
mkdir install
cp -a $CWD/slack-desc.aaa_glibc-solibs install/slack-desc
cat $CWD/doinst.sh-glibc $CWD/doinst.sh-deadcode | sed "s/@@LIBDIRSUFFIX@@/${LIBDIRSUFFIX}/g" > install/doinst.sh
/sbin/makepkg -l y -c n $TMP/aaa_glibc-solibs-${VERSION}-$SLACKWARE_ARCH-${BUILD}.txz

# glibc (all-in-one, from leftover):
cd $PGLIBC
mv $PKG/* .
mkdir install
cp -a $CWD/slack-desc.glibc install/slack-desc
cat $CWD/doinst.sh-glibc $CWD/doinst.sh-deadcode | sed "s/@@LIBDIRSUFFIX@@/${LIBDIRSUFFIX}/g" > install/doinst.sh
/sbin/makepkg -l y -c n $TMP/glibc-${VERSION}-$SLACKWARE_ARCH-${BUILD}.txz

echo
echo "glibc packages built in $TMP!"
