kin*_*er1 1 c linux memory-management dlopen
有人可以帮助我了解如何使用 dlopen 来获取 libc 内存分配函数的句柄吗?特别是,像搜索 libc 路径然后获取句柄之类的东西。应该使用什么模式来调用 dlsym?
想法是:
请帮助我提供上述 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)