title: Constructing working ELF binary from memory dump
body: <p>I've written the following simple C program</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  
  int main()
  {
    printf("Hello\n");
    return 0;
  }
  </code></pre>
  
  <p>After compiling I load this program in GDB and continue as follows</p>
  
  <pre><code>&gt; catch syscall brk  
  *run and wait for GDB to catch syscall*
  &gt; info proc mappings
  
  Start Addr    End Addr    Size    Offset    
  0x8000000     0x8001000   0x1000  0x0       &lt;--- this region is r-xp, so this is the code in memory
  0x8200000     0x8202000   0x2000  0x0       &lt;--- this region is rw-p, so this is the data in memory
  &gt; dump binary memory testdump 0x8000000 0x8001000
  </code></pre>
  
  <p>(the reason I set a catchpoint on brk is because this syscall is called before execution of the program, but with the program loaded in memory)</p>
  
  <p>Using <em>readelf</em> on the memory dump gives the following output</p>
  
  <pre><code>$ readelf -h testdump
  ELF Header:
    Magic:   7f 45 4c 46 02 01 01 00 00 00 00 00 00 00 00 00
    Class:                             ELF64
    Data:                              2's complement, little endian
    Version:                           1 (current)
    OS/ABI:                            UNIX - System V
    ABI Version:                       0
    Type:                              DYN (Shared object file)
    Machine:                           Advanced Micro Devices X86-64
    Version:                           0x1
    Entry point address:               0x530
    Start of program headers:          64 (bytes into file)
    Start of section headers:          6440 (bytes into file)
    Flags:                             0x0
    Size of this header:               64 (bytes)
    Size of program headers:           56 (bytes)
    Number of program headers:         9
    Size of section headers:           64 (bytes)
    Number of section headers:         29
    Section header string table index: 28
  readelf: Error: Reading 1856 bytes extends past end of file for section headers
  readelf: Error: Section headers are not available!
  </code></pre>
  
  <p>I was wondering how I can fix these errors and make an executable ELF binary from this memory dump which runs the same as the original program. Note that I want to do this with just a hexeditor (e.g. <em>hexedit</em>) and without using the original binary.</p>