gpt4 book ai didi

c - 如何从程序本身获取指向特定可执行文件部分的指针? (也许与 libelf)

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

我在 Linux 环境中,我需要制作一个程序来检索位于其可执行文件的某个部分中的一些数据。那么,如何从自身内部获取指向程序部分(通过其名称)的指针?

我知道可以使用 elf_getdata() 将节的索引作为参数传递给 get 和 Elf_Data 结构,该结构的字段之一是 d_buf,这是一个指向实际数据的指针。但是,似乎 elf_getdata() 函数将节数据从文件复制到内存,这不是我想要的。我想要一个指向加载时已加载到内存中的数据的指针。

那么,伙计们,有什么想法吗?

最佳答案

实际上,使用 libelf,可以使用 Elf64_Shdr 结构(对于 64 位系统)来获取指向某个部分的指针,因为 sh_addr 字段 do 指向该部分将在运行时加载的实际地址。因此,它可以用作指针。这样,甚至不必使用 elf_getdata() 函数来检索 Elf_Data 结构。

因为我想做的是一个可以链接其他目标文件的库,我的代码可能有一个函数可以打开可执行文件本身以利用一些 libelf 特性,这样它可以从主要文件部分读取数据,如下所示:

// A global variable which stores the executable file name
extern const char *__progname;

void retrieve_data() {
int fd; // File descriptor for the executable ELF file
char *section_name, path[384];
size_t shstrndx;

Elf *e; // ELF struct
Elf_Scn *scn; // Section index struct
Elf64_Shdr *shdr; // Section struct

// Create the full path of the executable
getcwd(path, 255);
strcat(path, "/");
strncat(path, __progname, 127);

if (elf_version(EV_CURRENT) == EV_NONE)
errx(EXIT_FAILURE, "ELF library iinitialization failed: %s", elf_errmsg(-1));

if ((fd = open(path, O_RDONLY, 0)) < 0)
err(EXIT_FAILURE, "open \"%s\" failed", path);

if ((e = elf_begin(fd, ELF_C_READ, NULL)) == NULL)
errx(EXIT_FAILURE, "elf_begin() failed: %s.", elf_errmsg(-1));

// Retrieve the section index of the ELF section containing the string table of section names
if (elf_getshdrstrndx(e, &shstrndx) != 0)
errx(EXIT_FAILURE, "elf_getshdrstrndx() failed: %s.", elf_errmsg(-1));

scn = NULL;

// Loop over all sections in the ELF object
while ((scn = elf_nextscn(e, scn)) != NULL) {
// Given a Elf Scn pointer, retrieve the associated section header
if ((shdr = elf64_getshdr(scn)) != shdr)
errx(EXIT_FAILURE, "getshdr() failed: %s.", elf_errmsg(-1));

// Retrieve the name of the section
if ((section_name = elf_strptr(e, shstrndx, shdr->sh_name)) == NULL)
errx(EXIT_FAILURE, "elf_strptr() failed: %s.", elf_errmsg(-1));

// If the section is the one we want... (in my case, it is one of the main file sections)
if (!strcmp(section_name, "Section name")) {
// We can use the section adress as a pointer, since it corresponds to the actual
// adress where the section is placed in the virtual memory
struct data_t * section_data = (struct data_t *) shdr->sh_addr;

// Do whatever we want

// End the loop (if we only need this section)
break;
}
}

elf_end(e);
close(fd);
}

关于c - 如何从程序本身获取指向特定可执行文件部分的指针? (也许与 libelf),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12159595/

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