티스토리 뷰

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));

reference: https://stackoverflow.com/questions/22196097/ld-preload-causing-segmentation-fault-for-linux-commands

'리눅스' 카테고리의 다른 글

Asus Zenbook UX5304VA No Sound in Ubuntu [Solved]  (1) 2024.01.08
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
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
글 보관함