From 263f80deb8b4b90f3eaba156b083633e6d7d6c4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Tue, 21 Jan 2020 20:19:51 +0100 Subject: [PATCH] ExprEngine: Add variable value checker --- lib/exprengine.cpp | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp index fa9dbdfa4..c01af1ab4 100644 --- a/lib/exprengine.cpp +++ b/lib/exprengine.cpp @@ -754,7 +754,7 @@ bool ExprEngine::IntRange::isEqual(DataBase *dataBase, int value) const bool ExprEngine::IntRange::isGreaterThan(DataBase *dataBase, int value) const { - if (value <= minValue || value >= maxValue) + if (maxValue <= value) return false; const Data *data = dynamic_cast(dataBase); @@ -783,7 +783,7 @@ bool ExprEngine::IntRange::isGreaterThan(DataBase *dataBase, int value) const bool ExprEngine::IntRange::isLessThan(DataBase *dataBase, int value) const { - if (value <= minValue || value >= maxValue) + if (minValue >= value) return false; const Data *data = dynamic_cast(dataBase); @@ -2070,9 +2070,40 @@ void ExprEngine::runChecks(ErrorLogger *errorLogger, const Tokenizer *tokenizer, #endif }; + std::function checkAssignment = [=](const Token *tok, const ExprEngine::Value &value, ExprEngine::DataBase *dataBase) { + if (!Token::simpleMatch(tok->astParent(), "=")) + return; + const Token *lhs = tok->astParent()->astOperand1(); + if (!lhs || !lhs->variable() || !lhs->variable()->nameToken()) + return; + + const Token *vartok = lhs->variable()->nameToken(); + + MathLib::bigint low; + if (vartok->getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::LOW, &low)) { + if (value.isLessThan(dataBase, low)) { + dataBase->addError(tok->linenr()); + std::list callstack{tok}; + ErrorLogger::ErrorMessage errmsg(callstack, &tokenizer->list, Severity::SeverityType::error, "bughuntingAssign", "There is assignment, cannot determine that value is greater or equal with " + std::to_string(low), CWE_INCORRECT_CALCULATION, false); + errorLogger->reportErr(errmsg); + } + } + + MathLib::bigint high; + if (vartok->getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::HIGH, &high)) { + if (value.isGreaterThan(dataBase, high)) { + dataBase->addError(tok->linenr()); + std::list callstack{tok}; + ErrorLogger::ErrorMessage errmsg(callstack, &tokenizer->list, Severity::SeverityType::error, "bughuntingAssign", "There is assignment, cannot determine that value is lower or equal with " + std::to_string(high), CWE_INCORRECT_CALCULATION, false); + errorLogger->reportErr(errmsg); + } + } + }; + std::vector callbacks; callbacks.push_back(divByZero); callbacks.push_back(checkFunctionCall); + callbacks.push_back(checkAssignment); #ifdef BUG_HUNTING_INTEGEROVERFLOW callbacks.push_back(integerOverflow); #endif