title: Linux: executing code that is loaded to memory manually
body: <p>I'm expermenting with function pointers on Linux and trying to execute this C program:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  
  int myfun() 
  {
      return 42;
  }
  
  int main()
  {
      char data[500];
      memcpy(data, myfun, sizeof(data));
      int (*fun_pointer)() = (void*)data;
      printf("%d\n", fun_pointer());
  
      return 0;
  }
  </code></pre>
  
  <p>Unfortunately it segfaults on <code>fun_pointer()</code> call.  I suspect that it is connected with some memory flags, but I don't found information about it.</p>
  
  <p>Could you explain why this code segfaults? Don't see to the fixed <code>data</code> array size, it is ok and copying without calling the function is successfull.</p>
  
  <p><strong>UPD</strong>: Finally I've found that the memory segment should be marked as executable using <a href="http://linux.die.net/man/2/mprotect" rel="noreferrer" title="man 2 mprotect">mprotect</a> system call called with <code>PROT_EXEC</code> flag. Moreover the memory segment should be returned by <a href="http://linux.die.net/man/2/mmap" rel="noreferrer" title="man 2 mmap">mmap</a> function as stated in the POSIX specification.
  There is the same code that uses allocated by <code>mmap</code> memory with <code>PROT_EXEC</code> flag (and works):</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;string.h&gt;
  #include &lt;sys/mman.h&gt;
  
  int myfun() 
  {
      return 42;
  }
  
  int main()
  {
      size_t size = (char*)main - (char*)myfun;
      char *data = mmap(NULL, size, PROT_EXEC | PROT_READ | PROT_WRITE,
          MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
      memcpy(data, myfun, size);
  
      int (*fun_pointer)() = (void*)data;
      printf("%d\n", fun_pointer());
  
      munmap(data, size);
      return 0;
  }
  </code></pre>
  
  <p>This example should be complied with <code>-fPIC</code> gcc option to ensure that the code in functions is position-independent.</p>