mprotect总是返回无效的参数 [英] mprotect always returns invalid arguments

查看:282
本文介绍了mprotect总是返回无效的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用保护修改.text段中的值以使我具有写权限:

I'm trying to modify a value in the .text segment using protect to give me writing access:

 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错误.

mprotect does never work. It always returns an mprotect failed with error:: Invalid argument error.

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

foo is a method that returns an int that is stored 5bytes after the function(thats the reason for foo+5)

推荐答案

我已经在OS X 10.9上执行了以下代码,它似乎具有所需的行为.输出为"foo返回23".

I have executed the following code on OS X 10.9, and it appears to have the desired behavior. The output is "foo returns 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构建的.

For foo, I used this assembly code. Both sources were built with cc -arch i386.

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

您仅应在学习过程中以这种方式修改代码,而不应在任何已部署的应用程序中使用它.

You should modify code this way only as a learning exercise and not use it in any deployed application.

这篇关于mprotect总是返回无效的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆