FindPython: Fails with LDFLAGS='-specs=/usr/lib/rpm/redhat/redhat-hardened-ld'
When building Python bindings on some RHEL and derivatives, hardened RPM builds fail because CMake cannot find Python. Below is a minimal way to reproduce this failure. It seems that this may have been fixed in newer versions of CMake, but at least EL 8 and 9 are affected by this problem.
$ cat CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(TEST LANGUAGES CXX)
find_package(Python REQUIRED COMPONENTS Interpreter Development)
$ cmake .
-- The CXX compiler identification is GNU 11.3.1
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Python: /usr/bin/python3.9 (found version "3.9.16") found components: Interpreter Development Development.Module Development.Embed
-- Configuring done
-- Generating done
-- Build files have been written to: /tmp/test
$ rm CMakeCache.txt
$ LDFLAGS=-specs=/usr/lib/rpm/redhat/redhat-hardened-ld cmake -S . -B build
CMake Error at /usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:230 (message):
Could NOT find Python (missing: Python_EXECUTABLE Python_INCLUDE_DIRS
Python_LIBRARIES Interpreter Development Development.Module
Development.Embed)
Call Stack (most recent call first):
/usr/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:594 (_FPHSA_FAILURE_MESSAGE)
/usr/share/cmake/Modules/FindPython.cmake:556 (find_package_handle_standard_args)
CMakeLists.txt:5 (find_package)
-- Configuring incomplete, errors occurred!
See also "/tmp/test/build/CMakeFiles/CMakeOutput.log".
See also "/tmp/test/build/CMakeFiles/CMakeError.log".
$ cmake --version
cmake version 3.20.2
CMake suite maintained and supported by Kitware (kitware.com/cmake).
$ cat /usr/lib/rpm/redhat/redhat-hardened-ld
*self_spec:
+ %{!static:%{!shared:%{!r:-pie}}}
$ # The error can also be triggered just with LDFLAGS=-pie (which is why it fails with the spec file):
$ LDFLAGS=-pie cmake .