Dynamically change the symbol table at run time (in C)

Is it possible to dynamically change the character table at run time in C (in elf format on Linux)?

My ultimate goal is as follows:

Inside a specific say foo function, I want to override the malloc function on my custom my_malloc handler. But outside of foo , any malloc should still call malloc, as in glibc.

Note: this is different from LD_PRELOAD , which will cancel malloc during the entire execution of the program.

+7
symbols systems-programming elf ld-preload
source share
1 answer

Is it possible to dynamically change the character table at run time in C (in elf format on Linux)?

In theory, this is possible, but in practice it is too difficult to do.

Inside a specific say foo function, I want to override the malloc function on my custom my_malloc handler. But outside of foo any malloc should still access malloc , as in glibc.

Changing the symbol table (even if it was possible) will not lead you to your desired goal.

All calls from anywhere inside your ELF binary (assuming foo is in the main executable), allow the use of the same PLT import interval malloc@plt . This slot is allowed by glibc malloc on the first call (from anywhere in your program, unless you use LD_BIND_NOW=1 or similar). Once this slot is enabled, any further modification of the symbol table will have no effect.

You did not say how much control over foo you have.

If you can recompile it, the problem becomes trivial:

 #define malloc my_malloc int foo() { // same code as before } #undef malloc 

If you are given a pre-compiled foo.o , you associate it with my_malloc.o , and you want to redirect all calls from inside foo.o from malloc to my_malloc , which is actually quite simple to do at the object level (i.e., to the end link )

All you have to do is go through the rewriting records of foo.o and change those that say "put the address of the external malloc here" to "put the address of the external my_malloc here".

If foo.o contains additional functions besides foo , it is quite simple to restrict the redistribution of redirects only to movement inside foo .

+6
source share

All Articles