scoped_mmap.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* scoped_mmap, automatically unmap files
  2. Copyright (C) 2018-2022 Free Software Foundation, Inc.
  3. This file is part of GDB.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program 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
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #ifndef COMMON_SCOPED_MMAP_H
  15. #define COMMON_SCOPED_MMAP_H
  16. #ifdef HAVE_SYS_MMAN_H
  17. #include <sys/mman.h>
  18. /* A smart-pointer-like class to mmap() and automatically munmap() a memory
  19. mapping. */
  20. class scoped_mmap
  21. {
  22. public:
  23. scoped_mmap () noexcept : m_mem (MAP_FAILED), m_length (0) {}
  24. scoped_mmap (void *addr, size_t length, int prot, int flags, int fd,
  25. off_t offset) noexcept : m_length (length)
  26. {
  27. m_mem = mmap (addr, m_length, prot, flags, fd, offset);
  28. }
  29. ~scoped_mmap ()
  30. {
  31. destroy ();
  32. }
  33. scoped_mmap (scoped_mmap &&rhs) noexcept
  34. : m_mem (rhs.m_mem),
  35. m_length (rhs.m_length)
  36. {
  37. rhs.m_mem = MAP_FAILED;
  38. rhs.m_length = 0;
  39. }
  40. DISABLE_COPY_AND_ASSIGN (scoped_mmap);
  41. ATTRIBUTE_UNUSED_RESULT void *release () noexcept
  42. {
  43. void *mem = m_mem;
  44. m_mem = MAP_FAILED;
  45. m_length = 0;
  46. return mem;
  47. }
  48. void reset (void *addr, size_t length, int prot, int flags, int fd,
  49. off_t offset) noexcept
  50. {
  51. destroy ();
  52. m_length = length;
  53. m_mem = mmap (addr, m_length, prot, flags, fd, offset);
  54. }
  55. size_t size () const noexcept { return m_length; }
  56. void *get () const noexcept { return m_mem; }
  57. private:
  58. void destroy ()
  59. {
  60. if (m_mem != MAP_FAILED)
  61. munmap (m_mem, m_length);
  62. }
  63. void *m_mem;
  64. size_t m_length;
  65. };
  66. /* Map FILENAME in memory. Throw an error if anything goes wrong. */
  67. scoped_mmap mmap_file (const char *filename);
  68. #endif /* HAVE_SYS_MMAN_H */
  69. #endif /* COMMON_SCOPED_MMAP_H */