title: Executing binary/elf-file directly from (shared)-memory in C
body: <p>we are trying to copy a binary/elf file into a shared-memory region of our system and then execute it thereafter. We don't want to call our "client"-program directly, since we need to execute it from the memory itself for our purpose. </p>
  
  <p>While we know that our approach (<em>described below</em>) won't really work, we are (<em>obviously</em>) trying to get it to work. How would it be possible to copy a binary/elf/etc. file directly into the (shared)-memory and execute it thereafter? Maybe we just compiled it in the wrong way? Or something else was done wrong?</p>
  
  <p>We also don't want to convert it into hex/shell-code, we already did that. We are looking for an easier and more practical solution.</p>
  
  <p>Is anyone able to help? Would be much appreciated!</p>
  
  <p><strong>Two programs:</strong></p>
  
  <ol>
  <li>"Host"-Program (<em>copy &amp; execute client-program in shared memory</em>)</li>
  <li>"Client"-Program (<em>basically a hello-world echo</em>)</li>
  </ol>
  
  <p><strong>"Client"-Program:</strong></p>
  
  <pre><code>#include &lt;stdio.h&gt;
  int main()
  {
      printf("Hello, World!\n");
      return 0;
  }
  </code></pre>
  
  <p>Compiled with <code>gcc -o binfile clientprogram.c -static</code>.</p>
  
  <p><strong>"Host"-Program:</strong></p>
  
  <pre><code>#include &lt;string.h&gt;
  #include &lt;sys/mman.h&gt;
  #include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  int main(int argc, char **argv)
  {
    FILE *fp; //filepointer
    size_t size; //filesize
    unsigned char *buffer; //buffer
  
    fp = fopen("binfile","rb"); 
    fseek(fp, 0, SEEK_END); 
    size = ftell(fp);
    fseek(fp, 0, SEEK_SET); 
    buffer = (unsigned char *) malloc(size);
    if (fp == NULL){ //file empty?
        printf("Error: There was an Error reading the file %s \n", "binfile");           
        exit(1);
    }
    else if (fread(buffer, sizeof *buffer, size, fp) != size){ 
        printf("Error: There was an Error reading the file %s\n", "binfile");
        exit(1);
    }else{
      int i;
      // for(i=0; i&lt;size;i++){       
      //    printf("%02x", buffer[i]);
      // }
    }
  
  
    void *mem = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
    memcpy(mem, buffer, size);
    mprotect(mem, size, PROT_READ|PROT_WRITE|PROT_EXEC);
  
    void (*func)();
    func = (void (*)()) buffer;
    func();  
  
    munmap(mem, size);
  
    fclose(fp);
    free(buffer);
    return 0;
  }
  </code></pre>
  
  <p>Compiled with <code>gcc hostprogram.c</code>.</p>