gpt4 book ai didi

c++ - 如何保护 Linux 中的堆内存?

转载 作者:IT王子 更新时间:2023-10-29 00:32:35 37 4
gpt4 key购买 nike

我想将一 block 堆内存设为只读。为此,我尝试使用 memalign()mprotect()。但是从 memalignment 我能得到什么,memalign 从进程堆中分配内存。

我想将堆的某些部分设置为只读。有什么帮助吗?

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

我需要保护堆内的内存地址。使用 malloc() 我得到大约 0x10012008 的地址,而使用 mmap() 它是 0xf7ec9000。我的目的是让堆内存的一部分只读以捕获任何可能试图穿过该堆的践踏者。

最佳答案

是的,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;
}

关于c++ - 如何保护 Linux 中的堆内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11142951/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com