在动态分配的内存上调用mprotect导致错误,错误代码为EACCES

时间:2018-01-05 01:40:57

标签: c linux mprotect

在C课程中听到它后,我一直在尝试使用自修改代码。我有一个函数,它使用mprotect为一段内存设置内存保护:

int SetMemoryProtections(void* addr, size_t length, int protection_flag)
{
  size_t addr_as_int = (size_t)(byte*)addr;
  size_t page_size = getpagesize();
  //Address must be multiple of system page size
  size_t aligned_addr_as_int = (addr_as_int / page_size) * page_size;
  size_t additional_length = addr_as_int - aligned_addr_as_int;
  void* aligned_addr = (byte*)addr - additional_length;
  if(mprotect(aligned_addr, length + additional_length, protection_flag))
  {
    return -1;
  }
  else
  {
    return 0;
  }
}

然而,当我尝试在我的动态分配内存块上调用它时,出现错误代码EACCES的错误。为什么会发生这种情况,有什么方法可以解决这个问题吗?在堆栈上分配f_data_buffer时,没有错误消息(表示注释掉的行)。

代码致电SetMemoryProtections

//byte f_data_buffer[16384];//Converts function pointer to byte pointer
byte* f_data_buffer = malloc(sizeof(byte) * getpagesize() * 3);
byte* f_data = f_data_buffer + getpagesize();
if(SetMemoryProtections(f_data, 20, PROT_READ | PROT_WRITE | PROT_EXEC))
{
  printf("SetMemoryProtections encountered error. Error code: ");
  switch(errno)
  {
    case EACCES: printf("EACCES"); break;
    case EINVAL: printf("EINVAL"); break;
    case ENOMEM: printf("ENOMEM"); break;
  }
  printf("\n");
  return -1;
}

更新:我重写了代码,它在调用printf之前读取了errno。 (它创建一个名为err的局部变量,将err设置为errno,然后使用err调用开关)并获得相同的EACCES错误代码。

0 个答案:

没有答案
相关问题