Skip to content
This repository has been archived by the owner on Dec 22, 2024. It is now read-only.

Commit

Permalink
mapped_file: Fix *nix file accesses
Browse files Browse the repository at this point in the history
mmap was failing due to missing either MAP_SHARED or MAP_PRIVATE flags.

Once I had that figured out and enabled submodules, open would fail due to lacking open file limits. The error is now visible here for diagnosis.
  • Loading branch information
lat9nq committed Apr 1, 2024
1 parent 76be900 commit 94338e7
Showing 1 changed file with 7 additions and 4 deletions.
11 changes: 7 additions & 4 deletions source/mapped_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#define NOMINMAX
#include <Windows.h>
#else
#include <cerrno>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
Expand All @@ -40,14 +41,16 @@ mapped_file::mapped_file(const std::filesystem::path& path) : _path(path)
throw std::runtime_error("MapViewOfFile failed.");
}
#else
_file.reset(reinterpret_cast<void*>(open(path.generic_string().c_str(), O_NOATIME | O_RDONLY)), [](void* p) { close(reinterpret_cast<size_t>(p)); });
int fd = open(path.generic_string().c_str(), O_NOATIME | O_RDONLY);
int err = errno;
_file.reset(reinterpret_cast<void*>(fd), [](void* p) { close(reinterpret_cast<size_t>(p)); });
if (reinterpret_cast<size_t>(_file.get()) == -1) {
throw std::runtime_error("open failed.");
throw std::runtime_error(std::string{"open failed: "} + std::to_string(err));
}

size_t size = std::filesystem::file_size(path);
_map.reset(reinterpret_cast<void*>(mmap(nullptr, size, PROT_READ, MAP_NORESERVE, reinterpret_cast<size_t>(_file.get()), 0)), [&size](void* p) { munmap(p, size); });
if (!_map) {
_map.reset(reinterpret_cast<void*>(mmap(nullptr, size, PROT_READ, MAP_NORESERVE | MAP_PRIVATE, reinterpret_cast<size_t>(_file.get()), 0)), [&size](void* p) { munmap(p, size); });
if (_map.get() == reinterpret_cast<void*>(-1)) {
throw std::runtime_error("mmap failed.");
}

Expand Down

0 comments on commit 94338e7

Please sign in to comment.