1
0

Add test_wrap.c

This commit is contained in:
2024-12-31 12:19:20 +01:00
parent ab0b73af5b
commit 8316726635
7 changed files with 131 additions and 15 deletions

View File

@@ -8,8 +8,9 @@ Option 1: `LD_PRELOAD`
* No need to re-link
* Works for *all* functions
* Works only on dynamically linked executables
* Intercepts all calls (including stack allocations etc.)
Example:
Example (`preload.c`):
```c
#include <stdlib.h>
#include <dlfcn.h>
@@ -17,7 +18,7 @@ Example:
void *malloc(size_t size) {
// before call to malloc
void *(* _malloc)(size_t);
void *(*_malloc)(size_t);
if ((_malloc = dlsym(RTLD_NEXT, "malloc")) == NULL) {
errno = ENOSYS;
return NULL;
@@ -28,21 +29,30 @@ void *malloc(size_t size) {
}
```
```shell
# ./main is already compiled and ready
gcc -shared -fPIC -o preload.so preload.c
LD_PRELOAD="$(pwd)/preload.so" ./main
```
Option 2: `gcc --wrap`
----------------------
* Need to re-link
* Need to re-link(/-comiple)
* Relatively simple code:
* Function name: `__wrap_<symbol>`
* Call to real function inside wrapper: `__real_<symbol>`
* Works for *all* functions
* Works only on dynamically linked executables
* Intercepts only calls inside the given source file
Example:
Example (`wrap.c`):
```c
#include <stdlib.h>
extern void *__real_malloc(size_t size);
void *__wrap_malloc(size_t size) {
// before call to malloc
void *ret = __real_malloc(size);
@@ -51,6 +61,11 @@ void *__wrap_malloc(size_t size) {
}
```
```shell
gcc -o main_wrapped main.c wrap.c -Wl,--wrap=malloc
./main_wrapped
```
Option 3: Linux kernel
----------------------