使用 dlopen 获取 libc 内存分配函数的句柄

kin*_*er1 1 c linux memory-management dlopen

有人可以帮助我了解如何使用 dlopen 来获取 libc 内存分配函数的句柄吗?特别是,像搜索 libc 路径然后获取句柄之类的东西。应该使用什么模式来调用 dlsym?

想法是:

  1. 搜索 libc 路径
  2. 对其调用 dlopen
  3. 使用 dlsym 访问内存函数(malloc、calloc 等)和
  4. 使用函数

请帮助我提供上述 4 个步骤的代码片段。

小智 5

这是一个代码片段,HTH

#include <dlfcn.h>
#include <stdio.h>
int main()
{  
   void *handle; 

   // dlopen will search the path for you
   // /usr/lib/libc.so is a linker script, not an elf file
   // so it won't work with dlopen. 
   handle = dlopen("libc.so.6", 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;
}
Run Code Online (Sandbox Code Playgroud)