Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

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

I know the name of the symbols are in the shstrtab. But I don't get how to catch them. Should I cast my shstrab into a Elf64_Sym so that I can use the 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
", &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
", &str[shstrtab[i].sh_name]);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

No.

Here is the loop you want:

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
", str + sym[i].st_name);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...