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
[CPU] Fix TopK OOB read when k > axis_dim (#35237)
Vladislav Golubev032c2f51151d
diff --git a/src/plugins/intel_cpu/src/nodes/topk.cpp b/src/plugins/intel_cpu/src/nodes/topk.cppindex ff5bb76e946..a07e1949049 100644--- a/src/plugins/intel_cpu/src/nodes/topk.cpp+++ b/src/plugins/intel_cpu/src/nodes/topk.cpp@@ -2078,13 +2078,19 @@ void TopK::prepareParams() {if (isDynamicNode()) {const int src_k = getSrcDataAtPortAs<int>(TOPK_K)[0];- CPU_NODE_ASSERT(static_cast<size_t>(src_k) <= src_dims[axis], "gets top_k out of range!");if (top_k != src_k) {top_k = src_k;}} else {top_k = getSrcDataAtPortAs<int>(TOPK_K)[0];}+ CPU_NODE_ASSERT(top_k >= 1, "K (", top_k, ") must be greater or equal to 1.");+ CPU_NODE_ASSERT(static_cast<size_t>(top_k) <= src_dims[axis],+ "K (",+ top_k,+ ") exceeds the axis dimension (",+ src_dims[axis],+ ").");if (jit_mode) {if (!preset_params_done) {diff --git a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/topk.cpp b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/topk.cppindex 51a45e42e22..ad7d95a90eb 100644--- a/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/topk.cpp+++ b/src/plugins/intel_cpu/tests/functional/custom/single_layer_tests/topk.cpp@@ -228,6 +228,19 @@ TEST_P(TopKLayerCPUTest, CompareWithRefs) {CheckPluginRelatedResults(compiledModel, "TopK");}+class TopKLayerInvalidK : public TopKLayerCPUTest {};++TEST_P(TopKLayerInvalidK, CompareWithRefsNegative) {+ bool exception_caught = false;+ set_callback_exception([&exception_caught](const std::exception& ex) {+ exception_caught = true;+ EXPECT_NE(dynamic_cast<const ov::Exception*>(&ex), nullptr)+ << "Expected ov::Exception but got: " << ex.what();+ });+ run();+ EXPECT_TRUE(exception_caught) << "Expected an ov::Exception for invalid K value";+}+namespace {const std::vector<ElementType> netPrecisions = {@@ -396,6 +409,20 @@ INSTANTIATE_TEST_SUITE_P(::testing::ValuesIn(additionalConfig)),TopKLayerCPUTest::getTestCaseName);+INSTANTIATE_TEST_SUITE_P(+ smoke_TopK_negative,+ TopKLayerInvalidK,+ ::testing::Combine(::testing::Combine(::testing::Values(0, 22),+ ::testing::Values(0),+ ::testing::Values(SortMode::MAX),+ ::testing::Values(std::tuple<SortType, bool>{SortType::SORT_VALUES, false}),+ ::testing::Values(ElementType::f32),+ ::testing::Values(ElementType::dynamic),+ ::testing::Values(ElementType::dynamic),+ ::testing::Values(InputShape{{}, {{21, 21, 21, 21}}})),+ ::testing::Values(CPUSpecificParams({nchw, x}, {nchw, nchw}, {}, {})),+ ::testing::Values(additionalConfig[0])),+ TopKLayerCPUTest::getTestCaseName);} // namespace} // namespace test-} // namespace ov+} // namespace ov\ No newline at end of file