标签:
malloc_readonly.h
#ifndef _MALLOC_READONLY_H_ #define _MALLOC_READONLY_H_ const void * malloc_readonly(const void * copy_from, unsigned size); #endif
malloc_readonly.c
#include "malloc_readonly.h"
#include <unistd.h>
#include <malloc.h>
#include <string.h>
#include <sys/mman.h>
const void * malloc_readonly(const void * copy_from, unsigned size)
{
    if(size == 0) {
        return NULL;
    }
    int page_size = sysconf(_SC_PAGE_SIZE);
    if(page_size == -1) {
        return NULL;
    }
    unsigned new_size = (size + (page_size - 1)) / page_size * page_size;
    void * buf = memalign(page_size, new_size);
    if(buf == NULL) {
        return NULL;
    }
    (void)memcpy(buf, copy_from, size);
    (void)mprotect(buf, new_size, PROT_READ);
    return buf;
} 
demo.c
#include "malloc_readonly.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
static void catch_sig(int sig, siginfo_t * si, void * unused)
{
    printf("Got SIG%d @ %p\n", sig, si->si_addr);
    exit(1);
}
int main(void)
{
    struct sigaction sa;
    sa.sa_flags = SA_SIGINFO;
    sigemptyset(&sa.sa_mask);
    sa.sa_sigaction = catch_sig;
    sigaction(SIGSEGV, &sa, NULL);
    char * c = (char *)malloc_readonly("123456", 6);
    c[0] = 0;
    free(c);
    return 0;
} 
标签:
原文地址:http://my.oschina.net/2bit/blog/389016