C - why can't mmap small (256UL or less) memory size?

Please tell me why my simple application cannot mmap a small memory size?

And why is such a specific border 257UL?

// #define MAP_SIZE 256UL or below - fail // #define MAP_SIZE 257UL - ok #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <signal.h> #include <fcntl.h> #include <ctype.h> #include <termios.h> #include <sys/types.h> #include <sys/mman.h> #define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \ __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0) #define MAP_SIZE 4096UL #define MAP_MASK (MAP_SIZE - 1) int main(int argc, char **argv) { int fd; void *map_base, *virt_addr; unsigned long read_result, writeval; off_t target = strtoul("0x00002000", 0, 0); if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL; printf("/dev/mem opened.\n"); fflush(stdout); map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~MAP_MASK); if(map_base == (void *) -1) FATAL; printf("Memory mapped at address %p.\n", map_base); fflush(stdout); ... } 
+4
source share
2 answers

mmap works in multiple page sizes on your system. If you do this on i386 / amd64 or in fact on most modern processors, this will be 4096.

The mmap man page on my system says: "the offset must be a multiple of the page size returned by sysconf (_SC_PAGE_SIZE)." On some systems, for historical reasons, the length argument may not be a multiple of the page size, but in any case, mmap will be rounded to the full page.

+2
source

You probably just do not have write permissions to /dev/mem . This is probably not what you need, matching all of the lower-level physical memory in your address space.

Take a look at shm_open to open memory segments or MAP_ANONYMOUS to display anonymously.

Edit:

Make man mem to find out what the /dev/mem node device is:

Byte addresses in memory are interpreted as physical address memory. Links to nonexistent locations cause errors to return.

If you want to map a node device to a memory segment, you should use /dev/zero , but these days the tools described above should be sufficient.

Then, do not do this, do not run such code with root privileges, if you really do not know what you are doing. Writing to physical memory and thus rewriting data and programs from the kernel and user space can only lead to disasters.

+4
source

Source: https://habr.com/ru/post/1438841/


All Articles