MappedFile.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2023, kleines Filmröllchen <filmroellchen@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/ScopeGuard.h>
  8. #include <LibCore/File.h>
  9. #include <LibCore/MappedFile.h>
  10. #include <LibCore/System.h>
  11. #include <sys/mman.h>
  12. namespace Core {
  13. ErrorOr<NonnullOwnPtr<MappedFile>> MappedFile::map(StringView path, Mode mode)
  14. {
  15. auto const file_mode = mode == Mode::ReadOnly ? O_RDONLY : O_RDWR;
  16. auto fd = TRY(Core::System::open(path, file_mode | O_CLOEXEC, 0));
  17. return map_from_fd_and_close(fd, path, mode);
  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, Mode mode)
  24. {
  25. ScopeGuard fd_close_guard = [fd] {
  26. (void)System::close(fd);
  27. };
  28. auto stat = TRY(Core::System::fstat(fd));
  29. auto size = stat.st_size;
  30. int protection;
  31. int flags;
  32. switch (mode) {
  33. case Mode::ReadOnly:
  34. protection = PROT_READ;
  35. flags = MAP_SHARED;
  36. break;
  37. case Mode::ReadWrite:
  38. protection = PROT_READ | PROT_WRITE;
  39. // Don't map a read-write mapping shared as a precaution.
  40. flags = MAP_PRIVATE;
  41. break;
  42. }
  43. auto* ptr = TRY(Core::System::mmap(nullptr, size, protection, flags, fd, 0, 0, path));
  44. return adopt_own(*new MappedFile(ptr, size, mode));
  45. }
  46. MappedFile::MappedFile(void* ptr, size_t size, Mode mode)
  47. : FixedMemoryStream(Bytes { ptr, size }, mode)
  48. , m_data(ptr)
  49. , m_size(size)
  50. {
  51. }
  52. MappedFile::~MappedFile()
  53. {
  54. auto res = Core::System::munmap(m_data, m_size);
  55. if (res.is_error())
  56. dbgln("Failed to unmap MappedFile (@ {:p}): {}", m_data, res.error());
  57. }
  58. }