MappedFile.cpp 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 <LibCore/File.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<NonnullOwnPtr<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<NonnullOwnPtr<MappedFile>> MappedFile::map_from_file(NonnullOwnPtr<Core::File> stream, StringView path)
  20. {
  21. return map_from_fd_and_close(stream->leak_fd(Badge<MappedFile> {}), path);
  22. }
  23. ErrorOr<NonnullOwnPtr<MappedFile>> MappedFile::map_from_fd_and_close(int fd, [[maybe_unused]] StringView 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 = TRY(Core::System::mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0, 0, path));
  32. return adopt_own(*new MappedFile(ptr, size));
  33. }
  34. MappedFile::MappedFile(void* ptr, size_t size)
  35. : m_data(ptr)
  36. , m_size(size)
  37. {
  38. }
  39. MappedFile::~MappedFile()
  40. {
  41. auto res = Core::System::munmap(m_data, m_size);
  42. if (res.is_error())
  43. dbgln("Failed to unmap MappedFile (@ {:p}): {}", m_data, res.error());
  44. }
  45. }