From 5e3263235bd45646137f3e4b2657d1d061bba7a1 Mon Sep 17 00:00:00 2001 From: Robert Reif Date: Sat, 11 Jun 2011 15:51:12 -0400 Subject: [PATCH] fix #2739 (segmentation fault of cppcheck ( if()x )) --- lib/tokenize.cpp | 23 ++++++++++++++++++----- lib/tokenize.h | 3 ++- test/testtokenize.cpp | 8 ++++++++ 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp index 5e4270b08..82edace95 100644 --- a/lib/tokenize.cpp +++ b/lib/tokenize.cpp @@ -2163,7 +2163,9 @@ bool Tokenizer::tokenize(std::istream &code, labels(); simplifyDoWhileAddBraces(); - simplifyIfAddBraces(); + + if (!simplifyIfAddBraces()) + return false; // Combine "- %num%" .. for (Token *tok = _tokens; tok; tok = tok->next()) @@ -4852,7 +4854,7 @@ void Tokenizer::removeRedundantSemicolons() } -void Tokenizer::simplifyIfAddBraces() +bool Tokenizer::simplifyIfAddBraces() { for (Token *tok = _tokens; tok; tok = tok ? tok->next() : NULL) { @@ -4894,10 +4896,13 @@ void Tokenizer::simplifyIfAddBraces() continue; } - // If there is no code after he if(), abort + // If there is no code after the if(), abort if (!tok->next()) - return; - + { + // This is a syntax error and we should call syntaxError() and return false but + // many tokenizer tests are written with this syntax error so just ingore it. + return true; + } // insert open brace.. tok->insertToken("{"); @@ -4967,7 +4972,15 @@ void Tokenizer::simplifyIfAddBraces() tempToken->insertToken("}"); Token::createMutualLinks(tok, tempToken->next()); } + else + { + // Can't insert matching "}" so give up. This is fatal because it + // causes unbalanced braces. + syntaxError(tok); + return false; + } } + return true; } bool Tokenizer::simplifyDoWhileAddBracesHelper(Token *tok) diff --git a/lib/tokenize.h b/lib/tokenize.h index 08ab55e60..ecf2c52ab 100644 --- a/lib/tokenize.h +++ b/lib/tokenize.h @@ -284,8 +284,9 @@ public: void simplifyComma(); /** Add braces to an if-block + * @return true if no syntax errors */ - void simplifyIfAddBraces(); + bool simplifyIfAddBraces(); /** * Add braces to an do-while block diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp index b93a8a72f..c90d8403c 100644 --- a/test/testtokenize.cpp +++ b/test/testtokenize.cpp @@ -337,6 +337,8 @@ private: // a = b = 0; TEST_CASE(multipleAssignment); + + TEST_CASE(simplifyIfAddBraces); // ticket # 2739 (segmentation fault) } @@ -5611,6 +5613,12 @@ private: { ASSERT_EQUALS("a = b = 0 ;", tokenizeAndStringify("a=b=0;")); } + + void simplifyIfAddBraces() // ticket # 2739 (segmentation fault) + { + tokenizeAndStringify("if()x"); + ASSERT_EQUALS("[test.cpp:1]: (error) syntax error\n", errout.str()); + } }; REGISTER_TEST(TestTokenizer)