MappedFile.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/ScopeGuard.h>
  7. #include <AK/String.h>
  8. #include <LibCore/MappedFile.h>
  9. #include <LibCore/System.h>
  10. #include <errno.h>
  11. #include <fcntl.h>
  12. #include <sys/mman.h>
  13. #include <sys/stat.h>
  14. #include <unistd.h>
  15. namespace Core {
  16. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map(String const& path)
  17. {
  18. int fd = open(path.characters(), O_RDONLY | O_CLOEXEC, 0);
  19. if (fd < 0)
  20. return Error::from_errno(errno);
  21. return map_from_fd_and_close(fd, path);
  22. }
  23. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map_from_fd_and_close(int fd, [[maybe_unused]] String const& path)
  24. {
  25. TRY(Core::System::fcntl(fd, F_SETFD, FD_CLOEXEC));
  26. ScopeGuard fd_close_guard = [fd] {
  27. close(fd);
  28. };
  29. auto stat = TRY(Core::System::fstat(fd));
  30. auto size = stat.st_size;
  31. auto* ptr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
  32. if (ptr == MAP_FAILED)
  33. return Error::from_errno(errno);
  34. #ifdef __serenity__
  35. if (set_mmap_name(ptr, size, path.characters()) < 0) {
  36. perror("set_mmap_name");
  37. }
  38. #endif
  39. return adopt_ref(*new MappedFile(ptr, size));
  40. }
  41. MappedFile::MappedFile(void* ptr, size_t size)
  42. : m_data(ptr)
  43. , m_size(size)
  44. {
  45. }
  46. MappedFile::~MappedFile()
  47. {
  48. auto rc = munmap(m_data, m_size);
  49. VERIFY(rc == 0);
  50. }
  51. }