MappedFile.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/MappedFile.h>
  7. #include <AK/ScopeGuard.h>
  8. #include <AK/String.h>
  9. #include <errno.h>
  10. #include <fcntl.h>
  11. #include <sys/mman.h>
  12. #include <sys/stat.h>
  13. #include <unistd.h>
  14. namespace AK {
  15. Result<NonnullRefPtr<MappedFile>, OSError> MappedFile::map(const String& path)
  16. {
  17. int fd = open(path.characters(), O_RDONLY | O_CLOEXEC, 0);
  18. if (fd < 0)
  19. return OSError(errno);
  20. ScopeGuard fd_close_guard = [fd] {
  21. close(fd);
  22. };
  23. struct stat st;
  24. if (fstat(fd, &st) < 0) {
  25. auto saved_errno = errno;
  26. return OSError(saved_errno);
  27. }
  28. auto size = st.st_size;
  29. auto* ptr = mmap(nullptr, size, PROT_READ, MAP_SHARED, fd, 0);
  30. if (ptr == MAP_FAILED)
  31. return OSError(errno);
  32. return adopt_ref(*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 rc = munmap(m_data, m_size);
  42. VERIFY(rc == 0);
  43. }
  44. }