3

I'm trying to learn more about the ELF format, particularly, section headers and I just came across the following:

Elf32_Ehdr *ehdr = (Elf32_Ehdr*)p;
Elf32_Shdr *shdr = (Elf32_Shdr *)(p + ehdr->e_shoff);
int shnum = ehdr->e_shnum;

Elf32_Shdr *sh_strtab = &shdr[ehdr->e_shstrndx];
const char *const sh_strtab_p = p + sh_strtab->sh_offset;

for (int i = 0; i < shnum; ++i) {
   printf("%2d: %4d '%s'\n", i, shdr[i].sh_name,
          sh_strtab_p + shdr[i].sh_name);
}

 return 0;
}

Now, I understand that this is basically iterating through the section table and printing the section names but I'm still confused about the sh_offset field. What exactly does it do? If e_shstrndx is already pointing to the string table section why do we need sh_offset?

Trey
  • 474
  • 2
  • 9
  • 32

1 Answers1

5

If e_shstrndx is already pointing to the string table section why do we need sh_offset

The e_shstrndx is an index into section table; it tells you which section describes (contains) the string table.

But it doesn't tell you where the data (the strings themselves) resides. You need sh_offset for that.

Here is a picture. .e_shoff tells you where the table of sections starts, .e_shstrndx tells you which element of that table is the one you want, and that element's .sh_offset tells you where in the file .shstrtab section's data is (i.e. where the strings themselves are).

Employed Russian
  • 199,314
  • 34
  • 295
  • 362