···11+# shellcheck shell=bash
22+# List all dynamically linked ELF files in the outputs and apply a generic fix
33+# action provided as a parameter (currently used to add the CUDA or the
44+# cuda_compat driver to the runpath of binaries)
55+echo "Sourcing fix-elf-files.sh"
66+77+# Returns the exit code of patchelf --print-rpath.
88+# A return code of 0 (success) means the ELF file has a dynamic section, while
99+# a non-zero return code means the ELF file is statically linked (or is not an
1010+# ELF file).
1111+elfHasDynamicSection() {
1212+ local libPath
1313+1414+ if [[ $# -eq 0 ]]; then
1515+ echo "elfHasDynamicSection: no library path provided" >&2
1616+ exit 1
1717+ elif [[ $# -gt 1 ]]; then
1818+ echo "elfHasDynamicSection: too many arguments" >&2
1919+ exit 1
2020+ elif [[ "$1" == "" ]]; then
2121+ echo "elfHasDynamicSection: empty library path" >&2
2222+ exit 1
2323+ else
2424+ libPath="$1"
2525+ shift 1
2626+ fi
2727+2828+ patchelf --print-rpath "$libPath" >& /dev/null
2929+ return $?
3030+}
3131+3232+# Run a fix action on all dynamically linked ELF files in the outputs.
3333+autoFixElfFiles() {
3434+ local fixAction
3535+ local outputPaths
3636+3737+ if [[ $# -eq 0 ]]; then
3838+ echo "autoFixElfFiles: no fix action provided" >&2
3939+ exit 1
4040+ elif [[ $# -gt 1 ]]; then
4141+ echo "autoFixElfFiles: too many arguments" >&2
4242+ exit 1
4343+ elif [[ "$1" == "" ]]; then
4444+ echo "autoFixElfFiles: empty fix action" >&2
4545+ exit 1
4646+ else
4747+ fixAction="$1"
4848+ fi
4949+5050+ mapfile -t outputPaths < <(for o in $(getAllOutputNames); do echo "${!o}"; done)
5151+5252+ find "${outputPaths[@]}" -type f -print0 | while IFS= read -rd "" f; do
5353+ if ! isELF "$f"; then
5454+ continue
5555+ elif elfHasDynamicSection "$f"; then
5656+ # patchelf returns an error on statically linked ELF files, and in
5757+ # practice fixing actions all involve patchelf
5858+ echo "autoFixElfFiles: using $fixAction to fix $f" >&2
5959+ $fixAction "$f"
6060+ elif (( "${NIX_DEBUG:-0}" >= 1 )); then
6161+ echo "autoFixElfFiles: skipping a statically-linked ELF file $f"
6262+ fi
6363+ done
6464+}