Skip to content

Commit 13997d2

Browse files
committed
add header synchronisation for shrinked files
1 parent 0d5fa4a commit 13997d2

2 files changed

Lines changed: 21 additions & 1 deletion

File tree

cpp/MMapEncryptedFile.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
struct EncryptedFileHeader {
1111
uint16_t magic;
1212
uint16_t version;
13-
uint64_t size;
13+
volatile uint64_t size;
1414
uint8_t encryptedDataKey[16];
1515
uint8_t iv[16];
1616
uint16_t keyHash;
@@ -147,6 +147,7 @@ class MMapEncryptedFile
147147
if (newSize < size()) {
148148
// the order is important here to avoid inconsistencies
149149
reinterpret_cast<EncryptedFileHeader*>(file_.data())->size = FixEndianness((uint64_t)newSize);
150+
file_.sync(0, sizeof(EncryptedFileHeader));
150151
file_.resize(newSize + sizeof(EncryptedFileHeader), strictResize);
151152
} else {
152153
// the order is important here to avoid inconsistencies

cpp/MMapFile.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,25 @@ class MMapFile {
284284
inline bool readOnly() const { return readOnly_; }
285285
inline bool isOpen() const { return fd_ >= 0; }
286286

287+
inline void sync(size_t offset, size_t length) {
288+
if (length == 0) [[unlikely]] {
289+
return; // Nothing to sync
290+
}
291+
assertFileIsOpen();
292+
293+
// compute page-aligned offset and length
294+
size_t pageSize = sysconf(_SC_PAGE_SIZE);
295+
size_t alignedOffset = offset - (offset % pageSize);
296+
length += (offset - alignedOffset);
297+
if (alignedOffset + length > size_) [[unlikely]] {
298+
length = size_ - alignedOffset; // Adjust length to not exceed the size of the file
299+
}
300+
301+
if (msync(data_ + alignedOffset, length, MS_SYNC) == -1) [[unlikely]] {
302+
throw std::runtime_error("Failed to sync memory-mapped file: " + std::string(strerror(errno)));
303+
}
304+
}
305+
287306
inline void assertFileIsOpen() const {
288307
if (fd_ < 0) [[unlikely]] {
289308
throw std::runtime_error("File is not open");

0 commit comments

Comments
 (0)