title: Understanding section headers ELF
body: <pre><code>static inline Elf32_Shdr *elf_sheader(Elf32_Ehdr *hdr) {
      return (Elf32_Shdr *)((int)hdr + hdr-&gt;e_shoff);
  }
  
  static inline Elf32_Shdr *elf_section(Elf32_Ehdr *hdr, int idx) {
      return &amp;elf_sheader(hdr)[idx];
  }
  </code></pre>
  
  <p>Okay the first function here returns a pointer to a elf section header by using <code>hdr_shoff</code> 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 . </p>
  
  <pre><code>static inline char *elf_str_table(Elf32_Ehdr *hdr) {
      if(hdr-&gt;e_shstrndx == SHN_UNDEF) return NULL;
      return (char *)hdr + elf_section(hdr, hdr-&gt;e_shstrndx)-&gt;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;
  }
  </code></pre>
  
  <p>I am having problems with the above two function used for accessing section names . <code>e-&gt;shstrndx</code> is the index of the string table . So in <code>elf_str_table</code> we first check it against <code>SHN_UNDEF</code> . But in the <code>return</code> I don't understand that <code>hdr-&gt;e_shstrndx</code> 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 <code>sh_offset</code> ) . My confusion is that <code>e-&gt;shstrndx</code> is an index to a string table but how is it that this index along with <code>elf_section</code> returning a pointer to <code>struct Elf32_Shdr</code>  ?  </p>
  
  <p>Reference : <a href="http://wiki.osdev.org/ELF_Tutorial#Accessing_Section_Headers" rel="noreferrer">http://wiki.osdev.org/ELF_Tutorial#Accessing_Section_Headers</a></p>