Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c - mmap: Operation not permitted

I am trying to use mmap in user space to read the physical memory where 'mem_map' starts. It's an array that contains all the physical pages. This is a i386 machine running 3.0 kernel.

The code is like this:

....

//define page size
//
#define PAGE_SIZE 0x1000 //4096 bytes
#define PAGE_MASK (PAGE_SIZE - 1)

....

  /* open /dev/mem file*/
  if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) {
        printf("/dev/mem could not be opened.
");
    perror("open");
        exit(1);
  } else {
    printf("/dev/mem opened.
");
  }

  /* Map one page */
  printf(" mem_map is at physical addr: 0x%x
", mem_map_phy_addr);

  map_base = mmap(0, PAGE_SIZE, PROT_READ, MAP_SHARED, fd, (mem_map_phy_addr & ~PAGE_MASK)); //mem_map_phy_addr is at 0x356f2000

  if(map_base == (void *) -1) {
    printf("Memory map failed. err num = %d
",errno);
    perror("mmap"); //failed here
  } else {
    printf("Memory mapped at address %p.
", map_base);
  }

I ran this as a root. The output is:

/dev/mem opened.
 mem_map is at physical addr: 0x356f2000
Memory map failed. err num = 1
mmap: Operation not permitted

To be sure, I googled the problem and added the following line to my /etc/sysctl.conf file:

vm.mmap_min_addr = 0

But this doesn't work either.

Anyone knows why mem_map operation like this is not permitted and how I can get around it?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like the kernel has been compiled with CONFIG_STRICT_DEVMEM enabled. This is a security feature to prevent user space access to (possibly sensitive) physical memory above 1MB (IIRC). You might be able to disable this with sysctl dev.mem.restricted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...