1 | // Chaining malloc
|
2 | // https://stackoverflow.com/questions/6083337/overriding-malloc-using-the-ld-preload-mechanism
|
3 |
|
4 | #define _GNU_SOURCE
|
5 |
|
6 | #include <dlfcn.h>
|
7 | #include <stdio.h>
|
8 | #include <stdlib.h>
|
9 |
|
10 | #if 0
|
11 | FILE *fopen(const char *path, const char *mode) {
|
12 | printf("Always failing fopen\n");
|
13 | return NULL;
|
14 | }
|
15 | #endif
|
16 |
|
17 | #if 1
|
18 | static void *(*real_malloc)(size_t) = NULL;
|
19 |
|
20 | static void mtrace_init(void) {
|
21 | real_malloc = dlsym(RTLD_NEXT, "malloc");
|
22 | if (NULL == real_malloc) {
|
23 | fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
|
24 | }
|
25 | }
|
26 |
|
27 | void *malloc(size_t size) {
|
28 | if (real_malloc == NULL) {
|
29 | mtrace_init();
|
30 | }
|
31 |
|
32 | void *p = NULL;
|
33 | fprintf(stderr, "HOOK malloc(%ld) = ", size);
|
34 | p = real_malloc(size);
|
35 | fprintf(stderr, "%p\n", p);
|
36 | return p;
|
37 | }
|
38 | #endif
|