next_to_fault.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* Memory allocation next to an unmapped page.
  2. Copyright (C) 2017-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <support/check.h>
  16. #include <support/next_to_fault.h>
  17. #include <support/xunistd.h>
  18. #include <sys/mman.h>
  19. #include <sys/param.h>
  20. struct support_next_to_fault
  21. support_next_to_fault_allocate (size_t size)
  22. {
  23. long page_size = sysconf (_SC_PAGE_SIZE);
  24. TEST_VERIFY_EXIT (page_size > 0);
  25. struct support_next_to_fault result;
  26. result.region_size = roundup (size, page_size) + page_size;
  27. if (size + page_size <= size || result.region_size <= size)
  28. FAIL_EXIT1 ("support_next_to_fault_allocate (%zu): overflow", size);
  29. result.region_start
  30. = xmmap (NULL, result.region_size, PROT_READ | PROT_WRITE,
  31. MAP_PRIVATE | MAP_ANONYMOUS, -1);
  32. /* Unmap the page after the allocation. */
  33. xmprotect (result.region_start + (result.region_size - page_size),
  34. page_size, PROT_NONE);
  35. /* Align the allocation within the region so that it ends just
  36. before the PROT_NONE page. */
  37. result.buffer = result.region_start + result.region_size - page_size - size;
  38. result.length = size;
  39. return result;
  40. }
  41. void
  42. support_next_to_fault_free (struct support_next_to_fault *ntf)
  43. {
  44. xmunmap (ntf->region_start, ntf->region_size);
  45. *ntf = (struct support_next_to_fault) { NULL, };
  46. }