首页 > 解决方案 > 如何在 Windows 中使用 sys 标头(或找到它们的 MSVC 对应标头)?

问题描述

我正在学习如何构建 JIT 编译器并偶然发现了一段代码(附在下面):

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


// Allocates RWX memory of given size and returns a pointer to it. On failure,
// prints out the error and returns NULL.
void* alloc_executable_memory(size_t size) {
  void* ptr = mmap(0, size,
                   PROT_READ | PROT_WRITE | PROT_EXEC,
                   MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (ptr == (void*)-1) {
    perror("mmap");
    return NULL;
  }
  return ptr;
}

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

const size_t SIZE = 1024;
typedef long (*JittedFunc)(long);

// Allocates RWX memory directly.
void run_from_rwx() {
  void* m = alloc_executable_memory(SIZE);
  emit_code_into_memory(m);

  JittedFunc func = m;
  int result = func(2);
  printf("result = %d\n", result);
}

现在,在我的终端上乱扔错误消息之前,我在 MSDN 上搜索了这些功能,令我惊讶的是,它们都没有出现。这些显然是在 Windows 中不可用的 POSIX 头文件。我的问题是这些标头的 MSVC 替代品是否存在?

我已经安装了 Cygwin,但我得到 header not found 错误。

标签: c++visual-c++mingwjit

解决方案


推荐阅读