如何像nm一样打印ELF文件的符号名?

How to print the name of the symbols of ELF files like the nm?

我知道符号的名称在 shstrtab 中。 但我不知道如何抓住他们。 我是否应该将我的 shstrab 转换为 Elf64_Sym 以便我可以使用 st_name?

Elf64_Shdr      *shdr = (Elf64_Shdr *) (data + elf->e_shoff);
Elf64_Shdr      *symtab;
Elf64_Shdr      *shstrtab;
Elf64_Shdr      *strtab;
char            *str = (char *) (data + shdr[elf->e_shstrndx].sh_offset);

for (int i = 0; i < elf->e_shnum; i++) {
  if (shdr[i].sh_size) {
    printf("%s\n", &str[shdr[i].sh_name]);
    if (strcmp(&str[shdr[i].sh_name], ".symtab") == 0)
      symtab = (Elf64_Shdr *) &shdr[i];
    if (strcmp(&str[shdr[i].sh_name], ".shstrtab") == 0)
      shstrtab = (Elf64_Shdr *) &shdr[i];
    if (strcmp(&str[shdr[i].sh_name], ".strtab") == 0)
      strtab = (Elf64_Shdr *) &shdr[i];
  }
}

str = (char *) shstrtab;
for (size_t i = 0; i < (symtab->sh_size / sizeof(Elf64_Sym *)); i ++) {
  printf("%s\n", &str[shstrtab[i].sh_name]);
}

Should I cast my shstrab into a Elf64_Sym so that I can use the st_name?

没有

这是你想要的循环:

Elf64_Sym *sym = (Elf64_Sym*) (data + symtab->sh_offset);
str = (char*) (data + strtab->sh_offset);

for (size_t i = 0; i < symtab->sh_size / sizeof(Elf64_Sym); i++) {
  printf("%s\n", str + sym[i].st_name);
}

你必须写 symtab->sh_size / symtab->sh_entsize 而不是像上面 post 所说的 symtab->sh_size / sizeof(Elf64_Sym *)