MappedFile.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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 <fcntl.h>
  11. #include <sys/mman.h>
  12. #include <unistd.h>
  13. namespace Core {
  14. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map(StringView path)
  15. {
  16. auto fd = TRY(Core::System::open(path, O_RDONLY | O_CLOEXEC, 0));
  17. return map_from_fd_and_close(fd, path);
  18. }
  19. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map_from_fd_and_close(int fd, [[maybe_unused]] StringView path)
  20. {
  21. TRY(Core::System::fcntl(fd, F_SETFD, FD_CLOEXEC));
  22. ScopeGuard fd_close_guard = [fd] {
  23. close(fd);
  24. };
  25. auto stat = TRY(Core::System::fstat(fd));
  26. auto size = stat.st_size;
  27. auto* ptr = TRY(Core::System::mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0, 0, path));
  28. return adopt_ref(*new MappedFile(ptr, size));
  29. }
  30. MappedFile::MappedFile(void* ptr, size_t size)
  31. : m_data(ptr)
  32. , m_size(size)
  33. {
  34. }
  35. MappedFile::~MappedFile()
  36. {
  37. auto res = Core::System::munmap(m_data, m_size);
  38. if (res.is_error())
  39. dbgln("Failed to unmap MappedFile (@ {:p}): {}", m_data, res.error());
  40. }
  41. }