memalign 和 mprotect用法

2019-08-15  本文已影响0人  ebayboy

#include <unistd.h>

#include <signal.h>

#include <stdio.h>

#include <malloc.h>

#include <stdlib.h>

#include <errno.h>

#include <sys/mman.h>

#include <string.h>

#define handle_error(msg) \

    do { perror(msg); exit(EXIT_FAILURE); } while (0)

char *buffer;

static void handler(int sig, siginfo_t *si, void *unused)

{

    printf("Got SIGSEGV at address: 0x%lx\n", (long) si->si_addr);

    exit(EXIT_FAILURE);

}

int main(int argc, char *argv[])

{

    char *p;

    int pagesize;

    pagesize = sysconf(_SC_PAGE_SIZE);

    if (pagesize == -1)

        handle_error("sysconf");

    size_t len = 8097;

    size_t all_size = pagesize * (len/pagesize + 1);

    printf("allsize:%d\n", all_size);

/* memalign申请的内存是按页面对齐的, 但是按时间长度申请的, 而mproject保护的长度如果不足一页是按一页去保护的, 所以如果memalign申请的内存要是l(en/pagesize + 1)的长度, 以防mproject保护的地址越界*/

 buffer = memalign(pagesize, all_size);

    if (buffer == NULL)

        handle_error("memalign");

    printf("Start of region:        0x%lx\n", (long) buffer);

    strcpy(buffer, "hello world");

    if (mprotect(buffer, len, PROT_READ) == -1)

        handle_error("mprotect");

    //buffer[8191] = '9';

    char *buffer2 = memalign(pagesize, len);

    if (buffer2 == NULL)

        handle_error("memalign");

    buffer2[4] = '8';

    if (mprotect(buffer, len, PROT_READ|PROT_WRITE) == -1) {

        perror("mproject");

    }

    buffer[8191] = '9';

#if 0

    buffer[4] = '9';

    for (p = buffer ; ; )

        *(p++) = 'a';

#endif

    printf("Loop completed\n");    /* Should never happen */

    exit(EXIT_SUCCESS);

}

上一篇 下一篇

猜你喜欢

热点阅读