I'm trying to read the symbols names from an ELF binary using the two functions below, but I don't know if this is the right way to do it.
Elf64_Shdr *get_shdr(void *ptr, char *name)
function gives me the address of the section header of the target section with name name
.
void elf64(void *ptr)
is simply used to print the symbols names, and you can see that I targeted the section .strtab
specificly and not .shstrtab
.
I understand the difference between .strtab
and .shstrtab
sections. The first is associated with the section .symtab
and it contains the names of the symbols as refered in https://refspecs.linuxbase.org/elf/elf.pdf, and the second is the section that contains the names of all sections in the ELF binary (Please correct me if I was wrong).
Elf64_Shdr *get_shdr(void *ptr, char *name)
{
int idx;
Elf64_Ehdr *ehdr;
Elf64_Shdr *shdr;
Elf64_Shdr *shstrtab;
if (ptr && name)
{
idx = -1;
ehdr = (Elf64_Ehdr *)ptr;
shdr = (Elf64_Shdr *)(ptr + ehdr->e_shoff);
shstrtab = &shdr[ehdr->e_shstrndx];
while (++idx < ehdr->e_shnum)
{
if (!strcmp(ptr + shstrtab->sh_offset + shdr[idx].sh_name, name))
return (&shdr[idx]);
}
}
return (NULL);
}
void elf64(void *ptr)
{
int i, name;
Elf64_Shdr *symtab;
Elf64_Shdr *strtab;
symtab = get_shdr(ptr, ".symtab");
strtab = get_shdr(ptr, ".strtab");
i = -1;
while (++i < symtab->sh_size / sizeof(Elf64_Sym))
{
if (name > 0)
printf("%s\n", (char *)(ptr + strtab->sh_offset + symtab[i].sh_name));
}
}
If the code in the second function is not the proper way to read the symbols names, how would I do it instead?