mmap2.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /* When trying to map /dev/mem with offset 0xFFFFF000 on the ARM platform, mmap
  2. * returns -EOVERFLOW.
  3. *
  4. * Since off_t is defined as a long int and the sign bit is set in the address,
  5. * the shift operation shifts in ones instead of zeroes
  6. * from the left. This results the offset sent to the kernel function becomes
  7. * 0xFFFFFFFF instead of 0x000FFFFF with MMAP2_PAGE_SHIFT set to 12.
  8. */
  9. #include <unistd.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <errno.h>
  14. #include <fcntl.h>
  15. #include <sys/mman.h>
  16. #define FATAL do { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", \
  17. __LINE__, __FILE__, errno, strerror(errno)); exit(1); } while(0)
  18. #define MAP_SIZE 4096UL
  19. #define MAP_MASK (MAP_SIZE - 1)
  20. int main(int argc, char **argv) {
  21. void* map_base = 0;
  22. int fd;
  23. off_t target = 0xfffff000;
  24. if((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) FATAL;
  25. printf("/dev/mem opened.\n");
  26. fflush(stdout);
  27. /* Map one page */
  28. map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
  29. fd, target & ~MAP_MASK);
  30. if(map_base == (void *) -1) FATAL;
  31. printf("Memory mapped at address %p.\n", map_base);
  32. fflush(stdout);
  33. if(munmap(map_base, MAP_SIZE) == -1) FATAL;
  34. close(fd);
  35. return 0;
  36. }