-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhook _memcpy using a trampoline approach
46 lines (30 loc) · 1.25 KB
/
hook _memcpy using a trampoline approach
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
Here is another method to hook _memcpy using a trampoline approach:
```cpp
#include <dlfcn.h>
void* (*original_memcpy)(void* dest, const void* src, size_t n);
// Trampoline that will contain our hook logic
void* trampoline_memcpy(void* dest, const void* src, size_t n) {
// Manipulate data before original
void* result = original_memcpy(dest, src, n);
// Manipulate data after original
return result;
}
// Our _memcpy thunk
void* _memcpy(void* dest, const void* src, size_t n) {
// Jump to the trampoline
void* result = trampoline_memcpy(dest, src, n);
return result;
}
// Hook by modifying _memcpy
void hook_memcpy() {
// Get the original address
original_memcpy = dlsym(RTLD_NEXT, "memcpy");
// Override _memcpy with a jump to our trampoline
void* _memcpy_addr = (void*)&_memcpy;
unsigned char jump[5] = {0xE9, 0xXX, 0XX, 0XX, 0XFF};
int trampoline_offset = (int)&trampoline_memcpy - ((int)_memcpy_addr + 5);
memcpy(&jump[1], &trampoline_offset, 4);
memcpy(_memcpy_addr, jump, 5);
}
```
Instead of putting the hook logic directly in _memcpy, we redirect execution to a separate trampoline function. This avoids modifying the target function. The key steps are similar - get original, add a jump, execute custom logic.