Detour: A detour through the Linux dynamic linker
10 months ago
- #Dynamic Linking
- #Linux
- #Static Linking
- Detour is a static library that allows building statically linked executables without depending on glibc or musl while still enabling dynamic linking at runtime.
- It provides access to the system dynamic linker (ld-linux.so) without requiring libc, enabling functionalities like dlopen, dlsym, and mixing multiple C runtimes in the same process.
- Detour works by using a minimal stub ELF executable to bootstrap the dynamic linker, capturing essential symbols before returning control to the main application.
- It supports both static and dynamic contexts, though currently limited to x86_64 Linux, with potential for other architectures requiring additional assembly work.
- Fully static linking has tradeoffs, such as losing access to system components that rely on dynamic linking (e.g., GPU drivers, window systems, audio subsystems).
- Detour solves this by allowing static linking of the core application while setting up a dynamic linker for runtime use.
- The helper ELF stub used by Detour is small (~35 lines of C) and designed for maximum compatibility with glibc-based systems.
- A demo included with Detour shows a fully freestanding static executable dynamically loading libc, libm, libSDL2, and libGL at runtime.
- Use cases include creating libc-free executables that load plugins, avoiding dependency hell, mixing musl and glibc, and accessing hardware-accelerated APIs without linking glibc.
- Detour leverages Linux's existing mechanisms for launching dynamic binaries, providing surgical control over the dynamic linker's involvement.