scoped_mmap.cc 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. #include "common-defs.h"
  15. #include "scoped_mmap.h"
  16. #include "scoped_fd.h"
  17. #include "gdbsupport/filestuff.h"
  18. #ifdef HAVE_SYS_MMAN_H
  19. scoped_mmap
  20. mmap_file (const char *filename)
  21. {
  22. scoped_fd fd = gdb_open_cloexec (filename, O_RDONLY, 0);
  23. if (fd.get () < 0)
  24. perror_with_name (("open"));
  25. off_t size = lseek (fd.get (), 0, SEEK_END);
  26. if (size < 0)
  27. perror_with_name (("lseek"));
  28. /* We can't map an empty file. */
  29. if (size == 0)
  30. error (_("file to mmap is empty"));
  31. scoped_mmap mmapped_file (nullptr, size, PROT_READ, MAP_PRIVATE, fd.get (), 0);
  32. if (mmapped_file.get () == MAP_FAILED)
  33. perror_with_name (("mmap"));
  34. return mmapped_file;
  35. }
  36. #endif /* HAVE_SYS_MMAN_H */