sys_mman.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <sys/mman.h>
  4. #include <unistd.h>
  5. #include "test_helpers.h"
  6. int main() {
  7. int page_size = getpagesize();
  8. printf("Page size: %d\n", page_size);
  9. puts("Mapping 1 page of memory...");
  10. char *map1 = mmap((void *) 0x200000000, (size_t) page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
  11. puts("Mapping 3 pages of memory...");
  12. char *map2 = mmap(map1 + page_size, (size_t) page_size * 3, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE, -1, 0);
  13. ERROR_IF(mmap, map1, == MAP_FAILED);
  14. ERROR_IF(mmap, map2, == MAP_FAILED);
  15. puts("Randomizing mapping #1");
  16. for (int i = 0; i < page_size; ++i) {
  17. map1[i] = (char) (rand() & 0xFF);
  18. }
  19. puts("Randomizing mapping #2");
  20. for (int i = 0; i < page_size * 3; ++i) {
  21. map2[i] = (char) (rand() & 0xFF);
  22. }
  23. puts("Unmapping page 2 of map2");
  24. munmap(map2 + page_size, page_size);
  25. puts("Randomizing page 1 of mapping #2");
  26. for (int i = 0; i < page_size; ++i) {
  27. map2[i] = (char) (rand() % 256);
  28. }
  29. puts("Randomizing page 3 of mapping #2");
  30. for (int i = 0; i < page_size; ++i) {
  31. map2[page_size * 2 + i] = (char) (rand() % 256);
  32. }
  33. // Page fault:
  34. // map2[page_size] = 0;
  35. puts("Unmapping it all at once!");
  36. munmap(map1, (size_t) page_size * 4);
  37. // Page fault:
  38. // *map2 = 0;
  39. }