如何分配具有执行权限的内存? [英] How to allocate a memory with execute permissions?
问题描述
我想分配一个具有执行权限的内存.因此,我使用mprotect来更改权限..为了获得页面对齐的内存,我使用了 valloc
函数.
I want to allocate a memory with execute permissions.
So I use mprotect to change the permissions.. To get a page aligned memory I use a valloc
function.
void * temp = (void *) valloc(x);
然后
if( mprotect(temp, BLOCK_SIZE, (PROT_READ | PROT_WRITE |PROT_EXEC))) {
exit(-1);
}
现在,我想向此分配的块添加更多的内存.因此,我使用了 realloc
函数.
Now I want to add more memory to this allocated block. Hence I use a realloc
function.
void * new_temp = (void *) realloc(temp, 1024);
此重新分配会自动将分配的内存的权限更改为我之前设置的权限吗?如果 realloc
将整个块移动到另一个位置,那么较早分配的内存和新分配的内存的权限是什么?
Will this reallocate automatically change the permissions of the allocated memory to the ones I had set earlier ?? In case realloc
moves the entire block to a different location, what be the permissions of allocated memory earlier and the newly allocated memory?
应该再次使用 mprotect
来获取执行权限内存.并且在页面大小边界上是否有 realloc
的API,例如 valloc
.?
Should mprotect
be used again to get execute permissions memory. And is there a API to realloc
on page size boundary like valloc
. ?
推荐答案
尝试使用另一个 valloc
分配一个新区域,并在其中复制旧内容.更好的是,停止使用已弃用的 valloc
,并用 posix_memalign
调用替换,或者直接使用 mmap
进行非常大的分配.使用 mremap
,您可以有效地 realloc
页面对齐的内存区域.
Try allocating a new region with another valloc
, and copying the old contents across. Better yet, stop using the deprecated valloc
, and replace it with either posix_memalign
calls, or directly mmap
for very large allocations. Using mremap
you could effectively realloc
page-aligned memory regions.
这篇关于如何分配具有执行权限的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!