title: How to execute raw instructions from a memory buffer in Rust?
body: <p>I'm attempting to make a buffer of memory executable, then execute it in Rust. I've gotten all the way until I need to cast the raw executable bytes as code/instructions. You can see a <strong>working example</strong> in C below.</p>
  
  <p>Extra details:</p>
  
  <ul>
  <li>Rust 1.34</li>
  <li>Linux</li>
  <li>CC 8.2.1</li>
  </ul>
  
  <pre class="lang-c prettyprint-override"><code>unsigned char code[] = {
  0x55,                           //    push   %rbp
  0x48, 0x89, 0xe5,               //    mov    %rsp,%rbp
  0xb8, 0x37, 0x00, 0x00, 0x00,   //    mov    $0x37,%eax
  0xc9,                           //    leaveq
  0xc3                            //    retq
  };
  
  
  void reflect(const unsigned char *code) {
    void *buf;
  
    /* copy code to executable buffer */    
    buf = mmap(0, sizeof(code), PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_ANON,-1,0);
    memcpy(buf, code, sizeof(code));
  
    ((void (*) (void))buf)();
  }
  </code></pre>
  
  <pre class="lang-rust prettyprint-override"><code>extern crate mmap;
  
  use mmap::{MapOption, MemoryMap};
  
  unsafe fn reflect(instructions: &amp;[u8]) {
      let map = MemoryMap::new(
          instructions.len(),
          &amp;[
              MapOption::MapAddr(0 as *mut u8),
              MapOption::MapOffset(0),
              MapOption::MapFd(-1),
              MapOption::MapReadable,
              MapOption::MapWritable,
              MapOption::MapExecutable,
              MapOption::MapNonStandardFlags(libc::MAP_ANON),
              MapOption::MapNonStandardFlags(libc::MAP_PRIVATE),
          ],
      )
      .unwrap();
  
      std::ptr::copy(instructions.as_ptr(), map.data(), instructions.len());
      // How to cast into extern "C" fn() ?
  }
  </code></pre>