From 719763dfcb427af70a140767f4c76f055cb50d73 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Wed, 15 May 2024 22:16:50 +0100 Subject: [PATCH] Codechange: Store start and end position in RandomAccessFile. This allows callers to do more bounds checking. --- src/random_access_file.cpp | 16 +++++++++++++++- src/random_access_file_type.h | 5 +++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/src/random_access_file.cpp b/src/random_access_file.cpp index 29764521ed28e..e949ca865b5a9 100644 --- a/src/random_access_file.cpp +++ b/src/random_access_file.cpp @@ -24,13 +24,18 @@ */ RandomAccessFile::RandomAccessFile(const std::string &filename, Subdirectory subdir) : filename(filename) { - this->file_handle = FioFOpenFile(filename, "rb", subdir); + size_t file_size; + this->file_handle = FioFOpenFile(filename, "rb", subdir, &file_size); if (this->file_handle == nullptr) UserError("Cannot open file '{}'", filename); /* When files are in a tar-file, the begin of the file might not be at 0. */ long pos = ftell(this->file_handle); if (pos < 0) UserError("Cannot read file '{}'", filename); + /* Make a note of start and end position for readers who check bounds. */ + this->start_pos = pos; + this->end_pos = this->start_pos + file_size; + /* Store the filename without path and extension */ auto t = filename.rfind(PATHSEPCHAR); std::string name_without_path = filename.substr(t != std::string::npos ? t + 1 : 0); @@ -76,6 +81,15 @@ size_t RandomAccessFile::GetPos() const return this->pos + (this->buffer - this->buffer_end); } +/** + * Test if we have reached the end of the file. + * @return True iff the current position as at or after the end of the file. + */ +bool RandomAccessFile::AtEndOfFile() const +{ + return this->GetPos() >= this->GetEndPos(); +} + /** * Seek in the current file. * @param pos New position. diff --git a/src/random_access_file_type.h b/src/random_access_file_type.h index 38b414824754d..600e89007fcf7 100644 --- a/src/random_access_file_type.h +++ b/src/random_access_file_type.h @@ -28,6 +28,8 @@ class RandomAccessFile { FILE *file_handle; ///< File handle of the open file. size_t pos; ///< Position in the file of the end of the read buffer. + size_t start_pos; ///< Start position of file. May be non-zero if file is within a tar file. + size_t end_pos; ///< End position of file. uint8_t *buffer; ///< Current position within the local buffer. uint8_t *buffer_end; ///< Last valid byte of buffer. @@ -44,7 +46,10 @@ class RandomAccessFile { const std::string &GetSimplifiedFilename() const; size_t GetPos() const; + size_t GetStartPos() const { return this->start_pos; } + size_t GetEndPos() const { return this->end_pos; } void SeekTo(size_t pos, int mode); + bool AtEndOfFile() const; uint8_t ReadByte(); uint16_t ReadWord();