gpt4 book ai didi

c - mprotect 总是返回无效参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:43:12 27 4
gpt4 key购买 nike

我正在尝试使用 protect 修改 .text 段中的值以授予我写入权限:

 int pageSize = sysconf(_SC_PAGE_SIZE);

int *toModify = (int *)(foo+5);
if (mprotect(toModify, pageSize, PROT_WRITE) < 0 ) {
perror("mprotect failed with error:");
return -1;
}
*toModify = 5;
printf("Modify :%i",foo());

mprotect 从不工作。它总是返回一个 mprotect failed with error::Invalid argument 错误。

foo 是一种方法,它返回一个存储在函数后 5 个字节的 int(这就是 foo+5 的原因)

最佳答案

我在 OS X 10.9 上执行了以下代码,它似乎具有所需的行为。输出是“foo 返回 23”。

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>
#include <sys/mman.h>


extern int foo(void);


int main(void)
{
// New value to write into foo+5.
int NewValue = 23;

// Find page size for this system.
size_t pagesize = sysconf(_SC_PAGESIZE);

// Calculate start and end addresses for the write.
uintptr_t start = (uintptr_t) &foo + 5;
uintptr_t end = start + sizeof NewValue;

// Calculate start of page for mprotect.
uintptr_t pagestart = start & -pagesize;

// Change memory protection.
if (mprotect((void *) pagestart, end - pagestart,
PROT_READ | PROT_WRITE | PROT_EXEC))
{
perror("mprotect");
exit(EXIT_FAILURE);
}

// Write new bytes to desired location.
memcpy((void *) start, &NewValue, sizeof NewValue);

// Some systems could require an invalidate of instruction cache here.

// Try modified function.
printf("foo returns %d.\n", foo());

return 0;
}

对于foo,我使用了这个汇编代码。这两个源代码都是使用 cc -arch i386 构建的。

    .globl  _foo
_foo:
nop
nop
nop
nop
mov $42, %eax
ret

您应该仅将这种方式修改代码作为学习练习,而不要在任何已部署的应用程序中使用它。

关于c - mprotect 总是返回无效参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20381812/

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