title: Why ELF's segments aren't contiguous?
body: <p>I've read this <a href="https://github.com/BR903/ELFkickers/blob/master/infect/infect.c" rel="nofollow noreferrer">infect.c</a> source which demonstrates how to infect ELF file with a malicious entry point.</p>
  <p>It proceeds like this :</p>
  <ol>
  <li>Load an executable file into memory</li>
  <li>Find a suitable segment to extend with the payload</li>
  <li>Update the payload to jump the original entry point location</li>
  <li>Update the entry point to jump the payload location</li>
  <li>Extend the segment with the malicious payload</li>
  </ol>
  <p>Here is how it discover the suitable phdr :</p>
  <pre><code>static int findinfectionphdr(Elf64_Phdr const *phdr, int count)
  {
      Elf64_Off pos, endpos;
      int i, j;
  
      for (i = 0 ; i &lt; count ; ++i) {
      if (phdr[i].p_filesz &gt; 0 &amp;&amp; phdr[i].p_filesz == phdr[i].p_memsz
                   &amp;&amp; (phdr[i].p_flags &amp; PF_X)) {
          pos = phdr[i].p_offset + phdr[i].p_filesz;
          endpos = pos + sizeof infection;
          for (j = 0 ; j &lt; count ; ++j) {
          if (phdr[j].p_offset &gt;= pos &amp;&amp; phdr[j].p_offset &lt; endpos
                          &amp;&amp; phdr[j].p_filesz &gt; 0)
              break;
          }
          if (j == count)
          return i;
      }
      }
      return -1;
  }
  </code></pre>
  <p>The first loop looks for an executable segment to infect and the second test if there is any other segment susceptible to overlap the infected one.</p>
  <p>If all the segments were contiguous this infection could not be performed.</p>
  <p>So here is my question : why compilers don't produce contiguous segments in ELF files ?
  Or alternatively : what justifies the gap between them ?</p>