我怎样才能保护linux中的堆内存?

tub*_*ban 7 c++ linux memory-management

我想以堆内存的方式进行只读.对于我曾尝试与memalign()mprotect()来自memalignment我什么都能搞定,memalign可分配内存从进程堆离开.但是.

我想让堆的一部分只读.对此有何帮助?

malloc()->mmap()->mprotect() 一个假设的想法,但不确定这是否有帮助...上面要实现的任何示例代码?

我需要保护堆内的内存地址.使用malloc()我得到0x10012008附近的地址,而使用mmap()它是0xf7ec9000.我的意图是使堆-meory的一部分只被读取以捕获可能试图通过该堆运行的任何trampler.

tim*_*mos 4

是的,mmap 和 mprotect 是正确的函数。我不明白你当前的方法有什么问题,即你的意思是“我已经尝试使用 memalign() 和 mprotect()。但是从 memalignment 中我能得到什么,memalign 从进程堆中分配内存”。

下面是如何创建写保护内存区域的示例:

#include <fcntl.h>  
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

static int alloc_size;
static char* memory;

void segv_handler (int signal_number)  {
 printf ("memory accessed!\n");
 mprotect (memory, alloc_size, PROT_READ | PROT_WRITE);
} 

int main () {
 int fd;
 struct sigaction sa;

 /* Install segv_handler as the handler for SIGSEGV. */
 memset (&sa, 0, sizeof (sa));
  sa.sa_handler = &segv_handler;
 sigaction (SIGSEGV, &sa, NULL);

 /* Allocate one page of memory by mapping /dev/zero. Map the memory
 as write-only, initially. */
  alloc_size = getpagesize ();
 fd = open ("/dev/zero", O_RDONLY);
  memory = mmap (NULL, alloc_size, PROT_WRITE, MAP_PRIVATE, fd, 0);
  close (fd);
  /* Write to the page to obtain a private copy. */
  memory[0] = 0;
 /* Make the memory unwritable. */
  mprotect (memory, alloc_size, PROT_NONE);

 /* Write to the allocated memory region. */
 memory[0] = 1;

  /* All done; unmap the memory. */
 printf ("all done\n");
 munmap (memory, alloc_size);
 return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 我可以建议使用“MAP_ANONYMOUS”并避免整个“fopen()”等怪异吗? (5认同)
  • 小挑剔:“printf”不是[异步安全](https://www.securecoding.cert.org/confluence/display/seccode/SIG30-C.+Call+only+asynchronous-safe+functions+within+signal +处理程序) (4认同)