patchelf

Modify ELF binaries after compilation — change interpreter, RPATH/RUNPATH, needed shared libraries, and other dynamic linking metadata.

Category: Binary Manipulation ELF modification Dynamic linking Toolchain Post-build editing

What it does

patchelf allows you to modify dynamic linking information inside an ELF binary without recompiling it. You can change the dynamic loader (interpreter), adjust RPATH/RUNPATH entries, add or remove shared library dependencies, and tweak other ELF metadata.

How it works (mechanical)

patchelf rewrites ELF headers and dynamic sections in place. It modifies fields such as:

  • PT_INTERP (dynamic loader path)
  • DT_RPATH / DT_RUNPATH
  • DT_NEEDED (required shared libraries)

It does not recompile code — it surgically edits ELF metadata.

10 Practical Examples

# 1) Show current interpreter
patchelf --print-interpreter ./binary
# 2) Set new interpreter (dynamic loader)
patchelf --set-interpreter /lib64/ld-linux-x86-64.so.2 ./binary
# 3) Print current RPATH/RUNPATH
patchelf --print-rpath ./binary
# 4) Set RPATH
patchelf --set-rpath '$ORIGIN/lib' ./binary
# 5) Remove RPATH
patchelf --remove-rpath ./binary
# 6) Add needed library
patchelf --add-needed libcustom.so ./binary
# 7) Remove needed library
patchelf --remove-needed libunused.so ./binary
# 8) Replace needed library
patchelf --replace-needed libold.so libnew.so ./binary
# 9) Shrink RPATH (cleanup)
patchelf --shrink-rpath ./binary
# 10) Verify with eu-readelf
eu-readelf -d ./binary

Notes & Gotchas

  • Backups first: always copy the binary before patching.
  • Compatibility: ensure new interpreter matches system architecture.
  • RPATH vs RUNPATH: modern linkers prefer RUNPATH.
  • Static binaries: patchelf has limited/no effect.
  • Breakage risk: improper changes can make binaries unusable.

Historical Context

patchelf gained popularity in packaging systems, container builds, NixOS workflows, and binary redistribution scenarios where recompilation was not feasible. It became a practical solution for adjusting dynamic linking paths in portable or relocatable environments.

Modern Equivalent / Related Tools

  • eu-readelf — inspect ELF structure
  • readelf — GNU equivalent
  • ldd — check shared dependencies
  • objdump — disassembly and inspection
  • chrpath — modify RPATH (limited scope)