From 18abe4a142e1ced5d8a85561fc0da6d1b1c8f2ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Wed, 7 Jun 2017 19:32:56 +0200 Subject: [PATCH] Fixed #6021 (TemplateSimplifier::simplifyCalculations causes heap corruption on invalid code) --- lib/templatesimplifier.cpp | 7 ++++--- test/testsimplifytemplate.cpp | 12 ++++++++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/lib/templatesimplifier.cpp b/lib/templatesimplifier.cpp index fa8624887..35ad24620 100644 --- a/lib/templatesimplifier.cpp +++ b/lib/templatesimplifier.cpp @@ -1136,11 +1136,12 @@ bool TemplateSimplifier::simplifyCalculations(Token *_tokens) } } - if (Token::simpleMatch(tok->previous(), "* 1") || Token::simpleMatch(tok, "1 *")) { - if (tok->previous() && tok->previous()->isConstOp()) + if (Token::Match(tok->tokAt(-2), "%any% * 1") || Token::Match(tok->previous(), "%any% 1 *")) { + if (tok->isNumber()) tok = tok->previous(); + tok = tok->previous(); + tok->deleteNext(); tok->deleteNext(); - tok->deleteThis(); ret = true; } diff --git a/test/testsimplifytemplate.cpp b/test/testsimplifytemplate.cpp index 8e416e259..76c690427 100644 --- a/test/testsimplifytemplate.cpp +++ b/test/testsimplifytemplate.cpp @@ -95,6 +95,7 @@ private: TEST_CASE(template55); // #6604 - simplify "const const" to "const" in template instantiations TEST_CASE(template56); // #7117 - const ternary operator simplification as template parameter TEST_CASE(template57); // #7891 + TEST_CASE(template58); // #6021 - use after free (deleted tokens in simplifyCalculations) TEST_CASE(template_enum); // #6299 Syntax error in complex enum declaration (including template) TEST_CASE(template_unhandled); TEST_CASE(template_default_parameter); @@ -1047,6 +1048,17 @@ private: ASSERT_EQUALS(exp, tok(code)); } + void template58() { // #6021 + const char code[] = "template \n" + "void TestArithmetic() {\n" + " x(1 * CheckedNumeric());\n" + "}\n" + "void foo() {\n" + " TestArithmetic();\n" + "}"; + ASSERT_THROW(tok(code), InternalError); + } + void template_enum() { const char code1[] = "template \n" "struct Unconst {\n"