Files
2026-11-03 20:29:35 +07:00

157 lines
5.4 KiB
C++

// filemap.cpp — реализация mmap-обёртки (POSIX / Windows).
#ifndef _WIN32
# ifndef _DEFAULT_SOURCE
# define _DEFAULT_SOURCE // mincore/munlock в glibc
# endif
#endif
#include "filemap.h"
#include "platform.h"
#include <cstdio>
#include <cstring>
#include <vector>
#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else
# include <fcntl.h>
# include <sys/mman.h>
# include <sys/stat.h>
# include <unistd.h>
# include <cerrno>
#endif
namespace xt {
MappedFile::~MappedFile() { close(); }
MappedFile::MappedFile(MappedFile&& o) noexcept
: addr_(o.addr_), size_(o.size_), path_(std::move(o.path_)), fd_(o.fd_),
file_handle_(o.file_handle_), mapping_handle_(o.mapping_handle_), mlocked_(o.mlocked_) {
o.addr_ = nullptr; o.size_ = 0; o.fd_ = -1;
o.file_handle_ = nullptr; o.mapping_handle_ = nullptr; o.mlocked_ = false;
}
MappedFile& MappedFile::operator=(MappedFile&& o) noexcept {
if (this != &o) {
close();
addr_ = o.addr_; size_ = o.size_; path_ = std::move(o.path_); fd_ = o.fd_;
file_handle_ = o.file_handle_; mapping_handle_ = o.mapping_handle_; mlocked_ = o.mlocked_;
o.addr_ = nullptr; o.size_ = 0; o.fd_ = -1;
o.file_handle_ = nullptr; o.mapping_handle_ = nullptr; o.mlocked_ = false;
}
return *this;
}
bool MappedFile::open(const std::string& path, bool mlock, std::string* err) {
close();
auto fail = [&](const std::string& m) {
if (err) *err = m;
close();
return false;
};
#ifdef _WIN32
// W-версии: путь модели может содержать кириллицу (CreateFileA прочитал бы
// его в ANSI и не нашёл файл).
const std::filesystem::path wp = path_from_utf8(path);
HANDLE fh = CreateFileW(wp.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if (fh == INVALID_HANDLE_VALUE)
return fail("не удалось открыть файл: " + path);
LARGE_INTEGER sz;
if (!GetFileSizeEx(fh, &sz) || sz.QuadPart <= 0) {
CloseHandle(fh);
return fail("пустой или недоступный файл: " + path);
}
HANDLE mh = CreateFileMappingW(fh, nullptr, PAGE_READONLY, 0, 0, nullptr);
if (!mh) { CloseHandle(fh); return fail("CreateFileMapping не удался: " + path); }
void* p = MapViewOfFile(mh, FILE_MAP_COPY, 0, 0, 0); // COPY = приватные COW-страницы
if (!p) {
CloseHandle(mh); CloseHandle(fh);
return fail("MapViewOfFile не удался: " + path);
}
file_handle_ = fh; mapping_handle_ = mh;
addr_ = p; size_ = (size_t)sz.QuadPart; path_ = path;
if (mlock) {
// Windows: VirtualLock держит страницы в рабочем наборе (в пределах квоты)
mlocked_ = VirtualLock(p, (SIZE_T)sz.QuadPart) ? true : false;
if (!mlocked_ && err) *err = "предупреждение: VirtualLock не сработал (не хватает квоты)";
}
return true;
#else
struct stat sb{};
if (::stat(path.c_str(), &sb) != 0)
return fail(std::string("stat: ") + std::strerror(errno) + ": " + path);
if (sb.st_size <= 0)
return fail("пустой файл: " + path);
const int fd = ::open(path.c_str(), O_RDONLY);
if (fd < 0)
return fail(std::string("open: ") + std::strerror(errno) + ": " + path);
// MAP_PRIVATE: файл не меняется, запись в страницы — copy-on-write.
void* p = ::mmap(nullptr, (size_t)sb.st_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE, fd, 0);
if (p == MAP_FAILED) {
const int e = errno;
::close(fd);
return fail(std::string("mmap: ") + std::strerror(e) + ": " + path);
}
addr_ = p; size_ = (size_t)sb.st_size; fd_ = fd; path_ = path;
if (mlock) {
mlocked_ = (::mlock(p, size_) == 0);
if (!mlocked_ && err) *err = "предупреждение: mlock не сработал (не хватает лимитов)";
}
return true;
#endif
}
void MappedFile::close() {
#ifdef _WIN32
if (addr_) {
if (mlocked_) VirtualUnlock(addr_, size_);
UnmapViewOfFile(addr_);
}
if (mapping_handle_) CloseHandle(mapping_handle_);
if (file_handle_) CloseHandle(file_handle_);
file_handle_ = nullptr; mapping_handle_ = nullptr;
#else
if (addr_) {
if (mlocked_) ::munlock(addr_, size_);
::munmap(addr_, size_);
}
if (fd_ >= 0) ::close(fd_);
fd_ = -1;
#endif
(void)mlocked_;
addr_ = nullptr; size_ = 0; mlocked_ = false; path_.clear();
}
void MappedFile::advise_sequential() const {
#ifndef _WIN32
if (addr_) ::madvise(addr_, size_, MADV_SEQUENTIAL);
#endif
// Windows: предвыборка и так выполняется диспетчером памяти
}
size_t MappedFile::resident_bytes() const {
if (!addr_) return 0;
#ifndef _WIN32
// mincore: сколько страниц сейчас в памяти
const size_t page = 4096;
const size_t npages = (size_ + page - 1) / page;
std::vector<unsigned char> vec(npages);
if (::mincore(addr_, size_, vec.data()) != 0) return 0;
size_t n = 0;
for (unsigned char c : vec) if (c & 1) ++n;
return n * page;
#else
return size_; // без PSAPI точнее не скажем
#endif
}
} // namespace xt