From bd8258a389bf6337b0440cd06006e2e6e7fe097b Mon Sep 17 00:00:00 2001
From: Ryan Burns <rtburns@protonmail.com>
Date: Tue, 24 Aug 2021 00:21:04 -0700
Subject: [PATCH] cc-wrapper: ensure PIE flags precede PIC flags

fixes:
pkgsMusl.bulletml
pkgsMusl.proot
pkgsMusl.python3

Debian explains this issue well in the dpkg-buildflags manpage:

-fPIE
    Can be linked into any program, but not a shared library (recommended).
-fPIC
    Can be linked into any program and shared library.

On projects that build both programs and shared libraries you might need to
make sure that when building the shared libraries -fPIC is always passed last
(so that it overrides any previous -PIE) to compilation flags such as CFLAGS.

(from https://manpages.debian.org/bullseye/dpkg-dev/dpkg-buildflags.1.en.html#hardening)
---
 pkgs/build-support/cc-wrapper/add-hardening.sh | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git a/pkgs/build-support/cc-wrapper/add-hardening.sh b/pkgs/build-support/cc-wrapper/add-hardening.sh
index 8e2fe6c407ea..dc530bf943d2 100644
--- a/pkgs/build-support/cc-wrapper/add-hardening.sh
+++ b/pkgs/build-support/cc-wrapper/add-hardening.sh
@@ -45,11 +45,12 @@ for flag in "${!hardeningEnableMap[@]}"; do
       hardeningCFlags+=('-fstack-protector-strong' '--param' 'ssp-buffer-size=4')
       ;;
     pie)
+      # NB: we do not use `+=` here, because PIE flags must occur before any PIC flags
       if (( "${NIX_DEBUG:-0}" >= 1 )); then echo HARDENING: enabling CFlags -fPIE >&2; fi
-      hardeningCFlags+=('-fPIE')
+      hardeningCFlags=('-fPIE' "${hardeningCFlags[@]}")
       if [[ ! ("$*" =~ " -shared " || "$*" =~ " -static ") ]]; then
         if (( "${NIX_DEBUG:-0}" >= 1 )); then echo HARDENING: enabling LDFlags -pie >&2; fi
-        hardeningCFlags+=('-pie')
+        hardeningCFlags=('-pie' "${hardeningCFlags[@]}")
       fi
       ;;
     pic)