如何保护Linux中的堆内存? [英] how can I protect a heap memory in linux?
问题描述
我想将堆内存块设为只读.为此,我尝试将memalign()
与mprotect()
一起使用.但是,从memalignment可以得到什么,memalign从进程堆中分配内存.
I want to make a chunck of heap memory read-only. For that I have tried with memalign()
with mprotect()
.But from the memalignment what can I get , memalign allocates memory away from the process heap.
我想使堆的某些部分为只读.有什么帮助吗?
I want to make some portion of the heap read-only. Any help on that ?
malloc()->mmap()->mprotect()
是一个假设性的想法,但不确定是否可以帮助...以上要实现的任何示例代码?
malloc()->mmap()->mprotect()
a hypothetical thought , but not sure if that can help ... Any sample code to implement above ?
我需要保护堆中的内存地址.使用malloc()可以得到0x10012008左右的地址,而使用mmap()则可以得到0xf7ec9000的地址.我的意图是使堆内存的一部分只读,以捕获任何可能试图在该堆中运行的流浪汉.
I need to protect the memory address within the heap. with malloc() i get address around 0x10012008 whereas with mmap() it is 0xf7ec9000.My intention is to make a part of heap-meory to be read only to catch any trampler that might try to run through that heap.
推荐答案
是的,mmap和mprotect是正确的功能.我不了解您当前的方法有什么问题,即您的意思是为此,我尝试使用memalign()和mprotect()进行操作.但是从memalignment中我可以得到什么,memalign从进程堆中分配内存" ."
Yes, mmap and mprotect are the right functions. I do not understand what's the problem with your current approch, i.e., what you mean by "For that I have tried with memalign() with mprotect().But from the memalignment what can I get , memalign allocates memory away from the process heap."
下面是一个如何创建写保护存储区的示例:
Below is an example how to create a write-protected memory area:
#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;
}
这篇关于如何保护Linux中的堆内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!