Auto-patch downloaded binaries?

Is there a tool that updates all ELF binaries in a tree to use the NixOS ld.so and adds libraries to rpath?

I develop NodeJS, and there’s quite a lot of packages that download pre-built binaries. In some cases, that binary is Chromium, so I’m happy I don’t have to build it. However, these binaries of course don’t work.

I made a wrapper to run Live Share in vscode, but it’s quite primitive. Did anyone make a smarter one that will identify missing libraries, perhaps even propose packages?

#! /usr/bin/env nix-shell
#! nix-shell -i sh -p patchelf gcc

# patch ELF loaders where needed
GCCLIB=$(dirname $(gcc -print-file-name=libstdc++.so.6))
LOADER=$(dirname $(gcc -print-file-name=ld-linux-x86-64.so.2))
find "$@" -type f \( -perm -100 -o -name \*.so\* \) -print0 | xargs -0 file \
| grep 'interpreter /lib' | cut -d: -f1 | while read f; do
	echo "Patching $f" >&2
	patchelf --set-interpreter "$LOADER" "$f"
	MISSING="$(ldd "$f" | grep 'not found' | sed -e 's/^\s*//' -e 's/\s*=>.*$//')"
	if [ -n "$MISSING" ]; then
	  echo missing libs: >&2
		echo "$MISSING" >&2
		if echo "$MISSING" | grep -q 'libstdc++'; then
			RPATH=$(patchelf --print-rpath "$f")
			patchelf --set-rpath "${RPATH+RPATH:}$GCCLIB" "$f"
		fi
	fi
done
1 Like