gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:41:54 26 4
gpt4 key购买 nike

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

想法是:

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

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

最佳答案

这是一个代码片段,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;
}

关于c - 使用 dlopen 获取 libc 内存分配函数的句柄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6841311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com