티스토리 뷰
there is some codes in the system programming lecture metarial for load time interposition.
The code of mymalloc.c
belows.
#ifdef RUNTIME
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
void _malloc(size_t size)
{
void *(_mallocp) (size_t size) = NULL;
mallocp = dlsym(RTLD_NEXT, "malloc");
if(!mallocp) {
fputs(dlerror(), stderr);
exit(1);
}
void *ptr = mallocp(size);
printf("malloc(%d): %p\n", (int) size, ptr);
return ptr;
}
#endif
The code of int.c
belows.
#include<stdio.h>
#include<malloc.h>
int main() {
int *p = malloc(32);
free(p);
return 0;
}
I compiled the souce code mymalloc.c
with gcc -Wall -DRUNTIME -shared -fpic -o mymalloc.so mymalloc..c -ldl
,
and int.c
with gcc -Wall -o intr int.c
.
but the result of LD_PRELOAD="./mymalloc.so" ./intr
was segmentation fault
.
The reason was that printf()
uses malloc function itself, so the shared object causes infinite recursion.
I can fix the sigsegv
error by replacing printf("malloc(%d): %p\n", (int) size, ptr);
to
char str_buf[256] = {0};
sprintf(str_buf, "malloc(%d): %p\n", (int) size, ptr);
write(1, str_buf, strlen(str_buf));
'리눅스' 카테고리의 다른 글
Asus Zenbook UX5304VA No Sound in Ubuntu [Solved] (1) | 2024.01.08 |
---|