Hack the standard function in library and call the native library function afterwards

后端 未结 3 1269
谎友^
谎友^ 2021-01-26 01:26

I am trying to hack the malloc function to call my malloc function first.Once my malloc function is executed within that, I want to invoke the standard malloc. But, I am getting

3条回答
  •  无人及你
    2021-01-26 02:03

    To override shared functions you need to compile your own shared library and preload it via the LD_PRELOAD environment variable.

    #define _GNU_SOURCE
    
    #include 
    #include 
    #include 
    
    void *malloc(size_t size) {
        printf("called..my malloc\r\n");
    
        void *(*original_malloc)(size_t size);
        // Find original malloc function
        original_malloc = dlsym(RTLD_NEXT, "malloc");
    
        if ( dlerror() != NULL)
        {
            puts("malloc symbol not found..");
            exit(1);
        }
    
        printf("This should call actual malloc now..\r\n");
        return (*original_malloc)(size);
    }
    
    $ gcc -Wall -fPIC -shared -o mymalloc.so mymalloc.c -ldl
    $ LD_PRELOAD=./mymalloc.so ./prog
    

    Now your program will use malloc from preloaded library.

提交回复
热议问题