Search code examples
dynamiclinkerldelfbinutils

How to keep dynamic symbols only in shared objects for dynamic linking?


When the linker LD does dynamic linking, it checks the SO files and does dynamic linking. However, the SO files used in linking may not be used at run time. This happens a lot in cross-compilation, for example, when I used Ubuntu X86_64 as a host to cross-compile the Hello World application for Raspberry PI 4B (using aarch64-linux-gnu-gcc), it will be linked using the libc.so.6 from the cross-compile toolchain (/usr/aarch64-linux-gnu/lib/libc.so.6 on my PC). However, it will use the libc.so.6 in the Raspberry Pi 4b's rootfs at run time.

In the example above, the libc.so.6 in Ubuntu is only used for linking, most of the content is usless. For the linker ld, it may only read the dynamic symbols table from libc.so.6. I want to save space for host(ubuntu x86-64), is there any ways to process the libc.so.6 in ubuntu, only keep the contents used during linking, and remove useless contents.

I have tried objcopy --extract-symbol libc.so.6, however, it remove the dynamic symbols table. I have also tried objcopy -j .dynsym -j .dynstr -j .dynamic libc.so.6, it seens to be work, but I don't know if there are any other bad effects.


Solution

  • For the linker ld, it may only read the dynamic symbols table from libc.so.6. I want to save space for host(ubuntu x86-64)

    This is a strange request -- usually the host has all the space one wants, and it's the target that is (disk) size constrained.

    The solution I recommend is: buy a bigger disk for the host, SSDs are cheap!

    is there any ways to process the libc.so.6 in ubuntu, only keep the contents used during linking, and remove useless contents.

    Yes, Google internally uses "interface shared object builder" to do exactly this (for a different reason). Search for bazel+ifso to find references to it. There is a bazel ticket to create a public implementation (which is not trivial).

    That ticket references clang-ifso, which apparently didn't quite work at the time, and the source to which is no longer available.

    Here is a slide deck describing the tool. I do see -emit-interface-stubs in the Clang documentation, so the tool has been merged in (I have no experience with it).