gpt4 book ai didi

c - 我的 C 代码如何在运行时(在 Linux 中)找到与地址对应的符号?

转载 作者:IT王子 更新时间:2023-10-29 00:57:02 27 4
gpt4 key购买 nike

给定一个函数或变量运行时地址,我的代码需要找出名称,如果是变量,则需要符号的类型信息。或者至少为以后离线提取名称(和类型信息)提供足够的信息。

这是 Linux 代码,假定调试信息可用。

我试图研究 ELF 文件格式、binutils 和所有但主题很大,所以我希望有人能帮助我缩小范围。

我可以看到以下类型的解决方案:

  • 找到当前加载到内存中的模块的代码/数据段的范围 - 怎么做?。保存地址的模块和段名称以及在其段中的偏移量。离线然后使用 binutils 在模块的调试信息中查找符号 - 再次,如何做?

  • 使用一些我不知道的 API/系统服务在运行时查找符号和信息 - 如何?

提前谢谢你。

最佳答案

GNU libc 提供了一个 dladdr function为了这个确切的目的。但是,它仅适用于函数,不适用于变量。

   #define _GNU_SOURCE         /* See feature_test_macros(7) */
#include <dlfcn.h>

int dladdr(void *addr, Dl_info *info);

The function dladdr() takes a function pointer and tries to resolve
name and file where it is located. Information is stored in the
Dl_info structure:

typedef struct {
const char *dli_fname; /* Pathname of shared object that
contains address */
void *dli_fbase; /* Address at which shared object
is loaded */
const char *dli_sname; /* Name of symbol whose definition
overlaps addr */
void *dli_saddr; /* Exact address of symbol named
in dli_sname */
} Dl_info;

If no symbol matching addr could be found, then dli_sname and dli_saddr
are set to NULL.

dladdr() returns 0 on error, and nonzero on success.

当然,通常我在 gdb 中而不是在程序本身中执行此类操作。

关于c - 我的 C 代码如何在运行时(在 Linux 中)找到与地址对应的符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31148272/

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