lightningbolt/lib/base/MmapFile.linux.cpp

67 lines
1.3 KiB
C++
Raw Normal View History

// Copyright 2023 The LightningBolt Authors
// SPDX-License-Identifier: MIT
#include "MmapFile.hpp"
#include <fcntl.h>
#include <sys/file.h>
#include <sys/mman.h>
namespace lightningbolt {
struct MmapFile::Impl {
2023-11-19 20:24:40 -05:00
~Impl() {
Close();
}
2023-11-19 20:24:40 -05:00
void Close() {
if(mapping) {
munmap(mapping, mappingSize);
mapping = nullptr;
mappingSize = 0;
}
}
2023-11-19 20:24:40 -05:00
ErrorOr<void> Open(const fs::path& path) {
int fd = open(path.string().c_str(), O_RDONLY);
2023-11-19 20:24:40 -05:00
// Error opening file.
if(fd == -1)
return std::error_code{errno, std::system_category()};
2023-11-19 20:24:40 -05:00
{
auto last = lseek64(fd, 0, SEEK_END);
mappingSize = lseek64(fd, 0, SEEK_CUR);
lseek64(fd, last, SEEK_SET);
}
2023-11-19 20:24:40 -05:00
mapping = static_cast<u8*>(mmap(nullptr, mappingSize, PROT_READ, MAP_PRIVATE, fd, 0));
if(mapping == static_cast<u8*>(MAP_FAILED)) {
mappingSize = 0;
return std::error_code{errno, std::system_category()};
}
2023-11-19 20:24:40 -05:00
// Once the mapping has successfully been created
// we can close the file descriptor instead of needing
// to remember it (the kernel will do so for us.)
close(fd);
2023-11-19 20:24:40 -05:00
// No error.
return {};
}
2023-11-19 20:24:40 -05:00
u8* GetMapping() const {
return mapping;
}
2023-11-19 20:24:40 -05:00
usize GetMappingSize() const {
return mappingSize;
}
2023-11-19 20:24:40 -05:00
private:
u8* mapping;
usize mappingSize;
};
2023-11-19 20:24:40 -05:00
} // namespace lightningbolt