I have a (relatively big) static binary in which I'd like to replace a function with the other one. Given the function's complexity, I'd like to use C and gcc to compile spliced-in function and then just replace the code. For this to work, obviously, I need somehow to enforce functions and certain global variables I would access to be located at specific offsets. How do I do that using gcc and ld?
A very simple example - given a program like that:
int global = 42;
int get_global() { return global; }
int main() {
return get_global();
}
Compiling and disassembling this function yields the following:
00000000004004ad <get_global>:
4004ad: 55 push %rbp
4004ae: 48 89 e5 mov %rsp,%rbp
4004b1: 8b 05 61 04 20 00 mov 0x200461(%rip),%eax # 600918 <global>
4004b7: 5d pop %rbp
4004b8: c3 retq
Note that:
global
variable has address 0x600918get_global
got 0x4004ad
Basically, the question is, how do I use gcc and ld to produce the code for a function that would:
- reference
global
variable and/or function on exactly addresses mentioned - start at the address I'd like it to start (I'm particularly interested in starting at address 0x4004ad, so it could potentially be used to splice over existing
get_global
implementation)
I thought that it could be possible with either some pragmas or compiler-specific attributes specified for function prototypes and/or globals, and, indeed, gcc has some variables attributes that control packing and placement of functions/variables in certain sections, but it's impossible to specify fixed addresses.
I strongly suspect that it could be done with manually invoking ld
and using some ld linker script magic, but a quick look at its documentation doesn't seem to ring any bells for me. Am I missing something?
Definitely related: Fixed address variable in C