OpenVINO™ is an open source toolkit for optimizing and deploying AI inference
C++ aicomputer-visiondeep-learningdeploy-aidiffusion-modelsgenerative-aigood-first-issueinferencellm-inferencenatural-language-processingnlpopenvinooptimize-aiperformance-boostrecommendation-systemspeech-recognitionstable-diffusiontransformersyolo
[NPU] Metadata: check the sizes of lengths before allocating buffers (#37198)
Razvan Apetroaiedeaee5d81f2a
diff --git a/src/plugins/intel_npu/src/plugin/include/metadata.hpp b/src/plugins/intel_npu/src/plugin/include/metadata.hppindex e19f1971eab..bcaeca6da24 100644--- a/src/plugins/intel_npu/src/plugin/include/metadata.hpp+++ b/src/plugins/intel_npu/src/plugin/include/metadata.hpp@@ -24,14 +24,13 @@ class MetadataBase {public:MetadataBase(uint32_t version, uint64_t blobDataSize);- using uninitialized_source = void*;- using Source = std::- variant<uninitialized_source, std::reference_wrapper<std::istream>, std::reference_wrapper<const ov::Tensor>>;+ using Source =+ std::variant<std::monostate, std::reference_wrapper<std::istream>, std::reference_wrapper<const ov::Tensor>>;/*** @brief Reads metadata from a stream.*/- void read(std::istream& tensor);+ void read(std::istream& stream);/*** @brief Reads metadata from a ov::Tensor.@@ -55,9 +54,14 @@ public:virtual void read_as_text() = 0;/**- * @brief Writes metadata to a stream.+ * @brief Writes metadata to a stream. The footer (blob size & magic) is included.*/- virtual void write(std::ostream& stream) = 0;+ void write(std::ostream& stream);++ /**+ * @brief Writes metadata to a stream. The footer (blob size & magic) is omitted.+ */+ virtual void write_without_footer(std::ostream& stream) = 0;virtual void write_as_text(std::ostream& stream) = 0;@@ -87,7 +91,7 @@ public:virtual ~MetadataBase() = default;- static size_t getFileSize(std::istream& stream);+ static size_t get_stream_remaining_size(std::istream& stream);/*** @brief Returns a uint32_t value which represents two uint16_t values concatenated.@@ -125,13 +129,9 @@ protected:void read_data_from_source(char* destination, const size_t size);/**- * @brief Adds the size of the binary object and the magic string to the end of the stream.- * @details This should be called after the "write" method in order to conclude writing the metadata into the given- * stream.- * @note This operation was detached from "write" since "write" writes at the beginning of the stream, while this- * method writes at the end. This change allows better extension of class hierarchy.+ * @return The number of bytes until the cursor reaches the end of the source*/- void append_blob_size_and_magic(std::ostream& stream);+ size_t get_remaining_source_size() const;uint32_t _version;uint64_t _blobDataSize;@@ -148,6 +148,7 @@ protected:* "uninitialized_source" (void*) is the default type assigned upon creation.*/Source _source;+ size_t _sourceSize;/*** @brief Used only when the source buffer is an OV tensor for managing the read coursor.@@ -280,7 +281,7 @@ public:* This is the quickest way to handle many incompatible blob cases without needing to traverse the whole NPU* metadata section.*/- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;void write_as_text(std::ostream& stream) override;@@ -312,7 +313,7 @@ public:* @details The number of init schedules, along with the size of each init binary object are written in addition to* the information registered by the previous metadata versions.*/- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;void write_as_text(std::ostream& stream) override;@@ -338,7 +339,7 @@ public:void read_as_text() override;- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;void write_as_text(std::ostream& stream) override;@@ -364,7 +365,7 @@ public:void read() override;- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;std::optional<std::vector<ov::Layout>> get_input_layouts() const override;@@ -391,7 +392,7 @@ public:void read() override;- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;std::optional<uint32_t> get_compiler_version() const override;@@ -417,7 +418,7 @@ public:void read() override;- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;std::optional<bool> is_encrypted_blob() const override;@@ -445,7 +446,7 @@ public:void read_as_text() override;- void write(std::ostream& stream) override;+ void write_without_footer(std::ostream& stream) override;void write_as_text(std::ostream& stream) override;diff --git a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cppindex 3b727e76039..d10c6fb3bfc 100644--- a/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp+++ b/src/plugins/intel_npu/src/plugin/src/blob_format_importers.cpp@@ -181,7 +181,7 @@ public:: IBlobFormatImporter(original_model,config,Logger(RAW_BLOB_HANDLER_LOGGER_NAME.data(), config.get<LOG_LEVEL>())) {- const size_t blob_size = MetadataBase::getFileSize(compiler_main_schedule);+ const size_t blob_size = MetadataBase::get_stream_remaining_size(compiler_main_schedule);OPENVINO_ASSERT(blob_size > 0, EMPTY_BLOB_MESSAGE);m_main_schedule = allocate_aligned_tensor(blob_size);@@ -493,7 +493,7 @@ std::unique_ptr<IBlobFormatImporter> create(std::istream& npu_formatted_blob,const std::shared_ptr<const ov::Model>& original_model,const FilteredConfig& config) {OV_ITT_SCOPED_TASK(itt::domains::NPUPlugin, "blob_format_importer_factory::create(std::istream)");- const size_t input_size = MetadataBase::getFileSize(npu_formatted_blob);+ const size_t input_size = MetadataBase::get_stream_remaining_size(npu_formatted_blob);OPENVINO_ASSERT(input_size > 0, EMPTY_BLOB_MESSAGE);const Logger logger(HANDLER_FACTOR_LOGGER_NAME.data(), config.get<LOG_LEVEL>());diff --git a/src/plugins/intel_npu/src/plugin/src/metadata.cpp b/src/plugins/intel_npu/src/plugin/src/metadata.cppindex 731c3ceaae6..c2c08f80d08 100644--- a/src/plugins/intel_npu/src/plugin/src/metadata.cpp+++ b/src/plugins/intel_npu/src/plugin/src/metadata.cpp@@ -15,8 +15,12 @@namespace {+// Compiler payload size + magic bytes+constexpr size_t FOOTER_SIZE = sizeof(uint64_t) + intel_npu::MAGIC_BYTES.size();// Metadata version + compiler payload size + magic bytes-constexpr size_t MINIMUM_BLOB_SIZE = sizeof(uint32_t) + sizeof(uint64_t) + intel_npu::MAGIC_BYTES.size();+constexpr size_t MINIMUM_BLOB_SIZE = sizeof(uint32_t) + FOOTER_SIZE;+constexpr size_t SIZE_OF_INIT_SCHEDULE_SIZE = sizeof(uint64_t);+constexpr size_t SIZE_OF_LAYOUT_SIZE = sizeof(uint16_t);constexpr std::string_view MISSING_METADATA_MESSAGE = "The blob is missing the NPU metadata!";constexpr std::string_view BLOB_TOO_SMALL_MESSAGE =@@ -24,6 +28,8 @@ constexpr std::string_view BLOB_TOO_SMALL_MESSAGE =constexpr std::string_view INVALID_PAYLOAD_SIZE_MESSAGE ="The size of the compiler payload parsed from the blob is greater ""than the size of the blob. Compiler payload size: ";+constexpr std::string_view MISSING_BLOB_MESSAGE = "No blob has been provided to NPU plugin's metadata reader.";+constexpr std::string_view STREAM_BAD_STATUS_MESSAGE = "The stream is in bad status";template <typename T>void write_text_field(std::ostream& stream, std::string_view key, const T& value) {@@ -62,6 +68,20 @@ std::vector<uint16_t> parse_version(std::string_view sv) {return parts;}+/**+ * @return The size of the underlying buffer, from the beginning of the stream to its end.+ */+size_t get_stream_total_size(std::istream& stream) {+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);++ const std::streampos backupCursor = stream.tellg();+ stream.seekg(0, std::ios_base::end);+ const std::streampos streamEnd = stream.tellg();+ stream.seekg(backupCursor, std::ios_base::beg);++ return streamEnd;+}+} // namespacenamespace intel_npu {@@ -200,13 +220,20 @@ Metadata<METADATA_VERSION_2_6>::Metadata(uint64_t blobSize,_version = METADATA_VERSION_2_6;}-void MetadataBase::read(std::istream& tensor) {- _source = Source(tensor);+void MetadataBase::read(std::istream& stream) {+ _source = Source(stream);+ _sourceSize = get_stream_total_size(stream);read();++ // Note: we could have placed an additional safeguard here. Something like "cursorPosition = streamEnd -+ // footerSize", to make sure the whole content of the metadata section has been read. However, such a safeguard+ // would break compatibility, because some previous plugin versions are padding the space between the end of the+ // metadata and the footer.}void MetadataBase::read(const ov::Tensor& tensor) {_source = Source(tensor);+ _sourceSize = tensor.get_byte_size();read();}@@ -215,31 +242,46 @@ void MetadataBase::read_as_text(std::map<std::string, std::string, std::less<>>read_as_text();}+size_t MetadataBase::get_remaining_source_size() const {+ if (const std::reference_wrapper<std::istream>* stream =+ std::get_if<std::reference_wrapper<std::istream>>(&_source)) {+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);++ const auto offset = static_cast<size_t>(stream->get().tellg());+ return (offset <= _sourceSize) ? _sourceSize - offset : 0;+ } else if (std::get_if<std::reference_wrapper<const ov::Tensor>>(&_source)) {+ return (_cursorOffset <= _sourceSize) ? _sourceSize - _cursorOffset : 0;+ } else {+ OPENVINO_THROW(MISSING_BLOB_MESSAGE);+ }+}+void MetadataBase::read_data_from_source(char* destination, const size_t size) {+ const size_t remaining = get_remaining_source_size();+ OPENVINO_ASSERT(size <= remaining,+ "NPU metadata: attempted to read ",+ size,+ " bytes but only ",+ remaining,+ " bytes remain in the metadata buffer.");+if (const std::reference_wrapper<std::istream>* stream =std::get_if<std::reference_wrapper<std::istream>>(&_source)) {+ OPENVINO_ASSERT(stream, STREAM_BAD_STATUS_MESSAGE);+stream->get().read(destination, size);} else if (const std::reference_wrapper<const ov::Tensor>* tensor =std::get_if<std::reference_wrapper<const ov::Tensor>>(&_source)) {- const size_t available = tensor->get().get_byte_size();- const size_t remaining = (_cursorOffset <= available) ? available - _cursorOffset : 0;- if (size > remaining) {- OPENVINO_THROW("NPU metadata: attempted to read ",- size,- " bytes at offset ",- _cursorOffset,- " but only ",- remaining,- " bytes remain in the metadata buffer.");- }std::memcpy(destination, tensor->get().data<const char>() + _cursorOffset, size);_cursorOffset += size;} else {- OPENVINO_THROW("No blob has been provided to NPU plugin's metadata reader.");+ OPENVINO_THROW(MISSING_BLOB_MESSAGE);}}-void MetadataBase::append_blob_size_and_magic(std::ostream& stream) {+void MetadataBase::write(std::ostream& stream) {+ write_without_footer(stream);+stream.write(reinterpret_cast<const char*>(&_blobDataSize), sizeof(_blobDataSize));stream.write(MAGIC_BYTES.data(), MAGIC_BYTES.size());}@@ -264,6 +306,10 @@ void Metadata<METADATA_VERSION_2_1>::read() {read_data_from_source(reinterpret_cast<char*>(&numberOfInits), sizeof(numberOfInits));if (numberOfInits) {+ OPENVINO_ASSERT(+ numberOfInits <= (get_remaining_source_size() - FOOTER_SIZE) / SIZE_OF_INIT_SCHEDULE_SIZE,+ "The number of init schedules read from the blob is too great relative to the size of the blob");+_initSizes = std::vector<uint64_t>(numberOfInits);for (uint64_t initIndex = 0; initIndex < numberOfInits; ++initIndex) {read_data_from_source(reinterpret_cast<char*>(&_initSizes->at(initIndex)),@@ -288,6 +334,10 @@ void Metadata<METADATA_VERSION_2_3>::read() {read_data_from_source(reinterpret_cast<char*>(&numberOfInputLayouts), sizeof(numberOfInputLayouts));read_data_from_source(reinterpret_cast<char*>(&numberOfOutputLayouts), sizeof(numberOfOutputLayouts));+ OPENVINO_ASSERT(numberOfInputLayouts + numberOfOutputLayouts <=+ (get_remaining_source_size() - FOOTER_SIZE) / SIZE_OF_LAYOUT_SIZE,+ "The number of I/O layouts read from the blob is too great relative to the size of the blob");+const auto readNLayouts = [&](const uint64_t numberOfLayouts, const char* loggerAddition) {std::optional<std::vector<ov::Layout>> layouts = std::nullopt;if (!numberOfLayouts) {@@ -299,6 +349,8 @@ void Metadata<METADATA_VERSION_2_3>::read() {layouts->reserve(numberOfLayouts);for (uint64_t layoutIndex = 0; layoutIndex < numberOfLayouts; ++layoutIndex) {read_data_from_source(reinterpret_cast<char*>(&stringLength), sizeof(stringLength));+ OPENVINO_ASSERT(stringLength <= get_remaining_source_size() - FOOTER_SIZE,+ "The size of at least one layout exceeds the limit of the blob");std::string layoutString(stringLength, 0);read_data_from_source(const_cast<char*>(layoutString.c_str()), stringLength);@@ -344,6 +396,9 @@ void Metadata<METADATA_VERSION_2_6>::read() {uint64_t reqs_len;read_data_from_source(reinterpret_cast<char*>(&reqs_len), sizeof(reqs_len));if (reqs_len > 0) {+ OPENVINO_ASSERT(reqs_len <= (get_remaining_source_size() - FOOTER_SIZE),+ "The size of the runtime requirements surpasses the limit of the blob");+std::string reqs(reqs_len, '\0');read_data_from_source(reqs.data(), reqs_len);_compatibilityDescriptor = std::move(reqs);@@ -404,13 +459,13 @@ void Metadata<METADATA_VERSION_2_6>::read_as_text() {}}-void Metadata<METADATA_VERSION_2_0>::write(std::ostream& stream) {+void Metadata<METADATA_VERSION_2_0>::write_without_footer(std::ostream& stream) {stream.write(reinterpret_cast<const char*>(&_version), sizeof(_version));_ovVersion.write(stream);}-void Metadata<METADATA_VERSION_2_1>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_0>::write(stream);+void Metadata<METADATA_VERSION_2_1>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_0>::write_without_footer(stream);_numberOfInits = _initSizes.has_value() ? _initSizes->size() : 0;stream.write(reinterpret_cast<const char*>(&_numberOfInits), sizeof(_numberOfInits));@@ -422,15 +477,15 @@ void Metadata<METADATA_VERSION_2_1>::write(std::ostream& stream) {}}-void Metadata<METADATA_VERSION_2_2>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_1>::write(stream);+void Metadata<METADATA_VERSION_2_2>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_1>::write_without_footer(stream);int64_t batchValue = _batchSize.value_or(0);stream.write(reinterpret_cast<const char*>(&batchValue), sizeof(batchValue));}-void Metadata<METADATA_VERSION_2_3>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_2>::write(stream);+void Metadata<METADATA_VERSION_2_3>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_2>::write_without_footer(stream);const uint64_t numberOfInputLayouts = _inputLayouts.has_value() ? _inputLayouts->size() : 0;const uint64_t numberOfOutputLayouts = _outputLayouts.has_value() ? _outputLayouts->size() : 0;@@ -452,22 +507,22 @@ void Metadata<METADATA_VERSION_2_3>::write(std::ostream& stream) {writeLayouts(_outputLayouts);}-void Metadata<METADATA_VERSION_2_4>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_3>::write(stream);+void Metadata<METADATA_VERSION_2_4>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_3>::write_without_footer(stream);uint32_t compilerVersion = _compilerVersion.value_or(0);stream.write(reinterpret_cast<const char*>(&compilerVersion), sizeof(compilerVersion));}-void Metadata<METADATA_VERSION_2_5>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_4>::write(stream);+void Metadata<METADATA_VERSION_2_5>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_4>::write_without_footer(stream);const uint8_t isEncryptedBlob = _isEncryptedBlob.value_or(false);stream.write(reinterpret_cast<const char*>(&isEncryptedBlob), sizeof(isEncryptedBlob));}-void Metadata<METADATA_VERSION_2_6>::write(std::ostream& stream) {- Metadata<METADATA_VERSION_2_5>::write(stream);+void Metadata<METADATA_VERSION_2_6>::write_without_footer(std::ostream& stream) {+ Metadata<METADATA_VERSION_2_5>::write_without_footer(stream);const std::string& compatDesc = _compatibilityDescriptor.value_or("");const uint64_t compatDesc_len = compatDesc.size();@@ -475,8 +530,6 @@ void Metadata<METADATA_VERSION_2_6>::write(std::ostream& stream) {if (compatDesc_len > 0) {stream.write(compatDesc.data(), static_cast<std::streamsize>(compatDesc_len));}-- append_blob_size_and_magic(stream);}void Metadata<METADATA_VERSION_2_0>::write_as_text(std::ostream& stream) {@@ -518,43 +571,45 @@ void Metadata<METADATA_VERSION_2_6>::write_as_text(std::ostream& stream) {}std::unique_ptr<MetadataBase> create_metadata(uint32_t version, uint64_t blobSize) {- uint16_t major = MetadataBase::get_major(version), minor = MetadataBase::get_minor(version);- if (major != CURRENT_METADATA_MAJOR_VERSION || minor > CURRENT_METADATA_MINOR_VERSION) {- OPENVINO_THROW("Metadata version is not supported! Imported blob metadata version: ",- major,- ".",- minor,- " but the current version is: ",- CURRENT_METADATA_MAJOR_VERSION,- ".",- CURRENT_METADATA_MINOR_VERSION);- }+ auto logger = Logger::global().clone("create_metadata");switch (version) {case METADATA_VERSION_2_0:+ logger.debug("Creating a metadata object of version 2.0");return std::make_unique<Metadata<METADATA_VERSION_2_0>>(blobSize);case METADATA_VERSION_2_1:+ logger.debug("Creating a metadata object of version 2.1");return std::make_unique<Metadata<METADATA_VERSION_2_1>>(blobSize);case METADATA_VERSION_2_2:+ logger.debug("Creating a metadata object of version 2.2");return std::make_unique<Metadata<METADATA_VERSION_2_2>>(blobSize);case METADATA_VERSION_2_3:+ logger.debug("Creating a metadata object of version 2.3");return std::make_unique<Metadata<METADATA_VERSION_2_3>>(blobSize);case METADATA_VERSION_2_4:+ logger.debug("Creating a metadata object of version 2.4");return std::make_unique<Metadata<METADATA_VERSION_2_4>>(blobSize);case METADATA_VERSION_2_5:+ logger.debug("Creating a metadata object of version 2.5");return std::make_unique<Metadata<METADATA_VERSION_2_5>>(blobSize);case METADATA_VERSION_2_6:+ logger.debug("Creating a metadata object of version 2.6");return std::make_unique<Metadata<METADATA_VERSION_2_6>>(blobSize);default:- return nullptr;+ OPENVINO_THROW("Metadata version is not supported! Imported blob metadata version: ",+ MetadataBase::get_major(version),+ ".",+ MetadataBase::get_minor(version),+ " but the current version is: ",+ CURRENT_METADATA_MAJOR_VERSION,+ ".",+ CURRENT_METADATA_MINOR_VERSION);}}-size_t MetadataBase::getFileSize(std::istream& stream) {- auto log = Logger::global().clone("getFileSize");- if (!stream) {- OPENVINO_THROW("Stream is in bad status! Please check the passed stream status!");- }+size_t MetadataBase::get_stream_remaining_size(std::istream& stream) {+ auto log = Logger::global().clone("get_stream_remaining_size");+ OPENVINO_ASSERT(stream, "Stream is in bad status! Please check the passed stream status!");if (dynamic_cast<ov::SharedStreamBuffer*>(stream.rdbuf()) != nullptr) {return stream.rdbuf()->in_avail();@@ -564,22 +619,23 @@ size_t MetadataBase::getFileSize(std::istream& stream) {const std::streampos streamEnd = stream.tellg();stream.seekg(streamStart, std::ios_base::beg);- log.debug("Read blob size: streamStart=%zu, streamEnd=%zu", streamStart, streamEnd);+ log.debug("Read blob size: streamStart=%zu, streamEnd=%zu",+ static_cast<size_t>(streamStart),+ static_cast<size_t>(streamEnd));- if (streamEnd < streamStart) {- OPENVINO_THROW("Invalid stream size: streamEnd (",- streamEnd,- ") is not larger than streamStart (",- streamStart,- ")!");- }+ OPENVINO_ASSERT(streamEnd >= streamStart,+ "Invalid stream size: streamEnd (",+ streamEnd,+ ") is not larger than streamStart (",+ streamStart,+ ")!");return streamEnd - streamStart;}std::unique_ptr<MetadataBase> read_metadata_from(std::istream& stream) {std::streampos currentStreamPos = stream.tellg();- const size_t streamSize = MetadataBase::getFileSize(stream);+ const size_t streamSize = MetadataBase::get_stream_remaining_size(stream);OPENVINO_ASSERT(streamSize >= MINIMUM_BLOB_SIZE, BLOB_TOO_SMALL_MESSAGE, streamSize);diff --git a/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp b/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cppindex 34d26d1380d..750b04c15c5 100644--- a/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp+++ b/src/plugins/intel_npu/tests/unit/npu/metadata/metadata_version.cpp@@ -11,18 +11,28 @@using namespace intel_npu;using MetadataUnitTests = ::testing::Test;+using testing::_;++namespace {++// Compiler payload size + magic bytes+constexpr size_t FOOTER_SIZE = sizeof(uint64_t) + intel_npu::MAGIC_BYTES.size();+constexpr size_t SIZE_OF_INIT_SCHEDULE_SIZE = sizeof(uint64_t);+constexpr size_t SIZE_OF_LAYOUT_SIZE = sizeof(uint16_t);++} // namespaceTEST_F(MetadataUnitTests, readUnversionedBlob) {std::stringstream blob("this_is an_unversioned bl0b");std::unique_ptr<MetadataBase> storedMeta;- ASSERT_ANY_THROW(storedMeta = read_metadata_from(blob));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(blob), ov::Exception, _);blob.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(blob);+ size_t streamSize = MetadataBase::get_stream_remaining_size(blob);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});blob.read(tensor.data<char>(), tensor.get_byte_size());- ASSERT_ANY_THROW(storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);}TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {@@ -36,7 +46,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlob) {OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));@@ -56,7 +66,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContent) {ASSERT_TRUE(storedMeta->get_blob_size() == blobSize);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));@@ -74,7 +84,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWeightsSeparation)OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(stream));stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));@@ -116,7 +126,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithContentAllAttri}stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));@@ -165,7 +175,7 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithCompatibilityDeASSERT_EQ(storedMeta->get_compatibility_descriptor().value(), compatDesc);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));@@ -194,14 +204,14 @@ TEST_F(MetadataUnitTests, writeAndReadCurrentMetadataFromBlobWithEmptyCompatibilASSERT_FALSE(storedMeta->get_compatibility_descriptor().has_value());stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());OV_ASSERT_NO_THROW(storedMeta = read_metadata_from(tensor));ASSERT_FALSE(storedMeta->get_compatibility_descriptor().has_value());}-TEST_F(MetadataUnitTests, compatibilityDescriptorLenExceedsTensorBounds) {+TEST_F(MetadataUnitTests, compatibilityDescriptorLenExceedsBounds) {std::stringstream stream;const std::string compatDesc = "platform=NPU3720;tiles=2;etc=...";auto meta = Metadata<METADATA_VERSION_2_6>(0,@@ -216,13 +226,17 @@ TEST_F(MetadataUnitTests, compatibilityDescriptorLenExceedsTensorBounds) {meta.write(stream);std::string blob = stream.str();- const size_t compatDescLenOffset = blob.size() - MAGIC_BYTES.size() - sizeof(uint64_t) - compatDesc.size() - sizeof(uint64_t);- const uint64_t badLen = compatDesc.size() + 0xFF;- std::memcpy(&blob[compatDescLenOffset], &badLen, sizeof(badLen));+ const uint64_t badCompatibilityDescriptorSize = compatDesc.size() + 0xFF;+ const size_t compatDescLenOffset =+ blob.size() - FOOTER_SIZE - sizeof(badCompatibilityDescriptorSize) - compatDesc.size();+ std::memcpy(&blob[compatDescLenOffset], &badCompatibilityDescriptorSize, sizeof(badCompatibilityDescriptorSize));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});std::memcpy(tensor.data<char>(), blob.data(), blob.size());- ASSERT_ANY_THROW(read_metadata_from(tensor));+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);}TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {@@ -234,13 +248,13 @@ TEST_F(MetadataUnitTests, writeAndReadInvalidMetadataVersion) {meta.set_version(dummyVersion);OV_ASSERT_NO_THROW(meta.write(stream));- ASSERT_ANY_THROW(auto storedMeta = read_metadata_from(stream));+ OV_EXPECT_THROW(auto storedMeta = read_metadata_from(stream), ov::Exception, _);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());- ASSERT_ANY_THROW(auto storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(auto storedMeta = read_metadata_from(tensor), ov::Exception, _);}TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {@@ -254,13 +268,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerMinorVersion) {OV_ASSERT_NO_THROW(meta.write(stream));std::unique_ptr<MetadataBase> storedMeta;- ASSERT_ANY_THROW(storedMeta = read_metadata_from(stream));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());- ASSERT_ANY_THROW(storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);}TEST_P(MetadataVersionTestFixture, writeAndReadInvalidMetadataVersion) {@@ -274,13 +288,13 @@ TEST_P(MetadataVersionTestFixture, writeAndReadInvalidMetadataVersion) {dummyMeta.set_version(metaVersion);OV_ASSERT_NO_THROW(dummyMeta.write(blob));- EXPECT_ANY_THROW(read_metadata_from(blob));+ OV_EXPECT_THROW(read_metadata_from(blob), ov::Exception, _);blob.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(blob);+ size_t streamSize = MetadataBase::get_stream_remaining_size(blob);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});blob.read(tensor.data<char>(), tensor.get_byte_size());- EXPECT_ANY_THROW(read_metadata_from(tensor));+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);}const std::vector badMetadataVersions = {@@ -316,13 +330,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtEnd) {stream << temp;std::unique_ptr<MetadataBase> storedMeta;- ASSERT_ANY_THROW(storedMeta = read_metadata_from(stream));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());- ASSERT_ANY_THROW(storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);}TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {@@ -345,13 +359,13 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithNewerFieldAtMiddle) {stream << temp;std::unique_ptr<MetadataBase> storedMeta;- EXPECT_ANY_THROW(storedMeta = read_metadata_from(stream));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());- EXPECT_ANY_THROW(storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);}TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {@@ -374,11 +388,138 @@ TEST_F(MetadataUnitTests, writeAndReadMetadataWithRemovedField) {stream << temp;std::unique_ptr<MetadataBase> storedMeta;- EXPECT_ANY_THROW(storedMeta = read_metadata_from(stream));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(stream), ov::Exception, _);stream.seekg(0, std::ios::beg);- size_t streamSize = MetadataBase::getFileSize(stream);+ size_t streamSize = MetadataBase::get_stream_remaining_size(stream);auto tensor = ov::Tensor(ov::element::u8, ov::Shape{streamSize});stream.read(tensor.data<char>(), tensor.get_byte_size());- EXPECT_ANY_THROW(storedMeta = read_metadata_from(tensor));+ OV_EXPECT_THROW(storedMeta = read_metadata_from(tensor), ov::Exception, _);+}++/**+ * @brief Throw if the size of the compiler payload is too big relative to the size of the blob+ */+TEST_F(MetadataUnitTests, compilerPayloadSizeExceedsBlobLimit) {+ std::stringstream stream;++ auto meta = Metadata<METADATA_VERSION_2_0>(0, std::nullopt);+ meta.write(stream);+ std::string blob = stream.str();++ const uint64_t badCompilerPayloadSize = 0xFF;+ const size_t compilerPayloadSizeOffset = blob.size() - FOOTER_SIZE;+ std::memcpy(&blob[compilerPayloadSizeOffset], &badCompilerPayloadSize, sizeof(badCompilerPayloadSize));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);++ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data<char>(), blob.data(), blob.size());+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);+}++/**+ * @brief Throw if the number of init schedules is too big relative to the size of the blob+ */+TEST_F(MetadataUnitTests, numberOfInitSchedulesExceedsBlobLimit) {+ std::stringstream stream;+ std::vector<uint64_t> initSizes{16, 32};++ auto meta = Metadata<METADATA_VERSION_2_1>(0, std::nullopt, initSizes);+ meta.write(stream);+ std::string blob = stream.str();++ const uint64_t badNumberOfInits = initSizes.size() + 1;+ const size_t numberOfInitsOffset =+ blob.size() - FOOTER_SIZE - initSizes.size() * SIZE_OF_INIT_SCHEDULE_SIZE - sizeof(badNumberOfInits);+ std::memcpy(&blob[numberOfInitsOffset], &badNumberOfInits, sizeof(badNumberOfInits));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);++ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data<char>(), blob.data(), blob.size());+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);+}++/**+ * @brief Throw if the number of input layouts is too big relative to the size of the blob+ */+TEST_F(MetadataUnitTests, numberOfInputLayoutsExceedsBlobLimit) {+ std::stringstream stream;+ std::vector<ov::Layout> inputLayouts{"1"};+ std::vector<ov::Layout> outputLayouts{"2"};++ auto meta =+ Metadata<METADATA_VERSION_2_3>(0, std::nullopt, std::nullopt, std::nullopt, inputLayouts, outputLayouts);+ meta.write(stream);+ std::string blob = stream.str();++ const uint64_t badNumberOfLayouts = inputLayouts.size() + 0xFF;+ const size_t numberOfLayoutsOffset =+ blob.size() - FOOTER_SIZE - (inputLayouts.size() + outputLayouts.size()) * SIZE_OF_LAYOUT_SIZE -+ inputLayouts.at(0).to_string().size() - outputLayouts.at(0).to_string().size() - 2 * sizeof(badNumberOfLayouts);+ std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);++ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data<char>(), blob.data(), blob.size());+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);+}++/**+ * @brief Throw if the number of output layouts is too big relative to the size of the blob+ */+TEST_F(MetadataUnitTests, numberOfOutputLayoutsExceedsBlobLimit) {+ std::stringstream stream;+ std::vector<ov::Layout> inputLayouts{"1"};+ std::vector<ov::Layout> outputLayouts{"2"};++ auto meta =+ Metadata<METADATA_VERSION_2_3>(0, std::nullopt, std::nullopt, std::nullopt, inputLayouts, outputLayouts);+ meta.write(stream);+ std::string blob = stream.str();++ const uint64_t badNumberOfLayouts = outputLayouts.size() + 0xFF;+ const size_t numberOfLayoutsOffset =+ blob.size() - FOOTER_SIZE - (inputLayouts.size() + outputLayouts.size()) * SIZE_OF_LAYOUT_SIZE -+ inputLayouts.at(0).to_string().size() - outputLayouts.at(0).to_string().size() - sizeof(badNumberOfLayouts);+ std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);++ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data<char>(), blob.data(), blob.size());+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);+}++/**+ * @brief Throw if the size of at least one layout is too big relative to the size of the blob+ */+TEST_F(MetadataUnitTests, layoutLengthExceedsBlobLimit) {+ std::stringstream stream;+ std::vector<ov::Layout> inputLayouts{"1"};+ std::vector<ov::Layout> outputLayouts{};++ auto meta =+ Metadata<METADATA_VERSION_2_3>(0, std::nullopt, std::nullopt, std::nullopt, inputLayouts, outputLayouts);+ meta.write(stream);+ std::string blob = stream.str();++ const uint64_t badNumberOfLayouts = inputLayouts.at(0).to_string().size() + 0xFF;+ const size_t numberOfLayoutsOffset = blob.size() - FOOTER_SIZE -+ (inputLayouts.size() + outputLayouts.size()) * SIZE_OF_LAYOUT_SIZE -+ inputLayouts.at(0).to_string().size();+ std::memcpy(&blob[numberOfLayoutsOffset], &badNumberOfLayouts, sizeof(badNumberOfLayouts));++ std::stringstream malformedStream(blob);+ OV_EXPECT_THROW(read_metadata_from(malformedStream), ov::Exception, _);++ auto tensor = ov::Tensor(ov::element::u8, ov::Shape{blob.size()});+ std::memcpy(tensor.data<char>(), blob.data(), blob.size());+ OV_EXPECT_THROW(read_metadata_from(tensor), ov::Exception, _);}