![](/img/trans.png)
[英]Undefined reference in a custom ELF file, but the symbol is defined in the files symbol table
[英]Print the symbol table of an ELF file
我有一个使用mmap系统调用的程序:
map_start = mmap(0, fd_stat.st_size, PROT_READ | PROT_WRITE , MAP_SHARED, fd, 0)
和一个标题变量:
header = (Elf32_Ehdr *) map_start;
如何访问符号表并使用标头变量打印其整个内容?
您可以通过查看elf标头的e_shoff
字段来获取节表:
sections = (Elf32_Shdr *)((char *)map_start + header->e_shoff);
您现在可以在节表中搜索类型为SHT_SYMBTAB
的节,即符号表。
for (i = 0; i < header->e_shnum; i++)
if (sections[i].sh_type == SHT_SYMTAB) {
symtab = (Elf32_Sym *)((char *)map_start + sections[i].sh_offset);
break; }
当然,如果您的文件不是ELF文件或以某种方式损坏,您还应该进行大量的健全性检查。
linux elf(5)手册页有很多关于格式的信息。
以下是一个示例: https : //docs.oracle.com/cd/E19683-01/817-0679/6mgfb878d/index.html
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <libelf.h>
#include <gelf.h>
void
main(int argc, char **argv)
{
Elf *elf;
Elf_Scn *scn = NULL;
GElf_Shdr shdr;
Elf_Data *data;
int fd, ii, count;
elf_version(EV_CURRENT);
fd = open(argv[1], O_RDONLY);
elf = elf_begin(fd, ELF_C_READ, NULL);
while ((scn = elf_nextscn(elf, scn)) != NULL) {
gelf_getshdr(scn, &shdr);
if (shdr.sh_type == SHT_SYMTAB) {
/* found a symbol table, go print it. */
break;
}
}
data = elf_getdata(scn, NULL);
count = shdr.sh_size / shdr.sh_entsize;
/* print the symbol names */
for (ii = 0; ii < count; ++ii) {
GElf_Sym sym;
gelf_getsym(data, ii, &sym);
printf("%s\n", elf_strptr(elf, shdr.sh_link, sym.st_name));
}
elf_end(elf);
close(fd);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.