Understanding section headers ELF

c, elf

Solution

You said yourself that `elf_section` returns a section header based on an index.

`e_shstrndx` is the index of the section header that contains the offset of the section header string table.

So, you use `e_shstrndx` as a parameter for `elf_section` to get that section header :

Elf32_Shdr* shstr = elf_section(hdr, hdr->e_shstrndx);

Then get the offset from that section header :

int strtab_offset = shstr->sh_offset;

And use it to get the actual string table :

char* strtab = (char*) hdr + strtab_offset;

From this string table, you can then get the names of sections based on their offset :

char* str = strtab + offset;

Problem

``` static inline Elf32_Shdr *elf_sheader(Elf32_Ehdr *hdr) { return (Elf32_Shdr *)((int)hdr + hdr->e_shoff); } static inline Elf32_Shdr *elf_section(Elf32_Ehdr *hdr, int idx) { return &elf_sheader(hdr)[idx]; } ``` Okay the first function here returns a pointer to a elf section header by using `hdr_shoff` because that is the offset to first section header . Now the second function is used to access more section headers ( if there be any ) just by using array indexing . ``` static inline char *elf_str_table(Elf32_Ehdr *hdr) { if(hdr->e_shstrndx == SHN_UNDEF) return NULL; return (char *)hdr + elf_section(hdr, hdr->e_shstrndx)->sh_offset; } static inline char *elf_lookup_string(Elf32_Ehdr *hdr, int offset) { char *strtab = elf_str_table(hdr); if(strtab == NULL) return NULL; return strtab + offset; } ``` I am having problems with the above two function used for accessing section names . `e->shstrndx` is the index of the string table . So in `elf_str_table` we first check it against `SHN_UNDEF` . But in the `return` I don't understand that `hdr->e_shstrndx` is the index to a string table , how is that index added to the starting address of the elf_section header giving another elf section header ( as we are using it access `sh_offset` ) . My confusion is that `e->shstrndx` is an index to a string table but how is it that this index along with `elf_section` returning a pointer to `struct Elf32_Shdr` ? Reference : http://wiki.osdev.org/ELF_Tutorial#Accessing_Section_Headers

Original source