1

The LD_PRELOAD trick can help for dynamic linking of binaries at runtime, but it will fail for a statically linked binary.

I want to override some c++ startup functions (like changing code for __libc_start_main, __libc_csu_init and a few others). I was thinking of changing the code directly from glibc but I want to be sure that there is no other way to get things worked out.

Is there any other way to override c++ startup functions than to change code from glibc and building it again?

Rohit
  • 175
  • 11

1 Answers1

4

Depending on what you want to exclude, you'll need -nostartfiles, -nodefaultlibs or -nostdlib. You'll then add your own replacements. If your replacement is incomplete (likely), you'd add the original libraries such as glibc after your own. The linker uses them in the listed order, so your overrides now get preference.

Implictly-linked libraries act as if they appeared first, which is why you need to specifically exclude them and then add them back. See also g++, static initialization and -nostdlib

MSalters
  • 173,980
  • 10
  • 155
  • 350
  • So if I were to override only a few functions, then I could override them and generate a shared object (to link with at compile time). So rest of the functions will be resolved by the linker directly at runtime? – Rohit Jun 10 '18 at 00:40
  • Well, you still need to link with `glibc` at build time. The runtime linker needs to told which libraries to load, and which functions to find in each library, precisely because the static link did not copy those functions. – MSalters Jun 10 '18 at 00:44
  • In that case, I'll add those compiler flags then add all the linking files making sure that mine is the first one to override the functions. Is this what you want to say? – Rohit Jun 10 '18 at 00:48
  • @Rohit: Yes, you got it. – MSalters Jun 10 '18 at 00:56