clinuxmemory-managementdlopen

Using dlopen to get handle of libc memory allocation functions


Can someone help me to know how can i use dlopen to get handle of libc memory allocation functions? Especially, something like searching the libc path and then taking the handle. What modes should be used to invoke dlsym?

Idea is:

  1. Search libc path
  2. Invoke dlopen on it
  3. Use dlsym to access the memory functions (malloc, calloc etc) and
  4. use the functions

Please help me with a code snippet of the above 4 steps.


Solution

  • Here's a code snippet, HTH

    #include <dlfcn.h>
    #include <stdio.h>
    
    // For LIBC_SO which expands to proper libc name
    #include <gnu/lib-names.h>
    
    int main()
    {  
       void *handle; 
       
       // dlopen will search the path for you
       // LIBC_SO expands to shared library name
       // for libc
       handle = dlopen(LIBC_SO, RTLD_LAZY); 
    
       if(handle){
             void* (*mallocptr)(size_t);
             void (*freeptr)(void*);
    
             // Locate symbols
             *(void**)(&mallocptr) = dlsym(handle, "malloc");
             *(void**)(&freeptr) = dlsym(handle, "free");
             
             if(!mallocptr || !freeptr){
                printf("%s\n", dlerror());
                return 1;
             }
    
             // Allocate and use memory
             char *ptr = (*mallocptr)(4);
             ptr[0] = 'H'; ptr[1] = 'i'; ptr[2] = '\n'; ptr[3] = '\0';
             printf(ptr);
             
             // Free it
             (*freeptr)(ptr);
       }
       else{
          printf("%s\n", dlerror());
          return 1;
       }
       return 0;
    }