#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的倍数。
评论
记得这个域名是sky的自留地~现在变了咩?
@xema sky自留地www.03sec.com