从内存中执行代码

时间:2017-02-09 09:13:08

标签: c memory jit

假设我想在C中进行JIT编译。我反汇编函数并将其代码插入到我的程序中的内存中:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>


void* alloc_executable_memory(size_t size) {

  void *ptr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

  if (ptr == MAP_FAILED) {
      fprintf(stderr, "%s\n", "mmap failed");
      return NULL;
  }

  return ptr;
}

void push_code_into_memory(unsigned char *memory) {
  unsigned char code[] = {
    0x48, 0x89, 0xf8,       // mov %rdi, %rax
    0,48, 0x83, 0xc0, 0x04, // add $4, %rax
    0xc3                    // ret
  };

  memcpy(memory, code, sizeof(code));
}

int make_memory_executable(void* memory, size_t size) {

  if (mprotect(memory, size, PROT_READ | PROT_EXEC) == -1) {
      fprintf(stderr, "%s\n", "mprotect failed");
      return -1;
  }
  return 0;
}

const size_t SIZE = 512;
typedef long (*jitFunc)(long);

int main(int argc, char const *argv[]) {

  void *mem = alloc_executable_memory(SIZE);
  push_code_into_memory((unsigned char *)mem);
  make_memory_executable(mem, SIZE);

  jitFunc foo = (jitFunc)mem;
  int res = foo(2);
  printf("%d\n", res);

  return 0;
}

但是,在调用foo之后,我总是得到段错11(macOS)。这段代码有什么问题?首先,我认为问题出在访问权限上,但标志似乎设置正确。

1 个答案:

答案 0 :(得分:6)

想想我找到了它:

0,48, 0x83, 0xc0, 0x04

应该是

0x48, 0x83, 0xc0, 0x04