I'm currently working on a project and it involves replacing a function by another. Let's say I have this simple function I want to hook:
int bad_func(int a, int b) {
return a * b;
}
I want to replace it with the following method:
int good_func(int a, int b) {
return a + b;
}
At the moment here is how I proceed:
- Attach to the process with
ptrace
- Get the address of
bad_func
in the code segment - Inject
mmap2
syscall to allocate a newrwx
memory segment - Copy the assembly code of
good_func
to the newly allocated segment - Replace the first bytes of
bad_func
with aJMP good_func
instruction
All of this is working great, I can confirm that the child process goes into the newly allocated memory and execute good_func
. The problem is that it never returns to the rest of the code that hasn't been executed yet.
Since both methods contains the following instructions,
push %ebp
mov %esp, %ebp
...
pop %ebp
ret
I suppose that I don't need to save/change the ebp
and esp
registers for it to work, but I guess I'm wrong...
Does anyone know how I can achieve my goal?
Many thanks in advance for your time.