MappedFile.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedString.h>
  7. #include <AK/ScopeGuard.h>
  8. #include <LibCore/File.h>
  9. #include <LibCore/MappedFile.h>
  10. #include <LibCore/System.h>
  11. #include <fcntl.h>
  12. #include <sys/mman.h>
  13. #include <unistd.h>
  14. namespace Core {
  15. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map(StringView path)
  16. {
  17. auto fd = TRY(Core::System::open(path, O_RDONLY | O_CLOEXEC, 0));
  18. return map_from_fd_and_close(fd, path);
  19. }
  20. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map_from_file(NonnullOwnPtr<Core::File> stream, StringView path)
  21. {
  22. return map_from_fd_and_close(stream->leak_fd(Badge<MappedFile> {}), path);
  23. }
  24. ErrorOr<NonnullRefPtr<MappedFile>> MappedFile::map_from_fd_and_close(int fd, [[maybe_unused]] StringView path)
  25. {
  26. TRY(Core::System::fcntl(fd, F_SETFD, FD_CLOEXEC));
  27. ScopeGuard fd_close_guard = [fd] {
  28. close(fd);
  29. };
  30. auto stat = TRY(Core::System::fstat(fd));
  31. auto size = stat.st_size;
  32. auto* ptr = TRY(Core::System::mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0, 0, path));
  33. return adopt_ref(*new MappedFile(ptr, size));
  34. }
  35. MappedFile::MappedFile(void* ptr, size_t size)
  36. : m_data(ptr)
  37. , m_size(size)
  38. {
  39. }
  40. MappedFile::~MappedFile()
  41. {
  42. auto res = Core::System::munmap(m_data, m_size);
  43. if (res.is_error())
  44. dbgln("Failed to unmap MappedFile (@ {:p}): {}", m_data, res.error());
  45. }
  46. }