Stay Hungry.Stay Foolish.
linux系统调用mprotect控制内存访问

使用

#include <stdlib.h>
#include <errno.h>
#include <sys/mman.h>
#include <stdio.h>

#ifndef PAGESIZE
#define PAGESIZE 4096
#endif

int
main(void)
{
    char *p;
    char c;

    /* Allocate a buffer; it will have the default
       protection of PROT_READ|PROT_WRITE. */
    p = malloc(1024+PAGESIZE-1);
    if (!p) {
        perror("Couldn’t malloc(1024)");
        exit(errno);
    }

    /* Align to a multiple of PAGESIZE, assumed to be a power of two */
    p = (char *)(((int) p + PAGESIZE) & ~(PAGESIZE - 1));

    c = p[666];         /* Read; ok */
    p[666] = 42;        /* Write; ok */

    /* Mark the buffer read-only. */
    if (mprotect(p, 1024, PROT_READ)) {
        perror("Couldn’t mprotect");
        exit(errno);
    }
    c = p[666];         /* Read; ok */
    p[666] = 42;        /* Write; program dies on SIGSEGV */

    exit(0);
}

其中的

p = (char *)(((int) p + PAGESIZE) & ~(PAGESIZE - 1)); 

比较难以理解,目的是使得到的内存地址是PAGESIZE的倍数。

自由转载-非商用-非衍生-保持署名(创意共享3.0许可证
评论
2016-11-18 11:38:23

记得这个域名是sky的自留地~现在变了咩?

2016-11-18 14:35:23

@xema sky自留地www.03sec.com