132 auto state = std::make_shared<mapped_file_detail::region>();
134 state->file = ::CreateFileW(path.c_str(), GENERIC_READ,
135 FILE_SHARE_READ | FILE_SHARE_DELETE,
nullptr,
136 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS,
nullptr);
137 if (state->file == INVALID_HANDLE_VALUE)
138 throw std::system_error(
static_cast<int>(::GetLastError()), std::system_category(),
"open mapped file");
139 BY_HANDLE_FILE_INFORMATION info{};
140 if (!::GetFileInformationByHandle(state->file, &info))
141 throw std::system_error(
static_cast<int>(::GetLastError()), std::system_category(),
"inspect mapped file");
142 if (::GetFileType(state->file) != FILE_TYPE_DISK || (info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
143 throw std::invalid_argument(
"mapped file must be a regular file");
144 LARGE_INTEGER
size{};
145 if (!::GetFileSizeEx(state->file, &
size))
146 throw std::system_error(
static_cast<int>(::GetLastError()), std::system_category(),
"size mapped file");
147 if (
size.QuadPart < 0)
throw std::length_error(
"negative mapped file size");
148 state->length =
static_cast<std::uint64_t
>(
size.QuadPart);
152 int flags = O_RDONLY | O_NONBLOCK;
156 state->file =
::open(path.c_str(), flags);
157 if (state->file == -1)
throw std::system_error(errno, std::generic_category(),
"open mapped file");
159 if (::fcntl(state->file, F_SETFD, FD_CLOEXEC) == -1)
160 throw std::system_error(errno, std::generic_category(),
"protect mapped descriptor");
163 if (::fstat(state->file, &info) == -1)
164 throw std::system_error(errno, std::generic_category(),
"inspect mapped file");
165 if (!S_ISREG(info.st_mode))
throw std::invalid_argument(
"mapped file must be a regular file");
166 if (info.st_size < 0)
throw std::length_error(
"negative mapped file size");
167 state->length =
static_cast<std::uint64_t
>(info.st_size);
169 if (state->length > (std::numeric_limits<std::size_t>::max)())
170 throw std::length_error(
"mapped file exceeds addressable span size");
173 state->mapping = ::CreateFileMappingW(state->file,
nullptr, PAGE_READONLY, 0, 0,
nullptr);
175 throw std::system_error(
static_cast<int>(::GetLastError()), std::system_category(),
"create file mapping");
176 state->data = ::MapViewOfFile(state->mapping, FILE_MAP_READ, 0, 0,
static_cast<SIZE_T
>(state->length));
178 throw std::system_error(
static_cast<int>(::GetLastError()), std::system_category(),
"map file view");
180 auto address = ::mmap(
nullptr,
static_cast<std::size_t
>(state->length), PROT_READ, MAP_PRIVATE, state->file, 0);
181 if (address == MAP_FAILED)
throw std::system_error(errno, std::generic_category(),
"map file view");
182 state->data = address;