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

后端 未结 3 1268
谎友^
谎友^ 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 <stdlib.h>
    #include <stdio.h>
    #include <dlfcn.h>
    
    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.

    0 讨论(0)
  • 2021-01-26 02:29

    The standard way I'm always using is creating a macro called MALLOC (or MYMALLOC or whatever) which does what you want. All occurrences of malloc I have to replace by the use of the macro, of course, and I can understand when this is not what you want.

    You also can achieve what you want by defining a macro called malloc (i. e. spelled like the original malloc) only when compiling the source you want to have your feature in. This malloc macro then would call a function called, say, wrappingMalloc which should be declared in a file which is compiled without defining the macro malloc and which then in turn can call the original function malloc. If this makefile fiddling is too much for you, you could also call the original function by calling (malloc) (this avoids running into the macro again):

        #include <stdlib.h>
        #include <stdio.h>
    
        #define malloc(size) myMalloc(size)
    
        void *myMalloc(size_t size) {
          void *result;
          printf("mallocing %ld bytes", size);
          result = (malloc)(size);
          printf(" at %p\n", result);
          return result;
        }
    
        int main(int argc, char *argv[]) {
          char *buffer;
          buffer = malloc(10);
          return 0;
        }
    

    In C++ you might get along by overloading the new operator for your classes.

    0 讨论(0)
  • 2021-01-26 02:30

    I cannot see a problem in your code. But why not move malloc_sysm = dlsym(handle_malloc,"malloc"); into your init() function?

    0 讨论(0)
提交回复
热议问题