Skip to content

Commit

Permalink
fix: Crash on linux when opened file gets modified (#487)
Browse files Browse the repository at this point in the history
  • Loading branch information
PredatorCZ authored Apr 17, 2022
1 parent 6ee71e3 commit 202a02a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ namespace hex::plugin::builtin::prv {
void readRaw(u64 offset, void *buffer, size_t size) override;
void writeRaw(u64 offset, const void *buffer, size_t size) override;
[[nodiscard]] size_t getActualSize() const override;
[[nodiscard]] size_t getRealTimeSize();

void save() override;
void saveAs(const std::fs::path &path) override;
Expand Down
22 changes: 18 additions & 4 deletions plugins/builtin/source/content/providers/file_provider.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ namespace hex::plugin::builtin::prv {
}

void FileProvider::readRaw(u64 offset, void *buffer, size_t size) {
if ((offset + size) > this->getActualSize() || buffer == nullptr || size == 0)
if ((offset + size) > this->getRealTimeSize() || buffer == nullptr || size == 0)
return;

std::memcpy(buffer, reinterpret_cast<u8 *>(this->m_mappedFile) + offset, size);
Expand Down Expand Up @@ -135,6 +135,20 @@ namespace hex::plugin::builtin::prv {
Provider::insert(offset, size);
}

size_t FileProvider::getRealTimeSize() {
#if defined(OS_LINUX)
if (struct stat newStats; (this->m_fileStatsValid = fstat(this->m_file, &newStats) == 0)) {
if (static_cast<off_t>(this->m_fileSize) != newStats.st_size ||
std::memcmp(&newStats.st_mtim, &this->m_fileStats.st_mtim, sizeof(newStats.st_mtim))) {
this->m_fileStats = newStats;
this->m_fileSize = this->m_fileStats.st_size;
msync(this->m_mappedFile, this->m_fileStats.st_size, MS_INVALIDATE);
}
}
#endif
return getActualSize();
}

size_t FileProvider::getActualSize() const {
return this->m_fileSize;
}
Expand Down Expand Up @@ -171,7 +185,7 @@ namespace hex::plugin::builtin::prv {

this->m_fileStatsValid = wstat(path.c_str(), &this->m_fileStats) == 0;

LARGE_INTEGER fileSize = { };
LARGE_INTEGER fileSize = {};
this->m_file = reinterpret_cast<HANDLE>(CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));

GetFileSizeEx(this->m_file, &fileSize);
Expand Down Expand Up @@ -236,10 +250,10 @@ namespace hex::plugin::builtin::prv {
fileCleanup.release();

#else
const auto &path = this->m_path.native();
const auto &path = this->m_path.native();
this->m_fileStatsValid = stat(path.c_str(), &this->m_fileStats) == 0;

int mmapprot = PROT_READ | PROT_WRITE;
int mmapprot = PROT_READ | PROT_WRITE;

this->m_file = ::open(path.c_str(), O_RDWR);
if (this->m_file == -1) {
Expand Down

0 comments on commit 202a02a

Please sign in to comment.