开发者

Reading memory protection

I would like to know if there is for linux a way of retrieving the protection of the memory. Like, I want to restore the protection that existed after changing it with m开发者_StackOverflow社区protect.


Based on the answer by davidg, here's the function unsigned int read_mprotection(void* addr): re_mprot.c, re_mprot.h from the reDroid project at github (the code works on Android, it should be portable to other linuxes).


The file /proc/self/maps on Linux contains information about the current layout of virtual memory, what each segment is and the memory protection of that segment. Changes made using mprotect will cause the file to be updated appropriately.

By parsing /proc/self/maps before you start modifying it with mprotect, you should have enough information to restore the previous layout.

The following example shows the contents of /proc/self/maps in three scenarios:

  • Prior to any operation being performed;
  • After a mmap (which shows one additional entry in the file); and finally
  • After a mprotect (which shows the permission bits changing in the file).

(Tested with 32-bit Linux 2.6).

#include <sys/mman.h>
#include <stdio.h>
#include <errno.h>
#define PAGE_SIZE 4096

void show_mappings(void)
{
    int a;
    FILE *f = fopen("/proc/self/maps", "r");
    while ((a = fgetc(f)) >= 0)
        putchar(a);
    fclose(f);
    printf("-----------------------------------------------\n");
}

int main(void)
{
    void *mapping;

    /* Show initial mappings. */
    show_mappings();

    /* Map in some pages. */
    mapping = mmap(NULL, 16 * PAGE_SIZE, PROT_READ, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
    printf("*** Returned mapping: %p\n", mapping);
    show_mappings();

    /* Change the mapping. */
    mprotect(mapping, PAGE_SIZE, PROT_READ | PROT_WRITE);
    show_mappings();

    return 0;
}

As far as I know, there is not mechanism other than the /proc/ interface that Linux provides to allow you to determine the layout of your virtual memory. Thus, parsing this file is about the best you can do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜