From 15be3ad422b5d39750f8d04dd3dad2740df7d472 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jean-Fran=C3=A7ois=20DEVERGE?= Date: Mon, 12 Oct 2026 12:03:30 +0200 Subject: [PATCH] Fix #15000: Propagate integral cast ranges with path-safe value flow --- .selfcheck_suppressions | 1 - Makefile | 10 +- lib/astutils.cpp | 135 +++- lib/astutils.h | 29 +- lib/checkcondition.cpp | 366 +++++++--- lib/checktype.cpp | 54 +- lib/infer.cpp | 252 +++++-- lib/infer.h | 18 +- lib/programmemory.cpp | 2 +- lib/settings.cpp | 3 + lib/symboldatabase.cpp | 337 +++++++-- lib/symboldatabase.h | 1 + lib/token.cpp | 6 +- lib/valueflow.cpp | 679 +++++++++++++++--- lib/valueflow.h | 3 +- lib/vf_analyzers.cpp | 13 + lib/vf_common.cpp | 1353 ++++++++++++++++++++++++++++++++++- lib/vf_common.h | 56 +- lib/vf_settokenvalue.cpp | 579 ++++++++++----- lib/vf_settokenvalue.h | 6 +- oss-fuzz/Makefile | 8 +- test/cfg/std.cpp | 11 - test/cli/other_test.py | 48 +- test/testbufferoverrun.cpp | 499 +++++++++++++ test/testcondition.cpp | 973 ++++++++++++++++++++++++- test/testfunctions.cpp | 86 +++ test/testother.cpp | 32 +- test/teststl.cpp | 36 + test/testsymboldatabase.cpp | 27 +- test/testtype.cpp | 196 +++++ test/testuninitvar.cpp | 10 + test/testvalueflow.cpp | 563 ++++++++++++++- 32 files changed, 5763 insertions(+), 629 deletions(-) diff --git a/.selfcheck_suppressions b/.selfcheck_suppressions index 14bc66314f6..9945386f649 100644 --- a/.selfcheck_suppressions +++ b/.selfcheck_suppressions @@ -49,7 +49,6 @@ functionStatic:*/gui/ui_*.h # --debug-warnings suppressions valueFlowBailout valueFlowBailoutIncompleteVar -valueFlowMaxIterations:gui/resultstree.cpp autoNoType:externals/simplecpp/simplecpp.cpp autoNoType:cli/*.cpp autoNoType:lib/*.cpp diff --git a/Makefile b/Makefile index 53c8b4c7aea..db43c1e925f 100644 --- a/Makefile +++ b/Makefile @@ -499,7 +499,7 @@ $(libcppdir)/addoninfo.o: lib/addoninfo.cpp externals/picojson/picojson.h lib/ad $(libcppdir)/analyzerinfo.o: lib/analyzerinfo.cpp externals/tinyxml2/tinyxml2.h lib/analyzerinfo.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/standards.h lib/utils.h lib/xml.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/analyzerinfo.cpp -$(libcppdir)/astutils.o: lib/astutils.cpp lib/astutils.h lib/check.h lib/checkclass.h lib/checkers.h lib/checkimpl.h lib/config.h lib/errortypes.h lib/findtoken.h lib/infer.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/valueflow.h lib/valueptr.h lib/vfvalue.h +$(libcppdir)/astutils.o: lib/astutils.cpp lib/astutils.h lib/check.h lib/checkclass.h lib/checkers.h lib/checkimpl.h lib/config.h lib/errortypes.h lib/findtoken.h lib/infer.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/valueflow.h lib/valueptr.h lib/vf_common.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/astutils.cpp $(libcppdir)/check64bit.o: lib/check64bit.cpp lib/check.h lib/check64bit.h lib/checkers.h lib/checkimpl.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h @@ -520,7 +520,7 @@ $(libcppdir)/checkbufferoverrun.o: lib/checkbufferoverrun.cpp externals/tinyxml2 $(libcppdir)/checkclass.o: lib/checkclass.cpp externals/tinyxml2/tinyxml2.h lib/astutils.h lib/check.h lib/checkclass.h lib/checkers.h lib/checkimpl.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h lib/xml.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/checkclass.cpp -$(libcppdir)/checkcondition.o: lib/checkcondition.cpp lib/astutils.h lib/check.h lib/checkcondition.h lib/checkers.h lib/checkimpl.h lib/checkother.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h +$(libcppdir)/checkcondition.o: lib/checkcondition.cpp lib/astutils.h lib/check.h lib/checkcondition.h lib/checkers.h lib/checkimpl.h lib/checkother.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vf_common.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/checkcondition.cpp $(libcppdir)/checkers.o: lib/checkers.cpp lib/checkers.h lib/config.h @@ -688,10 +688,10 @@ $(libcppdir)/utils.o: lib/utils.cpp lib/config.h lib/utils.h $(libcppdir)/vf_analyzers.o: lib/vf_analyzers.cpp lib/analyzer.h lib/astutils.h lib/calculate.h lib/checkers.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/programmemory.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/valueflow.h lib/valueptr.h lib/vf_analyzers.h lib/vf_common.h lib/vf_settokenvalue.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_analyzers.cpp -$(libcppdir)/vf_common.o: lib/vf_common.cpp lib/astutils.h lib/checkers.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vf_common.h lib/vf_settokenvalue.h lib/vfvalue.h +$(libcppdir)/vf_common.o: lib/vf_common.cpp lib/astutils.h lib/checkers.h lib/config.h lib/errortypes.h lib/infer.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vf_common.h lib/vf_settokenvalue.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_common.cpp -$(libcppdir)/vf_settokenvalue.o: lib/vf_settokenvalue.cpp lib/astutils.h lib/calculate.h lib/checkers.h lib/config.h lib/errortypes.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/valueflow.h lib/vf_common.h lib/vf_settokenvalue.h lib/vfvalue.h +$(libcppdir)/vf_settokenvalue.o: lib/vf_settokenvalue.cpp lib/astutils.h lib/calculate.h lib/checkers.h lib/config.h lib/errortypes.h lib/infer.h lib/library.h lib/mathlib.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/valueflow.h lib/valueptr.h lib/vf_common.h lib/vf_settokenvalue.h lib/vfvalue.h $(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_settokenvalue.cpp $(libcppdir)/vfvalue.o: lib/vfvalue.cpp lib/config.h lib/errortypes.h lib/mathlib.h lib/smallvector.h lib/templatesimplifier.h lib/token.h lib/utils.h lib/vfvalue.h @@ -961,7 +961,7 @@ test/testutils.o: test/testutils.cpp lib/check.h lib/checkers.h lib/color.h lib/ test/testvaarg.o: test/testvaarg.cpp lib/check.h lib/checkers.h lib/checkimpl.h lib/checkvaarg.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/standards.h lib/tokenize.h lib/tokenlist.h lib/utils.h test/fixture.h test/helpers.h $(CXX) ${INCLUDE_FOR_TEST} ${CFLAGS_FOR_TEST} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ test/testvaarg.cpp -test/testvalueflow.o: test/testvalueflow.cpp lib/check.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/standards.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h test/fixture.h test/helpers.h +test/testvalueflow.o: test/testvalueflow.cpp lib/check.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/infer.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/sourcelocation.h lib/standards.h lib/symboldatabase.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueptr.h lib/vf_common.h lib/vfvalue.h test/fixture.h test/helpers.h $(CXX) ${INCLUDE_FOR_TEST} ${CFLAGS_FOR_TEST} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ test/testvalueflow.cpp test/testvarid.o: test/testvarid.cpp lib/check.h lib/checkers.h lib/color.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/settings.h lib/smallvector.h lib/standards.h lib/templatesimplifier.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/vfvalue.h test/fixture.h test/helpers.h diff --git a/lib/astutils.cpp b/lib/astutils.cpp index a08d86a2f86..254873feaf9 100644 --- a/lib/astutils.cpp +++ b/lib/astutils.cpp @@ -33,6 +33,7 @@ #include "utils.h" #include "valueflow.h" #include "valueptr.h" +#include "vf_common.h" #include "vfvalue.h" #include "checkclass.h" @@ -42,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -835,6 +837,17 @@ bool astIsRHS(const Token* tok) return parent->astOperand2() == tok; } +std::string invertOperatorForOperandSwap(std::string op) +{ + if (op.empty()) + return op; + if (op[0] == '<') + op[0] = '>'; + else if (op[0] == '>') + op[0] = '<'; + return op; +} + template )> static T* getCondTokImpl(T* tok) { @@ -952,56 +965,66 @@ const Token *findNextTokenFromBreak(const Token *breakToken) return nullptr; } -bool extractForLoopValues(const Token *forToken, - nonneg int &varid, - bool &knownInitValue, - MathLib::bigint &initValue, - bool &partialCond, - MathLib::bigint &stepValue, - MathLib::bigint &lastValue) +ForLoopValues extractForLoopValues(const Token *forToken) { + ForLoopValues values; if (!Token::simpleMatch(forToken, "for (") || !Token::simpleMatch(forToken->next()->astOperand2(), ";")) - return false; + return values; const Token *initExpr = forToken->next()->astOperand2()->astOperand1(); const Token *condExpr = forToken->next()->astOperand2()->astOperand2()->astOperand1(); const Token *incExpr = forToken->next()->astOperand2()->astOperand2()->astOperand2(); if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%")) - return false; - std::vector minInitValue = - getMinValue(makeIntegralInferModel(), initExpr->astOperand2()->values()); - if (minInitValue.empty()) { - const ValueFlow::Value* v = initExpr->astOperand2()->getMinValue(true); - if (v) - minInitValue.push_back(v->intvalue); + return values; + const Token* const initToken = initExpr->astOperand2(); + const std::vector minInitValue = + getMinValue(makeIntegralInferModel(), initToken->values()); + values.initValueSource = getMinValueSource(makeIntegralInferModel(), initToken->values()); + values.hasMinimum = !minInitValue.empty(); + if (values.hasMinimum) { + values.knownInitValue = initToken->hasKnownIntValue(); + values.initValue = minInitValue.front(); + if (values.knownInitValue && values.initValueSource && + values.initValueSource->bound != ValueFlow::Value::Bound::Point) { + const auto it = std::find_if(initToken->values().cbegin(), + initToken->values().cend(), + [&](const ValueFlow::Value& value) { + return value.isIntValue() && !value.isImpossible() && !value.isInconclusive() && + value.bound == ValueFlow::Value::Bound::Point && value.intvalue == values.initValue; + }); + if (it != initToken->values().cend()) + values.initValueSource = &*it; + } } - if (minInitValue.empty()) - return false; - varid = initExpr->astOperand1()->varId(); - knownInitValue = initExpr->astOperand2()->hasKnownIntValue(); - initValue = minInitValue.front(); - partialCond = Token::Match(condExpr, "%oror%|&&"); - visitAstNodes(condExpr, [varid, &condExpr](const Token *tok) { + values.varid = initExpr->astOperand1()->varId(); + values.partialCond = Token::Match(condExpr, "%oror%|&&"); + visitAstNodes(condExpr, [&](const Token *tok) { if (Token::Match(tok, "%oror%|&&")) return ChildrenToVisit::op1_and_op2; - if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == varid && tok->astOperand2()->hasKnownIntValue()) { + if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == values.varid && + tok->astOperand2()->hasKnownIntValue()) { if (Token::Match(condExpr, "%oror%|&&") || tok->astOperand2()->getKnownIntValue() < condExpr->astOperand2()->getKnownIntValue()) condExpr = tok; } return ChildrenToVisit::none; }); - if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != varid || !condExpr->astOperand2()->hasKnownIntValue()) - return false; - if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != varid) - return false; - stepValue = 1; - if (condExpr->str() == "<") - lastValue = condExpr->astOperand2()->getKnownIntValue() - 1; - else - lastValue = condExpr->astOperand2()->getKnownIntValue(); - return true; + if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != values.varid || + !condExpr->astOperand2()->hasKnownIntValue()) + return values; + if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != values.varid) + return values; + values.stepValue = 1; + if (condExpr->str() == "<") { + const MathLib::bigint limit = condExpr->astOperand2()->getKnownIntValue(); + if (limit == std::numeric_limits::min()) + return values; + values.lastValue = limit - 1; + } else { + values.lastValue = condExpr->astOperand2()->getKnownIntValue(); + } + values.valid = true; + return values; } - static const Token * getVariableInitExpression(const Variable * var) { if (!var) @@ -1476,6 +1499,22 @@ static inline bool isDifferentKnownValues(const Token * const tok1, const Token }); } +// Like isDifferentKnownValues(), but the two constants are read as they compare against 'exprTok'. +static bool isDifferentKnownValues(const Token* tok1, const Token* tok2, const Token* exprTok, const Settings& settings) +{ + return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) { + if (!v1.isIntValue() || !v2.isIntValue()) { + bool equal = v1.equalValue(v2); + if (v1.isIteratorValue()) + equal &= sameLifetime; + return !equal; + } + const MathLib::bigint value1 = ValueFlow::castConstantToOperandType(tok1, exprTok, v1.intvalue, settings); + const MathLib::bigint value2 = ValueFlow::castConstantToOperandType(tok2, exprTok, v2.intvalue, settings); + return value1 != value2; + }); +} + static inline bool isSameConstantValue(bool macro, const Token* tok1, const Token* tok2) { if (tok1 == nullptr || tok2 == nullptr) @@ -1903,9 +1942,9 @@ bool isOppositeCond(bool isNot, const Token * const cond1, const Token * const c if (!isNot) { if (cond1->str() == "==" && cond2->str() == "==") { if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors)) - return isDifferentKnownValues(cond1->astOperand2(), cond2->astOperand2()); + return isDifferentKnownValues(cond1->astOperand2(), cond2->astOperand2(), cond1->astOperand1(), settings); if (isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors)) - return isDifferentKnownValues(cond1->astOperand1(), cond2->astOperand1()); + return isDifferentKnownValues(cond1->astOperand1(), cond2->astOperand1(), cond1->astOperand2(), settings); } if (Library::isContainerYield(cond1, Library::Container::Yield::EMPTY, "empty") && @@ -2011,10 +2050,16 @@ bool isOppositeCond(bool isNot, const Token * const cond1, const Token * const c const ValueFlow::Value &rhsValue1 = value1->values().front(); const ValueFlow::Value &rhsValue2 = value2->values().front(); + // The operands are compared in their common type. When one side is an unsigned constant and the + // other a signed expression, the comparison happens in the unsigned domain, so the constant must be + // read as that expression's type would see it: 0xFFFFFFFFu is -1 for an 'int' operand. + const MathLib::bigint bound1 = ValueFlow::castConstantToOperandType(value1, expr1, rhsValue1.intvalue, settings); + const MathLib::bigint bound2 = ValueFlow::castConstantToOperandType(value2, expr2, rhsValue2.intvalue, settings); + if (op1 == "<" || op1 == "<=") - return (op2 == "==" || op2 == ">" || op2 == ">=") && (rhsValue1.intvalue < rhsValue2.intvalue); + return (op2 == "==" || op2 == ">" || op2 == ">=") && (bound1 < bound2); if (op1 == ">=" || op1 == ">") - return (op2 == "==" || op2 == "<" || op2 == "<=") && (rhsValue1.intvalue > rhsValue2.intvalue); + return (op2 == "==" || op2 == "<" || op2 == "<=") && (bound1 > bound2); return false; } @@ -3934,6 +3979,20 @@ const Token *skipUnreachableBranch(const Token *tok) return tok; } +bool isInUnreachableBranch(const Token *tok) +{ + for (const Scope *scope = tok->scope(); scope; scope = scope->nestedIn) { + if (scope->type != ScopeType::eIf && scope->type != ScopeType::eElse) + continue; + const Token *body = scope->bodyStart; + if (!body || body->str() != "{" || scope->bodyEnd != body->link()) + continue; + if (skipUnreachableBranch(body) != body) + return true; + } + return false; +} + bool isEscapeKeyword(const Token *tok, const Settings &settings) { if (!tok) diff --git a/lib/astutils.h b/lib/astutils.h index 578763124ac..525af3fde06 100644 --- a/lib/astutils.h +++ b/lib/astutils.h @@ -213,6 +213,9 @@ std::vector getParentValueTypes(const Token* tok, bool astIsLHS(const Token* tok); bool astIsRHS(const Token* tok); +/** The comparison operator that tests the left operand, i.e. the one with the operands exchanged. */ +std::string invertOperatorForOperandSwap(std::string op); + Token* getCondTok(Token* tok); const Token* getCondTok(const Token* tok); @@ -230,15 +233,22 @@ const Token* getCondTokFromEnd(const Token* endBlock); const Token *findNextTokenFromBreak(const Token *breakToken); /** - * Extract for loop values: loopvar varid, init value, step value, last value (inclusive) + * The values of a for loop that can be extracted: loop variable id, init value, step value, + * last value (inclusive). `initValueSource` identifies the fact supplying the minimum. */ -bool extractForLoopValues(const Token *forToken, - nonneg int &varid, - bool &knownInitValue, - MathLib::bigint &initValue, - bool &partialCond, - MathLib::bigint &stepValue, - MathLib::bigint &lastValue); +struct ForLoopValues { + bool valid = false; + bool hasMinimum = false; + bool knownInitValue = false; + bool partialCond = false; + nonneg int varid = 0; + MathLib::bigint initValue = 0; + MathLib::bigint stepValue = 0; + MathLib::bigint lastValue = 0; + const ValueFlow::Value* initValueSource = nullptr; +}; + +ForLoopValues extractForLoopValues(const Token *forToken); bool precedes(const Token * tok1, const Token * tok2); bool succeeds(const Token* tok1, const Token* tok2); @@ -466,6 +476,9 @@ bool isUnreachableOperand(const Token *tok); const Token *skipUnreachableBranch(const Token *tok); +/** Is 'tok' inside a branch that skipUnreachableBranch() proves unreachable? */ +bool isInUnreachableBranch(const Token *tok); + bool isEscapeKeyword(const Token *tok, const Settings &settings); #endif // astutilsH diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index ad547cf543e..905bf08ce3b 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -30,6 +30,7 @@ #include "token.h" #include "tokenize.h" #include "utils.h" +#include "vf_common.h" #include "vfvalue.h" #include "checkother.h" // comparisonNonZeroExpressionLessThanZero and testIfNonZeroExpressionIsPositive @@ -946,15 +947,6 @@ void CheckConditionImpl::identicalConditionAfterEarlyExitError(const Token *cond // Inform that second comparison is always true when first comparison is true. //--------------------------------------------------------------------------- -static std::string invertOperatorForOperandSwap(std::string s) -{ - if (s[0] == '<') - s[0] = '>'; - else if (s[0] == '>') - s[0] = '<'; - return s; -} - template static int sign(const T v) { return static_cast(v > 0) - static_cast(v < 0); @@ -1994,123 +1986,291 @@ void CheckConditionImpl::assignmentInCondition(const Token *eq) Certainty::normal); } +struct IntegralRange +{ + bool inImage; + bool below; + bool above; + bool atMinimum; + bool atMaximum; +}; + +struct IntegralRangeComparison +{ + bool error; + bool result; +}; + +/** The bit width of the type; bool comparisons do not use the usual integral promotion rules. */ +static std::size_t getBits(const ValueType& type, const Settings& settings) +{ + if (type.type == ValueType::Type::BOOL) + return 1; + return ValueFlow::getTypeBits(type, settings); +} + +static bool getSignedBounds(std::size_t bits, MathLib::bigint& minimum, MathLib::bigint& maximum) +{ + if (bits == 0 || bits > 64) + return false; + if (bits == 64) { + minimum = std::numeric_limits::min(); + maximum = std::numeric_limits::max(); + } else { + const MathLib::bigint halfRange = MathLib::bigint{1} << (bits - 1); + minimum = -halfRange; + maximum = halfRange - 1; + } + return true; +} + +static bool valueFitsType(const ValueType& type, MathLib::bigint value, const Settings& settings) +{ + if (type.type == ValueType::Type::BOOL) + return value == 0 || value == 1; + const std::size_t bits = getBits(type, settings); + const std::size_t carrierBits = std::numeric_limits::digits; + if (type.sign == ValueType::Sign::SIGNED) { + MathLib::bigint minimum{}, maximum{}; + return !getSignedBounds(bits, minimum, maximum) || (value >= minimum && value <= maximum); + } + if (type.sign == ValueType::Sign::UNSIGNED) { + if (value < 0) + return false; + return bits == 0 || bits > carrierBits || + static_cast(value) <= ValueFlow::getUnsignedMaximum(bits); + } + MathLib::bigint signedMinimum{}, signedMaximum{}; + if (!getSignedBounds(bits, signedMinimum, signedMaximum)) + return true; + return value >= signedMinimum && + (value < 0 || bits == 0 || bits > carrierBits || + static_cast(value) <= ValueFlow::getUnsignedMaximum(bits)); +} + +// op is the operator of the comparison written with the constant as the right operand +static IntegralRangeComparison getIntegralRangeComparison(const std::string& op, const IntegralRange& range) +{ + IntegralRangeComparison comparison{}; + if (op == "==" || op == "!=") { + comparison.error = !range.inImage; + comparison.result = op == "!="; + } else if (range.below || range.above) { + comparison.error = true; + comparison.result = range.below ? (op == ">" || op == ">=") : (op == "<" || op == "<="); + } else if (range.atMinimum && (op == ">=" || op == "<")) { + comparison.error = true; + comparison.result = op == ">="; + } else if (range.atMaximum && (op == "<=" || op == ">")) { + comparison.error = true; + comparison.result = op == "<="; + } + return comparison; +} + +template +static bool evaluateComparison(const std::string& op, T lhs, T rhs) +{ + if (op == "==") + return lhs == rhs; + if (op == "!=") + return lhs != rhs; + if (op == "<") + return lhs < rhs; + if (op == "<=") + return lhs <= rhs; + if (op == ">") + return lhs > rhs; + return lhs >= rhs; +} + +// Record whether the comparison is true or false for some value of the operand's image [lower, upper]. +template +static void inspectRange(const std::string& op, + bool equality, + T known, + T lower, + T upper, + bool& sawTrue, + bool& sawFalse) +{ + const bool lowResult = evaluateComparison(op, lower, known); + const bool highResult = evaluateComparison(op, upper, known); + sawTrue = sawTrue || lowResult || highResult; + sawFalse = sawFalse || !lowResult || !highResult; + if (equality && known >= lower && known <= upper) { + sawTrue = true; + sawFalse = true; + } +} + void CheckConditionImpl::checkCompareValueOutOfTypeRange() { if (!mSettings.severity.isEnabled(Severity::style) && !mSettings.isPremiumEnabled("compareValueOutOfTypeRangeError")) return; - if (mSettings.platform.type == Platform::Type::Unspecified) return; logChecker("CheckCondition::checkCompareValueOutOfTypeRange"); // style,platform - const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); - for (const Scope * scope : symbolDatabase->functionScopes) { + const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); + for (const Scope* scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || !tok->isBinaryOp()) continue; for (int i = 0; i < 2; ++i) { - const Token * const valueTok = (i == 0) ? tok->astOperand1() : tok->astOperand2(); - const Token * const typeTok = valueTok->astSibling(); - const ValueType* const typeVt = typeTok->valueType(); - if (!valueTok->hasKnownIntValue() || !typeVt || typeVt->pointer) + const Token* const valueTok = (i == 0) ? tok->astOperand1() : tok->astOperand2(); + const Token* const typeTok = valueTok->astSibling(); + const ValueType* const valueType = valueTok->valueType(); + const ValueType* const type = typeTok ? typeTok->valueType() : nullptr; + if (!valueTok->hasKnownIntValue() || !valueType || !type || valueType->pointer || type->pointer || + !valueType->isIntegral() || !type->isIntegral() || typeTok->isLiteral()) continue; - if (valueTok->getKnownIntValue() < 0 && valueTok->valueType() && valueTok->valueType()->sign != ValueType::Sign::SIGNED) + + const MathLib::bigint knownValue = valueTok->getKnownIntValue(); + ValueType resolvedType = *type; + resolvedType.sign = ValueFlow::resolveCharSign(resolvedType, mSettings.platform); + const bool plainChar = resolvedType.type == ValueType::Type::CHAR && + resolvedType.sign == ValueType::Sign::UNKNOWN_SIGN; + const bool unsignedPlainChar = resolvedType.type == ValueType::Type::CHAR && + type->sign == ValueType::Sign::UNKNOWN_SIGN && + resolvedType.sign == ValueType::Sign::UNSIGNED; + if (knownValue == 0 && !unsignedPlainChar) + continue; // prevent overlap with TestOther::unsignedPositive/unsignedLessThanZero + if (!valueFitsType(*valueType, knownValue, mSettings)) continue; - if (typeTok->isLiteral()) + + const ValueType commonType = ValueType::getCommonIntegralType(&resolvedType, valueType, mSettings); + if (!commonType.isIntegral() || commonType.type == ValueType::Type::UNKNOWN_INT || + commonType.sign == ValueType::Sign::UNKNOWN_SIGN) continue; - std::uint8_t bits = 0; - switch (typeVt->type) { - case ValueType::Type::BOOL: - bits = 1; - break; - case ValueType::Type::CHAR: - bits = mSettings.platform.char_bit; - break; - case ValueType::Type::SHORT: - bits = mSettings.platform.short_bit; - break; - case ValueType::Type::INT: - bits = mSettings.platform.int_bit; - break; - case ValueType::Type::LONG: - bits = mSettings.platform.long_bit; - break; - case ValueType::Type::LONGLONG: - bits = mSettings.platform.long_long_bit; - break; - default: - break; - } - if (bits == 0 || bits >= 63) + + const std::size_t sourceBits = getBits(resolvedType, mSettings); + const std::size_t commonBits = getBits(commonType, mSettings); + if (sourceBits == 0 || sourceBits > 64 || commonBits == 0 || commonBits > 64) continue; - const auto typeMinValue = (typeVt->sign == ValueType::Sign::UNSIGNED) ? 0 : (-(1LL << (bits-1))); - const auto unsignedTypeMaxValue = (1LL << bits) - 1LL; - long long typeMaxValue; - if (typeVt->sign != ValueType::Sign::SIGNED && !(typeVt->sign == ValueType::Sign::UNKNOWN_SIGN && typeVt->type == ValueType::Type::CHAR && mSettings.platform.defaultSign == 's')) - typeMaxValue = unsignedTypeMaxValue; - else if (bits >= mSettings.platform.int_bit && (!valueTok->valueType() || valueTok->valueType()->sign != ValueType::Sign::SIGNED)) - typeMaxValue = unsignedTypeMaxValue; - else - typeMaxValue = unsignedTypeMaxValue / 2; + const bool commonUnsigned = commonType.sign == ValueType::Sign::UNSIGNED; + IntegralRange range{}; + + // The operator of the comparison written with the constant as the right operand. + const std::string op = i == 0 ? invertOperatorForOperandSwap(tok->str()) : tok->str(); + bool charInvariant = false; + bool charResult = false; + if (plainChar) { + const bool equality = op == "==" || op == "!="; + bool sawTrue = false; + bool sawFalse = false; + if (commonUnsigned) { + const MathLib::biguint commonMaximum = ValueFlow::getUnsignedMaximum(commonBits); + const MathLib::biguint known = ValueFlow::convertToUnsigned(knownValue, commonBits); + if (sourceBits > commonBits) + continue; + const MathLib::biguint sourceMaximum = ValueFlow::getUnsignedMaximum(sourceBits); + MathLib::bigint signedMinimum{}, signedMaximum{}; + if (!getSignedBounds(sourceBits, signedMinimum, signedMaximum)) + continue; + const MathLib::biguint negativeCount = MathLib::biguint{1} << (sourceBits - 1); + const MathLib::biguint negativeMinimum = commonMaximum - negativeCount + 1; + inspectRange(op, equality, known, MathLib::biguint{0}, sourceMaximum, sawTrue, sawFalse); + // Signed-char negatives after the unsigned conversion. + inspectRange(op, equality, known, negativeMinimum, commonMaximum, sawTrue, sawFalse); + } else { + MathLib::bigint commonMinimum{}, commonMaximum{}; + MathLib::bigint signedMinimum{}, signedMaximum{}; + if (!getSignedBounds(commonBits, commonMinimum, commonMaximum) || + !getSignedBounds(sourceBits, signedMinimum, signedMaximum) || + sourceBits >= commonBits || + ValueFlow::getUnsignedMaximum(sourceBits) > static_cast(commonMaximum)) + continue; + const MathLib::biguint sourceMaximum = ValueFlow::getUnsignedMaximum(sourceBits); + inspectRange(op, equality, knownValue, signedMinimum, signedMaximum, sawTrue, sawFalse); + // Unsigned-char image. + inspectRange(op, equality, knownValue, MathLib::bigint{0}, + static_cast(sourceMaximum), sawTrue, sawFalse); + } + charInvariant = !(sawTrue && sawFalse); + charResult = sawTrue; + } - bool result{}; - const auto kiv = valueTok->getKnownIntValue(); - if (kiv == 0) - continue; // prevent overlap with TestOther::unsignedPositive/unsignedLessThanZero - if (tok->str() == "==") - result = false; - else if (tok->str() == "!=") - result = true; - else if (tok->str()[0] == '>' && i == 0) - // num > var - result = (kiv > 0); - else if (tok->str()[0] == '>' && i == 1) - // var > num - result = (kiv < 0); - else if (tok->str()[0] == '<' && i == 0) - // num < var - result = (kiv < 0); - else if (tok->str()[0] == '<' && i == 1) - // var < num - result = (kiv > 0); - - bool error = false; - if (kiv < typeMinValue || kiv > typeMaxValue) { - error = true; - } else { - switch (i) { - case 0: // num cmp var - if (kiv == typeMinValue) { - if (tok->str() == "<=") { - result = true; - error = true; - } else if (tok->str() == ">") - error = true; - } - else if (kiv == typeMaxValue && (tok->str() == ">=" || tok->str() == "<")) { - error = true; - } - break; - case 1: // var cmp num - if (kiv == typeMinValue) { - if (tok->str() == ">=") { - result = true; - error = true; - } else if (tok->str() == "<") - error = true; - } - else if (kiv == typeMaxValue && (tok->str() == "<=" || tok->str() == ">")) { - error = true; - } - break; + if (!plainChar && commonUnsigned) { + const bool sourceUnsigned = resolvedType.sign == ValueType::Sign::UNSIGNED || + resolvedType.type == ValueType::Type::BOOL; + if ((!sourceUnsigned && resolvedType.sign != ValueType::Sign::SIGNED) || sourceBits > commonBits) + continue; + const MathLib::biguint commonMaximum = ValueFlow::getUnsignedMaximum(commonBits); + const MathLib::biguint unsignedValue = ValueFlow::convertToUnsigned(knownValue, commonBits); + // The source type is converted to [0, lowMaximum]. The negative values of a narrower + // signed source are converted to the top of the unsigned range instead. + MathLib::biguint lowMaximum = commonMaximum; + MathLib::biguint imageMaximum = commonMaximum; + bool inNegativeImage = false; + if (sourceUnsigned) { + lowMaximum = ValueFlow::getUnsignedMaximum(sourceBits); + imageMaximum = lowMaximum; + } else if (sourceBits < commonBits) { + const MathLib::biguint negativeCount = MathLib::biguint{1} << (sourceBits - 1); + lowMaximum = negativeCount - 1; + inNegativeImage = unsignedValue >= commonMaximum - negativeCount + 1; + } + range.inImage = unsignedValue <= lowMaximum || inNegativeImage; + range.above = unsignedValue > imageMaximum; + range.atMinimum = unsignedValue == 0; + range.atMaximum = unsignedValue == imageMaximum; + } else if (!plainChar) { + MathLib::bigint signedMinimum{}; + MathLib::bigint signedMaximum{}; + if (!getSignedBounds(commonBits, signedMinimum, signedMaximum)) + continue; + if (resolvedType.type == ValueType::Type::BOOL) { + signedMinimum = 0; + signedMaximum = 1; + } else if (resolvedType.sign == ValueType::Sign::SIGNED) { + if (sourceBits > commonBits || !getSignedBounds(sourceBits, signedMinimum, signedMaximum)) + continue; + } else if (resolvedType.sign == ValueType::Sign::UNSIGNED) { + const MathLib::biguint sourceMaximum = ValueFlow::getUnsignedMaximum(sourceBits); + if (sourceBits >= commonBits || sourceMaximum > static_cast(signedMaximum)) + continue; + signedMinimum = 0; + signedMaximum = static_cast(sourceMaximum); + } else { + continue; } + if (valueType->sign == ValueType::Sign::UNSIGNED && knownValue < 0) + continue; + range.below = knownValue < signedMinimum; + range.above = knownValue > signedMaximum; + range.inImage = !range.below && !range.above; + range.atMinimum = knownValue == signedMinimum; + range.atMaximum = knownValue == signedMaximum; + } + + IntegralRangeComparison outcome{}; + if (plainChar) { + outcome.error = charInvariant; + outcome.result = charResult; + } else { + if (tok->hasKnownIntValue() && range.inImage && sourceBits == commonBits) + continue; + outcome = getIntegralRangeComparison(op, range); } - if (!error || diag(tok)) + if (!outcome.error || diag(tok)) continue; - compareValueOutOfTypeRangeError(valueTok, typeVt->str(), kiv, result); + const bool boolWarningEnabled = mSettings.severity.isEnabled(Severity::warning) || + mSettings.isPremiumEnabled("compareBoolExpressionWithInt"); + const bool boolEqualityComparison = Token::Match(tok, "==|!="); + const bool boolWarningAlreadyCoversComparison = + boolWarningEnabled && type->type == ValueType::Type::BOOL && boolEqualityComparison && + (knownValue < 0 || knownValue > 1) && !(typeTok->isOp() && valueTok->isName()); + if (boolWarningAlreadyCoversComparison) + continue; + + compareValueOutOfTypeRangeError(valueTok, + type->str(), + knownValue, + outcome.result); } } } diff --git a/lib/checktype.cpp b/lib/checktype.cpp index 76f73bc5700..7cede666ac9 100644 --- a/lib/checktype.cpp +++ b/lib/checktype.cpp @@ -98,14 +98,51 @@ void CheckTypeImpl::checkTooBigBitwiseShift() else continue; - // Get biggest rhs value. preferably a value which doesn't have 'condition'. - const ValueFlow::Value * value = tok->astOperand2()->getValueGE(lhsbits, mSettings); + // Get the biggest feasible rhs value, preferring a value without a condition. + const Token* const shiftCount = tok->astOperand2(); + const auto isUnreachableTernaryValue = [&](const ValueFlow::Value& candidate) { + const Token* child = shiftCount; + for (const Token* parent = child->astParent(); parent; child = parent, parent = parent->astParent()) { + if (parent->str() != ":" || !Token::simpleMatch(parent->astParent(), "?")) + continue; + const bool inTrueBranch = child == parent->astOperand1(); + const bool inFalseBranch = child == parent->astOperand2(); + if (!inTrueBranch && !inFalseBranch) + continue; + const Token* condition = parent->astParent()->astOperand1(); + bool canEnterBranch = false; + bool canEnterOtherBranch = false; + for (const ValueFlow::Value& value : condition->values()) { + if (!value.isIntValue() || value.isImpossible() || value.bound != ValueFlow::Value::Bound::Point || + (value.path != 0 && (candidate.path == 0 || value.path != candidate.path))) + continue; + if ((value.intvalue != 0) == inTrueBranch) + canEnterBranch = true; + else + canEnterOtherBranch = true; + } + return canEnterOtherBranch && !canEnterBranch; + } + return false; + }; + const auto getShiftCountValueGE = [&](MathLib::bigint threshold) -> const ValueFlow::Value* { + return ValueFlow::findValue(shiftCount->values(), mSettings, [&](const ValueFlow::Value& candidate) { + if (candidate.isImpossible() || !candidate.isIntValue() || candidate.intvalue < threshold || + isUnreachableTernaryValue(candidate)) + return false; + return std::none_of(shiftCount->values().cbegin(), shiftCount->values().cend(), [&](const ValueFlow::Value& bound) { + return bound.isImpossible() && bound.isIntValue() && bound.bound == ValueFlow::Value::Bound::Lower && + bound.intvalue <= threshold && (bound.path == 0 || bound.path == candidate.path); + }); + }); + }; + const ValueFlow::Value * value = getShiftCountValueGE(lhsbits); if (value && mSettings.isEnabled(value, false)) tooBigBitwiseShiftError(tok, lhsbits, *value); else if (lhstype->sign == ValueType::Sign::SIGNED && Token::Match(tok, "<<|<<=")) { // Shifting a signed value left by its width minus one bit is undefined. A right shift by // that many bits is defined (implementation-defined for a negative value, as any right shift). - value = tok->astOperand2()->getValueGE(lhsbits-1, mSettings); + value = getShiftCountValueGE(lhsbits - 1); if (value && mSettings.isEnabled(value, false)) tooBigSignedBitwiseShiftError(tok, lhsbits, *value); } @@ -495,15 +532,18 @@ void CheckTypeImpl::checkFloatToIntegerOverflow(const Token *tok, const ValueTyp return; for (const ValueFlow::Value &f : floatValues) { - if (f.valueType != ValueFlow::Value::ValueType::FLOAT) + if (f.valueType != ValueFlow::Value::ValueType::FLOAT || f.isImpossible()) continue; if (!mSettings.isEnabled(&f, false)) continue; - if (f.floatValue >= std::exp2(mSettings.platform.long_long_bit)) + + const bool positiveEvidence = f.bound != ValueFlow::Value::Bound::Upper; + const bool negativeEvidence = f.bound != ValueFlow::Value::Bound::Lower; + if (positiveEvidence && f.floatValue >= std::exp2(mSettings.platform.long_long_bit)) floatToIntegerOverflowError(tok, f); - else if ((-f.floatValue) > std::exp2(mSettings.platform.long_long_bit - 1)) + else if (negativeEvidence && (-f.floatValue) > std::exp2(mSettings.platform.long_long_bit - 1)) floatToIntegerOverflowError(tok, f); - else if (mSettings.platform.type != Platform::Type::Unspecified) { + else if (positiveEvidence && mSettings.platform.type != Platform::Type::Unspecified) { int bits = 0; if (vtint->type == ValueType::Type::CHAR) bits = mSettings.platform.char_bit; diff --git a/lib/infer.cpp b/lib/infer.cpp index cad0761f68b..cfac7711b22 100644 --- a/lib/infer.cpp +++ b/lib/infer.cpp @@ -24,6 +24,7 @@ #include "valueptr.h" #include "vfvalue.h" +#include #include #include #include @@ -127,7 +128,8 @@ namespace { Interval result; const ValueFlow::Value* minValue = getCompareValue(values, predicate, std::less{}); if (minValue) { - if (minValue->isImpossible() && minValue->bound == ValueFlow::Value::Bound::Upper) + if (minValue->isImpossible() && minValue->bound == ValueFlow::Value::Bound::Upper && + minValue->intvalue != std::numeric_limits::max()) result.setMinValue(minValue->intvalue + 1, minValue); if (minValue->isPossible() && minValue->bound == ValueFlow::Value::Bound::Lower) result.setMinValue(minValue->intvalue, minValue); @@ -137,7 +139,8 @@ namespace { } const ValueFlow::Value* maxValue = getCompareValue(values, predicate, std::greater{}); if (maxValue) { - if (maxValue->isImpossible() && maxValue->bound == ValueFlow::Value::Bound::Lower) + if (maxValue->isImpossible() && maxValue->bound == ValueFlow::Value::Bound::Lower && + maxValue->intvalue != std::numeric_limits::min()) result.setMaxValue(maxValue->intvalue - 1, maxValue); if (maxValue->isPossible() && maxValue->bound == ValueFlow::Value::Bound::Upper) result.setMaxValue(maxValue->intvalue, maxValue); @@ -146,13 +149,6 @@ namespace { return result; } - static Interval fromValues(const std::list& values) - { - return Interval::fromValues(values, [](const ValueFlow::Value&) { - return true; - }); - } - template static std::vector apply(const std::vector& x, const std::vector& y, @@ -237,12 +233,37 @@ namespace { }; } -static void addToErrorPath(ValueFlow::Value& value, const std::vector& refs) +static bool isOnPath(const ValueFlow::Value& value, MathLib::bigint path) +{ + return value.path == 0 || value.path == path; +} + +static bool addToErrorPath(ValueFlow::Value& value, const std::vector& refs) { std::unordered_set locations; + const Token* condition = nullptr; + MathLib::bigint path = 0; + nonneg int varId = 0; + MathLib::bigint varvalue = 0; + bool conflictingVariable = false; for (const ValueFlow::Value* ref : refs) { - if (ref->condition && !value.condition) - value.condition = ref->condition; + if (ref->path < 0 || (ref->path > 0 && path > 0 && ref->path != path)) + return false; + if (ref->path > 0) + path = ref->path; + if (ref->condition && !condition) + condition = ref->condition; + if (ref->varId) { + if (varId && (varId != ref->varId || varvalue != ref->varvalue)) + conflictingVariable = true; + else { + varId = ref->varId; + varvalue = ref->varvalue; + } + } + value.conditional = value.conditional || ref->conditional; + value.defaultArg = value.defaultArg || ref->defaultArg; + value.safe = value.safe || ref->safe; std::copy_if(ref->errorPath.cbegin(), ref->errorPath.cend(), std::back_inserter(value.errorPath), @@ -256,6 +277,16 @@ static void addToErrorPath(ValueFlow::Value& value, const std::vector& refs) @@ -270,80 +301,131 @@ static void setValueKind(ValueFlow::Value& value, const std::vector 0) value.setPossible(); else value.setKnown(); } -static bool inferNotEqual(const std::list& values, MathLib::bigint x) +// The paths on which two value lists can be compared: 0 when both lists have values that +// are not tied to a path, and every path that occurs in both lists. An empty list is +// compatible with every path. +std::vector getCommonPaths(const std::list& lhsValues, + const std::list& rhsValues) { - return std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& value) { - return value.isImpossible() && value.intvalue == x; + std::vector paths; + const auto addPath = [&](MathLib::bigint path) { + if (std::find(paths.cbegin(), paths.cend(), path) == paths.cend()) + paths.push_back(path); + }; + const auto hasPath = [](const std::list& values, MathLib::bigint path) { + if (values.empty()) + return true; + return std::any_of(values.cbegin(), values.cend(), [path](const ValueFlow::Value& value) { + return isOnPath(value, path); + }); + }; + if (hasPath(lhsValues, 0) && hasPath(rhsValues, 0)) + addPath(0); + for (const ValueFlow::Value& value : lhsValues) { + if (value.path > 0 && hasPath(rhsValues, value.path)) + addPath(value.path); + } + for (const ValueFlow::Value& value : rhsValues) { + if (value.path > 0 && hasPath(lhsValues, value.path)) + addPath(value.path); + } + return paths; +} + +template +static const ValueFlow::Value* findImpossiblePoint(const ValuePtr& model, + const std::list& values, + const std::vector& scalarRefs, + MathLib::bigint x, + PathPredicate onPath) +{ + const auto it = std::find_if(values.cbegin(), values.cend(), [&](const ValueFlow::Value& value) { + if (!model->match(value) || !onPath(value) || !value.isImpossible() || + value.bound != ValueFlow::Value::Bound::Point || value.intvalue != x) + return false; + return std::any_of(scalarRefs.cbegin(), scalarRefs.cend(), [&](const ValueFlow::Value* ref) { + return model->match(*ref) && value.equalValue(*ref); + }); }); + return it == values.cend() ? nullptr : &*it; } -std::vector infer(const ValuePtr& model, - const std::string& op, - std::list lhsValues, - std::list rhsValues) +template +static std::vector inferIntervals(const ValuePtr& model, + const std::string& op, + const std::list& lhsValues2, + const std::list& rhsValues2, + PathPredicate onPath) { - std::vector result; - auto notMatch = [&](const ValueFlow::Value& value) { - return !model->match(value); + const auto predicate = [&](const ValueFlow::Value& value) { + return model->match(value) && onPath(value); }; - lhsValues.remove_if(notMatch); - if (lhsValues.empty()) - return result; - rhsValues.remove_if(notMatch); - if (rhsValues.empty()) - return result; - - Interval lhs = Interval::fromValues(lhsValues); - Interval rhs = Interval::fromValues(rhsValues); - + std::vector inferred; + Interval lhs = Interval::fromValues(lhsValues2, predicate); + Interval rhs = Interval::fromValues(rhsValues2, predicate); + + const ValueFlow::Value* excludedPoint = nullptr; + std::vector excludedRefs; + if (op == "!=" || op == "==") { + if (lhs.isScalar()) { + std::vector scalarRefs = lhs.getScalarRef(); + excludedPoint = findImpossiblePoint(model, rhsValues2, scalarRefs, lhs.getScalar(), onPath); + if (excludedPoint) + excludedRefs = std::move(scalarRefs); + } + if (!excludedPoint && rhs.isScalar()) { + std::vector scalarRefs = rhs.getScalarRef(); + excludedPoint = findImpossiblePoint(model, lhsValues2, scalarRefs, rhs.getScalar(), onPath); + if (excludedPoint) + excludedRefs = std::move(scalarRefs); + } + if (excludedPoint) + excludedRefs.push_back(excludedPoint); + } if (op == "-") { Interval diff = lhs - rhs; if (diff.isScalar()) { std::vector refs = diff.getScalarRef(); ValueFlow::Value value(diff.getScalar()); - addToErrorPath(value, refs); - setValueKind(value, refs); - result.push_back(std::move(value)); + if (addToErrorPath(value, refs)) { + setValueKind(value, refs); + inferred.push_back(std::move(value)); + } } else { if (!diff.minvalue.empty()) { ValueFlow::Value value(diff.minvalue.front() - 1); value.setImpossible(); value.bound = ValueFlow::Value::Bound::Upper; - addToErrorPath(value, diff.minRef); - result.push_back(std::move(value)); + if (addToErrorPath(value, diff.minRef)) + inferred.push_back(std::move(value)); } if (!diff.maxvalue.empty()) { ValueFlow::Value value(diff.maxvalue.front() + 1); value.setImpossible(); value.bound = ValueFlow::Value::Bound::Lower; - addToErrorPath(value, diff.maxRef); - result.push_back(std::move(value)); + if (addToErrorPath(value, diff.maxRef)) + inferred.push_back(std::move(value)); } } + } else if (excludedPoint) { + ValueFlow::Value value(op == "!="); + if (addToErrorPath(value, excludedRefs)) { + setValueKind(value, excludedRefs); + inferred.push_back(std::move(value)); + } } else if ((op == "!=" || op == "==") && lhs.isScalarOrEmpty() && rhs.isScalarOrEmpty()) { if (lhs.isScalar() && rhs.isScalar()) { std::vector refs = Interval::merge(lhs.getScalarRef(), rhs.getScalarRef()); ValueFlow::Value value(calculate(op, lhs.getScalar(), rhs.getScalar())); - addToErrorPath(value, refs); - setValueKind(value, refs); - result.push_back(std::move(value)); - } else { - std::vector refs; - if (lhs.isScalar() && inferNotEqual(rhsValues, lhs.getScalar())) - refs = lhs.getScalarRef(); - else if (rhs.isScalar() && inferNotEqual(lhsValues, rhs.getScalar())) - refs = rhs.getScalarRef(); - if (!refs.empty()) { - ValueFlow::Value value(op == "!="); - addToErrorPath(value, refs); + if (addToErrorPath(value, refs)) { setValueKind(value, refs); - result.push_back(std::move(value)); + inferred.push_back(std::move(value)); } } } else { @@ -351,12 +433,53 @@ std::vector infer(const ValuePtr& model, std::vector r = Interval::compare(op, lhs, rhs, &refs); if (!r.empty()) { ValueFlow::Value value(static_cast(r.front())); - addToErrorPath(value, refs); - setValueKind(value, refs); - result.push_back(std::move(value)); + if (addToErrorPath(value, refs)) { + setValueKind(value, refs); + inferred.push_back(std::move(value)); + } } } + return inferred; +} + +std::vector infer(const ValuePtr& model, + const std::string& op, + std::list lhsValues, + std::list rhsValues) +{ + auto notMatch = [&](const ValueFlow::Value& value) { + return !model->match(value); + }; + lhsValues.remove_if(notMatch); + if (lhsValues.empty()) + return {}; + rhsValues.remove_if(notMatch); + if (rhsValues.empty()) + return {}; + + lhsValues.remove_if([](const ValueFlow::Value& value) { + return value.path < 0; + }); + rhsValues.remove_if([](const ValueFlow::Value& value) { + return value.path < 0; + }); + if (lhsValues.empty() || rhsValues.empty()) + return {}; + + const std::vector paths = getCommonPaths(lhsValues, rhsValues); + if (paths.size() == 1 && paths.front() == 0) { + return inferIntervals(model, op, lhsValues, rhsValues, [](const ValueFlow::Value&) { + return true; + }); + } + std::vector result; + for (MathLib::bigint path : paths) { + std::vector inferred = inferIntervals(model, op, lhsValues, rhsValues, [path](const ValueFlow::Value& value) { + return isOnPath(value, path); + }); + std::move(inferred.begin(), inferred.end(), std::back_inserter(result)); + } return result; } @@ -378,14 +501,23 @@ std::vector infer(const ValuePtr& model, std::vector getMinValue(const ValuePtr& model, const std::list& values) { - return Interval::fromValues(values, [&](const ValueFlow::Value& v) { - return model->match(v); + return Interval::fromValues(values, [&](const ValueFlow::Value& value) { + return model->match(value); }).minvalue; } + +const ValueFlow::Value* getMinValueSource(const ValuePtr& model, const std::list& values) +{ + const Interval interval = Interval::fromValues(values, [&](const ValueFlow::Value& value) { + return model->match(value); + }); + return interval.minRef.empty() ? nullptr : interval.minRef.front(); +} + std::vector getMaxValue(const ValuePtr& model, const std::list& values) { - return Interval::fromValues(values, [&](const ValueFlow::Value& v) { - return model->match(v); + return Interval::fromValues(values, [&](const ValueFlow::Value& value) { + return model->match(value); }).maxvalue; } diff --git a/lib/infer.h b/lib/infer.h index 8d66d7da016..1f2072e3bc6 100644 --- a/lib/infer.h +++ b/lib/infer.h @@ -43,10 +43,10 @@ struct InferModel { InferModel() = default; }; -std::vector infer(const ValuePtr& model, - const std::string& op, - std::list lhsValues, - std::list rhsValues); +CPPCHECKLIB std::vector infer(const ValuePtr& model, + const std::string& op, + std::list lhsValues, + std::list rhsValues); std::vector infer(const ValuePtr& model, const std::string& op, @@ -59,9 +59,15 @@ std::vector infer(const ValuePtr& model, MathLib::bigint rhs); CPPCHECKLIB std::vector getMinValue(const ValuePtr& model, const std::list& values); -std::vector getMaxValue(const ValuePtr& model, const std::list& values); +/** The value in `values` that getMinValue() derives the minimum from, nullptr when there is no minimum */ +CPPCHECKLIB const ValueFlow::Value* getMinValueSource(const ValuePtr& model, const std::list& values); +CPPCHECKLIB std::vector getMaxValue(const ValuePtr& model, const std::list& values); + +/** The paths on which two value lists can be compared */ +std::vector getCommonPaths(const std::list& lhsValues, + const std::list& rhsValues); -ValuePtr makeIntegralInferModel(); +CPPCHECKLIB ValuePtr makeIntegralInferModel(); ValueFlow::Value inferCondition(const std::string& op, const Token* varTok, MathLib::bigint val); diff --git a/lib/programmemory.cpp b/lib/programmemory.cpp index 95d977e5f26..33ee9d0791c 100644 --- a/lib/programmemory.cpp +++ b/lib/programmemory.cpp @@ -523,7 +523,7 @@ static void programMemoryParseCondition(ProgramMemory& pm, if (Token::Match(tok, "==|>=|<=|<|>|!=")) { ValueFlow::Value truevalue; ValueFlow::Value falsevalue; - const Token* vartok = parseCompareInt(tok, truevalue, falsevalue, eval); + const Token* vartok = parseCompareInt(tok, truevalue, falsevalue, settings, eval); if (!vartok) return; if (vartok->exprId() == 0) diff --git a/lib/settings.cpp b/lib/settings.cpp index da576f7a5c8..5eba8aca405 100644 --- a/lib/settings.cpp +++ b/lib/settings.cpp @@ -350,6 +350,9 @@ void Settings::setCheckLevel(CheckLevel level) else if (level == CheckLevel::exhaustive) { // Checking can take a little while. ~ 10 times slower than normal analysis is OK. checkLevel = CheckLevel::exhaustive; + // A conversion can be proven from range facts that are only derived in the previous pass, + // so the facts a cast exposes need one more pass to reach their fixpoint. + vfOptions.maxIterations = 5; vfOptions.maxIfCount = -1; vfOptions.maxSubFunctionArgs = 256; vfOptions.doConditionExpressionAnalysis = true; diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp index d321281b31d..b17dc222b07 100644 --- a/lib/symboldatabase.cpp +++ b/lib/symboldatabase.cpp @@ -66,6 +66,12 @@ static int qualifierBit(int indirection) return static_cast(1U << indirection); } +// wchar_t is unsigned 16-bit on Windows and signed 32-bit on common Unix ABIs +static ValueType::Sign wcharSign(const Platform& platform) +{ + return platform.sizeof_wchar_t == 2 ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED; +} + SymbolDatabase::SymbolDatabase(Tokenizer& tokenizer) : mTokenizer(tokenizer) , mSettings(tokenizer.getSettings()) @@ -6968,7 +6974,7 @@ void SymbolDatabase::setValueType(Token* tok, const Variable& var, const SourceL } } -static ValueType::Type getEnumType(const Scope* scope, const Platform& platform); +static ValueType getEnumType(const Scope* scope, const Platform& platform); void SymbolDatabase::setValueType(Token* tok, const Enumerator& enumerator, const SourceLocation &loc) { @@ -6997,8 +7003,9 @@ void SymbolDatabase::setValueType(Token* tok, const Enumerator& enumerator, cons setValueType(tok, valuetype); } else { - valuetype.sign = ValueType::SIGNED; - valuetype.type = getEnumType(enumerator.scope, mSettings.platform); + const ValueType enumType = getEnumType(enumerator.scope, mSettings.platform); + valuetype.sign = enumType.sign; + valuetype.type = enumType.type; setValueType(tok, valuetype); } } @@ -7489,10 +7496,17 @@ void SymbolDatabase::setValueType(Token* tok, const ValueType& valuetype, const return; } - if (vt1->isTypeEqual(vt2)) { + if (vt1->isTypeEqual(vt2) && vt1->sign == vt2->sign) { setValueType(parent, *vt1); return; } + + if (vt1->pointer == 0U && vt2 && vt2->pointer == 0U && vt1->isIntegral() && vt2->isIntegral()) { + const ValueType commonType = ValueType::getCommonIntegralType(vt1, vt2, mSettings); + if (commonType.type != ValueType::Type::UNKNOWN_TYPE) + setValueType(parent, commonType); + return; + } } if (vt1->pointer != 0U) { @@ -7532,63 +7546,266 @@ void SymbolDatabase::setValueType(Token* tok, const ValueType& valuetype, const if (vt1->isIntegral() && vt1->pointer == 0U && (!vt2 || (vt2->isIntegral() && vt2->pointer == 0U)) && (ternary || parent->isArithmeticalOp() || parent->tokType() == Token::eBitOp || parent->tokType() == Token::eIncDecOp || parent->isAssignmentOp())) { + if (parent->isAssignmentOp()) { + setValueType(parent, *vt1); + return; + } + if (parent->tokType() == Token::eIncDecOp) { + // Build a fresh type so bitfield width, constness, references + // and similar operand properties are not copied to the result. + setValueType(parent, ValueType(vt1->sign, vt1->type, 0, 0, vt1->originalTypeName)); + return; + } + const ValueType vt = ValueType::getCommonIntegralType(vt1, vt2, mSettings); + if (vt.type != ValueType::Type::UNKNOWN_TYPE) + setValueType(parent, vt); + return; + } +} - ValueType vt; - if (!vt2 || vt1->type > vt2->type) { - vt.type = vt1->type; - vt.sign = vt1->sign; - vt.originalTypeName = vt1->originalTypeName; - } else if (vt1->type == vt2->type) { - vt.type = vt1->type; - if (vt1->sign == ValueType::Sign::UNSIGNED || vt2->sign == ValueType::Sign::UNSIGNED) - vt.sign = ValueType::Sign::UNSIGNED; - else if (vt1->sign == ValueType::Sign::UNKNOWN_SIGN || vt2->sign == ValueType::Sign::UNKNOWN_SIGN) - vt.sign = ValueType::Sign::UNKNOWN_SIGN; - else - vt.sign = ValueType::Sign::SIGNED; - vt.originalTypeName = (vt1->originalTypeName.empty() ? vt2 : vt1)->originalTypeName; - } else { - vt.type = vt2->type; - vt.sign = vt2->sign; - vt.originalTypeName = vt2->originalTypeName; +ValueType ValueType::getCommonIntegralType(const ValueType* lhs, const ValueType* rhs, const Settings& settings) +{ + if (!lhs || !lhs->isIntegral() || lhs->pointer || (rhs && (!rhs->isIntegral() || rhs->pointer))) + return {}; + + const auto getBits = [&](const ValueType& type) { + return type.getSizeOf(settings, Accuracy::ExactOrZero, SizeOf::Pointee) * settings.platform.char_bit; + }; + const auto promote = [&](const ValueType& type) { + if (type.type == Type::BOOL) + return ValueType(Sign::SIGNED, Type::INT, 0); + if (type.type != Type::CHAR && type.type != Type::SHORT && type.type != Type::WCHAR_T) { + // Not promoted: build a fresh type so bitfield width, constness, + // references and similar operand properties are not copied to the result. + return ValueType(type.sign, type.type, 0, 0, type.originalTypeName); + } + + ValueType result(Sign::UNKNOWN_SIGN, Type::INT, 0); + const std::size_t sourceBits = getBits(type); + const std::size_t intBits = settings.platform.int_bit; + if (sourceBits == 0 || intBits == 0) + return result; + if (type.sign == Sign::SIGNED) + result.sign = sourceBits <= intBits ? Sign::SIGNED : Sign::UNSIGNED; + else if (type.sign == Sign::UNSIGNED) + result.sign = sourceBits < intBits ? Sign::SIGNED : Sign::UNSIGNED; + else if (sourceBits < intBits) + result.sign = Sign::SIGNED; + return result; + }; + + const ValueType first = promote(*lhs); + if (!rhs) + return first; + const ValueType second = promote(*rhs); + if (first.type == Type::UNKNOWN_INT || second.type == Type::UNKNOWN_INT) { + if (first.type == second.type && first.sign == second.sign) + return first; + const Sign commonSign = first.sign == second.sign ? first.sign : Sign::UNKNOWN_SIGN; + return ValueType(commonSign, Type::UNKNOWN_INT, 0); + } + const ValueType* const higherRank = first.type >= second.type ? &first : &second; + ValueType result(Sign::UNKNOWN_SIGN, higherRank->type, 0); + result.originalTypeName = higherRank->originalTypeName; + + if (first.sign == second.sign) { + result.sign = first.sign; + return result; + } + if (first.sign == Sign::UNKNOWN_SIGN || second.sign == Sign::UNKNOWN_SIGN) + return result; + + const ValueType& unsignedType = first.sign == Sign::UNSIGNED ? first : second; + const ValueType& signedType = first.sign == Sign::SIGNED ? first : second; + if (unsignedType.type >= signedType.type) { + result.type = unsignedType.type; + result.sign = Sign::UNSIGNED; + result.originalTypeName = unsignedType.originalTypeName; + } else if (getBits(signedType) > getBits(unsignedType)) { + result.type = signedType.type; + result.sign = Sign::SIGNED; + result.originalTypeName = signedType.originalTypeName; + } else { + result.type = signedType.type; + result.sign = Sign::UNSIGNED; + result.originalTypeName.clear(); + } + return result; +} + + +namespace { + /** Constant value of an enumerator initializer, as an unsigned magnitude plus sign. */ + struct EnumConstant { + MathLib::biguint magnitude{}; + bool negative{}; + bool known{}; + }; + + unsigned int integralBits(ValueType::Type type, const Platform& platform) + { + switch (type) { + case ValueType::Type::INT: + return platform.int_bit; + case ValueType::Type::LONG: + return platform.long_bit; + case ValueType::Type::LONGLONG: + return platform.long_long_bit; + default: + return 0; } - if (vt.type < ValueType::Type::INT && !(ternary && vt.type==ValueType::Type::BOOL)) { - vt.type = ValueType::Type::INT; - vt.sign = ValueType::Sign::SIGNED; - vt.originalTypeName.clear(); + } + + /** Can the value be represented by the given (integral, non-pointer) type? */ + bool isEnumValueRepresentable(const ValueType& type, const EnumConstant& value, const Platform& platform) + { + const unsigned int bits = integralBits(type.type, platform); + if (bits == 0 || bits > MathLib::bigint_bits) + return true; // unknown size -> do not widen + const MathLib::biguint signBit = static_cast(1) << (bits - 1); + if (type.sign == ValueType::Sign::UNSIGNED) + return !value.negative && value.magnitude < signBit * 2; + return value.negative ? value.magnitude <= signBit : value.magnitude < signBit; + } + + /** Widen the type until it can represent the value. Follows the integer conversion rank. */ + ValueType widenEnumType(ValueType type, const EnumConstant& value, const Platform& platform) + { + while (!isEnumValueRepresentable(type, value, platform)) { + if (type.sign == ValueType::Sign::SIGNED) + type.sign = ValueType::Sign::UNSIGNED; + else if (type.type == ValueType::Type::INT) + type = ValueType(ValueType::Sign::SIGNED, ValueType::Type::LONG, 0); + else if (type.type == ValueType::Type::LONG) + type = ValueType(ValueType::Sign::SIGNED, ValueType::Type::LONGLONG, 0); + else + break; // does not fit even in unsigned long long } + return type; + } - setValueType(parent, vt); - return; + EnumConstant evaluateEnumConstant(const Token* tok, + const std::unordered_map& known, + int depth) + { + EnumConstant result; + if (!tok || depth < 0) + return result; + + if (const Enumerator* enumerator = tok->enumerator()) { + if (!enumerator->name) + return result; + const auto it = known.find(enumerator->name->str()); + if (it != known.end()) + return it->second; + return result; + } + + if (tok->isNumber() && MathLib::isInt(tok->str())) { + try { + result.magnitude = MathLib::toBigUNumber(MathLib::abs(tok->str()), tok); + result.known = true; + } catch (const InternalError&) { + // Bad integer literal + } + return result; + } + + const Token* lhs = tok->astOperand1(); + const Token* rhs = tok->astOperand2(); + if (!lhs && rhs) + return evaluateEnumConstant(rhs, known, depth - 1); + if (!lhs) + return result; + + if (tok->isUnaryOp("-")) { + result = evaluateEnumConstant(lhs, known, depth - 1); + if (result.known && result.magnitude != 0) + result.negative = !result.negative; + return result; + } + if (tok->isUnaryOp("+")) + return evaluateEnumConstant(lhs, known, depth - 1); + if (!rhs) + return result; + + const EnumConstant a = evaluateEnumConstant(lhs, known, depth - 1); + const EnumConstant b = evaluateEnumConstant(rhs, known, depth - 1); + if (!a.known || !b.known) + return result; + + const std::string& op = tok->str(); + if (op == "+" || op == "-") { + const bool bNegative = (op == "-") ? !b.negative : b.negative; + if (a.negative == bNegative) { + result.magnitude = a.magnitude + b.magnitude; + result.negative = a.negative; + } else if (a.magnitude >= b.magnitude) { + result.magnitude = a.magnitude - b.magnitude; + result.negative = a.negative; + } else { + result.magnitude = b.magnitude - a.magnitude; + result.negative = bNegative; + } + if (result.magnitude == 0) + result.negative = false; + result.known = true; + return result; + } + if (a.negative || b.negative) + return result; // the remaining operators are only folded for non-negative values + + if (op == "*") { + if (a.magnitude != 0 && b.magnitude > std::numeric_limits::max() / a.magnitude) + return result; + result.magnitude = a.magnitude * b.magnitude; + result.known = true; + } else if (op == "<<" || op == ">>") { + if (b.magnitude >= MathLib::bigint_bits) + return result; + result.magnitude = (op == "<<") ? (a.magnitude << b.magnitude) : (a.magnitude >> b.magnitude); + result.known = true; + } else if (op == "|") { + result.magnitude = a.magnitude | b.magnitude; + result.known = true; + } else if (op == "&") { + result.magnitude = a.magnitude & b.magnitude; + result.known = true; + } else if (op == "^") { + result.magnitude = a.magnitude ^ b.magnitude; + result.known = true; + } + return result; } } -static ValueType::Type getEnumType(const Scope* scope, const Platform& platform) // TODO: also determine sign? +static ValueType getEnumType(const Scope* scope, const Platform& platform) { - ValueType::Type type = ValueType::Type::INT; - for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { - if (const Token* lam = findLambdaEndToken(tok)) { - tok = lam; - continue; + ValueType type(ValueType::Sign::SIGNED, ValueType::Type::INT, 0); + + // The compatible type must represent every enumerator, so widen for each known value. + std::unordered_map known; + MathLib::biguint next = 0; + for (const Enumerator& enumerator : scope->enumeratorList) { + EnumConstant value; + if (enumerator.start) { + const Token* const vTok = enumerator.start->previous() ? enumerator.start->previous()->astOperand2() : nullptr; + value = evaluateEnumConstant(vTok, known, 32); + } else if (enumerator.value_known) { + value.magnitude = enumerator.value; + value.known = true; + } else { + value.magnitude = next; + value.known = true; } - if (!tok->isAssignmentOp()) - continue; - const Token* vTok = tok->astOperand2(); - if (!vTok->hasKnownIntValue()) { - if (!vTok->isLiteral()) - continue; - if (const ValueType* vt = vTok->valueType()) { - if ((vt->type > type && (vt->type == ValueType::Type::LONG || vt->type == ValueType::Type::LONGLONG))) - type = vt->type; - } + if (!value.known) { + next = 0; continue; } - const MathLib::bigint value = vTok->getKnownIntValue(); - if (!platform.isIntValue(value)) { - type = ValueType::Type::LONG; - if (!platform.isLongValue(value)) - type = ValueType::Type::LONGLONG; - } + type = widenEnumType(std::move(type), value, platform); + if (enumerator.name) + known[enumerator.name->str()] = value; + next = value.negative ? 0 : value.magnitude + 1; } return type; } @@ -7624,8 +7841,9 @@ static const Token* parsedecl(const Token* type, valuetype->type = t; else if (enum_type->isStandardType()) valuetype->fromLibraryType(enum_type->str(), settings); - } else - valuetype->type = getEnumType(valuetype->typeScope, settings.platform); + } else { + valuetype->type = getEnumType(valuetype->typeScope, settings.platform).type; + } } else valuetype->type = ValueType::Type::RECORD; const bool cpp = type->isCpp(); @@ -7791,8 +8009,9 @@ static const Token* parsedecl(const Token* type, valuetype->type = type->str() == "struct" ? ValueType::Type::RECORD : ValueType::Type::NONSTD; else if (!valuetype->typeScope && type->type() && type->type()->classScope && valuetype->type != ValueType::Type::SMART_POINTER) { if (type->type()->classScope->type == ScopeType::eEnum) { - valuetype->sign = ValueType::Sign::SIGNED; - valuetype->type = getEnumType(type->type()->classScope, settings.platform); + const ValueType enumType = getEnumType(type->type()->classScope, settings.platform); + valuetype->sign = enumType.sign; + valuetype->type = enumType.type; } else { valuetype->type = ValueType::Type::RECORD; } @@ -7812,7 +8031,9 @@ static const Token* parsedecl(const Token* type, // Set signedness for integral types.. if (valuetype->isIntegral() && valuetype->sign == ValueType::Sign::UNKNOWN_SIGN) { - if (valuetype->type >= ValueType::Type::SHORT) + if (valuetype->type == ValueType::Type::WCHAR_T) + valuetype->sign = wcharSign(settings.platform); + else if (valuetype->type >= ValueType::Type::SHORT) valuetype->sign = ValueType::Sign::SIGNED; } @@ -8168,7 +8389,8 @@ void SymbolDatabase::setValueTypeInTokenList(bool reportDebugWarnings, Token *to else if (tok->previous()->isSigned()) valuetype.sign = ValueType::Sign::SIGNED; else if (valuetype.isIntegral() && valuetype.type != ValueType::UNKNOWN_INT) - valuetype.sign = (valuetype.type == ValueType::Type::CHAR) ? mDefaultSignedness : ValueType::Sign::SIGNED; + valuetype.sign = (valuetype.type == ValueType::Type::CHAR) ? mDefaultSignedness : + (valuetype.type == ValueType::Type::WCHAR_T) ? wcharSign(mSettings.platform) : ValueType::Sign::SIGNED; setValueType(tok, valuetype); } @@ -8398,7 +8620,8 @@ void SymbolDatabase::setValueTypeInTokenList(bool reportDebugWarnings, Token *to else if (typeTok->isSigned()) vt.sign = ValueType::Sign::SIGNED; if (vt.sign == ValueType::Sign::UNKNOWN_SIGN && vt.isIntegral()) - vt.sign = (vt.type == ValueType::Type::CHAR) ? mDefaultSignedness : ValueType::Sign::SIGNED; + vt.sign = (vt.type == ValueType::Type::CHAR) ? mDefaultSignedness : + (vt.type == ValueType::Type::WCHAR_T) ? wcharSign(mSettings.platform) : ValueType::Sign::SIGNED; } setValueType(tok, vt); if (Token::simpleMatch(tok->astOperand1(), "(")) { diff --git a/lib/symboldatabase.h b/lib/symboldatabase.h index 485564e8dc4..c75a6cf1742 100644 --- a/lib/symboldatabase.h +++ b/lib/symboldatabase.h @@ -1340,6 +1340,7 @@ class CPPCHECKLIB ValueType { Pointee, }; size_t getSizeOf(const Settings& settings, Accuracy accuracy, SizeOf sizeOf, int maxRecursion = 0) const; + static ValueType getCommonIntegralType(const ValueType* lhs, const ValueType* rhs, const Settings& settings); /// Check if type is the same ignoring const and references bool isTypeEqual(const ValueType* that) const; diff --git a/lib/token.cpp b/lib/token.cpp index 3f8e2a88d4c..376980ce7aa 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -2018,8 +2018,10 @@ const Token *Token::getValueTokenMaxStrLength() const static bool isAdjacent(const ValueFlow::Value& x, const ValueFlow::Value& y) { - if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound) - return true; + if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound) { + // Possible ranges are witnesses; do not widen them away by merging same-direction bounds. + return !(x.isPossible() || x.isInconclusive()); + } if (x.valueType == ValueFlow::Value::ValueType::FLOAT) return false; // Compared without a difference, which could overflow diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index c8c029aa708..1763f44f5ef 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -114,6 +114,7 @@ #include #include #include +#include #include #include #include @@ -271,9 +272,161 @@ static void setConditionalValues(const Token* tok, setValueBound(false_value, tok, !lhs); } +// The values of a signed operand type that satisfy '(unsigned)operand >= c' when c lies in the upper half +// of the unsigned range, and the complement otherwise. The signed range [lo,hi] maps onto the unsigned one +// modulo 2^(n), so a set that does not wrap can be written as an interval of the signed range. +static bool unsignedDomainInterval(bool greaterEqual, + MathLib::bigint constant, + MathLib::bigint modulus, + MathLib::bigint& intervalLo, + MathLib::bigint& intervalHi) +{ + if (constant == 0) + return false; + if (greaterEqual) { + // '(unsigned)operand >= c' keeps only the negative values once c is out of the non-negative part + // of the signed range, because every negative value maps close to the unsigned maximum. + if (constant < modulus / 2) + return false; + intervalLo = constant - modulus; + intervalHi = -1; + return true; + } + // '(unsigned)operand < c' keeps only non-negative values, up to the point where c enters the upper + // half and the set wraps around into the negatives. + if (constant > modulus / 2) + return false; + intervalLo = 0; + intervalHi = constant - 1; + return true; +} + +// A branch whose set is not an interval is dropped. The other one is expressed as its bounds, or as the +// value it excludes when it consists of a single point: '(unsigned)x < 1u' fails only for x == 0. +static void appendIntervalValues(std::list& values, + const ValueFlow::Value& proto, + bool isInterval, + MathLib::bigint lo, + MathLib::bigint hi) +{ + if (!isInterval) + return; + ValueFlow::Value lower = proto; + lower.intvalue = lo; + lower.bound = ValueFlow::Value::Bound::Lower; + ValueFlow::Value upper = proto; + upper.intvalue = hi; + upper.bound = ValueFlow::Value::Bound::Upper; + values.push_back(std::move(lower)); + values.push_back(std::move(upper)); +} + +struct ConditionValues { + std::list trueValues; + std::list falseValues; +}; + +// Replace the bounds derived for a comparison that converts a signed operand to unsigned. The shifted +// counterpart the ordinary handling derives from the constant assumes the values order like the operand's +// own type, which the unsigned conversion breaks: '(unsigned)x >= 1' also holds for every negative x. +static ConditionValues getUnsignedDomainValues(const Token* tok, + bool lhs, + MathLib::bigint constant, + const Token* operandTok, + const Settings& settings, + const ValueFlow::Value& true_proto, + const ValueFlow::Value& false_proto) +{ + const auto unchanged = [&]() { + ConditionValues values; + values.trueValues.push_back(true_proto); + values.falseValues.push_back(false_proto); + return values; + }; + ConditionValues values; + // The operator as it reads from the compared operand's side. In the 'lhs' loop the constant is the + // left operand, so the comparison as the operand sees it has its operands exchanged. + const std::string op = lhs ? invertOperatorForOperandSwap(tok->str()) : tok->str(); + bool greaterEqual = false; + MathLib::bigint lowerConstant = 0; + if (op == ">=") { + greaterEqual = true; + lowerConstant = constant; + } else if (op == ">") { + greaterEqual = true; + lowerConstant = constant + 1; + } else if (op == "<") { + lowerConstant = constant; + } else if (op == "<=") { + lowerConstant = constant + 1; + } else { + return unchanged(); + } + MathLib::bigint typeLo = 0; + MathLib::bigint typeHi = 0; + if (!operandTok->valueType() || + !ValueFlow::getMinMaxValues(operandTok->valueType(), settings.platform, typeLo, typeHi) || + typeHi <= 0 || typeHi >= (MathLib::bigint{1} << 62)) + return unchanged(); + // The signed range covers exactly one period of the unsigned range. + const MathLib::bigint modulus = 2 * (typeHi + 1); + MathLib::bigint trueLo = 0; + MathLib::bigint trueHi = 0; + MathLib::bigint falseLo = 0; + MathLib::bigint falseHi = 0; + const bool trueIsInterval = unsignedDomainInterval(greaterEqual, lowerConstant, modulus, trueLo, trueHi); + const bool falseIsInterval = unsignedDomainInterval(!greaterEqual, lowerConstant, modulus, falseLo, falseHi); + // The complement of a single-point set is exactly its exclusion, so that fact belongs to the branch + // that does not hold the point: '(unsigned)x < 4294967295u' fails only for x == -1, and the branch + // where it fails therefore knows that -1 is not the value. + if (!trueIsInterval && falseIsInterval && falseLo == falseHi) { + ValueFlow::Value excluded = true_proto; + excluded.intvalue = falseLo; + excluded.bound = ValueFlow::Value::Bound::Point; + excluded.setImpossible(); + values.trueValues.push_back(std::move(excluded)); + } + if (!falseIsInterval && trueIsInterval && trueLo == trueHi) { + ValueFlow::Value excluded = false_proto; + excluded.intvalue = trueLo; + excluded.bound = ValueFlow::Value::Bound::Point; + excluded.setImpossible(); + values.falseValues.push_back(std::move(excluded)); + } + appendIntervalValues(values.trueValues, true_proto, trueIsInterval, trueLo, trueHi); + appendIntervalValues(values.falseValues, false_proto, falseIsInterval, falseLo, falseHi); + return values; +} + +// The facts the branches of the comparison derive from one of its operands being `constant`. +// `lhs` tells which side of the comparison the operand is on. +static ConditionValues getCompareValues(const Token* tok, + bool lhs, + const ValueFlow::Value& constant, + const Settings& settings) +{ + const Token* const constantTok = lhs ? tok->astOperand1() : tok->astOperand2(); + const Token* const operandTok = lhs ? tok->astOperand2() : tok->astOperand1(); + ValueFlow::Value true_value = constant; + ValueFlow::Value false_value = constant; + const MathLib::bigint bound = + ValueFlow::castConstantToOperandType(constantTok, operandTok, constant.intvalue, settings); + setConditionalValues(tok, lhs, bound, true_value, false_value); + if (!Token::Match(tok, "==|!=") && + ValueFlow::comparesSignedOperandAsUnsigned(constantTok, operandTok, settings)) + return getUnsignedDomainValues(tok, lhs, constant.intvalue, operandTok, settings, true_value, false_value); + ConditionValues result; + result.trueValues.push_back(std::move(true_value)); + result.falseValues.push_back(std::move(false_value)); + return result; +} + static void parseCompareEachInt( const Token* tok, - const std::function& each, + const Settings& settings, + const std::function true_values, + std::list false_values)>& each, const std::function(const Token*)>& evaluate) { if (!tok->astOperand1() || !tok->astOperand2()) @@ -290,27 +443,26 @@ static void parseCompareEachInt( for (const ValueFlow::Value& v1 : value1) { if (ValueFlow::isSaturated(v1.intvalue) || astIsFloat(tok->astOperand2(), /*unknown*/ false)) continue; - ValueFlow::Value true_value = v1; - ValueFlow::Value false_value = v1; - setConditionalValues(tok, true, v1.intvalue, true_value, false_value); - each(tok->astOperand2(), std::move(true_value), std::move(false_value)); + ConditionValues values = getCompareValues(tok, /*lhs*/ true, v1, settings); + each(tok->astOperand2(), std::move(values.trueValues), std::move(values.falseValues)); } for (const ValueFlow::Value& v2 : value2) { if (ValueFlow::isSaturated(v2.intvalue) || astIsFloat(tok->astOperand1(), /*unknown*/ false)) continue; - ValueFlow::Value true_value = v2; - ValueFlow::Value false_value = v2; - setConditionalValues(tok, false, v2.intvalue, true_value, false_value); - each(tok->astOperand1(), std::move(true_value), std::move(false_value)); + ConditionValues values = getCompareValues(tok, /*lhs*/ false, v2, settings); + each(tok->astOperand1(), std::move(values.trueValues), std::move(values.falseValues)); } } } static void parseCompareEachInt( const Token* tok, - const std::function& each) + const Settings& settings, + const std::function true_values, + std::list false_values)>& each) { - parseCompareEachInt(tok, each, [](const Token* t) -> std::vector { + parseCompareEachInt(tok, settings, each, [](const Token* t) -> std::vector { if (const ValueFlow::Value* v = t->getKnownValue(ValueFlow::Value::ValueType::INT)) return {*v}; std::vector result; @@ -328,17 +480,19 @@ static void parseCompareEachInt( const Token* ValueFlow::parseCompareInt(const Token* tok, ValueFlow::Value& true_value, ValueFlow::Value& false_value, + const Settings& settings, const std::function(const Token*)>& evaluate) { const Token* result = nullptr; parseCompareEachInt( tok, - [&](const Token* vartok, ValueFlow::Value true_value2, ValueFlow::Value false_value2) { - if (result) + settings, + [&](const Token* vartok, std::list true_values, std::list false_values) { + if (result || true_values.empty() || false_values.empty()) return; result = vartok; - true_value = std::move(true_value2); - false_value = std::move(false_value2); + true_value = std::move(true_values.front()); + false_value = std::move(false_values.front()); }, [&](const Token* t) -> std::vector { std::vector r; @@ -352,15 +506,6 @@ const Token* ValueFlow::parseCompareInt(const Token* tok, return result; } -const Token *ValueFlow::parseCompareInt(const Token *tok, ValueFlow::Value &true_value, ValueFlow::Value &false_value) -{ - return parseCompareInt(tok, true_value, false_value, [](const Token* t) -> std::vector { - if (const ValueFlow::Value* v = t->getKnownValue(Value::ValueType::INT)) - return {v->intvalue}; - return std::vector{}; - }); -} - static bool isEscapeScope(const Token* tok, const Library& library, bool unknown = false) { if (!Token::simpleMatch(tok, "{")) @@ -416,10 +561,12 @@ void ValueFlow::combineValueProperties(const ValueFlow::Value &value1, const Val if (value1.bound == ValueFlow::Value::Bound::Lower || value2.bound == ValueFlow::Value::Bound::Lower) result.bound = ValueFlow::Value::Bound::Lower; } - if (value1.path != value2.path) - result.path = -1; - else + if (value1.path == 0) + result.path = value2.path; + else if (value2.path == 0 || value1.path == value2.path) result.path = value1.path; + else + result.path = -1; } // Set the dimensions that are known when the array declaration ends at tok, so sizeof of the array is known @@ -996,7 +1143,7 @@ static void valueFlowRightShift(TokenList& tokenList, const Settings& settings) } } -static std::vector minUnsignedValue(const Token* tok, int depth = 8) +static std::vector minUnsignedValue(const Token* tok, const Settings& settings, int depth = 8) { std::vector result; if (!tok) @@ -1005,10 +1152,11 @@ static std::vector minUnsignedValue(const Token* tok, int depth return result; if (const ValueFlow::Value* v = tok->getKnownValue(ValueFlow::Value::ValueType::INT)) { result = {v->intvalue}; - } else if (!Token::Match(tok, "-|%|&|^") && tok->isConstOp() && tok->astOperand1() && tok->astOperand2()) { - std::vector op1 = minUnsignedValue(tok->astOperand1(), depth - 1); + } else if (!Token::Match(tok, "-|%|&|^") && tok->isConstOp() && tok->astOperand1() && tok->astOperand2() && + (!ValueFlow::isUnsignedArithmeticResult(tok) || ValueFlow::isUnsignedArithmeticNoWrap(tok, settings, true))) { + std::vector op1 = minUnsignedValue(tok->astOperand1(), settings, depth - 1); if (!op1.empty()) { - std::vector op2 = minUnsignedValue(tok->astOperand2(), depth - 1); + std::vector op2 = minUnsignedValue(tok->astOperand2(), settings, depth - 1); if (!op2.empty()) { result = calculate>(tok->str(), op1.front(), op2.front()); } @@ -1058,8 +1206,26 @@ static void valueFlowImpossibleValues(TokenList& tokenList, const Settings& sett upper.bound = ValueFlow::Value::Bound::Lower; upper.setImpossible(); setTokenValue(tok, std::move(upper), settings); + } else if (tok->isCast() && tok->valueType() && tok->valueType()->isIntegral() && !tok->valueType()->pointer) { + MathLib::bigint minValue; + MathLib::bigint maxValue; + if (!ValueFlow::getMinMaxValues(tok->valueType(), settings.platform, minValue, maxValue)) + continue; + + if (minValue > std::numeric_limits::min()) { + ValueFlow::Value lower{minValue - 1}; + lower.bound = ValueFlow::Value::Bound::Upper; + lower.setImpossible(); + setTokenValue(tok, std::move(lower), settings); + } + if (maxValue < std::numeric_limits::max()) { + ValueFlow::Value upper{maxValue + 1}; + upper.bound = ValueFlow::Value::Bound::Lower; + upper.setImpossible(); + setTokenValue(tok, std::move(upper), settings); + } } else if (astIsUnsigned(tok) && !astIsPointer(tok)) { - std::vector minvalue = minUnsignedValue(tok); + std::vector minvalue = minUnsignedValue(tok, settings); if (minvalue.empty()) continue; ValueFlow::Value value{std::max(0, minvalue.front()) - 1}; @@ -4095,43 +4261,113 @@ static void valueFlowForwardAssign(Token* const tok, static std::list truncateValues(std::list values, const ValueType* dst, const ValueType* src, + const Token* sourceTok, + const Token* useTok, const Settings& settings) { - if (!dst || !dst->isIntegral()) + if (!dst || !dst->isIntegral() || dst->pointer) return values; - const size_t sz = dst->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); - - if (src) { - const size_t osz = src->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); - if (osz >= sz && dst->sign == ValueType::Sign::SIGNED && src->sign == ValueType::Sign::UNSIGNED) { - values.remove_if([&](const ValueFlow::Value& value) { - if (!value.isIntValue()) - return false; - if (!value.isImpossible()) - return false; - if (value.bound != ValueFlow::Value::Bound::Upper) - return false; - if (osz == sz && value.intvalue < 0) - return true; - if (osz > sz) - return true; - return false; - }); + const int bits = static_cast(ValueFlow::getTypeBits(*dst, settings)); + for (auto it = values.begin(); it != values.end();) { + ValueFlow::Value& value = *it; + if (value.isSymbolicValue() || value.isImpossible() || value.bound != ValueFlow::Value::Bound::Point) { + const ValueType* const conversionSource = value.isSymbolicValue() && value.tokvalue && value.tokvalue->valueType() + ? value.tokvalue->valueType() + : src; + if (value.isSymbolicValue() && dst->type == ValueType::Type::BOOL && conversionSource && + conversionSource->pointer > 0 && value.isKnown() && value.bound == ValueFlow::Value::Bound::Point && + value.intvalue == 0) { + ++it; + continue; + } + if (value.isFloatValue()) { + ValueFlow::ConvertedValue converted = ValueFlow::castValue(value, dst->sign, bits); + if (!converted.valid) + it = values.erase(it); + else { + *it = std::move(converted.value); + ++it; + } + } else if (value.isIntValue() && value.bound != ValueFlow::Value::Bound::Point) { + ValueFlow::ConvertedValue converted = + ValueFlow::convertValueRange(value, conversionSource, dst, settings, sourceTok, useTok); + if (!converted.valid) { + it = values.erase(it); + } else { + *it = std::move(converted.value); + ++it; + } + } else if (!ValueFlow::isValueRangePreservingConversion(conversionSource, dst, settings, value)) { + it = values.erase(it); + } else if (value.isImpossible() && value.isIntValue() && + value.bound == ValueFlow::Value::Bound::Point && src && + src->sign == ValueType::Sign::SIGNED && dst->sign == ValueType::Sign::UNSIGNED && + dst->type != ValueType::Type::BOOL && + !ValueFlow::castValue(value, dst->sign, bits).valid) { + it = values.erase(it); + } else { + ++it; + } + continue; } - } + if (dst->type == ValueType::Type::BOOL && (value.isIntValue() || value.isFloatValue())) { + value.intvalue = value.isIntValue() ? value.intvalue != 0 : std::fpclassify(value.floatValue) != FP_ZERO; + value.valueType = ValueFlow::Value::ValueType::INT; + } else if (dst->type == ValueType::Type::CHAR && dst->sign == ValueType::Sign::UNKNOWN_SIGN && + value.isIntValue()) { + const ValueType::Sign sign = ValueFlow::resolveCharSign(*dst, settings.platform); + if (sign != ValueType::Sign::UNKNOWN_SIGN) { + ValueFlow::ConvertedValue converted = ValueFlow::castValue(value, sign, bits); + if (!converted.valid) { + it = values.erase(it); + continue; + } + *it = std::move(converted.value); + ++it; + continue; + } - for (ValueFlow::Value &value : values) { - // Don't truncate impossible values since those can be outside of the valid range - if (value.isImpossible()) + // Preserve both outcomes when the target leaves plain-char signedness unknown. + const MathLib::bigint originalValue = value.intvalue; + ValueFlow::ConvertedValue convertedUnsigned = ValueFlow::castValue(value, ValueType::Sign::UNSIGNED, bits); + if (!convertedUnsigned.valid) { + it = values.erase(it); + continue; + } + ValueFlow::Value unsignedValue = std::move(convertedUnsigned.value); + ValueType signedCharType(ValueType::Sign::SIGNED, ValueType::Type::CHAR, 0); + MathLib::bigint minValue{}, maxValue{}; + const bool signedRepresentable = ValueFlow::getMinMaxValues(&signedCharType, settings.platform, minValue, maxValue) && + originalValue >= minValue && originalValue <= maxValue; + if (signedRepresentable && unsignedValue.intvalue == originalValue) { + ++it; + continue; + } + auto next = it; + ++next; + value = std::move(unsignedValue); + value.setPossible(); + if (signedRepresentable) { + ValueFlow::Value signedValue = value; + signedValue.intvalue = originalValue; + signedValue.setPossible(); + values.insert(next, std::move(signedValue)); + } + it = next; continue; - if (value.isFloatValue()) { - value.intvalue = static_cast(value.floatValue); - value.valueType = ValueFlow::Value::ValueType::INT; + } else if ((value.isIntValue() || value.isFloatValue()) && + // Zero is representable in every integral type, even when its size is unknown. + !(value.isIntValue() && value.intvalue == 0) && + !ValueFlow::isValueRangePreservingConversion(src, dst, settings, value)) { + ValueFlow::ConvertedValue converted = ValueFlow::castValue(value, dst->sign, bits); + if (!converted.valid) { + it = values.erase(it); + continue; + } + *it = std::move(converted.value); } - - if (value.isIntValue() && sz > 0 && sz < sizeof(MathLib::biguint)) - value.intvalue = ValueFlow::truncateIntValue(value.intvalue, sz, dst, settings.platform); + ++it; } return values; } @@ -4212,17 +4448,16 @@ static void valueFlowAfterAssign(const TokenList &tokenlist, continue; std::list values = truncateValues( - rhs->values(), tok->astOperand1()->valueType(), rhs->valueType(), settings); - // Remove known values - std::set types; - if (tok->astOperand1()->hasKnownValue()) { - for (const ValueFlow::Value& value:tok->astOperand1()->values()) { - if (value.isKnown() && !value.isSymbolicValue()) - types.insert(value.valueType); - } - } + rhs->values(), tok->astOperand1()->valueType(), rhs->valueType(), rhs, tok, settings); + // Remove only values already represented by an identical known value on the LHS. values.remove_if([&](const ValueFlow::Value& value) { - return types.count(value.valueType) > 0; + if (!value.isKnown() || value.isSymbolicValue()) + return false; + return std::any_of(tok->astOperand1()->values().cbegin(), + tok->astOperand1()->values().cend(), + [&](const ValueFlow::Value& knownValue) { + return knownValue.isKnown() && !knownValue.isSymbolicValue() && knownValue.equalValue(value); + }); }); // Remove container size if its not a container - unless the size records its container // and flows into a pointer to the container data (e.g. p = v.data()) @@ -4421,10 +4656,12 @@ struct ConditionHandler { return it->path; } - MathLib::bigint getPath() const - { - assert(std::abs(findPath(true_values) - findPath(false_values)) == 0); - return findPath(true_values) | findPath(false_values); + MathLib::bigint getPath() const { + const MathLib::bigint truePath = findPath(true_values); + const MathLib::bigint falsePath = findPath(false_values); + assert(true_values.empty() || false_values.empty() || + std::abs(truePath - falsePath) == 0); + return truePath | falsePath; } Token* getContextAndValues(Token* condTok, @@ -4523,7 +4760,7 @@ struct ConditionHandler { continue; if (cond.vartok->hasKnownIntValue()) continue; - if (cond.true_values.empty() || cond.false_values.empty()) + if (cond.true_values.empty() && cond.false_values.empty()) continue; if (!isConstExpression(cond.vartok, settings.library)) continue; @@ -4896,7 +5133,8 @@ struct ConditionHandler { bailBlock = i; changeKnownToPossible(values); } - if (changeBlock >= 0 && !Token::simpleMatch(top->previous(), "while (")) { + if (changeBlock >= 0 && + (!Token::simpleMatch(top->previous(), "while (") || astIsFloat(cond.vartok, false))) { if (settings.debugwarnings) bailout(tokenlist, errorLogger, @@ -5058,23 +5296,58 @@ static const Token* getConditionVariable(const Token* tok) } struct SimpleConditionHandler : ConditionHandler { - std::vector parse(const Token* tok, const Settings& /*settings*/) const override { + std::vector parse(const Token* tok, const Settings& settings) const override { std::vector conds; - parseCompareEachInt(tok, [&](const Token* vartok, ValueFlow::Value true_value, ValueFlow::Value false_value) { + parseCompareEachInt(tok, settings, + [&](const Token* vartok, + std::list true_values, + std::list false_values) { if (vartok->hasKnownIntValue()) return; if (vartok->str() == "=" && vartok->astOperand1() && vartok->astOperand2()) vartok = vartok->astOperand1(); Condition cond; - cond.true_values.push_back(std::move(true_value)); - cond.false_values.push_back(std::move(false_value)); + cond.true_values = std::move(true_values); + cond.false_values = std::move(false_values); cond.vartok = vartok; conds.push_back(std::move(cond)); }); if (!conds.empty()) return conds; + if (Token::Match(tok, ">=|<=") && tok->astOperand1() && tok->astOperand2()) { + for (bool lhs : {true, false}) { + const Token* vartok = lhs ? tok->astOperand1() : tok->astOperand2(); + const Token* valuetok = lhs ? tok->astOperand2() : tok->astOperand1(); + if (!astIsFloat(vartok, false) || !valuetok->isLiteral()) + continue; + const ValueFlow::Value* value = valuetok->getKnownValue(ValueFlow::Value::ValueType::FLOAT); + if (!value) + continue; + + const bool lower = lhs == (tok->str() == ">="); + const ValueFlow::Value::Bound bound = lower ? ValueFlow::Value::Bound::Lower + : ValueFlow::Value::Bound::Upper; + Condition cond; + cond.vartok = vartok; + cond.impossible = false; + + ValueFlow::Value trueValue = *value; + trueValue.bound = bound; + trueValue.assumeCondition(tok); + trueValue.setPossible(); + cond.true_values.push_back(std::move(trueValue)); + + ValueFlow::Value falseValue = *value; + falseValue.bound = bound; + falseValue.assumeCondition(tok); + falseValue.setImpossible(); + cond.false_values.push_back(std::move(falseValue)); + return {std::move(cond)}; + } + } + const Token* vartok = getConditionVariable(tok); if (!vartok) return {}; @@ -5159,8 +5432,34 @@ static void valueFlowInferCondition(TokenList& tokenlist, const Settings& settin } } } else if (isIntegralOrPointer(tok->astOperand1()) && isIntegralOrPointer(tok->astOperand2())) { - std::vector result = - infer(makeIntegralInferModel(), tok->str(), tok->astOperand1()->values(), tok->astOperand2()->values()); + const bool isUnsignedArith = ValueFlow::isUnsignedArithmeticResult(tok); + const bool mayWrap = isUnsignedArith && !ValueFlow::isUnsignedArithmeticNoWrap(tok, settings, false); + std::vector result; + const auto isIntegralRange = [](const ValueFlow::Value& value) { + return value.bound != ValueFlow::Value::Bound::Point && + (value.isIntValue() || value.isSymbolicValue()); + }; + std::list lhsValues = tok->astOperand1()->values(); + std::list rhsValues = tok->astOperand2()->values(); + const auto convertValues = [&](const Token* operand, std::list& values) { + for (auto it = values.begin(); it != values.end();) { + ValueFlow::ConvertedValue converted = + ValueFlow::truncateImplicitConversion(tok, operand, *it, settings); + if (!converted.valid) { + it = values.erase(it); + } else { + *it = std::move(converted.value); + ++it; + } + } + }; + convertValues(tok->astOperand1(), lhsValues); + convertValues(tok->astOperand2(), rhsValues); + if (mayWrap) { + lhsValues.remove_if(isIntegralRange); + rhsValues.remove_if(isIntegralRange); + } + result = infer(makeIntegralInferModel(), tok->str(), std::move(lhsValues), std::move(rhsValues)); for (ValueFlow::Value& value : result) { setTokenValue(tok, std::move(value), settings); } @@ -5410,7 +5709,7 @@ static void valueFlowForLoopSimplify(Token* const bodyStart, } } -static void valueFlowForLoopSimplifyAfter(Token* fortok, nonneg int varid, const MathLib::bigint num, const TokenList& tokenlist, ErrorLogger & errorLogger, const Settings& settings) +static void valueFlowForLoopSimplifyAfter(Token* fortok, nonneg int varid, const MathLib::bigint num, const TokenList& tokenlist, ErrorLogger & errorLogger, const Settings& settings, bool possible = false) { const Token *vartok = nullptr; for (const Token *tok = fortok; tok; tok = tok->next()) { @@ -5437,12 +5736,57 @@ static void valueFlowForLoopSimplifyAfter(Token* fortok, nonneg int varid, const } if (blockTok != endToken) { ValueFlow::Value v{num}; + if (possible) { + // A compound condition's upper threshold does not prove the exact final value, + // but the exceeding step is still a feasible exit. + v.setPossible(); + } v.errorPath.emplace_back(fortok,"After for loop, " + var->name() + " has value " + v.infoString()); valueFlowForward(blockTok->next(), endToken, vartok, std::move(v), tokenlist, errorLogger, settings); } } +static bool isForLoopConditionFalseAtInit(const Token* condition, + nonneg int varid, + MathLib::bigint initValue, + const Settings& settings) +{ + if (!condition) + return false; + + ValueFlow::Value value{initValue}; + value.setKnown(); + ProgramMemory::Map vars; + visitAstNodes(condition, [&](const Token* tok) { + if (tok->varId() == varid && tok->exprId() != 0) + vars[ExprIdToken::create(tok->exprId())] = {value}; + return ChildrenToVisit::op1_and_op2; + }); + if (vars.empty()) + return false; + return conditionIsFalse(condition, ProgramMemory{}, settings, vars); +} + +// A value of the for loop initializer that shows the loop variable can start negative +static bool isNegativeEvidence(const ValueFlow::Value& candidate) +{ + return candidate.isIntValue() && !candidate.isImpossible() && !candidate.isInconclusive() && + candidate.path >= 0 && candidate.intvalue < 0 && + (candidate.bound == ValueFlow::Value::Bound::Point || candidate.bound == ValueFlow::Value::Bound::Upper); +} + +static const ValueFlow::Value* getNegativeInitWitness(const Token* initToken, + const ValueFlow::Value* initValueSource) +{ + if (initValueSource && isNegativeEvidence(*initValueSource)) + return initValueSource; + if (!initToken) + return nullptr; + const auto it = std::find_if(initToken->values().cbegin(), initToken->values().cend(), isNegativeEvidence); + return it == initToken->values().cend() ? nullptr : &*it; +} + static void valueFlowForLoop(const TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings) { for (const Scope &scope : symboldatabase.scopeList) { @@ -5456,31 +5800,147 @@ static void valueFlowForLoop(const TokenList &tokenlist, const SymbolDatabase& s !Token::simpleMatch(tok->next()->astOperand2()->astOperand2(), ";")) continue; - nonneg int varid; - bool knownInitValue, partialCond; - MathLib::bigint initValue, stepValue, lastValue; - - if (extractForLoopValues(tok, varid, knownInitValue, initValue, partialCond, stepValue, lastValue)) { - const bool executeBody = !knownInitValue || initValue <= lastValue; + const ForLoopValues extracted = extractForLoopValues(tok); + const Token* const initExpr = getInitTok(tok); + const ValueFlow::Value* initValueWitnessSource = nullptr; + if (extracted.valid && initExpr) + initValueWitnessSource = getNegativeInitWitness(initExpr->astOperand2(), extracted.initValueSource); + if (extracted.valid && (extracted.hasMinimum || initValueWitnessSource)) { + const nonneg int varid = extracted.varid; + const bool knownInitValue = extracted.knownInitValue; + const bool partialCond = extracted.partialCond; + const MathLib::bigint initValue = extracted.initValue; + const MathLib::bigint stepValue = extracted.stepValue; + const MathLib::bigint lastValue = extracted.lastValue; + const ValueFlow::Value* const initValueSource = extracted.initValueSource; + const Token* const condition = getCondTok(tok); + const bool hasDisjunction = partialCond && condition && findAstNode(condition, [](const Token* cond) { + return cond->str() == "||"; + }); + bool executeBody = !knownInitValue || initValue <= lastValue; + if (knownInitValue && partialCond) + executeBody = !isForLoopConditionFalseAtInit(condition, varid, initValue, settings); const Token* vartok = Token::findmatch(tok, "%varid%", bodyStart, varid); if (executeBody && vartok) { std::list initValues; - initValues.emplace_back(initValue, ValueFlow::Value::Bound::Lower); - initValues.push_back(ValueFlow::asImpossible(initValues.back())); - Analyzer::Result result = valueFlowForward(bodyStart, bodyStart->link(), vartok, std::move(initValues), tokenlist, errorLogger, settings); + const auto addPossiblePoint = [&](const ValueFlow::Value& source) { + ValueFlow::Value initValueFact = source; + initValueFact.bound = ValueFlow::Value::Bound::Lower; + initValueFact.setPossible(); + initValues.push_back(std::move(initValueFact)); + if (source.intvalue != std::numeric_limits::min()) + initValues.push_back(ValueFlow::asImpossible(initValues.back())); + }; + const auto addNegativeUpper = [&](const ValueFlow::Value& source) { + // The possible upper bound is the witness; its exclusion alone is only a constraint. + initValues.push_back(source); + }; + if (initValueSource && initValueSource->isImpossible() && + initValueSource->bound == ValueFlow::Value::Bound::Upper) { + // An excluded side constrains the initializer. When the exclusion is tight, that + // is when the initializer's minimum is exactly one past the excluded value, the + // minimum is the endpoint itself and is reachable: 'n - 1' with an unsigned 'n' + // excludes '<= -2' and reaches -1 when n is 0. Otherwise the exclusion only + // constrains and does not witness its endpoint. + initValues.push_back(*initValueSource); + // The exclusion is only tight when it removes a value that the initializer's own + // type can represent. A bound that excludes the type's minimum itself is vacuous, + // such as the trivial floor a cast range carries, and witnesses nothing. + const Token* const initAssign = tok->next()->astOperand2(); + const ValueType* const initType = + (initAssign && initAssign->astOperand1() && initAssign->astOperand1()->astOperand2()) + ? initAssign->astOperand1()->astOperand2()->valueType() + : nullptr; + MathLib::bigint typeMin{}; + MathLib::bigint typeMax{}; + const bool haveRange = initType && ValueFlow::getMinMaxValues(initType, settings.platform, typeMin, typeMax); + // One step below the initializer type's floor is a real exclusion when that floor + // still lies above the loop variable's own floor: 'unsigned char n' excludes + // '<= -1', which an 'int' index can express, and starts at 0 when n is 0. The + // trivial floor of a cast range, as in '-(int)u', already sits at the variable's + // floor, so the value it excludes is unrepresentable and must not be invented. + MathLib::bigint varMin{}; + MathLib::bigint varMax{}; + const Token* const loopVar = initAssign ? initAssign->astOperand1() : nullptr; + const ValueType* const loopVarType = loopVar ? loopVar->valueType() : nullptr; + const bool haveVarRange = + loopVarType && ValueFlow::getMinMaxValues(loopVarType, settings.platform, varMin, varMax); + const bool floorReached = haveRange && initValue == typeMin && + initValueSource->intvalue < typeMin && + (!haveVarRange || typeMin > varMin || + loopVarType->sign == ValueType::UNSIGNED); + if (initValue == initValueSource->intvalue + 1 && + (!haveRange || initValueSource->intvalue > typeMin || floorReached)) { + ValueFlow::Value initValueFact = *initValueSource; + initValueFact.intvalue = initValue; + initValueFact.bound = ValueFlow::Value::Bound::Point; + initValueFact.setPossible(); + initValues.push_back(std::move(initValueFact)); + } + } else if (initValueSource && initValueSource->bound == ValueFlow::Value::Bound::Point && + (initValueSource->isKnown() || initValueSource->isPossible())) { + addPossiblePoint(*initValueSource); + } else if (initValueSource && (initValueSource->isKnown() || initValueSource->isPossible()) && + initValueSource->bound == ValueFlow::Value::Bound::Upper && initValueSource->intvalue < 0) { + addNegativeUpper(*initValueSource); + } else if (initValueSource && initValueSource->isKnown() && + initValueSource->bound == ValueFlow::Value::Bound::Lower && initValue >= 0) { + ValueFlow::Value initValueFact = *initValueSource; + initValueFact.intvalue = initValue; + initValueFact.bound = ValueFlow::Value::Bound::Lower; + initValueFact.setPossible(); + initValues.push_back(std::move(initValueFact)); + initValues.push_back(ValueFlow::asImpossible(initValues.back())); + } + if (initValueWitnessSource && initValueWitnessSource != initValueSource) { + // The witness is always a known or possible negative point or upper bound. + if (initValueWitnessSource->bound == ValueFlow::Value::Bound::Point) + addPossiblePoint(*initValueWitnessSource); + else + addNegativeUpper(*initValueWitnessSource); + } + Token* valueFlowStart = bodyStart; + // Include the full loop condition so only feasible entry paths reach the body. + if (partialCond && condition) { + const auto conditionTokens = condition->findExpressionStartEndTokens(); + if (conditionTokens.first) + valueFlowStart = const_cast(conditionTokens.first); + } + Analyzer::Result result = valueFlowForward(valueFlowStart, + bodyStart->link(), + vartok, + std::move(initValues), + tokenlist, + errorLogger, + settings); - if (!result.action.isModified()) { + // An OR branch can bypass the extracted upper limit. + const bool modifiedInBody = partialCond && vartok->variable() && + isVariableChanged(bodyStart, + bodyStart->link(), + varid, + vartok->variable()->isGlobal(), + settings); + if (partialCond ? !modifiedInBody : !result.action.isModified()) { std::list lastValues; lastValues.emplace_back(lastValue, ValueFlow::Value::Bound::Upper); lastValues.back().conditional = true; - lastValues.push_back(ValueFlow::asImpossible(lastValues.back())); + if (!hasDisjunction && lastValue != std::numeric_limits::max()) + lastValues.push_back(ValueFlow::asImpossible(lastValues.back())); if (stepValue != 1) lastValues.pop_front(); valueFlowForward(bodyStart, bodyStart->link(), vartok, std::move(lastValues), tokenlist, errorLogger, settings); } } - const MathLib::bigint afterValue = executeBody ? lastValue + stepValue : initValue; - valueFlowForLoopSimplifyAfter(tok, varid, afterValue, tokenlist, errorLogger, settings); + if (!executeBody) { + valueFlowForLoopSimplifyAfter(tok, varid, initValue, tokenlist, errorLogger, settings); + } else if (lastValue != std::numeric_limits::max()) { + // The final increment has no representable successor at the carrier limit. + if (!partialCond) + valueFlowForLoopSimplifyAfter(tok, varid, lastValue + stepValue, tokenlist, errorLogger, settings); + else if (!knownInitValue || initValue <= lastValue) + valueFlowForLoopSimplifyAfter(tok, varid, lastValue + stepValue, tokenlist, errorLogger, settings, true); + } } else { ProgramMemory mem1, mem2, memAfter; if (valueFlowForLoop2(tok, mem1, mem2, memAfter, settings)) { @@ -5759,7 +6219,12 @@ static void valueFlowSubFunction(const TokenList& tokenlist, const Function* function = scope->function; if (!function) continue; + // A call in a branch proven unreachable cannot pass its arguments: doing so invents values + // for the callee that no execution reaches, e.g. a shift amount from a dead 'else'. + if (isInUnreachableBranch(scope->bodyStart)) + continue; for (auto* tok = const_cast(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { + tok = const_cast(skipUnreachableBranch(tok)); if (tok->isKeyword() || !Token::Match(tok, "%name% (")) continue; @@ -6969,15 +7434,20 @@ struct ContainerConditionHandler : ConditionHandler { std::vector parse(const Token* tok, const Settings& settings) const override { std::vector conds; - parseCompareEachInt(tok, [&](const Token* vartok, ValueFlow::Value true_value, ValueFlow::Value false_value) { + parseCompareEachInt(tok, settings, + [&](const Token* vartok, + std::list true_values, + std::list false_values) { vartok = settings.library.getContainerFromYield(vartok, Library::Container::Yield::SIZE); if (!vartok) return; - true_value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE; - false_value.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE; + for (ValueFlow::Value& v : true_values) + v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE; + for (ValueFlow::Value& v : false_values) + v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE; Condition cond; - cond.true_values.push_back(std::move(true_value)); - cond.false_values.push_back(std::move(false_value)); + cond.true_values = std::move(true_values); + cond.false_values = std::move(false_values); cond.vartok = vartok; conds.push_back(std::move(cond)); }); @@ -7590,7 +8060,6 @@ void ValueFlow::setValues(TokenList& tokenlist, VFA(valueFlowSwitchVariable(tokenlist, symboldatabase, errorLogger, settings)), VFA(valueFlowForLoop(tokenlist, symboldatabase, errorLogger, settings)), VFA(valueFlowDynamicBufferSize(tokenlist, symboldatabase, errorLogger, settings)), - VFA(valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings)), VFA(valueFlowFunctionReturn(tokenlist, errorLogger, settings)), VFA(valueFlowLifetime(tokenlist, errorLogger, settings)), VFA(valueFlowFunctionDefaultParameter(tokenlist, symboldatabase, errorLogger, settings)), @@ -7603,6 +8072,10 @@ void ValueFlow::setValues(TokenList& tokenlist, VFA_CPP(valueFlowIteratorInfer(tokenlist, settings)), VFA_CPP(valueFlowContainerSize(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions)), VFA(valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings)), + // A cast exposes excluded bounds that reach the callee arguments only after the assignment + // that converts them has run. Keeping this pass last lets it hand those facts to the call + // sites within the same iteration instead of needing one more iteration of the whole list. + VFA(valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings)), }); runner.run_once({ diff --git a/lib/valueflow.h b/lib/valueflow.h index f701f55c418..84a2a0f28d6 100644 --- a/lib/valueflow.h +++ b/lib/valueflow.h @@ -97,8 +97,7 @@ namespace ValueFlow { } }; - const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value, const std::function(const Token*)>& evaluate); - const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value); + const Token *parseCompareInt(const Token *tok, Value &true_value, Value &false_value, const Settings& settings, const std::function(const Token*)>& evaluate); const Token* solveExprValue(const Token* expr, const std::function(const Token*)>& eval, diff --git a/lib/vf_analyzers.cpp b/lib/vf_analyzers.cpp index ccadc3ef623..f428a5ab886 100644 --- a/lib/vf_analyzers.cpp +++ b/lib/vf_analyzers.cpp @@ -303,6 +303,13 @@ struct ValueFlowAnalyzer : Analyzer { // Only if its invertible if (value->isImpossible() && !Token::Match(parent, "+=|-=|*=|++|--")) return Action::None; + // Shifting an impossible range bound is unsound if the operation can wrap: unsigned types, and + // signed types narrower than int (promoted to int and converted back) + if (value->isImpossible() && value->bound != ValueFlow::Value::Bound::Point && tok->valueType() && + tok->valueType()->isIntegral() && !tok->valueType()->pointer && + (tok->valueType()->sign == ValueType::Sign::UNSIGNED || tok->valueType()->type == ValueType::Type::CHAR || + tok->valueType()->type == ValueType::Type::SHORT)) + return Action::None; if (value->isLifetimeValue()) { if (value->lifetimeKind != ValueFlow::Value::LifetimeKind::Iterator) return Action::None; @@ -1180,6 +1187,12 @@ struct SingleValueFlowAnalyzer : ValueFlowAnalyzer { } void addErrorPath(const Token* tok, const std::string& s) override { + // Only record assumptions about conditions the tracked value actually depends on. A + // condition that neither is the value's own condition nor mentions the value says nothing + // about it (e.g. an unrelated `if (length + 40 > 65535)`), and carrying its assumption into + // the value's error path would attribute a note to the wrong condition. + if (!value.isLifetimeValue() && value.condition && value.condition != tok && !conditionReferencesValue(tok)) + return; auto& ep = value.errorPath; if (std::any_of(ep.begin(), ep.end(), [&](const ErrorPathItem& epi) { return epi.first == tok && epi.second == s; diff --git a/lib/vf_common.cpp b/lib/vf_common.cpp index a96c0ea9ad4..247c978564b 100644 --- a/lib/vf_common.cpp +++ b/lib/vf_common.cpp @@ -19,6 +19,7 @@ #include "vf_common.h" #include "astutils.h" +#include "infer.h" #include "library.h" #include "mathlib.h" #include "path.h" @@ -34,8 +35,10 @@ #include #include #include +#include #include #include +#include #include #include @@ -46,7 +49,7 @@ namespace ValueFlow if (!vt || !vt->isIntegral() || vt->pointer) return false; - std::uint8_t bits; + std::size_t bits; switch (vt->type) { case ValueType::Type::BOOL: bits = 1; @@ -66,10 +69,16 @@ namespace ValueFlow case ValueType::Type::LONGLONG: bits = platform.long_long_bit; break; + case ValueType::Type::WCHAR_T: + bits = platform.sizeof_wchar_t * platform.char_bit; + break; default: return false; } + if (bits == 0) { + return false; + } if (bits == 1) { minValue = 0; maxValue = 1; @@ -77,25 +86,1324 @@ namespace ValueFlow if (vt->sign == ValueType::Sign::UNSIGNED) { minValue = 0; maxValue = (1LL << bits) - 1; - } else { + } else if (vt->sign == ValueType::Sign::SIGNED) { minValue = -(1LL << (bits - 1)); maxValue = (1LL << (bits - 1)) - 1; - } + } else + return false; } else if (bits == 64) { if (vt->sign == ValueType::Sign::UNSIGNED) { minValue = 0; - maxValue = LLONG_MAX; // todo max unsigned value - } else { + maxValue = LLONG_MAX; // MathLib::bigint cannot represent ULLONG_MAX; conservative max for unsigned 64-bit + } else if (vt->sign == ValueType::Sign::SIGNED) { minValue = LLONG_MIN; maxValue = LLONG_MAX; + } else + return false; + } else { + return false; + } + + return true; + } + ValueType::Sign resolveCharSign(const ValueType& type, const Platform& platform) + { + if (type.type != ValueType::Type::CHAR || type.sign != ValueType::Sign::UNKNOWN_SIGN) + return type.sign; + if (platform.defaultSign == 's' || platform.defaultSign == 'S') + return ValueType::Sign::SIGNED; + if (platform.defaultSign == 'u' || platform.defaultSign == 'U') + return ValueType::Sign::UNSIGNED; + return ValueType::Sign::UNKNOWN_SIGN; + } + + std::size_t getTypeBits(const ValueType& type, const Settings& settings) + { + return type.getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointee) * + settings.platform.char_bit; + } + + MathLib::biguint getUnsignedMaximum(std::size_t bits) + { + const std::size_t carrierBits = std::numeric_limits::digits; + if (bits >= carrierBits) + return std::numeric_limits::max(); + return (MathLib::biguint{1} << bits) - 1; + } + + MathLib::biguint convertToUnsigned(MathLib::bigint value, std::size_t bits) + { + auto converted = static_cast(value); + if (bits < std::numeric_limits::digits) + converted &= (MathLib::biguint{1} << bits) - 1; + return converted; + } + + // The sizes of the constant and operand of a mixed-sign comparison whose common type is unsigned, + // i.e. the comparison converts a signed operand to unsigned. + static bool getUnsignedDomainSizes(const Token* constantTok, + const Token* operandTok, + const Settings& settings, + std::size_t& constantSize, + std::size_t& operandSize) + { + if (!constantTok || !operandTok) + return false; + const ValueType* const constantType = constantTok->valueType(); + const ValueType* const operandType = operandTok->valueType(); + if (!constantType || !operandType) + return false; + if (!constantType->isIntegral() || constantType->pointer || !operandType->isIntegral() || operandType->pointer) + return false; + // bool operands are compared without the usual integral promotion rules + if (constantType->type == ValueType::Type::BOOL || operandType->type == ValueType::Type::BOOL) + return false; + // Only an unsigned constant compared with a signed operand needs the other interpretation + if (constantType->sign != ValueType::Sign::UNSIGNED) + return false; + if (resolveCharSign(*operandType, settings.platform) != ValueType::Sign::SIGNED) + return false; + // The common type of the comparison is the one with the higher rank, so only a constant of at + // least the operand's rank is converted away from its own type. + constantSize = constantType->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointee); + operandSize = operandType->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointee); + return constantSize != 0 && operandSize != 0 && constantSize >= operandSize; + } + + bool comparesSignedOperandAsUnsigned(const Token* constantTok, const Token* operandTok, const Settings& settings) + { + std::size_t constantSize = 0; + std::size_t operandSize = 0; + return getUnsignedDomainSizes(constantTok, operandTok, settings, constantSize, operandSize); + } + + MathLib::bigint castConstantToOperandType(const Token* constantTok, + const Token* operandTok, + const MathLib::bigint value, + const Settings& settings) + { + std::size_t constantSize = 0; + std::size_t operandSize = 0; + if (!getUnsignedDomainSizes(constantTok, operandTok, settings, constantSize, operandSize)) + return value; + const ValueType* const operandType = operandTok->valueType(); + const MathLib::bigint converted = truncateIntValue(value, operandSize, operandType, settings.platform); + // The comparison happens in the common type, which is the constant's own type here. The + // operand is sign-extended to that type before the conversion, so only a value of the + // operand's type that converts back to the constant's value can equal the constant. A + // 'short' sign-extends to 0xFFFFFFFF, so it never equals 0xFFFFu. + MathLib::bigint roundTrip = converted; + const std::size_t constantBits = constantSize * settings.platform.char_bit; + if (constantBits < static_cast(MathLib::bigint_bits)) { + const MathLib::biguint mask = (MathLib::biguint{1} << constantBits) - 1; + roundTrip = static_cast(static_cast(converted) & mask); + } + if (converted == value || roundTrip != value) + return value; + return converted; + } + static bool convertFloatToInteger(MathLib::bigint& result, + double value, + ValueType::Sign sign, + nonneg int bit) + { + if (!std::isfinite(value) || bit <= 0 || sign == ValueType::Sign::UNKNOWN_SIGN) + return false; + const double truncatedValue = std::trunc(value); + const int destinationBits = sign == ValueType::Sign::SIGNED ? bit - 1 : bit; + const int carrierBits = std::numeric_limits::digits; + const double upperExclusive = std::ldexp(1.0, std::min(destinationBits, carrierBits)); + if (sign == ValueType::Sign::SIGNED) { + if (truncatedValue < -upperExclusive || truncatedValue >= upperExclusive) + return false; + } else if (truncatedValue < 0.0 || truncatedValue >= upperExclusive) { + return false; + } + result = static_cast(truncatedValue); + return true; + } + + + template + struct Bounds { + bool valid; // false: the fact leaves no value of the type + T lower; + T upper; + }; + + template + static Bounds narrowBounds(Bounds bounds, const Value& fact, T endpoint) + { + if (fact.isImpossible()) { + if (fact.bound == Value::Bound::Upper) { + if (endpoint == std::numeric_limits::max()) + return Bounds{false, T{}, T{}}; + bounds.lower = std::max(bounds.lower, endpoint + 1); + } else if (fact.bound == Value::Bound::Lower) { + if (endpoint == std::numeric_limits::min()) + return Bounds{false, T{}, T{}}; + bounds.upper = std::min(bounds.upper, endpoint - 1); + } + } else if (fact.bound == Value::Bound::Lower) { + bounds.lower = std::max(bounds.lower, endpoint); + } else if (fact.bound == Value::Bound::Upper) { + bounds.upper = std::min(bounds.upper, endpoint); + } + return bounds; + } + + bool isValueRangePreservingConversion(const ValueType* source, + const ValueType* destination, + const Settings& settings, + const Value& value) + { + if (!destination || !destination->isIntegral() || destination->pointer) + return false; + const bool impossiblePoint = value.isIntValue() && value.isImpossible() && value.bound == Value::Bound::Point; + if (!source) + return impossiblePoint; + const std::size_t destinationBits = getTypeBits(*destination, settings); + if (source->pointer > 0) { + // A non-null pointer remains nonzero in bool, and in an integer type large enough to hold a pointer. + if (!impossiblePoint || value.intvalue != 0) + return false; + if (destination->type == ValueType::Type::BOOL) + return true; + const std::size_t sourceBits = source->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer) * settings.platform.char_bit; + return sourceBits > 0 && destinationBits >= sourceBits; + } + if (source->isFloat()) { + if (!value.isFloatValue() || value.isImpossible() || + value.bound == Value::Bound::Point || destination->type == ValueType::Type::BOOL) + return false; + MathLib::bigint converted{}; + return destinationBits > 0 && destinationBits <= static_cast(std::numeric_limits::max()) && + convertFloatToInteger(converted, value.floatValue, destination->sign, static_cast(destinationBits)); + } + if (!source->isIntegral()) + return false; + const std::size_t sourceBits = getTypeBits(*source, settings); + if (source->isTypeEqual(destination) && source->sign == destination->sign) + return true; + + if (value.isIntValue() && value.bound != Value::Bound::Point && !value.isInconclusive()) { + MathLib::bigint sourceMin{}, sourceMax{}, destinationMin{}, destinationMax{}; + if (getMinMaxValues(source, settings.platform, sourceMin, sourceMax) && + getMinMaxValues(destination, settings.platform, destinationMin, destinationMax)) { + const bool upperBoundedByFact = value.isImpossible() ? value.bound == Value::Bound::Lower + : value.bound == Value::Bound::Upper; + const Bounds bounds = narrowBounds( + Bounds{true, sourceMin, sourceMax}, + value, + value.intvalue); + if (!bounds.valid) + return false; + + const bool sourceHasRepresentableMaximum = source->sign != ValueType::Sign::UNSIGNED || + sourceBits <= std::numeric_limits::digits; + if (bounds.lower <= bounds.upper && (sourceHasRepresentableMaximum || upperBoundedByFact) && + bounds.lower >= destinationMin && bounds.upper <= destinationMax) + return true; + } + } + + if (value.isIntValue() && value.bound == Value::Bound::Point && + destination->type != ValueType::Type::BOOL && destination->sign != ValueType::Sign::UNKNOWN_SIGN) { + if (destinationBits == 0) { + const ValueType smallestType(destination->sign, ValueType::Type::CHAR, 0); + MathLib::bigint minimum{}, maximum{}; + return getMinMaxValues(&smallestType, settings.platform, minimum, maximum) && + value.intvalue >= minimum && value.intvalue <= maximum; + } + } + if (source->type == ValueType::Type::BOOL || destination->type == ValueType::Type::BOOL) { + MathLib::bigint sourceMin{}, sourceMax{}, destinationMin{}, destinationMax{}; + return getMinMaxValues(source, settings.platform, sourceMin, sourceMax) && + getMinMaxValues(destination, settings.platform, destinationMin, destinationMax) && + sourceMin >= destinationMin && sourceMax <= destinationMax; + } + + if (destination->sign == ValueType::Sign::UNKNOWN_SIGN) + return false; + + if (sourceBits == 0 || destinationBits == 0) + return false; + if (source->sign == ValueType::Sign::UNKNOWN_SIGN) + return destination->sign == ValueType::Sign::SIGNED && sourceBits < destinationBits; + + if (source->sign == destination->sign) + return sourceBits <= destinationBits; + if (impossiblePoint && source->sign == ValueType::Sign::SIGNED && + destination->sign == ValueType::Sign::UNSIGNED) { + MathLib::bigint sourceMin{}, sourceMax{}; + if (!getMinMaxValues(source, settings.platform, sourceMin, sourceMax) || value.intvalue < sourceMin || + value.intvalue > sourceMax) + return false; + return sourceBits <= destinationBits; + } + return source->sign == ValueType::Sign::UNSIGNED && destination->sign == ValueType::Sign::SIGNED && + sourceBits < destinationBits; + } + + + bool isUnsignedArithmeticResult(const Token* tok) + { + if (!Token::Match(tok, "+|-|*")) + return false; + const ValueType* vt = tok->valueType(); + return vt && vt->isIntegral() && vt->pointer == 0 && vt->sign == ValueType::Sign::UNSIGNED && + (vt->type == ValueType::Type::INT || + vt->type == ValueType::Type::LONG || + vt->type == ValueType::Type::LONGLONG || + vt->type == ValueType::Type::UNKNOWN_INT); + } + + namespace { + struct UnsignedArithmeticRange { + bool valid{}; // false: the expression has no proven range + MathLib::biguint lower{}; + MathLib::biguint upper{}; + // conditional symbolic bound: value <= symbolicUpper + symbolicUpperOffset + const Token* symbolicUpper{}; + MathLib::bigint symbolicUpperOffset{}; + }; + + bool getUnsignedTypeMaximum(const ValueType* valueType, + std::size_t bits, + MathLib::biguint& maximum) + { + if (valueType->type == ValueType::Type::BOOL) { + maximum = 1; + return true; + } + const std::size_t carrierBits = std::numeric_limits::digits; + if (valueType->sign != ValueType::Sign::UNSIGNED || bits == 0 || bits > carrierBits) + return false; + maximum = getUnsignedMaximum(bits); + return true; + } + + MathLib::biguint truncateUnsignedValue(MathLib::biguint value, std::size_t bits) + { + const std::size_t carrierBits = std::numeric_limits::digits; + if (bits < carrierBits) + value &= (MathLib::biguint{1} << bits) - 1; + return value; + } + + const Token* statementEnd(const Token* start) + { + if (!start) + return nullptr; + if (start->str() == "{") + return start->link(); + if (Token::Match(start, "if|for|while|switch|do|try|catch")) + return nullptr; + for (const Token* tok = start; tok; tok = tok->next()) { + if (Token::Match(tok, "(|[|{")) { + if (!tok->link()) + return nullptr; + tok = tok->link(); + continue; + } + if (tok->str() == ";") + return tok; + if (tok->str() == "}") + return nullptr; + } + return nullptr; + } + + bool containsToken(const Token* start, const Token* end, const Token* target) + { + return start && end && target && start->index() <= target->index() && target->index() <= end->index(); + } + + const Token* getIncrementedToken(const Token* step) + { + return step->astOperand1() ? step->astOperand1() : step->astOperand2(); + } + + bool exitsUnconditionally(const Token* start) + { + if (Token::simpleMatch(start, "{")) + start = start->next(); + while (start && start->str() != "}") { + if (Token::Match(start, "return|throw|break|continue")) + return true; + if (start->str() == "goto" || start->str() == "case" || start->str() == "default" || + start->str() == "{" || Token::Match(start, "%name% :")) + return false; + const Token* const end = statementEnd(start); + if (!end || end->str() != ";") + return false; + start = end->next(); + } + return false; + } + + const Scope* enclosingFunction(const Scope* scope) + { + while (scope && scope->type != ScopeType::eFunction && scope->type != ScopeType::eLambda) + scope = scope->nestedIn; + return scope; + } + // Which branch of its controlling condition the use sits in. `valid` is false when neither + // branch is proven, so `{}` is an invalid result. + struct ConditionBranch { + bool valid; // false: the use is not dominated by either branch + bool branchIsTrue; + }; + + ConditionBranch conditionBranchAtUse(const Token* conditionTop, const Token* use) + { + if (!conditionTop || !use) + return {}; + const Scope* const functionScope = enclosingFunction(conditionTop->scope()); + if (!functionScope || functionScope != enclosingFunction(use->scope())) + return {}; + const Token* control = conditionTop->previous(); + if (!Token::Match(control, "if|while|for (")) + return {}; + const Token* bodyStart = conditionTop->link() ? conditionTop->link()->next() : nullptr; + const Token* bodyEnd = statementEnd(bodyStart); + if (!bodyEnd) + return {}; + if (containsToken(bodyStart, bodyEnd, use)) + return ConditionBranch{true, true}; + if (control->str() != "if") + return {}; + const auto useAfterIfIsDominated = [&]() { + for (const Scope* scope = bodyStart->scope(); scope; scope = scope->nestedIn) { + if (scope->type == ScopeType::eIf && scope->classDef == control) + return use->scope()->isNestedIn(scope->nestedIn); + } + return false; + }; + + const Token* elseToken = bodyEnd->next(); + if (Token::simpleMatch(elseToken, "else")) { + const Token* elseStart = elseToken->next(); + const Token* elseEnd = statementEnd(elseStart); + if (!elseEnd) + return {}; + if (containsToken(elseStart, elseEnd, use)) + return ConditionBranch{true, false}; + if (!precedes(elseEnd, use) || !useAfterIfIsDominated()) + return {}; + const bool thenExits = exitsUnconditionally(bodyStart); + const bool elseExits = exitsUnconditionally(elseStart); + if (thenExits == elseExits) + return {}; + return ConditionBranch{true, !thenExits}; + } + + if (precedes(bodyEnd, use) && exitsUnconditionally(bodyStart) && useAfterIfIsDominated()) + return ConditionBranch{true, false}; + return {}; + } + + // A use inside the condition expression is dominated by the operands evaluated before it: the + // left operand of `&&` was true, the left operand of `||` was false, and a branch of a `?:` + // requires its condition to be true or false. When the fact's comparison sits in that already + // evaluated part, `branchIsTrue` reports which value the condition had at the use. + ConditionBranch conditionHoldsAtUse(const Token* condition, const Token* conditionTop, const Token* use) + { + if (!condition || !conditionTop || !use || !astHasToken(conditionTop, use)) + return {}; + for (const Token* node = use; node && node != conditionTop;) { + const Token* const parent = node->astParent(); + if (!parent) + return {}; + const Token* evaluatedBefore = nullptr; + bool evaluatedValue = false; + if (Token::simpleMatch(parent, "&&") && parent->astOperand2() == node) { + evaluatedBefore = parent->astOperand1(); + evaluatedValue = true; + } else if (Token::simpleMatch(parent, "||") && parent->astOperand2() == node) { + evaluatedBefore = parent->astOperand1(); + evaluatedValue = false; + } else if (parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?" && + parent->astParent()->astOperand2() == parent) { + evaluatedBefore = parent->astParent()->astOperand1(); + evaluatedValue = parent->astOperand1() == node; + } + if (evaluatedBefore && astHasToken(evaluatedBefore, condition)) + return ConditionBranch{true, evaluatedValue}; + node = parent; + } + return {}; + } + + bool sameValueExpression(const Token* lhs, const Token* rhs) + { + if (!lhs || !rhs) + return false; + if (lhs == rhs || (lhs->exprId() != 0 && lhs->exprId() == rhs->exprId())) + return true; + return lhs->varId() != 0 && lhs->varId() == rhs->varId(); + } + + bool isConditionFactActiveAtUse(const Value& value, const Token* valueTok, const Token* use) + { + if (!value.condition) + return true; + if (value.path > 0) + return true; + if (value.bound == Value::Bound::Point || !Token::Match(value.condition, "<|<=|>|>=")) + return false; + + const Token* const condition = value.condition; + const bool valueIsLhs = sameValueExpression(condition->astOperand1(), valueTok); + const bool valueIsRhs = sameValueExpression(condition->astOperand2(), valueTok); + if (valueIsLhs == valueIsRhs) + return false; + const bool conditionTrueMeansGreater = valueIsLhs ? Token::Match(condition, ">|>=") + : Token::Match(condition, "<|<="); + const bool factMeansGreater = (value.bound == Value::Bound::Lower) != value.isImpossible(); + bool requiredConditionValue = factMeansGreater == conditionTrueMeansGreater; + + const Token* const conditionTop = condition->astTop(); + // The expression that holds the comparison is the child of the top that contains it: the + // condition of an `if`/`while` hangs off astOperand2, the expression of a `return` off + // astOperand1. + const Token* conditionRoot = nullptr; + if (conditionTop) { + if (conditionTop->astOperand2() && astHasToken(conditionTop->astOperand2(), condition)) + conditionRoot = conditionTop->astOperand2(); + else if (conditionTop->astOperand1() && astHasToken(conditionTop->astOperand1(), condition)) + conditionRoot = conditionTop->astOperand1(); + } + if (!conditionTop || !conditionRoot) + return false; + ConditionBranch branch = conditionBranchAtUse(conditionTop, use); + if (!branch.valid) + branch = conditionHoldsAtUse(condition, conditionTop, use); + if (!branch.valid) + return false; + + for (const Token* node = condition; node != conditionRoot;) { + const Token* const parent = node->astParent(); + if (!parent) + return false; + // In a for-clause, stop at the semicolon that owns the condition subtree. + if (Token::simpleMatch(conditionTop->previous(), "for (") && parent->str() == ";" && + parent->astOperand1() == node) + break; + if (parent->str() == "(") { + node = parent; + continue; + } + if (parent->str() == "!") { + requiredConditionValue = !requiredConditionValue; + } else if (Token::simpleMatch(parent, "&&")) { + if (!requiredConditionValue) + return false; + requiredConditionValue = true; + } else if (Token::simpleMatch(parent, "||")) { + if (requiredConditionValue) + return false; + requiredConditionValue = false; + } else if (!(parent->isCast() && astIsBool(parent))) { + return false; + } + node = parent; + } + return branch.branchIsTrue == requiredConditionValue; + } + + bool isForLoopUpperBoundActiveAtUse(const Value& value, const Token* valueTok, const Token* useTok); + + UnsignedArithmeticRange getUnsignedArithmeticRange(const Token* tok, + MathLib::bigint path, + const ValueType* resultType, + MathLib::biguint resultMax, + const Settings& settings, + const Token* useTok, + bool contextual, + bool includeSymbolic, + int depth = 8) + { + UnsignedArithmeticRange range; + if (depth < 0) + return UnsignedArithmeticRange{}; + const ValueType* const valueType = tok ? tok->valueType() : nullptr; + if (!valueType || !valueType->isIntegral() || valueType->pointer) + return UnsignedArithmeticRange{}; + + const std::size_t valueSize = valueType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + const std::size_t valueBits = valueSize * settings.platform.char_bit; + const std::size_t resultSize = resultType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + const std::size_t resultBits = resultSize * settings.platform.char_bit; + if (valueBits == 0 || valueBits > 64 || resultBits == 0 || resultBits > 64) + return UnsignedArithmeticRange{}; + + const bool unsignedValue = valueType->sign == ValueType::Sign::UNSIGNED || + valueType->type == ValueType::Type::BOOL; + MathLib::bigint signedLower{}; + MathLib::bigint signedUpper{}; + if (unsignedValue) { + if (!getUnsignedTypeMaximum(valueType, valueBits, range.upper)) + return UnsignedArithmeticRange{}; + range.lower = 0; + } else { + if (valueType->sign != ValueType::Sign::SIGNED || + !getMinMaxValues(valueType, settings.platform, signedLower, signedUpper)) + return UnsignedArithmeticRange{}; + } + + const Token* symbolicSource = nullptr; + bool symbolicSourceConflict = false; + bool symbolicUpperConflict = false; + bool hasKnownPoint = false; + MathLib::bigint knownSignedPoint{}; + MathLib::biguint knownUnsignedPoint{}; + for (const Value& value : tok->values()) { + if (value.path < 0) + return UnsignedArithmeticRange{}; + if (value.path != 0 && value.path != path) + continue; + if (value.isSymbolicValue() ? !includeSymbolic : (!value.isIntValue() || value.isInconclusive())) + continue; + if (!contextual && (value.condition || value.conditional)) + continue; + if (contextual && value.path == 0 && value.condition && + !isConditionFactActiveAtUse(value, tok, useTok)) + continue; + if (contextual && value.conditional && !value.isSymbolicValue() && + !isForLoopUpperBoundActiveAtUse(value, tok, useTok)) + continue; + if (value.isSymbolicValue()) { + if (value.isImpossible()) + continue; + const bool isConditionalUpper = value.isPossible() && value.conditional && + value.bound == Value::Bound::Upper; + if (!value.tokvalue || value.tokvalue == tok) + continue; + if (value.bound == Value::Bound::Point && value.isKnown() && value.intvalue == 0) { + if (symbolicSource && symbolicSource != value.tokvalue) { + symbolicSource = nullptr; + symbolicSourceConflict = true; + } else if (!symbolicSourceConflict) { + symbolicSource = value.tokvalue; + } + } else if (isConditionalUpper && !symbolicUpperConflict) { + if (range.symbolicUpper && + (range.symbolicUpper != value.tokvalue || range.symbolicUpperOffset != value.intvalue)) { + range.symbolicUpper = nullptr; + symbolicUpperConflict = true; + } else { + range.symbolicUpper = value.tokvalue; + range.symbolicUpperOffset = value.intvalue; + } + } + continue; + } + + if (value.bound == Value::Bound::Point) { + if (!value.isKnown()) + continue; + if (unsignedValue) { + const MathLib::biguint point = truncateUnsignedValue(static_cast(value.intvalue), valueBits); + if (hasKnownPoint && point != knownUnsignedPoint) + return UnsignedArithmeticRange{}; + knownUnsignedPoint = point; + } else { + if (hasKnownPoint && value.intvalue != knownSignedPoint) + return UnsignedArithmeticRange{}; + knownSignedPoint = value.intvalue; + } + hasKnownPoint = true; + continue; + } + + if (unsignedValue) { + if (value.intvalue < 0) { + if (value.isImpossible()) { + if (value.bound == Value::Bound::Lower) + return UnsignedArithmeticRange{}; + } else if (value.bound == Value::Bound::Upper) { + return UnsignedArithmeticRange{}; + } + continue; + } + const Bounds bounds = narrowBounds( + Bounds{true, range.lower, range.upper}, + value, + static_cast(value.intvalue)); + if (!bounds.valid) + return UnsignedArithmeticRange{}; + range.lower = bounds.lower; + range.upper = bounds.upper; + } else { + const Bounds bounds = narrowBounds( + Bounds{true, signedLower, signedUpper}, + value, + value.intvalue); + if (!bounds.valid) + return UnsignedArithmeticRange{}; + signedLower = bounds.lower; + signedUpper = bounds.upper; + } + } + + if (unsignedValue) { + if (range.lower > range.upper) + return UnsignedArithmeticRange{}; + if (hasKnownPoint) { + if (knownUnsignedPoint < range.lower || knownUnsignedPoint > range.upper) + return UnsignedArithmeticRange{}; + range.lower = truncateUnsignedValue(knownUnsignedPoint, resultBits); + range.upper = range.lower; + } + } else { + if (signedLower > signedUpper) + return UnsignedArithmeticRange{}; + if (hasKnownPoint) { + if (knownSignedPoint < signedLower || knownSignedPoint > signedUpper) + return UnsignedArithmeticRange{}; + range.lower = convertToUnsigned(knownSignedPoint, resultBits); + range.upper = range.lower; + } else { + if (signedLower < 0) + return UnsignedArithmeticRange{}; + range.lower = static_cast(signedLower); + range.upper = static_cast(signedUpper); + } + } + + if (symbolicSource && !hasKnownPoint) { + const ValueType* const sourceType = symbolicSource->valueType(); + if (sourceType && sourceType->isIntegral() && !sourceType->pointer && + sourceType->sign == valueType->sign) { + const std::size_t sourceSize = sourceType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + if (sourceSize > 0 && sourceSize <= valueSize) { + const UnsignedArithmeticRange sourceRange = + getUnsignedArithmeticRange(symbolicSource, + path, + resultType, + resultMax, + settings, + useTok, + contextual, + includeSymbolic, + depth - 1); + if (sourceRange.valid) { + range.lower = std::max(range.lower, sourceRange.lower); + range.upper = std::min(range.upper, sourceRange.upper); + if (range.upper < range.lower) + return UnsignedArithmeticRange{}; + if (sourceRange.symbolicUpper && !symbolicUpperConflict) { + if (range.symbolicUpper && + (range.symbolicUpper != sourceRange.symbolicUpper || + range.symbolicUpperOffset != sourceRange.symbolicUpperOffset)) { + range.symbolicUpper = nullptr; + } else { + range.symbolicUpper = sourceRange.symbolicUpper; + range.symbolicUpperOffset = sourceRange.symbolicUpperOffset; + } + } + } + } + } + } + + range.valid = range.lower <= range.upper && range.upper <= resultMax; + return range; + } + bool getKnownPointIntValue(const Token* tok, MathLib::bigint& value) + { + if (!tok || !tok->hasKnownIntValue()) + return false; + const Value& knownValue = tok->values().front(); + if (knownValue.bound != Value::Bound::Point || knownValue.path != 0 || knownValue.condition || + knownValue.conditional) + return false; + value = knownValue.intvalue; + + return true; + } + + Bounds getForLoopIndexRange(const Token* valueTok, + const Token* useTok, + const Settings& settings) + { + if (!valueTok || valueTok->varId() == 0 || !useTok) + return Bounds{}; + const ValueType* const valueType = valueTok->valueType(); + MathLib::bigint typeMinimum{}, typeMaximum{}; + if (!valueType || valueType->sign != ValueType::Sign::SIGNED || valueType->pointer || + !getMinMaxValues(valueType, settings.platform, typeMinimum, typeMaximum)) + return Bounds{}; + + for (const Scope* loop = valueTok->scope(); loop; loop = loop->nestedIn) { + if (loop->type != ScopeType::eFor || !loop->classDef || + !containsToken(loop->bodyStart, loop->bodyEnd, useTok)) + continue; + const Token* const bodyStart = loop->bodyStart; + const Token* const init = getInitTok(loop->classDef); + const Token* const condition = getCondTok(loop->classDef); + const Token* const step = getStepTok(loop->classDef); + if (!Token::simpleMatch(init, "=") || + !sameValueExpression(init->astOperand1(), valueTok) || + !Token::Match(condition, "<|<=") || + !sameValueExpression(condition->astOperand1(), valueTok) || + !Token::simpleMatch(step, "++") || + !sameValueExpression(getIncrementedToken(step), valueTok)) + continue; + + MathLib::bigint initial{}; + MathLib::bigint limit{}; + if (!getKnownPointIntValue(init->astOperand2(), initial) || initial < 0 || + !getKnownPointIntValue(condition->astOperand2(), limit) || limit < initial) + continue; + const bool strict = Token::simpleMatch(condition, "<"); + if (strict && limit == initial) + continue; + const MathLib::bigint loopUpper = strict ? limit - 1 : limit; + const MathLib::bigint lower = std::max(initial, typeMinimum); + const MathLib::bigint upper = std::min(loopUpper, typeMaximum); + if (upper < lower) + continue; + + for (const Token* scan = bodyStart; scan && scan != useTok; scan = scan->next()) { + const Token* const nextToken = scan->isName() ? scan->next() : nullptr; + if (nextToken && nextToken->str() == "(" && + !Token::Match(scan, "if|while|for|switch|catch|sizeof|decltype")) + return Bounds{}; + if (scan->varId() != valueTok->varId()) + continue; + const Token* const parent = scan->astParent(); + if ((parent && (parent->isAssignmentOp() || Token::Match(parent, "++|--"))) || + Token::Match(scan->next(), "++|--") || Token::simpleMatch(scan->previous(), "&")) + return Bounds{}; + } + return Bounds{true, lower, upper}; + } + return Bounds{}; + } + + bool isForLoopUpperBoundActiveAtUse(const Value& value, const Token* valueTok, const Token* useTok) + { + if (!value.conditional || !value.isPossible() || value.bound != Value::Bound::Upper || value.condition || + !valueTok || valueTok->varId() == 0 || !useTok) + return false; + + for (const Scope* loop = valueTok->scope(); loop; loop = loop->nestedIn) { + if (loop->type != ScopeType::eFor || !loop->classDef || + !containsToken(loop->bodyStart, loop->bodyEnd, useTok)) + continue; + const Token* const condition = getCondTok(loop->classDef); + if (!condition || !condition->isComparisonOp() || !condition->astOperand1() || !condition->astOperand2()) + continue; + + const Token* boundTok = nullptr; + bool strict = false; + if (sameValueExpression(condition->astOperand1(), valueTok) && Token::Match(condition, "<|<=")) { + boundTok = condition->astOperand2(); + strict = Token::simpleMatch(condition, "<"); + } else if (sameValueExpression(condition->astOperand2(), valueTok) && + Token::Match(condition, ">|>=")) { + boundTok = condition->astOperand1(); + strict = Token::simpleMatch(condition, ">"); + } else { + continue; + } + + MathLib::bigint limit{}; + if (!getKnownPointIntValue(boundTok, limit) || + (strict && limit == std::numeric_limits::min())) + continue; + const MathLib::bigint upper = strict ? limit - 1 : limit; + if (value.intvalue == upper) + return true; + } + return false; + } + + bool isUnsignedArithmeticValue(const Token* tok) + { + const ValueType* const valueType = tok ? tok->valueType() : nullptr; + return valueType && valueType->isIntegral() && !valueType->pointer && + (valueType->sign == ValueType::Sign::UNSIGNED || valueType->type == ValueType::Type::BOOL); + } + + bool isSmallUnsignedConstant(const Token* tok, MathLib::biguint maximum) + { + MathLib::bigint value{}; + return getKnownPointIntValue(tok, value) && value >= 0 && + static_cast(value) <= maximum; + } + + bool isUnsignedAdditionOperand(const Token* tok, MathLib::biguint smallAddendLimit, unsigned int depth = 8) + { + if (!tok || depth == 0) + return false; + if (tok->isCast()) { + if (!isUnsignedArithmeticValue(tok)) + return false; + const Token* const source = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); + const ValueType* const sourceType = source ? source->valueType() : nullptr; + if (!sourceType || sourceType->pointer || + (sourceType->sign != ValueType::Sign::UNSIGNED && sourceType->type != ValueType::Type::BOOL)) + return false; + return isUnsignedAdditionOperand(source, smallAddendLimit, depth - 1); + } + if (tok->str() == "(") { + if (Token::Match(tok->previous(), "%name% (") || + (tok->astOperand1() && tok->astOperand1()->function())) + return isUnsignedArithmeticValue(tok); + const Token* const inner = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); + return isUnsignedAdditionOperand(inner, smallAddendLimit, depth - 1); + } + if (!isUnsignedArithmeticValue(tok)) + return false; + if (tok->variable() || tok->varId() != 0 || tok->str() == "." || tok->str() == "->") + return true; + if (tok->str() != "+" || !isUnsignedArithmeticResult(tok) || !tok->astOperand1() || !tok->astOperand2()) + return false; + if (isSmallUnsignedConstant(tok->astOperand1(), smallAddendLimit)) + return isUnsignedAdditionOperand(tok->astOperand2(), smallAddendLimit, depth - 1); + if (isSmallUnsignedConstant(tok->astOperand2(), smallAddendLimit)) + return isUnsignedAdditionOperand(tok->astOperand1(), smallAddendLimit, depth - 1); + return false; + } + + bool isSourceFactCompatible(const Value& fact, + MathLib::bigint path, + const Token* sourceTok, + const Token* useTok) + { + if (fact.path > 0 && (path == 0 || fact.path != path)) + return false; + // A conditional fact is only usable when it carries the condition it depends on: the + // branch at the use then decides whether the fact still holds. + if (fact.conditional && !fact.condition) + return false; + return fact.path != 0 || !fact.condition || isConditionFactActiveAtUse(fact, sourceTok, useTok); + } + + // Combine the excluded facts of a source expression into one interval. + // After `if (x < 0 || x > 100) return;` the facts `!<=-1` and `!>=101` are separate values. + // Neither one proves a bound that survives a narrowing conversion on its own, but together + // they describe the interval [0,100]. Only excluded bounds prove universal bounds; possible + // bounds can be witnesses from different merged paths and are used only to reject contradictions. + Bounds combineSourceRangeFacts(const Token* sourceTok, + MathLib::bigint path, + const Token* useTok) + { + bool hasLower = false; + bool hasUpper = false; + MathLib::bigint lower{}; + MathLib::bigint upper{}; + const auto isCompatible = [&](const Value& fact) { + return isSourceFactCompatible(fact, path, sourceTok, useTok); + }; + const auto updateBounds = [&](const Value& fact) { + if (fact.bound == Value::Bound::Point || !fact.isImpossible()) + return true; + if (fact.bound == Value::Bound::Upper) { + if (fact.intvalue == std::numeric_limits::max()) + return false; + const MathLib::bigint minimum = fact.intvalue + 1; + lower = hasLower ? std::max(lower, minimum) : minimum; + hasLower = true; + } else { + if (fact.intvalue == std::numeric_limits::min()) + return false; + const MathLib::bigint maximum = fact.intvalue - 1; + upper = hasUpper ? std::min(upper, maximum) : maximum; + hasUpper = true; + } + return !hasLower || !hasUpper || lower <= upper; + }; + if (!std::all_of(sourceTok->values().cbegin(), sourceTok->values().cend(), [&](const Value& fact) { + return fact.path >= 0 && + (!isCompatible(fact) || (fact.isIntValue() && !fact.isInconclusive() && updateBounds(fact))); + })) + return Bounds{}; + if (!hasLower || !hasUpper || lower > upper) + return Bounds{}; + // Possible bounds can reject contradictions but must not tighten this proof interval. + if (!std::all_of(sourceTok->values().cbegin(), sourceTok->values().cend(), [&](const Value& fact) { + if (!isCompatible(fact) || fact.isImpossible()) + return true; + if (fact.bound == Value::Bound::Point) + return !(fact.isPossible() || fact.isKnown()) || + (fact.intvalue >= lower && fact.intvalue <= upper); + return !((fact.bound == Value::Bound::Lower && fact.intvalue > upper) || + (fact.bound == Value::Bound::Upper && fact.intvalue < lower)); + })) + return Bounds{}; + return Bounds{true, lower, upper}; + } + + bool hasFittedSourceRange(const Token* sourceTok, + MathLib::bigint path, + const Token* useTok, + const ValueType* destination, + const Settings& settings) + { + if (!sourceTok || !useTok) + return false; + const Bounds bounds = combineSourceRangeFacts(sourceTok, path, useTok); + if (!bounds.valid) + return false; + const ValueType::Sign destinationSign = resolveCharSign(*destination, settings.platform); + if (destinationSign == ValueType::Sign::UNKNOWN_SIGN) + return false; + ValueType resolvedType = *destination; + resolvedType.sign = destinationSign; + MathLib::bigint destinationMinimum{}; + MathLib::bigint destinationMaximum{}; + return getMinMaxValues(&resolvedType, settings.platform, destinationMinimum, destinationMaximum) && + bounds.lower >= destinationMinimum && bounds.upper <= destinationMaximum; + } + } + + std::vector getFittedSourceValues(const Token* sourceTok, + const Value& value, + const Token* useTok, + const ValueType* destination, + const Settings& settings) + { + std::vector values; + if (!sourceTok || !useTok) + return values; + if (!hasFittedSourceRange(sourceTok, value.path, useTok, destination, settings)) + return values; + // The destination represents the whole proven interval exactly, so the conversion leaves every + // excluded bound unchanged. Collect them, keeping the error path of the fact they come from, + // but without the path id and the condition: what they record holds at the use, unconditionally. + // A bound that kept its path id would differ from the same bound derived by an earlier pass, so + // each pass would add a new value and value flow would never settle. + for (const Value& source : sourceTok->values()) { + if (!source.isIntValue() || source.isInconclusive() || source.bound == Value::Bound::Point || + !source.isImpossible() || !isSourceFactCompatible(source, value.path, sourceTok, useTok)) + continue; + Value fact = source; + fact.path = 0; + fact.conditional = false; + values.push_back(std::move(fact)); + } + return values; + } + + ConvertedValue convertValueRange(Value value, + const ValueType* source, + const ValueType* destination, + const Settings& settings, + const Token* sourceTok, + const Token* useTok) + { + if (!value.isIntValue() || value.bound == Value::Bound::Point || value.isInconclusive() || + !destination || !destination->isIntegral() || destination->pointer) + return ConvertedValue{}; + + if (source && source->isIntegral() && source->sign == ValueType::Sign::SIGNED && + destination->sign == ValueType::Sign::UNSIGNED && destination->type != ValueType::Type::BOOL && + value.isPossible() && value.bound == Value::Bound::Upper && sourceTok && useTok) { + MathLib::bigint destinationMinimum{}; + MathLib::bigint destinationMaximum{}; + const Bounds loopRange = getForLoopIndexRange(sourceTok, useTok, settings); + if (loopRange.valid && loopRange.lower >= 0 && loopRange.upper >= loopRange.lower && + value.intvalue >= loopRange.lower && + getMinMaxValues(destination, settings.platform, destinationMinimum, destinationMaximum)) { + const MathLib::bigint upper = std::min(value.intvalue, loopRange.upper); + if (loopRange.lower >= destinationMinimum && upper <= destinationMaximum) { + value.intvalue = upper; + return ConvertedValue(std::move(value)); + } } + } + + if (!source) { + if (!sourceTok || !useTok || sourceTok->valueType() || value.path < 0 || value.conditional || + (value.condition && value.path == 0 && !isConditionFactActiveAtUse(value, sourceTok, useTok))) + return ConvertedValue{}; + const Variable* const sourceVariable = sourceTok->variable(); + if (sourceVariable && sourceVariable->isPointer()) + return ConvertedValue{}; + + if (!hasFittedSourceRange(sourceTok, value.path, useTok, destination, settings)) + return ConvertedValue{}; + return ConvertedValue(std::move(value)); + } + + if (!source->isIntegral() || source->pointer) + return ConvertedValue{}; + if (isValueRangePreservingConversion(source, destination, settings, value)) + return ConvertedValue(std::move(value)); + // Implicit conversions (assignments, arguments) reach this function directly, without the cast + // path that re-emits the fitted facts, so accept the combined range here as well. + if (hasFittedSourceRange(sourceTok, value.path, useTok, destination, settings)) + return ConvertedValue(std::move(value)); + if (value.isImpossible() || + destination->sign != ValueType::Sign::UNSIGNED || destination->type == ValueType::Type::BOOL || + (source->sign != ValueType::Sign::SIGNED && source->sign != ValueType::Sign::UNSIGNED)) + return ConvertedValue{}; + + const std::size_t destinationBits = getTypeBits(*destination, settings); + const std::size_t carrierBits = std::numeric_limits::digits; + if (destinationBits == 0 || destinationBits > carrierBits) + return ConvertedValue{}; + if (destinationBits == carrierBits) { + if (source->sign != ValueType::Sign::SIGNED) + return ConvertedValue{}; + MathLib::bigint sourceMinimum{}; + MathLib::bigint sourceMaximum{}; + if (!getMinMaxValues(source, settings.platform, sourceMinimum, sourceMaximum)) + return ConvertedValue{}; + const Bounds bounds = narrowBounds( + Bounds{true, sourceMinimum, sourceMaximum}, + value, + value.intvalue); + if (!bounds.valid || bounds.lower > bounds.upper || bounds.upper >= 0) + return ConvertedValue{}; + value.intvalue = std::numeric_limits::max(); + value.bound = Value::Bound::Lower; + return ConvertedValue(std::move(value)); + } + const MathLib::biguint destinationMaximum = (MathLib::biguint{1} << destinationBits) - 1; + + MathLib::biguint imageMinimum{}; + MathLib::biguint imageMaximum{}; + if (source->sign == ValueType::Sign::SIGNED) { + MathLib::bigint sourceMinimum{}; + MathLib::bigint sourceMaximum{}; + if (!getMinMaxValues(source, settings.platform, sourceMinimum, sourceMaximum)) + return ConvertedValue{}; + const Bounds bounds = narrowBounds( + Bounds{true, sourceMinimum, sourceMaximum}, + value, + value.intvalue); + if (!bounds.valid || bounds.lower > bounds.upper) + return ConvertedValue{}; + const MathLib::biguint distance = static_cast(bounds.upper) - + static_cast(bounds.lower); + if (distance >= destinationMaximum) + return ConvertedValue{}; + imageMinimum = static_cast(bounds.lower) & destinationMaximum; + imageMaximum = static_cast(bounds.upper) & destinationMaximum; } else { + const std::size_t sourceBits = getTypeBits(*source, settings); + MathLib::biguint sourceMaximum{}; + if (!getUnsignedTypeMaximum(source, sourceBits, sourceMaximum) || value.intvalue < 0) + return ConvertedValue{}; + const Bounds bounds = narrowBounds( + Bounds{true, MathLib::biguint{0}, sourceMaximum}, + value, + static_cast(value.intvalue)); + if (!bounds.valid || bounds.lower > bounds.upper) + return ConvertedValue{}; + const MathLib::biguint distance = bounds.upper - bounds.lower; + if (distance >= destinationMaximum) + return ConvertedValue{}; + imageMinimum = bounds.lower & destinationMaximum; + imageMaximum = bounds.upper & destinationMaximum; + } + if (imageMinimum > imageMaximum) + return ConvertedValue{}; + + if (imageMinimum > 0) { + if (imageMinimum > static_cast(std::numeric_limits::max())) + return ConvertedValue{}; + value.intvalue = static_cast(imageMinimum); + value.bound = Value::Bound::Lower; + return ConvertedValue(std::move(value)); + } + if (imageMaximum < destinationMaximum) { + value.intvalue = static_cast(imageMaximum); + value.bound = Value::Bound::Upper; + return ConvertedValue(std::move(value)); + } + return ConvertedValue{}; + } + + // A known small non-negative addend whose other operand cannot reach the type's maximum. + static bool canAssumeNoWrap(const Token* expr, + const Token* addend, + const Token* value, + MathLib::biguint smallAddendLimit, + MathLib::biguint resultMax, + const Settings& settings) + { + MathLib::bigint addendValue{}; + if (!getKnownPointIntValue(addend, addendValue) || addendValue < 0 || + static_cast(addendValue) > smallAddendLimit) return false; + if (!isUnsignedAdditionOperand(value, smallAddendLimit)) { + const Bounds loopRange = getForLoopIndexRange(value, expr, settings); + if (!loopRange.valid || loopRange.lower < 0 || + loopRange.upper < loopRange.lower || + static_cast(loopRange.upper) > + resultMax - static_cast(addendValue)) + return false; } + const Token* expression = expr; + const Token* parent = expression->astParent(); + while (parent && (parent->str() == "(" || parent->isCast())) { + expression = parent; + parent = parent->astParent(); + } + if (parent && parent->isComparisonOp()) { + const Token* compareValue = nullptr; + if (parent->astOperand1() == expression) + compareValue = parent->astOperand2(); + else if (parent->astOperand2() == expression) + compareValue = parent->astOperand1(); + MathLib::bigint compareConstant{}; + if (getKnownPointIntValue(compareValue, compareConstant) && + (compareConstant < addendValue || + (compareConstant == addendValue && Token::Match(parent, "<|<=")))) + return false; + } return true; } + // An addition of a relative offset that the enclosing for loop keeps below the type's maximum. + static bool isSafeRelativeAddition(const UnsignedArithmeticRange& boundedRange, + const UnsignedArithmeticRange& addendRange, + const Token* boundedOperand, + std::size_t resultBits, + const Settings& settings) + { + if (!boundedRange.symbolicUpper || + !boundedOperand || !boundedOperand->variable() || + !boundedRange.symbolicUpper->variable() || + addendRange.upper > static_cast(std::numeric_limits::max())) + return false; + const auto addendUpper = static_cast(addendRange.upper); + if (boundedRange.symbolicUpperOffset > -addendUpper) + return false; + const ValueType* const upperType = boundedRange.symbolicUpper->valueType(); + if (!upperType || !upperType->isIntegral() || upperType->pointer || + upperType->sign != ValueType::Sign::UNSIGNED) + return false; + const std::size_t upperSize = upperType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + if (upperSize == 0 || upperSize * settings.platform.char_bit > resultBits) + return false; + for (const Scope* loop = boundedOperand->scope(); loop; loop = loop->nestedIn) { + if (loop->type != ScopeType::eFor || !loop->classDef) + continue; + const Token* const init = getInitTok(loop->classDef); + const Token* const condition = getCondTok(loop->classDef); + const Token* const step = getStepTok(loop->classDef); + if (!Token::simpleMatch(condition, "<") || + condition->astOperand1()->varId() != boundedOperand->varId() || + condition->astOperand2()->varId() != boundedRange.symbolicUpper->varId() || + !Token::simpleMatch(init, "=") || + init->astOperand1()->varId() != boundedOperand->varId() || + !Token::simpleMatch(step, "++")) + continue; + const Token* const stepVariable = getIncrementedToken(step); + if (stepVariable && stepVariable->varId() == boundedOperand->varId()) + return true; + } + return false; + } + + bool isUnsignedArithmeticNoWrap(const Token* tok, const Settings& settings, bool requireGlobalContext) + { + if (!isUnsignedArithmeticResult(tok) || !tok->astOperand1() || !tok->astOperand2()) + return false; + + const ValueType* const resultType = tok->valueType(); + const std::size_t resultSize = resultType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + const std::size_t resultBits = resultSize * settings.platform.char_bit; + if (resultBits == 0 || resultBits > 64) + return false; + MathLib::biguint resultMax{}; + if (!getUnsignedTypeMaximum(resultType, resultBits, resultMax)) + return false; + + if (tok->str() == "+") { + // Keep the historical small-increment assumption for simple unsigned values. The relative + // cap avoids applying it to increments that are large for the result type; explicit wrap + // checks such as x + 1 == 0 and x + c < c remain subject to the range proof below. + const MathLib::biguint smallAddendLimit = std::min(0xFFFF, resultMax >> 1); + if (canAssumeNoWrap(tok, tok->astOperand1(), tok->astOperand2(), smallAddendLimit, resultMax, settings) || + canAssumeNoWrap(tok, tok->astOperand2(), tok->astOperand1(), smallAddendLimit, resultMax, settings)) + return true; + } + + const Token* const lhs = tok->astOperand1(); + const Token* const rhs = tok->astOperand2(); + const auto hasOnlyNonnegativePaths = [](const Token* operand) { + return std::all_of(operand->values().cbegin(), operand->values().cend(), [](const Value& value) { + return value.path >= 0; + }); + }; + if (!hasOnlyNonnegativePaths(lhs) || !hasOnlyNonnegativePaths(rhs)) + return false; + std::vector paths; + if (requireGlobalContext) + paths.push_back(0); + else + paths = getCommonPaths(lhs->values(), rhs->values()); + if (paths.empty()) + return false; + + const bool contextual = !requireGlobalContext; + return std::all_of(paths.cbegin(), paths.cend(), [&](MathLib::bigint path) { + if (tok->str() == "-") { + const UnsignedArithmeticRange rhsPoint = getUnsignedArithmeticRange(rhs, path, resultType, resultMax, + settings, tok, contextual, false); + if (rhsPoint.valid && rhsPoint.lower == rhsPoint.upper) { + if (rhsPoint.upper == 0) + return true; + const UnsignedArithmeticRange lhsRange = getUnsignedArithmeticRange(lhs, path, resultType, resultMax, + settings, tok, contextual, false); + if (lhsRange.valid && lhsRange.lower >= rhsPoint.upper) + return true; + } + } + if (tok->str() == "+") { + const auto isZeroOperand = [&](const Token* operand) { + const UnsignedArithmeticRange zeroRange = getUnsignedArithmeticRange(operand, path, resultType, + resultMax, settings, tok, + contextual, false); + return zeroRange.valid && zeroRange.lower == 0 && zeroRange.upper == 0; + }; + if (isZeroOperand(lhs) || isZeroOperand(rhs)) + return true; + } + const UnsignedArithmeticRange lhsRange = getUnsignedArithmeticRange(lhs, path, resultType, resultMax, + settings, tok, contextual, true); + const UnsignedArithmeticRange rhsRange = getUnsignedArithmeticRange(rhs, path, resultType, resultMax, + settings, tok, contextual, true); + if (!lhsRange.valid || !rhsRange.valid) + return false; + + if (tok->str() == "-") { + if (lhsRange.lower < rhsRange.upper) + return false; + } else if (tok->str() == "+") { + if (lhsRange.upper > resultMax - rhsRange.upper && + !isSafeRelativeAddition(lhsRange, rhsRange, lhs, resultBits, settings) && + !isSafeRelativeAddition(rhsRange, lhsRange, rhs, resultBits, settings)) + return false; + } else if (tok->str() == "*") { + if (lhsRange.upper != 0 && rhsRange.upper > resultMax / lhsRange.upper) + return false; + } + return true; + }); + } + MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType* dst, const Platform& platform) { if (value_size == 0) @@ -104,7 +1412,7 @@ namespace ValueFlow const MathLib::biguint unsignedMaxValue = std::numeric_limits::max() >> ((sizeof(unsignedMaxValue) - value_size) * 8); const MathLib::biguint signBit = 1ULL << ((value_size * 8) - 1); value &= unsignedMaxValue; - if ((dst->sign == ValueType::Sign::SIGNED || (dst->sign == ValueType::Sign::UNKNOWN_SIGN && dst->type == ValueType::Type::CHAR && platform.defaultSign == 's')) && (value & signBit)) + if (resolveCharSign(*dst, platform) == ValueType::Sign::SIGNED && (value & signBit)) value |= ~unsignedMaxValue; return value; @@ -354,24 +1662,33 @@ namespace ValueFlow return tok->next(); } - Value castValue(Value value, const ValueType::Sign sign, nonneg int bit) + ConvertedValue castValue(Value value, const ValueType::Sign sign, nonneg int bit) { + if (bit <= 0 || sign == ValueType::Sign::UNKNOWN_SIGN) + return ConvertedValue{}; + if (value.isFloatValue()) { + MathLib::bigint converted{}; + if (value.isImpossible() || !convertFloatToInteger(converted, value.floatValue, sign, bit)) + return ConvertedValue{}; + value.intvalue = converted; value.valueType = Value::ValueType::INT; - if (value.floatValue >= std::numeric_limits::min() && value.floatValue <= std::numeric_limits::max()) { - value.intvalue = static_cast(value.floatValue); - } else { // don't perform UB - value.intvalue = 0; - } + return ConvertedValue(std::move(value)); } + + if (value.bound != Value::Bound::Point || !value.isIntValue()) + return ConvertedValue{}; if (bit < MathLib::bigint_bits) { - constexpr MathLib::biguint one = 1; - value.intvalue &= (one << bit) - 1; - if (sign == ValueType::Sign::SIGNED && value.intvalue & (one << (bit - 1))) { - value.intvalue |= ~((one << bit) - 1ULL); - } + const MathLib::biguint mask = (MathLib::biguint{1} << bit) - 1; + const MathLib::biguint raw = static_cast(value.intvalue) & mask; + if (sign == ValueType::Sign::SIGNED && (raw & (MathLib::biguint{1} << (bit - 1)))) + value.intvalue = -1 - static_cast((~raw) & mask); + else + value.intvalue = static_cast(raw); + } else if (sign == ValueType::Sign::UNSIGNED && value.intvalue < 0) { + return ConvertedValue{}; } - return value; + return ConvertedValue(std::move(value)); } std::string debugString(const Value& v) diff --git a/lib/vf_common.h b/lib/vf_common.h index 2557b5a1bff..0e96e995b2f 100644 --- a/lib/vf_common.h +++ b/lib/vf_common.h @@ -23,10 +23,13 @@ #include "mathlib.h" #include "sourcelocation.h" #include "symboldatabase.h" +#include "vfvalue.h" #include #include #include +#include +#include class Token; class Settings; @@ -35,12 +38,53 @@ class Library; namespace ValueFlow { - class Value; -} + /** A conversion result: valid when the value was converted, else the conversion failed. */ + struct ConvertedValue { + ConvertedValue() = default; + explicit ConvertedValue(Value v) : valid(true), value(std::move(v)) {} -namespace ValueFlow -{ - bool getMinMaxValues(const ValueType* vt, const Platform& platform, MathLib::bigint& minValue, MathLib::bigint& maxValue); + bool valid = false; + Value value; + }; + + ValueType::Sign resolveCharSign(const ValueType& type, const Platform& platform); + /** The bit width of an integral type; 0 when its size is unknown. */ + std::size_t getTypeBits(const ValueType& type, const Settings& settings); + /** 2^bits - 1, saturating at the carrier width. Requires bits > 0. */ + MathLib::biguint getUnsignedMaximum(std::size_t bits); + MathLib::biguint convertToUnsigned(MathLib::bigint value, std::size_t bits); + // Whether a comparison of a signed integral operand with an unsigned integral constant is + // performed in the unsigned domain, i.e. the operand is converted to unsigned first. + CPPCHECKLIB bool comparesSignedOperandAsUnsigned(const Token* constantTok, const Token* operandTok, const Settings& settings); + // Read an unsigned constant in the type of the signed integral expression it is compared with. + // Returns the value unchanged unless the comparison converts the operand to unsigned and the + // constant reads differently in the operand's type, e.g. 0xFFFFFFFFu -> -1 for an 'int'. + CPPCHECKLIB MathLib::bigint castConstantToOperandType(const Token* constantTok, + const Token* operandTok, + MathLib::bigint value, + const Settings& settings); + CPPCHECKLIB bool getMinMaxValues(const ValueType* vt, const Platform& platform, MathLib::bigint& minValue, MathLib::bigint& maxValue); + CPPCHECKLIB bool isValueRangePreservingConversion(const ValueType* source, + const ValueType* destination, + const Settings& settings, + const Value& value); + // Collect the excluded bounds of a source expression when they together describe an interval that the + // destination represents exactly. Each of them survives the conversion unchanged. + CPPCHECKLIB std::vector getFittedSourceValues(const Token* sourceTok, + const Value& value, + const Token* useTok, + const ValueType* destination, + const Settings& settings); + // Transfer an integer range fact through a conversion when its image is soundly representable. + CPPCHECKLIB ConvertedValue convertValueRange(Value value, + const ValueType* source, + const ValueType* destination, + const Settings& settings, + const Token* sourceTok, + const Token* useTok); + + bool isUnsignedArithmeticResult(const Token* tok); + bool isUnsignedArithmeticNoWrap(const Token* tok, const Settings& settings, bool requireGlobalContext); MathLib::bigint truncateIntValue(MathLib::bigint value, size_t value_size, const ValueType* dst, const Platform& platform); @@ -52,7 +96,7 @@ namespace ValueFlow Token * valueFlowSetConstantValue(Token *tok, const Settings &settings); - Value castValue(Value value, ValueType::Sign sign, nonneg int bit); + CPPCHECKLIB ConvertedValue castValue(Value value, ValueType::Sign sign, nonneg int bit); std::string debugString(const Value& v); diff --git a/lib/vf_settokenvalue.cpp b/lib/vf_settokenvalue.cpp index 2e5b229c0a7..82c9d8caa0a 100644 --- a/lib/vf_settokenvalue.cpp +++ b/lib/vf_settokenvalue.cpp @@ -21,6 +21,7 @@ #include "astutils.h" #include "calculate.h" #include "config.h" +#include "infer.h" #include "library.h" #include "mathlib.h" #include "platform.h" @@ -29,12 +30,14 @@ #include "token.h" #include "utils.h" #include "valueflow.h" +#include "valueptr.h" #include "vfvalue.h" #include "vf_common.h" #include #include +#include #include #include #include @@ -64,35 +67,105 @@ namespace ValueFlow return Library::Container::Yield::NO_YIELD; } - static Value truncateImplicitConversion(Token* parent, const Value& value, const Settings& settings) + static const ValueType* getImplicitConversionType(Token* parent, + const Token* sourceTok, + const Settings& settings, + ValueType& commonType) { - if (!value.isIntValue() && !value.isFloatValue()) - return value; if (!parent) - return value; - if (!parent->isBinaryOp()) - return value; - if (!parent->isConstOp() && !parent->isAssignmentOp()) - return value; - if (!astIsIntegral(parent->astOperand1(), false)) - return value; - if (!astIsIntegral(parent->astOperand2(), false)) - return value; - const ValueType* vt1 = parent->astOperand1()->valueType(); - const ValueType* vt2 = parent->astOperand2()->valueType(); - // If the sign is the same there is no truncation - if (vt1->sign == vt2->sign) - return value; - const size_t n1 = vt1->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); - const size_t n2 = vt2->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer); - ValueType::Sign sign = ValueType::Sign::UNSIGNED; - if (n1 < n2) - sign = vt2->sign; - else // (n1 >= n2) - sign = vt1->sign; - Value v = castValue(value, sign, std::max(n1, n2) * 8); - v.wideintvalue = value.intvalue; - return v; + return nullptr; + + const Token* lhs = parent->astOperand1(); + const Token* rhs = parent->astOperand2(); + if (parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?") + return parent->astParent()->valueType(); + if (parent->str() == "=") + return nullptr; + if ((parent->isConstOp() || parent->isAssignmentOp()) && lhs && rhs && lhs->valueType() && rhs->valueType()) { + if (Token::Match(parent, "<<|>>")) { + const Token* operand = sourceTok == lhs ? lhs : rhs; + commonType = ValueType::getCommonIntegralType(operand->valueType(), nullptr, settings); + } else { + commonType = ValueType::getCommonIntegralType(lhs->valueType(), rhs->valueType(), settings); + } + return &commonType; + } + return nullptr; + } + + // Like castValue(), but resolves plain char via the shared platform-sign policy. + // If the default sign is unknown, the value is kept only when both interpretations agree. + static ConvertedValue castIntegralValue(Value value, const ValueType& type, int bits, const Settings& settings) + { + const ValueType::Sign sign = resolveCharSign(type, settings.platform); + if (sign != ValueType::Sign::UNKNOWN_SIGN) + return castValue(std::move(value), sign, bits); + const char defaultSign = settings.platform.defaultSign; + if (defaultSign == 's' || defaultSign == 'S') + return castValue(std::move(value), ValueType::Sign::SIGNED, bits); + if (defaultSign == 'u' || defaultSign == 'U') + return castValue(std::move(value), ValueType::Sign::UNSIGNED, bits); + ConvertedValue signedValue = castValue(value, ValueType::Sign::SIGNED, bits); + const ConvertedValue unsignedValue = castValue(std::move(value), ValueType::Sign::UNSIGNED, bits); + if (!signedValue.valid || !unsignedValue.valid || + signedValue.value.intvalue != unsignedValue.value.intvalue) + return ConvertedValue{}; + return signedValue; + } + + ConvertedValue truncateImplicitConversion(Token* parent, const Token* sourceTok, Value value, const Settings& settings) + { + if (!parent || (!value.isIntValue() && + !(value.isSymbolicValue() && value.bound != Value::Bound::Point))) + return ConvertedValue(std::move(value)); + + ValueType commonType; + const ValueType* const destination = getImplicitConversionType(parent, sourceTok, settings, commonType); + + if (!destination || !destination->isIntegral() || destination->pointer) + return ConvertedValue(std::move(value)); + const ValueType* const source = sourceTok ? sourceTok->valueType() : nullptr; + const ValueType::Sign sourceSign = source ? resolveCharSign(*source, settings.platform) : + ValueType::Sign::UNKNOWN_SIGN; + const ValueType::Sign destinationSign = resolveCharSign(*destination, settings.platform); + if (source && source->isIntegral() && !source->pointer && source->type != ValueType::Type::BOOL && + destination->type != ValueType::Type::BOOL && sourceSign != ValueType::Sign::UNKNOWN_SIGN && + sourceSign == destinationSign) + return ConvertedValue(std::move(value)); + + if (value.isImpossible() && value.isIntValue() && value.bound == Value::Bound::Point) { + if (!isValueRangePreservingConversion(source, destination, settings, value)) + return ConvertedValue{}; + if (sourceSign == ValueType::Sign::SIGNED && destinationSign == ValueType::Sign::UNSIGNED && + destination->type != ValueType::Type::BOOL) { + const MathLib::bigint originalValue = value.intvalue; + const int bits = static_cast(ValueFlow::getTypeBits(*destination, settings)); + ConvertedValue converted = castIntegralValue(std::move(value), *destination, bits, settings); + if (!converted.valid) + return ConvertedValue{}; + converted.value.wideintvalue = originalValue; + return converted; + } + return ConvertedValue(std::move(value)); + } + if (value.isIntValue() && value.bound != Value::Bound::Point) + return convertValueRange(std::move(value), source, destination, settings, sourceTok, parent); + if (value.isImpossible() || value.bound != Value::Bound::Point || value.isSymbolicValue()) + return isValueRangePreservingConversion(source, destination, settings, value) ? + ConvertedValue(std::move(value)) : ConvertedValue{}; + if (destination->type == ValueType::Type::BOOL) { + value.intvalue = value.intvalue != 0; + return ConvertedValue(std::move(value)); + } + if (isValueRangePreservingConversion(source, destination, settings, value)) + return ConvertedValue(std::move(value)); + const int bits = static_cast(ValueFlow::getTypeBits(*destination, settings)); + const MathLib::bigint originalValue = value.intvalue; + ConvertedValue converted = castIntegralValue(std::move(value), *destination, bits, settings); + if (!converted.valid) + return ConvertedValue{}; + converted.value.wideintvalue = originalValue; + return converted; } static const Token *getCastTypeStartToken(const Token *parent, const Library& library) @@ -126,21 +199,91 @@ namespace ValueFlow return value.isIntValue() || value.isFloatValue(); } - static void setTokenValueCast(Token *parent, const ValueType &valueType, Value value, const Settings &settings) + static void setTokenValueCast(Token* parent, + const ValueType& valueType, + const Token* sourceTok, + Value value, + const Settings& settings) { - if (valueType.pointer || value.isImpossible()) - setTokenValue(parent,std::move(value),settings); - else if (valueType.type == ValueType::Type::CHAR) - setTokenValue(parent, castValue(std::move(value), valueType.sign, settings.platform.char_bit), settings); - else if (valueType.type == ValueType::Type::SHORT) - setTokenValue(parent, castValue(std::move(value), valueType.sign, settings.platform.short_bit), settings); - else if (valueType.type == ValueType::Type::INT) - setTokenValue(parent, castValue(std::move(value), valueType.sign, settings.platform.int_bit), settings); - else if (valueType.type == ValueType::Type::LONG) - setTokenValue(parent, castValue(std::move(value), valueType.sign, settings.platform.long_bit), settings); - else if (valueType.type == ValueType::Type::LONGLONG) - setTokenValue(parent, castValue(std::move(value), valueType.sign, settings.platform.long_long_bit), settings); - else if (valueType.isFloat() && isNumeric(value)) { + const ValueType* const sourceType = sourceTok ? sourceTok->valueType() : nullptr; + if (valueType.type == ValueType::Type::BOOL && sourceType && sourceType->pointer > 0 && + value.isSymbolicValue() && value.isKnown() && value.bound == Value::Bound::Point && value.intvalue == 0) { + setTokenValue(parent, std::move(value), settings); + return; + } + if (valueType.pointer) + setTokenValue(parent, std::move(value), settings); + else if (valueType.isIntegral() && (isNumeric(value) || value.isSymbolicValue())) { + if (value.isImpossible() || value.bound != Value::Bound::Point || value.isSymbolicValue()) { + if (value.isFloatValue()) { + const int bits = static_cast(ValueFlow::getTypeBits(valueType, settings)); + ConvertedValue converted = castIntegralValue(std::move(value), valueType, bits, settings); + if (!converted.valid) + return; + value = std::move(converted.value); + } else { + if (value.isIntValue() && value.bound != Value::Bound::Point) { + // Value flow visits the bounds of the source one by one, so the fact that proves a + // range may arrive after the fact that needs it. Once the facts together prove a + // range the destination represents exactly, keep all of them. A fact that is + // already recorded counts as recorded, whatever path introduced it first. + std::vector fitted; + if (sourceType && sourceType->isIntegral() && !sourceType->pointer) + fitted = getFittedSourceValues(sourceTok, value, parent, &valueType, settings); + if (!fitted.empty()) { + for (const Value& fact : fitted) { + const bool recorded = std::any_of(parent->values().cbegin(), parent->values().cend(), + [&](const Value& existing) { + return existing.valueType == fact.valueType && existing.bound == fact.bound && + existing.isImpossible() == fact.isImpossible() && + existing.intvalue == fact.intvalue && existing.tokvalue == fact.tokvalue; + }); + if (!recorded) + setTokenValue(parent, fact, settings); + } + setTokenValue(parent, std::move(value), settings); + return; + } + ConvertedValue converted = convertValueRange(std::move(value), sourceType, &valueType, settings, + sourceTok, parent); + if (!converted.valid) + return; + value = std::move(converted.value); + } else if (!isValueRangePreservingConversion(sourceType, &valueType, settings, value)) { + return; + } + if (value.isImpossible() && value.isIntValue() && value.bound == Value::Bound::Point && sourceType && + sourceType->sign == ValueType::Sign::SIGNED && valueType.sign == ValueType::Sign::UNSIGNED && + valueType.type != ValueType::Type::BOOL) { + const int bits = static_cast(ValueFlow::getTypeBits(valueType, settings)); + ConvertedValue converted = castIntegralValue(std::move(value), valueType, bits, settings); + if (!converted.valid) + return; + value = std::move(converted.value); + } + } + setTokenValue(parent, std::move(value), settings); + return; + } + if (valueType.type == ValueType::Type::BOOL) { + value.intvalue = value.isFloatValue() ? std::fpclassify(value.floatValue) != FP_ZERO : value.intvalue != 0; + value.valueType = Value::ValueType::INT; + } else { + const int bits = static_cast(ValueFlow::getTypeBits(valueType, settings)); + if (bits == 0) { + if (!isValueRangePreservingConversion(sourceType, &valueType, settings, value)) + return; + } else { + ConvertedValue converted = castIntegralValue(std::move(value), valueType, bits, settings); + if (!converted.valid) + return; + value = std::move(converted.value); + } + } + setTokenValue(parent, std::move(value), settings); + } else if (valueType.isFloat() && isNumeric(value)) { + if (value.isImpossible() || value.bound != Value::Bound::Point) + return; if (value.isIntValue()) value.floatValue = static_cast(value.intvalue); value.valueType = Value::ValueType::FLOAT; @@ -150,7 +293,7 @@ namespace ValueFlow const long long charMin = settings.platform.signedCharMin(); if (charMin <= value.intvalue && value.intvalue <= charMax) { // unknown type, but value is small so there should be no truncation etc - setTokenValue(parent,std::move(value),settings); + setTokenValue(parent, std::move(value), settings); } } } @@ -236,6 +379,188 @@ namespace ValueFlow } /** set ValueFlow value and perform calculations if possible */ + class UnsignedWrapCheck { + public: + explicit UnsignedWrapCheck(const Token* parent) + : mParent(parent), mUnsignedResult(isUnsignedArithmeticResult(parent)) {} + + bool mayWrap(const Settings& settings) { + if (!mUnsignedResult) + return false; + if (!mChecked) { + mMayWrap = !isUnsignedArithmeticNoWrap(mParent, settings, false); + mChecked = true; + } + return mMayWrap; + } + + private: + const Token* mParent; + bool mUnsignedResult; + bool mChecked = false; + bool mMayWrap = false; + }; + + static bool hasRangeBound(const Value& value) + { + return (value.isIntValue() || value.isSymbolicValue()) && value.bound != Value::Bound::Point; + } + + // The values of an operand as the operation sees them, after the conversion to the common type. + // Values whose converted value is not known are left out. + struct OperandValues { + std::list converted; + std::vector values; + }; + + static OperandValues convertOperandValues(Token* parent, const Token* operand, const Settings& settings) + { + OperandValues result; + for (const Value& storedValue : operand->values()) { + if (!storedValue.isIntValue() && !storedValue.isSymbolicValue()) { + result.values.push_back(&storedValue); + continue; + } + ValueType commonType; + const ValueType* const destination = getImplicitConversionType(parent, operand, settings, commonType); + if (!destination || !destination->isIntegral() || destination->pointer || + isValueRangePreservingConversion(operand->valueType(), destination, settings, storedValue)) { + result.values.push_back(&storedValue); + continue; + } + ConvertedValue converted = truncateImplicitConversion(parent, operand, storedValue, settings); + if (!converted.valid) + continue; + result.converted.push_back(std::move(converted.value)); + result.values.push_back(&result.converted.back()); + } + return result; + } + + static void setTokenValueBinaryOp(Token* parent, + const Value& value1, + const Value& value2, + UnsignedWrapCheck& wrapCheck, + const Settings& settings) + { + if (!isComputableValue(parent, value1) || !isComputableValue(parent, value2)) + return; + if (value1.path != value2.path && value1.path != 0 && value2.path != 0) + return; + if (value1.isIteratorValue() && value2.isIteratorValue()) + return; + if (!isCompatibleValues(value1, value2)) + return; + if ((hasRangeBound(value1) || hasRangeBound(value2)) && wrapCheck.mayWrap(settings)) + return; + Value result(0); + combineValueProperties(value1, value2, result); + if (astIsFloat(parent, false)) { + if (!result.isIntValue() && !result.isFloatValue()) + return; + result.valueType = Value::ValueType::FLOAT; + } + const bool isFloat = value1.isFloatValue() || value2.isFloatValue(); + if (isFloat && Token::Match(parent, "&|^|%|<<|>>|==|!=|%or%")) + return; + const auto intValue1 = [&]() -> MathLib::bigint { + return value1.isFloatValue() ? static_cast(value1.floatValue) : value1.intvalue; + }; + const auto intValue2 = [&]() -> MathLib::bigint { + return value2.isFloatValue() ? static_cast(value2.floatValue) : value2.intvalue; + }; + if (Token::Match(parent, "==|!=")) { + if ((value1.isIntValue() && value2.isTokValue()) || (value1.isTokValue() && value2.isIntValue())) { + if (parent->str() == "==") + result.intvalue = 0; + else if (parent->str() == "!=") + result.intvalue = 1; + } else if (value1.isIntValue() && value2.isIntValue()) { + bool error = false; + result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error); + if (error) + return; + } else if (value1.isTokValue() && value2.isTokValue() && + (astIsContainer(parent->astOperand1()) || astIsContainer(parent->astOperand2()))) { + const Token* tok1 = value1.tokvalue; + const Token* tok2 = value2.tokvalue; + bool equal = false; + if (Token::Match(tok1, "%str%") && Token::Match(tok2, "%str%")) { + equal = tok1->str() == tok2->str(); + } else if (Token::simpleMatch(tok1, "{") && Token::simpleMatch(tok2, "{")) { + std::vector args1 = getArguments(tok1); + std::vector args2 = getArguments(tok2); + if (args1.size() == args2.size()) { + if (!std::all_of(args1.begin(), args1.end(), std::mem_fn(&Token::hasKnownIntValue))) + return; + if (!std::all_of(args2.begin(), args2.end(), std::mem_fn(&Token::hasKnownIntValue))) + return; + equal = std::equal(args1.begin(), + args1.end(), + args2.begin(), + [&](const Token* atok, const Token* btok) { + return atok->getKnownIntValue() == btok->getKnownIntValue(); + }); + } else { + equal = false; + } + } else { + return; + } + result.intvalue = parent->str() == "==" ? equal : !equal; + } else { + return; + } + setTokenValue(parent, std::move(result), settings); + } else if (Token::Match(parent, "%op%")) { + if (Token::Match(parent, "%comp%")) { + if (!isFloat && !value1.isIntValue() && !value2.isIntValue()) + return; + } else if (value1.isTokValue() || value2.isTokValue()) { + return; + } + bool error = false; + if (isFloat) { + const double floatValue1 = value1.isFloatValue() ? value1.floatValue : static_cast(value1.intvalue); + const double floatValue2 = value2.isFloatValue() ? value2.floatValue : static_cast(value2.intvalue); + auto val = calculate(parent->str(), floatValue1, floatValue2, &error); + if (result.isFloatValue()) { + result.floatValue = val; + } else { + result.intvalue = static_cast(val); + } + } else { + auto val = calculate(parent->str(), intValue1(), intValue2(), &error); + if (result.isFloatValue()) { + result.floatValue = static_cast(val); + } else { + result.intvalue = val; + } + } + if (error) + return; + if (isUnsignedArithmeticResult(parent) && value1.bound == Value::Bound::Point && + value2.bound == Value::Bound::Point && result.isIntValue()) { + const ValueType* const resultType = parent->valueType(); + const size_t resultSize = resultType->getSizeOf(settings, + ValueType::Accuracy::ExactOrZero, + ValueType::SizeOf::Pointer); + if (resultSize > 0 && resultSize < sizeof(MathLib::bigint)) { + result.wideintvalue = result.intvalue; + result.intvalue = ValueFlow::truncateIntValue(result.intvalue, + resultSize, + resultType, + settings.platform); + } + } + // If the bound comes from the second value then invert the bound when subtracting + if (Token::simpleMatch(parent, "-") && value2.bound == result.bound && + value2.bound != Value::Bound::Point) + result.invertBound(); + setTokenValue(parent, std::move(result), settings); + } + } + void setTokenValue(Token* tok, Value value, const Settings& settings, @@ -246,10 +571,6 @@ namespace ValueFlow && tok->valueType()->getSizeOf(settings, ValueType::Accuracy::LowerBound, ValueType::SizeOf::Pointer) >= sizeof(MathLib::bigint)) return; - - if (!value.isImpossible() && value.isIntValue()) - value = truncateImplicitConversion(tok->astParent(), value, settings); - // a container size value on a container expression belongs to that expression, while a // pointer or an iterator only transports the size of the container it was obtained from if (value.isContainerSizeValue() && !astIsPointer(tok) && astIsContainer(tok)) @@ -261,8 +582,10 @@ namespace ValueFlow if (!tok->addValue(value)) return; - if (value.path < 0) + ConvertedValue truncated = truncateImplicitConversion(tok->astParent(), tok, value, settings); + if (!truncated.valid || truncated.value.path < 0) return; + value = std::move(truncated.value); Token *parent = tok->astParent(); if (!parent) @@ -415,12 +738,7 @@ namespace ValueFlow Token::simpleMatch(parent->astOperand1(), "dynamic_cast")) return; const ValueType &valueType = ValueType::parseDecl(castType, settings); - if (value.isImpossible() && value.isIntValue() && value.intvalue < 0 - && astIsUnsigned(tok) && valueType.sign == ValueType::SIGNED && tok->valueType() - && tok->valueType()->getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer) - >= valueType.getSizeOf(settings, ValueType::Accuracy::ExactOrZero, ValueType::SizeOf::Pointer)) - return; - setTokenValueCast(parent, valueType, std::move(value), settings); + setTokenValueCast(parent, valueType, tok, std::move(value), settings); } else if (parent->str() == ":" && Token::simpleMatch(parent->astParent(), "?")) { @@ -505,113 +823,15 @@ namespace ValueFlow return; } - for (const Value &value1 : parent->astOperand1()->values()) { - if (!isComputableValue(parent, value1)) - continue; - for (const Value &value2 : parent->astOperand2()->values()) { - if (value1.path != value2.path && value1.path != 0 && value2.path != 0) - continue; - if (!isComputableValue(parent, value2)) - continue; - if (value1.isIteratorValue() && value2.isIteratorValue()) - continue; - if (!isCompatibleValues(value1, value2)) - continue; - Value result(0); - combineValueProperties(value1, value2, result); - if (astIsFloat(parent, false)) { - if (!result.isIntValue() && !result.isFloatValue()) - continue; - result.valueType = Value::ValueType::FLOAT; - } - const bool isFloat = value1.isFloatValue() || value2.isFloatValue(); - if (isFloat && Token::Match(parent, "&|^|%|<<|>>|==|!=|%or%")) - continue; - const auto intValue1 = [&]() -> MathLib::bigint { - return value1.isFloatValue() ? static_cast(value1.floatValue) : value1.intvalue; - }; - const auto intValue2 = [&]() -> MathLib::bigint { - return value2.isFloatValue() ? static_cast(value2.floatValue) : value2.intvalue; - }; - if (Token::Match(parent, "==|!=")) { - if ((value1.isIntValue() && value2.isTokValue()) || (value1.isTokValue() && value2.isIntValue())) { - if (parent->str() == "==") - result.intvalue = 0; - else if (parent->str() == "!=") - result.intvalue = 1; - } else if (value1.isIntValue() && value2.isIntValue()) { - bool error = false; - result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error); - if (error) - continue; - } else if (value1.isTokValue() && value2.isTokValue() && - (astIsContainer(parent->astOperand1()) || astIsContainer(parent->astOperand2()))) { - const Token* tok1 = value1.tokvalue; - const Token* tok2 = value2.tokvalue; - bool equal = false; - if (Token::Match(tok1, "%str%") && Token::Match(tok2, "%str%")) { - equal = tok1->str() == tok2->str(); - } else if (Token::simpleMatch(tok1, "{") && Token::simpleMatch(tok2, "{")) { - std::vector args1 = getArguments(tok1); - std::vector args2 = getArguments(tok2); - if (args1.size() == args2.size()) { - if (!std::all_of(args1.begin(), args1.end(), std::mem_fn(&Token::hasKnownIntValue))) - continue; - if (!std::all_of(args2.begin(), args2.end(), std::mem_fn(&Token::hasKnownIntValue))) - continue; - equal = std::equal(args1.begin(), - args1.end(), - args2.begin(), - [&](const Token* atok, const Token* btok) { - return atok->getKnownIntValue() == - btok->getKnownIntValue(); - }); - } else { - equal = false; - } - } else { - continue; - } - result.intvalue = parent->str() == "==" ? equal : !equal; - } else { - continue; - } - setTokenValue(parent, std::move(result), settings); - } else if (Token::Match(parent, "%op%")) { - if (Token::Match(parent, "%comp%")) { - if (!isFloat && !value1.isIntValue() && !value2.isIntValue()) - continue; - } else { - if (value1.isTokValue() || value2.isTokValue()) - break; - } - bool error = false; - if (isFloat) { - const double floatValue1 = value1.isFloatValue() ? value1.floatValue : static_cast(value1.intvalue); - const double floatValue2 = value2.isFloatValue() ? value2.floatValue : static_cast(value2.intvalue); - auto val = calculate(parent->str(), floatValue1, floatValue2, &error); - if (result.isFloatValue()) { - result.floatValue = val; - } else { - result.intvalue = static_cast(val); - } - } else { - auto val = calculate(parent->str(), intValue1(), intValue2(), &error); - if (result.isFloatValue()) { - result.floatValue = static_cast(val); - } else { - result.intvalue = val; - } - } - if (error) - continue; - // If the bound comes from the second value then invert the bound when subtracting - if (Token::simpleMatch(parent, "-") && value2.bound == result.bound && - value2.bound != Value::Bound::Point) - result.invertBound(); - setTokenValue(parent, std::move(result), settings); - } - } + UnsignedWrapCheck wrapCheck(parent); + + const Token* const lhs = parent->astOperand1(); + const Token* const rhs = parent->astOperand2(); + const OperandValues values1 = convertOperandValues(parent, lhs, settings); + const OperandValues values2 = convertOperandValues(parent, rhs, settings); + for (const Value* value1 : values1.values) { + for (const Value* value2 : values2.values) + setTokenValueBinaryOp(parent, *value1, *value2, wrapCheck, settings); } } @@ -647,8 +867,19 @@ namespace ValueFlow else if (tok->valueType()->type == ValueType::Type::LONG) bits = settings.platform.long_bit; } - if (bits > 0 && bits < MathLib::bigint_bits) + if (bits > 0 && bits < MathLib::bigint_bits) { + // ~ is only a decreasing bijection inside the unsigned range; a bound + // outside of it cannot be masked into a meaningful bound. + if (v.bound != Value::Bound::Point && + (val.intvalue < 0 || val.intvalue > static_cast((1ULL<isUnaryOp("-") && !astIsUnsigned(parent)) { for (const Value &val : tok->values()) { + if (val.isSymbolicValue() && val.isImpossible() && val.tokvalue && + val.bound != Value::Bound::Point) { + std::list symbolicValues; + std::copy_if(val.tokvalue->values().cbegin(), + val.tokvalue->values().cend(), + std::back_inserter(symbolicValues), + [&](const Value& symbolicValue) { + return symbolicValue.path == 0 || symbolicValue.path == val.path; + }); + const std::vector range = val.bound == Value::Bound::Upper + ? ::getMinValue(::makeIntegralInferModel(), symbolicValues) + : ::getMaxValue(::makeIntegralInferModel(), symbolicValues); + if (range.empty() || range.front() == std::numeric_limits::min()) + continue; + const MathLib::bigint negated = -range.front(); + if ((val.intvalue > 0 && negated < std::numeric_limits::min() + val.intvalue) || + (val.intvalue < 0 && negated > std::numeric_limits::max() + val.intvalue)) + continue; + Value v(val); + v.valueType = Value::ValueType::INT; + v.tokvalue = nullptr; + v.intvalue = negated - val.intvalue; + v.invertBound(); + setTokenValue(parent, std::move(v), settings); + continue; + } if (!val.isIntValue() && !val.isFloatValue()) continue; Value v(val); diff --git a/lib/vf_settokenvalue.h b/lib/vf_settokenvalue.h index 65722d5a0ac..ffbd8fa5dd9 100644 --- a/lib/vf_settokenvalue.h +++ b/lib/vf_settokenvalue.h @@ -20,10 +20,10 @@ #define vfSetTokenValueH #include "sourcelocation.h" +#include "vf_common.h" class Token; class Settings; -namespace ValueFlow { class Value; } namespace ValueFlow { @@ -31,6 +31,10 @@ namespace ValueFlow Value value, const Settings& settings, SourceLocation loc = SourceLocation::current()); + ConvertedValue truncateImplicitConversion(Token* parent, + const Token* sourceTok, + Value value, + const Settings& settings); } #endif // vfSetTokenValueH diff --git a/oss-fuzz/Makefile b/oss-fuzz/Makefile index a71b026618b..8f5a3a57b73 100644 --- a/oss-fuzz/Makefile +++ b/oss-fuzz/Makefile @@ -168,7 +168,7 @@ $(libcppdir)/addoninfo.o: ../lib/addoninfo.cpp ../externals/picojson/picojson.h $(libcppdir)/analyzerinfo.o: ../lib/analyzerinfo.cpp ../externals/tinyxml2/tinyxml2.h ../lib/analyzerinfo.h ../lib/config.h ../lib/errorlogger.h ../lib/errortypes.h ../lib/filesettings.h ../lib/mathlib.h ../lib/path.h ../lib/platform.h ../lib/refthunk.h ../lib/standards.h ../lib/utils.h ../lib/xml.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/analyzerinfo.cpp -$(libcppdir)/astutils.o: ../lib/astutils.cpp ../lib/astutils.h ../lib/check.h ../lib/checkclass.h ../lib/checkers.h ../lib/checkimpl.h ../lib/config.h ../lib/errortypes.h ../lib/findtoken.h ../lib/infer.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/valueflow.h ../lib/valueptr.h ../lib/vfvalue.h +$(libcppdir)/astutils.o: ../lib/astutils.cpp ../lib/astutils.h ../lib/check.h ../lib/checkclass.h ../lib/checkers.h ../lib/checkimpl.h ../lib/config.h ../lib/errortypes.h ../lib/findtoken.h ../lib/infer.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/valueflow.h ../lib/valueptr.h ../lib/vf_common.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/astutils.cpp $(libcppdir)/check64bit.o: ../lib/check64bit.cpp ../lib/check.h ../lib/check64bit.h ../lib/checkers.h ../lib/checkimpl.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/tokenize.h ../lib/tokenlist.h ../lib/utils.h ../lib/vfvalue.h @@ -189,7 +189,7 @@ $(libcppdir)/checkbufferoverrun.o: ../lib/checkbufferoverrun.cpp ../externals/ti $(libcppdir)/checkclass.o: ../lib/checkclass.cpp ../externals/tinyxml2/tinyxml2.h ../lib/astutils.h ../lib/check.h ../lib/checkclass.h ../lib/checkers.h ../lib/checkimpl.h ../lib/config.h ../lib/errorlogger.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/tokenize.h ../lib/tokenlist.h ../lib/utils.h ../lib/vfvalue.h ../lib/xml.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/checkclass.cpp -$(libcppdir)/checkcondition.o: ../lib/checkcondition.cpp ../lib/astutils.h ../lib/check.h ../lib/checkcondition.h ../lib/checkers.h ../lib/checkimpl.h ../lib/checkother.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/tokenize.h ../lib/tokenlist.h ../lib/utils.h ../lib/vfvalue.h +$(libcppdir)/checkcondition.o: ../lib/checkcondition.cpp ../lib/astutils.h ../lib/check.h ../lib/checkcondition.h ../lib/checkers.h ../lib/checkimpl.h ../lib/checkother.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/tokenize.h ../lib/tokenlist.h ../lib/utils.h ../lib/vf_common.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/checkcondition.cpp $(libcppdir)/checkers.o: ../lib/checkers.cpp ../lib/checkers.h ../lib/config.h @@ -357,10 +357,10 @@ $(libcppdir)/utils.o: ../lib/utils.cpp ../lib/config.h ../lib/utils.h $(libcppdir)/vf_analyzers.o: ../lib/vf_analyzers.cpp ../lib/analyzer.h ../lib/astutils.h ../lib/calculate.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/programmemory.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/valueflow.h ../lib/valueptr.h ../lib/vf_analyzers.h ../lib/vf_common.h ../lib/vf_settokenvalue.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_analyzers.cpp -$(libcppdir)/vf_common.o: ../lib/vf_common.cpp ../lib/astutils.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vf_common.h ../lib/vf_settokenvalue.h ../lib/vfvalue.h +$(libcppdir)/vf_common.o: ../lib/vf_common.cpp ../lib/astutils.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/infer.h ../lib/library.h ../lib/mathlib.h ../lib/path.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vf_common.h ../lib/vf_settokenvalue.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_common.cpp -$(libcppdir)/vf_settokenvalue.o: ../lib/vf_settokenvalue.cpp ../lib/astutils.h ../lib/calculate.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/valueflow.h ../lib/vf_common.h ../lib/vf_settokenvalue.h ../lib/vfvalue.h +$(libcppdir)/vf_settokenvalue.o: ../lib/vf_settokenvalue.cpp ../lib/astutils.h ../lib/calculate.h ../lib/checkers.h ../lib/config.h ../lib/errortypes.h ../lib/infer.h ../lib/library.h ../lib/mathlib.h ../lib/platform.h ../lib/refthunk.h ../lib/settings.h ../lib/smallvector.h ../lib/sourcelocation.h ../lib/standards.h ../lib/symboldatabase.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/valueflow.h ../lib/valueptr.h ../lib/vf_common.h ../lib/vf_settokenvalue.h ../lib/vfvalue.h $(CXX) ${LIB_FUZZING_ENGINE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $(libcppdir)/vf_settokenvalue.cpp $(libcppdir)/vfvalue.o: ../lib/vfvalue.cpp ../lib/config.h ../lib/errortypes.h ../lib/mathlib.h ../lib/smallvector.h ../lib/templatesimplifier.h ../lib/token.h ../lib/utils.h ../lib/vfvalue.h diff --git a/test/cfg/std.cpp b/test/cfg/std.cpp index 25aa5b5892b..3bdf9bd9b4f 100644 --- a/test/cfg/std.cpp +++ b/test/cfg/std.cpp @@ -2714,7 +2714,6 @@ void uninitvar_fpclassify(void) void bool_isfinite(float f) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isfinite(f)==123) {} } @@ -2736,7 +2735,6 @@ void uninitvar_isfinite(void) void bool_isgreater(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isgreater(f1,f2)==123) {} } @@ -2758,7 +2756,6 @@ void uninitvar_isgreater(void) void bool_isgreaterequal(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isgreaterequal(f1, f2)==123) {} } @@ -2780,7 +2777,6 @@ void uninitvar_isgreaterequal(void) void bool_isinf(float f) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isinf(f)==123) {} } @@ -2809,7 +2805,6 @@ void uninitvar_logb(void) void bool_isless(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isless(f1,f2)==123) {} } @@ -2831,7 +2826,6 @@ void uninitvar_isless(void) void bool_islessequal(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::islessequal(f1,f2)==123) {} } @@ -2853,7 +2847,6 @@ void uninitvar_islessequal(void) void bool_islessgreater(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::islessgreater(f1,f2)==123) {} } @@ -2886,7 +2879,6 @@ void uninitvar_nan(void) void bool_isnan(float f) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isnan(f)==123) {} } @@ -2900,7 +2892,6 @@ void uninitvar_isnan(void) void bool_isnormal(float f) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isnormal(f)==123) {} } @@ -2914,7 +2905,6 @@ void uninitvar_isnormal(void) void bool_isunordered(float f1, float f2) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::isunordered(f1,f2)==123) {} } @@ -3456,7 +3446,6 @@ void uninivar_scalbln(void) void bool_signbit(float f) { // cppcheck-suppress compareBoolExpressionWithInt - // cppcheck-suppress compareValueOutOfTypeRangeError if (std::signbit(f)==123) {} } diff --git a/test/cli/other_test.py b/test/cli/other_test.py index b3769320ca0..9848579caf7 100644 --- a/test/cli/other_test.py +++ b/test/cli/other_test.py @@ -41,6 +41,31 @@ def test_missing_include(tmpdir): # #11283 assert stderr == '{}:2:2: information: Include file: "test.h" not found. [missingInclude]\n'.format(test_file) +@pytest.mark.parametrize("extension", [".c", ".cpp"]) +def test_floating_strict_bounds_do_not_mark_parameters_uninitialized(tmpdir, extension): + test_file = os.path.join(tmpdir, 'floating_bounds' + extension) + with open(test_file, 'wt') as f: + f.write(""" +float f1(float x) { if (x >= 1.0f) return 1; return x; } +float f5(float x) { if (x >= 1.0f) return 1; if (x < 1.0f) return 2; return x; } +long double g1(long double x) { if (x <= 2.0L) return 1; return x; } +float g2(float x) { if (1.0f <= x) return 1; return x * 2; } +double control(double x) { if (x >= 1.0) return 1; return x; } +float guarded_else(float x) { + if (x <= 0.0f) return 0; + else return x; +} +float real_uninitialized(void) { + float real_uninitialized; + return real_uninitialized; +} +""") + + exitcode, _, stderr = cppcheck(['-q', '--enable=style,warning', '--platform=unix64', '--template=simple', test_file]) + assert exitcode == 0 + assert stderr.count('[uninitvar]') == 1 + assert 'real_uninitialized [uninitvar]' in stderr + def __test_missing_include_check_config(tmpdir, use_j): test_file = os.path.join(tmpdir, 'test.c') with open(test_file, 'wt') as f: @@ -241,8 +266,6 @@ def test_progress(tmpdir): "progress: ValueFlow::valueFlowForLoop(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n" "progress: ValueFlow::valueFlowDynamicBufferSize(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n" "progress: ValueFlow::valueFlowDynamicBufferSize(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n" - "progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n" - "progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n" "progress: ValueFlow::valueFlowFunctionReturn(tokenlist, errorLogger, settings) 1 0%\n" "progress: ValueFlow::valueFlowFunctionReturn(tokenlist, errorLogger, settings) 1 100%\n" "progress: ValueFlow::valueFlowLifetime(tokenlist, errorLogger, settings) 1 0%\n" @@ -265,6 +288,8 @@ def test_progress(tmpdir): "progress: ValueFlow::valueFlowContainerSize(tokenlist, symboldatabase, errorLogger, settings, skippedFunctions) 1 100%\n" "progress: ValueFlow::valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n" "progress: ValueFlow::valueFlowSafeFunctions(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n" + "progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 0%\n" + "progress: ValueFlow::valueFlowSubFunction(tokenlist, symboldatabase, errorLogger, settings) 1 100%\n" "progress: ValueFlow 100%\n" "progress: Run checkers 0%\n" "progress: Run checkers 100%\n" @@ -3447,6 +3472,25 @@ def test_unique_error(tmp_path): # #6366 ] +def test_unsigned_loop_index_wrap_remains_out_of_bounds(tmp_path): + test_file = tmp_path / 'unsigned_wrap.cpp' + test_file.write_text( + "void f() {\n" + " int a[4];\n" + " for (unsigned int i = 0; i < 1; ++i)\n" + " a[i - 1] = 0;\n" + "}\n" + ) + + args = ['-q', '--enable=warning,style', '--platform=unix64', '--template=simple', str(test_file)] + exitcode, stdout, stderr = cppcheck(args) + assert exitcode == 0, stdout + assert stdout.splitlines() == [] + assert stderr.splitlines() == [ + "{}:4:10: error: Array 'a[4]' accessed at index 4294967295, which is out of bounds. [arrayIndexOutOfBounds]".format(test_file) + ] + + def test_check_unused_templates_class(tmp_path): test_file_h = tmp_path / 'test.h' with open(test_file_h, 'wt') as f: diff --git a/test/testbufferoverrun.cpp b/test/testbufferoverrun.cpp index a77b89d8f23..ebc1b78dc65 100644 --- a/test/testbufferoverrun.cpp +++ b/test/testbufferoverrun.cpp @@ -167,6 +167,10 @@ class TestBufferOverrun : public TestFixture { TEST_CASE(array_index_77); TEST_CASE(array_index_78); TEST_CASE(array_index_79); // #15225 + TEST_CASE(array_index_loop_guard); + TEST_CASE(array_index_unsigned_loop_arithmetic); + TEST_CASE(array_index_loop_guard_partial_cond_after_loop); + TEST_CASE(array_index_cast_range); TEST_CASE(array_index_multidim); TEST_CASE(array_index_switch_in_for); TEST_CASE(array_index_for_in_for); // FP: #2634 @@ -189,6 +193,7 @@ class TestBufferOverrun : public TestFixture { TEST_CASE(array_index_for_neq); // #2211: Using != in condition TEST_CASE(array_index_for_question); // #2561: for, ?: TEST_CASE(array_index_for_andand_oror); // FN: using && or || in the for loop condition + TEST_CASE(array_index_for_tightLowerBound); TEST_CASE(array_index_for_varid0); // #4228: No varid for counter variable TEST_CASE(array_index_vla_for); // #3221: access VLA inside for TEST_CASE(array_index_extern); // FP when using 'extern'. #1684 @@ -203,6 +208,9 @@ class TestBufferOverrun : public TestFixture { TEST_CASE(array_index_container_data); // pointer from data()/c_str() carries the container size TEST_CASE(array_index_two_for_loops); TEST_CASE(array_index_new); // #7690 + TEST_CASE(array_index_guile); + TEST_CASE(array_index_abiword); + TEST_CASE(array_index_caller_inference); TEST_CASE(buffer_overrun_2_struct); TEST_CASE(buffer_overrun_3); @@ -2031,6 +2039,329 @@ class TestBufferOverrun : public TestFixture { "}\n"); ASSERT_EQUALS("[test.cpp:7:11]: (error) Array 'a[2]' accessed at index 2, which is out of bounds. [arrayIndexOutOfBounds]\n", errout_str()); + const Settings settingsUnix64 = settingsBuilder(settings0_i).platform(Platform::Type::Unix64).build(); + // The loop index x is at least colsToTranslate, and the cast range of + // (int)cloudDx only provides the trivial floor of int. x - colsToTranslate + // must not be reported as a negative index. + check("static float cloudDx;\n" + "static int g_dst[400];\n" + "static int g_src[400];\n" + "void updateClouds(float elapsedTime) {\n" + " cloudDx += elapsedTime * 5;\n" + " if (cloudDx >= 1.0f) {\n" + " const int colsToTranslate = (int)cloudDx;\n" + " for (int x = colsToTranslate; x < 400; ++x) {\n" + " g_dst[x - colsToTranslate] = g_src[x];\n" + " }\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + check("int a[10];\n" + "void mixed(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + + check("int a[10];\n" + "void guarded(int x) {\n" + " if (x < 0) return;\n" + " for (int i = x; i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void negative_index(int idx) {\n" + " int buf[10];\n" + " if (idx < 0) return;\n" + " buf[idx - 1] = 0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3:13] -> [test.cpp:4:8]: (warning) Either the condition 'idx<0' is redundant or the array 'buf[10]' is accessed at index -1, which is out of bounds. [negativeIndex]\n", + errout_str()); + + // A genuinely negative literal index must still be reported + check("static int a[10];\n" + "void f() {\n" + " a[-1] = 0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:3:4]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n", + errout_str()); + + check("class SyncEvolution {\n" + " enum class Status : unsigned { None, First, Last };\n" + "public:\n" + " static void update(Status status) {\n" + " int dst[10];\n" + " if (status == Status::First) {}\n" + " const int offset = static_cast(status);\n" + " for (int x = offset; x < 10; ++x)\n" + " dst[x - offset] = 0;\n" + " }\n" + "};\n"); + ASSERT(errout_str().find("[negativeIndex]") == std::string::npos); + check("int a[10];\n" + "enum class Status : unsigned { None, First, Last };\n" + "void f(Status status, bool flag) {\n" + " int offset = static_cast(status);\n" + " if (flag) offset = 4;\n" + " for (int i = offset; i < 10; ++i)\n" + " a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[negativeIndex]") == std::string::npos); + + + check("void f() {\n" + " int a[4];\n" + " for (unsigned int i = 0; i < 1; ++i)\n" + " a[(int)i - 1] = 0;\n" + "}\n"); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + + check("void f() {\n" + " int a[4];\n" + " for (unsigned int i = 0; i < 1; ++i)\n" + " a[i - 1] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[negativeIndex]") == std::string::npos); + + check("enum E { Negative = -1 };\n" + "void f() {\n" + " int a[4];\n" + " for (int i = Negative; i < 1; ++i)\n" + " a[i] = 0;\n" + "}\n"); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + + check("void f() {\n" + " int a[4];\n" + " for (int i = -1; i < 1; ++i)\n" + " a[i] = 0;\n" + "}\n"); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + } + + void array_index_loop_guard() + { + const Settings settingsUnix64 = settingsBuilder(settings0_i).platform(Platform::Type::Unix64).build(); + + check("int a[10];\n" + "void lower_first(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; i >= 0 && i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int a[10];\n" + "void upper_first(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; i < 10 && i >= 0; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int a[10];\n" + "void reversed_lower(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; 0 <= i && i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int a[10];\n" + "void never_enters() {\n" + " for (int i = -1; i >= 0 && i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int a[10];\n" + "void never_enters_upper_first() {\n" + " for (int i = -1; i < 10 && i >= 0; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int a[10];\n" + "void strict_lower(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; i > -2 && i < 10; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + + check("int a[10];\n" + "void negative_or_branch(int x) {\n" + " if (x >= 0) {}\n" + " for (int i = x; (i >= 0 && i < 10) || i == -1; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + + check("int a[10];\n" + "void high_or_branch() {\n" + " for (int i = 100; i < 10 || i == 100; ++i) a[i] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBounds]") != std::string::npos); + } + void array_index_unsigned_loop_arithmetic() + { + const Settings settingsUnix64 = settingsBuilder(settings0_i).platform(Platform::Type::Unix64).build(); + check("typedef unsigned long size_t;\n" + "void f1(void) { int a[10]; for (unsigned i = 0; i < 10; i++) a[i + 1] = 0; }\n" + "void f2(void) { int a[10]; for (size_t i = 0; i < 10; i++) a[i + 1] = 0; }\n" + "void f3(void) { char buf[10]; for (unsigned i = 0; i < sizeof(buf); i++) buf[i + 1] = 0; }\n" + "void f4(void) { int a[10]; for (int i = 0; i < 10; i++) a[i + 1u] = 0; }\n" + "void f5(void) { int a[10]; for (unsigned i = 0; i < 10; i++) a[2 * i] = 0; }\n" + "void f6(void) { int a[10]; for (size_t i = 0; i < 10; i++) a[2 * i] = 0; }\n" + "void f7(void) { int a[10]; int i = 0; while (i < 10) { a[i + 1] = 0; i++; } }\n", + settingsUnix64, false); + ASSERT_EQUALS("[test.c:2:63]: (error) Array 'a[10]' accessed at index 10, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:3:61]: (error) Array 'a[10]' accessed at index 10, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:4:77]: (error) Array 'buf[10]' accessed at index 10, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:5:58]: (error) Array 'a[10]' accessed at index 10, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:6:63]: (error) Array 'a[10]' accessed at index 18, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:7:61]: (error) Array 'a[10]' accessed at index 18, which is out of bounds. [arrayIndexOutOfBounds]\n" + "[test.c:8:48] -> [test.c:8:57]: (warning) Either the condition 'i<10' is redundant or the array 'a[10]' is accessed at index 10, which is out of bounds. [arrayIndexOutOfBoundsCond]\n", + errout_str()); + } + + void array_index_loop_guard_partial_cond_after_loop() + { + // the compound condition does not prove the exact final value, + // but the exceeding increment is still a feasible exit + check("int a[10];\n" + "void p4(int* x) {\n" + " int i;\n" + " for (i = 0; i < 10 && x[i]; i++) {}\n" + " a[i] = 0;\n" + "}\n"); + ASSERT(errout_str().find("[arrayIndexOutOfBounds]") != std::string::npos); + } + + + void array_index_cast_range() + { + const Settings settingsUnix64 = settingsBuilder(settings0_i).platform(Platform::Type::Unix64).build(); + const Settings settingsUnix32 = settingsBuilder(settings0_i).platform(Platform::Type::Unix32).build(); + const Settings* const platforms[] = {&settingsUnix64, &settingsUnix32}; + + const char assignment[] = "void f(int x) {\n" + " int a[10];\n" + " if (x < 0) {}\n" + " unsigned int u = x;\n" + " a[u] = 0;\n" + "}\n"; + const char cast[] = "void f(int x) {\n" + " int a[10];\n" + " if (x < 0) {}\n" + " a[(unsigned int)x] = 0;\n" + "}\n"; + const char operand[] = "void f(int x) {\n" + " int a[10];\n" + " if (x < 0) {}\n" + " a[x + 0u] = 0;\n" + "}\n"; + for (const Settings* platform : platforms) { + check(assignment, *platform); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + check(cast, *platform); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + check(operand, *platform); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + } + + check("void f(int x) {\n" + " int a[10];\n" + " if (x == -1) {}\n" + " a[(unsigned int)x] = 0;\n" + "}\n", settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + + check("void f(int x) {\n" + " int a[10];\n" + " if (x < 0 || x >= 10) return;\n" + " a[(unsigned int)x] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void f(int x) {\n" + " int a[10];\n" + " if (x == -256) {}\n" + " a[(unsigned char)x] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + // Model size_t's target width explicitly for SimpleTokenizer's platform settings. + const char sizeT64[] = "typedef unsigned long size_t;\n" + "void f(int x) {\n" + " int a[10];\n" + " if (x < 0) {}\n" + " a[(size_t)x] = 0;\n" + "}\n"; + check(sizeT64, settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + const char sizeT32[] = "typedef unsigned int size_t;\n" + "void f(int x) {\n" + " int a[10];\n" + " if (x < 0) {}\n" + " a[(size_t)x] = 0;\n" + "}\n"; + check(sizeT32, settingsUnix32); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + + const char opaqueSource[] = "const char *xlat[10];\n" + "struct Unknown;\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type < 0 || p->type >= 20) return 0;\n" + " return xlat[(int)p->type];\n" + "}\n"; + check(opaqueSource, settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + const char adjustedOpaqueSource[] = "const char *xlat[10];\n" + "struct Unknown;\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type >= 20) p->type -= 20;\n" + " if (p->type < 0 || p->type >= 20) return 0;\n" + " return xlat[(int)p->type];\n" + "}\n"; + check(adjustedOpaqueSource, settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + const char guardedOpaqueSource[] = "const char *xlat[10];\n" + "struct Unknown;\n" + "void report(void);\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type >= 20) p->type -= 20;\n" + " if (p->type < 0 || p->type >= 20) { report(); return 0; }\n" + " return xlat[(int)p->type];\n" + "}\n"; + check(guardedOpaqueSource, settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + + const char typedSource[] = "const char *xlat[10];\n" + "struct Unknown { char type; };\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type < 0 || p->type >= 20) return 0;\n" + " return xlat[(int)p->type];\n" + "}\n"; + check(typedSource, settingsUnix64); + ASSERT(errout_str().find("[arrayIndexOutOfBoundsCond]") != std::string::npos); + + check("const char *xlat[10];\n" + "struct Unknown;\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type < 0 || p->type >= 10) return 0;\n" + " return xlat[(int)p->type];\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("const char *xlat[20];\n" + "struct Unknown;\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type < 0 || p->type >= 20) return 0;\n" + " return xlat[(int)p->type];\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("const char *xlat[10];\n" + "struct Unknown;\n" + "const char *lookup(Unknown *p) {\n" + " if (p->type < 0 || p->type >= 20) return 0;\n" + " return xlat[(int)p->type % 10];\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); } void array_index_78() @@ -2485,6 +2816,40 @@ class TestBufferOverrun : public TestFixture { "}\n"); ASSERT_EQUALS("[test.cpp:5:12]: (error) Array 'val[5]' accessed at index -9994, which is out of bounds. [negativeIndex]\n" "[test.cpp:5:23]: (error) Array 'val[5]' accessed at index -9995, which is out of bounds. [negativeIndex]\n", errout_str()); + + check("void f(void) {\n" + " int a[10];\n" + " for (int i = 0; i-- > -3; i++) {\n" + " a[i] = 0;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:10]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n", errout_str()); + + check("void f(void) {\n" + " int a[10];\n" + " for (int i = 0; (i = 0) < 1; i++) {\n" + " a[i] = 0;\n" + " break;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("void f(void) {\n" + " int a[10];\n" + " for (int i = 0; --i > -3; i++) {\n" + " a[i] = 0;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:10]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n", errout_str()); + + check("void f(void) {\n" + " int n = 10;\n" + " int a[10];\n" + " for (int i = 0; i < n; i++) {\n" + " a[i] = 0;\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); } @@ -2572,6 +2937,53 @@ class TestBufferOverrun : public TestFixture { ASSERT_EQUALS("", errout_str()); } + void array_index_for_tightLowerBound() { + // The initializer 'n - 1' on an unsigned 'n' carries only an excluded bound '!<=-2', but the + // bound is tight: the minimum -1 is reached when n is 0, so the index is really out of bounds. + check("int a[10];\n" + "void n1(unsigned char n) { for (int i = n - 1; i < 10; i++) a[i] = 0; }\n" + "void n2(unsigned short n) { for (int i = n - 2; i < 10; i++) a[i] = 0; }\n" + "void n3(unsigned char n) { for (int i = (int)n - 1; i < 10; i++) a[i] = 0; }\n" + "void n4(unsigned char u) { for (int i = u - 300; i < 10; i++) a[i] = 0; }\n"); + ASSERT_EQUALS("[test.cpp:2:62]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n" + "[test.cpp:3:63]: (error) Array 'a[10]' accessed at index -2, which is out of bounds. [negativeIndex]\n" + "[test.cpp:4:67]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n" + "[test.cpp:5:64]: (error) Array 'a[10]' accessed at index -300, which is out of bounds. [negativeIndex]\n", + errout_str()); + + // '-(int)u' excludes INT_MIN itself, which the type cannot represent below: the exclusion is + // vacuous and must not be forwarded as the reachable minimum. + check("int a[10];\n" + "void f(unsigned char u) { for (int i = -(int)u; i < 10; i++) a[i] = 0; }\n"); + ASSERT_EQUALS("", errout_str()); + + // The floor of a narrower initializer type is reachable when the loop variable can express + // one below it: 'unsigned char n' starts at 0 when n is 0, which is not out of bounds. + check("int a[10];\n" + "void t1(unsigned char n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }\n" + "void t2(unsigned short n) { for (int i = n; i < 10; i++) a[i - 1] = 0; }\n" + "void t3(int x) { for (int i = (unsigned char)x; i < 10; i++) a[i - 1] = 0; }\n"); + ASSERT_EQUALS("[test.cpp:2:58]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n" + "[test.cpp:3:59]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n" + "[test.cpp:4:63]: (error) Array 'a[10]' accessed at index -1, which is out of bounds. [negativeIndex]\n", + errout_str()); + + // The trivial floor of a cast range already sits at the variable's floor, so the value it + // excludes cannot be represented and must not be reported. + check("static float cloudDx;\n" + "static int g_dst[400];\n" + "static int g_src[400];\n" + "void updateClouds(float elapsedTime) {\n" + " cloudDx += elapsedTime * 5;\n" + " if (cloudDx >= 1.0f) {\n" + " const int colsToTranslate = (int)cloudDx;\n" + " for (int x = colsToTranslate; x < 400; ++x)\n" + " g_dst[x - colsToTranslate] = g_src[x];\n" + " }\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + } + void array_index_for_continue() { // #3913 check("void f() {\n" @@ -4146,6 +4558,22 @@ class TestBufferOverrun : public TestFixture { "}\n", settings0_p); ASSERT_EQUALS("[test.cpp:3:11] -> [test.cpp:4:14]: (portability) Undefined behaviour, when 'i' is -1 the pointer arithmetic 'x+i' is out of bounds. [pointerOutOfBoundsCond]\n", errout_str()); + check("void decimal_remainder(uint32_t i) {\n" + " char table[200];\n" + " while (i != 0U) {\n" + " uint32_t q = i / 100U;\n" + " uint32_t offset = (i - q * 100U) << 1;\n" + " char *p = table + offset;\n" + " (void)p;\n" + " i = q;\n" + " }\n" + "}\n" + "void actual_overrun(void) {\n" + " char table[200];\n" + " char *p = table + 201;\n" + "}\n", settings0_p); + ASSERT_EQUALS("[test.cpp:13:21]: (portability) Undefined behaviour, pointer arithmetic 'table+201' is out of bounds. [pointerOutOfBounds]\n", errout_str()); + check("void f() {\n" // #6350 - fp when there is cast of buffer " wchar_t buf[64];\n" " p = (unsigned char *) buf + sizeof (buf);\n" @@ -6227,6 +6655,77 @@ class TestBufferOverrun : public TestFixture { "}\n", settings); ASSERT_EQUALS("", errout_str()); } + void array_index_guile() { + check("#include \n" + "double f(double x) {\n" + " if (x <= -1.0) {\n" + " if (x == -1.0) return -100.0;\n" + " else return 0.0 / 0.0;\n" + " }\n" + " if (x < -0.5 || x > 1.0) return log(1.0 + x);\n" + " if (x == 0.0) return x;\n" + " double m = round(x * 256.0);\n" + " const double table[385] = {0};\n" + " return table[128 + (int)m];\n" + "}\n", dinit(CheckOptions, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + } + + void array_index_abiword() { + const Settings settingsUnix64 = settingsBuilder(settings0_i).platform(Platform::Type::Unix64).build(); + check("void f(unsigned int keyval) {\n" + " int table[256];\n" + " if (keyval > 0xFFFF) return;\n" + " if (keyval > 0xFF00) return;\n" + " if (keyval > 0xFE00) table[keyval - 0xFE00] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:16] -> [test.cpp:5:31]: (warning) Either the condition 'keyval>0xFF00' is redundant or the array 'table[256]' is accessed at index 256, which is out of bounds. [arrayIndexOutOfBoundsCond]\n", errout_str()); + + check("void f(unsigned int keyval) {\n" + " int table[256];\n" + " if (keyval <= 0xFFFF && keyval <= 0xFF00 && keyval > 0xFE00)\n" + " table[keyval - 0xFE00] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:36] -> [test.cpp:4:14]: (warning) Either the condition 'keyval<=0xFF00' is redundant or the array 'table[256]' is accessed at index 256, which is out of bounds. [arrayIndexOutOfBoundsCond]\n", errout_str()); + + check("void f(unsigned int keyval) {\n" + " int table[256];\n" + " if (0xFFFF < keyval || 0xFF00 < keyval) return;\n" + " if (0xFE00 >= keyval) return;\n" + " table[keyval - 0xFE00] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:35] -> [test.cpp:5:10]: (warning) Either the condition '0xFF00 0xFFFF) return;\n" + " if (keyval >= 0xFF00) return;\n" + " if (keyval > 0xFE00) table[keyval - 0xFE00] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void f(unsigned int keyval) {\n" + " int table[257];\n" + " if (keyval > 0xFFFF) return;\n" + " if (keyval > 0xFF00) return;\n" + " if (keyval > 0xFE00) table[keyval - 0xFE00] = 0;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + } + void array_index_caller_inference() + { + check("struct Scope { unsigned short sp; };\n" + "int buffer[4];\n" + "void pop_n(Scope *s, int n) {\n" + " if ((int)s->sp - n < 0)\n" + " buffer[(int)s->sp - n] = 1;\n" + "}\n" + "void caller_underflow(Scope *s) {\n" + " s->sp = 0;\n" + " pop_n(s, 1);\n" + "}\n", settings0_i); + ASSERT(errout_str().find("[negativeIndex]") != std::string::npos); + } }; REGISTER_TEST(TestBufferOverrun) diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 5961dca21a9..ae8a1a5bef1 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -46,6 +46,7 @@ class TestCondition : public TestFixture { TEST_CASE(assignAndCompare); // assignment and comparison don't match TEST_CASE(mismatchingBitAnd); // overlapping bitmasks TEST_CASE(comparison); // CheckCondition::comparison test cases + TEST_CASE(unsignedArithmeticNoWrap); TEST_CASE(multicompare); // mismatching comparisons TEST_CASE(overlappingElseIfCondition); // overlapping conditions in if and else-if TEST_CASE(oppositeElseIfCondition); // opposite conditions in if and else-if @@ -125,12 +126,15 @@ class TestCondition : public TestFixture { TEST_CASE(checkAssignmentInCondition); TEST_CASE(compareOutOfTypeRange); + TEST_CASE(sizelessPodtypeConversions); + TEST_CASE(conditionInferenceProvenance); TEST_CASE(knownConditionCast); // #9976 TEST_CASE(knownConditionIncrementLoop); // #9808 TEST_CASE(knownConditionAfterBailout); // #12526 TEST_CASE(knownConditionIncDecOperator); TEST_CASE(knownConditionFloating); TEST_CASE(knownConditionRecordedComparison); + TEST_CASE(knownConditionUnrelatedAssumptionNote); } struct CheckOptions @@ -3727,7 +3731,7 @@ class TestCondition : public TestFixture { " if (handle) return 1;\n" " else return 0;\n" "}\n"); - ASSERT_EQUALS("[test.cpp:3:9]: (style) Condition 'handle' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:2:16] -> [test.cpp:3:9]: (style) Condition 'handle' is always true [knownConditionTrueFalse]\n", errout_str()); check("int f(void *handle) {\n" " if (handle != 0) return 0;\n" @@ -3815,7 +3819,7 @@ class TestCondition : public TestFixture { " if(array){}\n" " }\n" "}\n"); - ASSERT_EQUALS("[test.cpp:5:12]: (style) Condition 'array' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:3:18] -> [test.cpp:5:12]: (style) Condition 'array' is always true [knownConditionTrueFalse]\n", errout_str()); check("void f(int *array, int size ) {\n" " for(int i = 0; i < size; ++i) {\n" @@ -3824,7 +3828,7 @@ class TestCondition : public TestFixture { " else if(array){}\n" " }\n" "}\n"); - ASSERT_EQUALS("[test.cpp:5:17]: (style) Condition 'array' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:3:18] -> [test.cpp:5:17]: (style) Condition 'array' is always true [knownConditionTrueFalse]\n", errout_str()); // #9277 check("int f() {\n" @@ -4508,7 +4512,7 @@ class TestCondition : public TestFixture { "void S::f() {\n" " if ((p == NULL) || ((p) && (g() >= *p))) {}\n" "}\n"); - ASSERT_EQUALS("[test.cpp:7:26]: (style) Condition 'p' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:7:12] -> [test.cpp:7:26]: (style) Condition 'p' is always true [knownConditionTrueFalse]\n", errout_str()); // #10749 check("struct Interface {\n" @@ -4707,7 +4711,7 @@ class TestCondition : public TestFixture { " if (o[1] == '\\0') {}\n" " }\n" "}\n"); - ASSERT_EQUALS("[test.cpp:6:18]: (style) Condition 'o[1]=='\\0'' is always false [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:4:25] -> [test.cpp:6:18]: (style) Condition 'o[1]=='\\0'' is always false [knownConditionTrueFalse]\n", errout_str()); check("void f(int x) {\n" // #11449 " int i = x;\n" @@ -4891,7 +4895,7 @@ class TestCondition : public TestFixture { " const S* sp2 = s.get2();\n" " if (sp2) {}\n" "}\n"); - ASSERT_EQUALS("[test.cpp:12:9]: (style) Condition 'sp2' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:3:13] -> [test.cpp:12:9]: (style) Condition 'sp2' is always true [knownConditionTrueFalse]\n", errout_str()); check("struct S {\n" " void f(int i);\n" @@ -5512,7 +5516,7 @@ class TestCondition : public TestFixture { check("bool f(const int *p, const int *q) {\n" " return p != NULL && q != NULL && p == NULL;\n" "}\n"); - ASSERT_EQUALS("[test.cpp:2:40]: (style) Condition 'p==NULL' is always false [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:2:14] -> [test.cpp:2:40]: (style) Condition 'p==NULL' is always false [knownConditionTrueFalse]\n", errout_str()); check("struct S {\n" // #11789 " std::vector v;\n" @@ -5621,7 +5625,7 @@ class TestCondition : public TestFixture { " return -1;\n" " return *it;\n" "}\n"); - ASSERT_EQUALS("[test.cpp:4:12]: (style) Condition 'it!=vector.end()' is always true [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:2:14] -> [test.cpp:4:12]: (style) Condition 'it!=vector.end()' is always true [knownConditionTrueFalse]\n", errout_str()); // #11303 check("void f(int n) {\n" @@ -5630,7 +5634,7 @@ class TestCondition : public TestFixture { " buffer.back() == '\\n' ||\n" " buffer.back() == '\\0') {}\n" "}\n"); - ASSERT_EQUALS("[test.cpp:5:22]: (style) Condition 'buffer.back()=='\\0'' is always false [knownConditionTrueFalse]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:3:22] -> [test.cpp:5:22]: (style) Condition 'buffer.back()=='\\0'' is always false [knownConditionTrueFalse]\n", errout_str()); // #9353 check("struct X { std::string s; };\n" @@ -6562,6 +6566,78 @@ class TestCondition : public TestFixture { void compareOutOfTypeRange() { const Settings settingsUnix64 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build(); + const Settings settingsUnix32 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix32).build(); + const Settings settingsWin64 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Win64).build(); + const char plainCharComparisons[] = "void f(char c) {\n" + " if (c == 300) {}\n" + " if (c > 300) {}\n" + " if (c < -200) {}\n" + " if (c == 128) {}\n" + " if (c < -1) {}\n" + " if (c > 300u) {}\n" + " if (c == 300u) {}\n" + " if (300 < c) {}\n" + "}\n"; + const std::string plainCharDiagnostics = "[test.cpp:2:12]: (style) Comparing expression of type 'char' against value 300. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:3:11]: (style) Comparing expression of type 'char' against value 300. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:4:12]: (style) Comparing expression of type 'char' against value -200. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:5:12]: (style) Comparing expression of type 'char' against value 128. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:8:12]: (style) Comparing expression of type 'char' against value 300. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:9:7]: (style) Comparing expression of type 'char' against value 300. Condition is always false. [compareValueOutOfTypeRangeError]\n"; + const Settings* const platforms[] = {&settingsUnix64, &settingsUnix32, &settingsWin64}; + for (const Settings* platform : platforms) { + check(plainCharComparisons, *platform); + ASSERT_EQUALS(plainCharDiagnostics, errout_str()); + } + + const char danmarPlainCharComparisons[] = "void f(char c, const char* s) {\n" + " if (c == 0xFF) {}\n" + " if (c == 200) {}\n" + " if (*s == 0xEF) {}\n" + " if (c > 127) {}\n" + " if (c == 128) {}\n" + "}\n"; + const std::string danmarPlainCharDiagnostics = + "[test.cpp:2:12]: (style) Comparing expression of type 'char' against value 255. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:3:12]: (style) Comparing expression of type 'char' against value 200. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:4:13]: (style) Comparing expression of type 'const char' against value 239. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:5:11]: (style) Comparing expression of type 'char' against value 127. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:6:12]: (style) Comparing expression of type 'char' against value 128. Condition is always false. [compareValueOutOfTypeRangeError]\n"; + const Settings* const signedCharPlatforms[] = {&settingsUnix64, &settingsWin64}; + for (const Settings* platform : signedCharPlatforms) { + check(danmarPlainCharComparisons, *platform); + ASSERT_EQUALS(danmarPlainCharDiagnostics, errout_str()); + } + + Settings settingsUnsignedChar = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build(); + settingsUnsignedChar.platform.defaultSign = 'u'; + check("void f(char c) {\n" + " if (c == 200) {}\n" + " if (c == 300) {}\n" + " if (c < 0) {}\n" + "}\n", settingsUnsignedChar); + ASSERT_EQUALS("[test.cpp:3:12]: (style) Comparing expression of type 'char' against value 300. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:4:11]: (style) Comparing expression of type 'char' against value 0. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("void f(char ch2) {\n" + " if (ch2 == static_cast(0xbb)) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + // wchar_t is unsigned 16-bit on Windows + check("void f(wchar_t w, const wchar_t* s, long long x) {\n" + " if (w == 0xFFFF) {}\n" + " if (w > 32767) {}\n" + " if (*s == 0xFEFF) {}\n" + " if ((wchar_t)x > 40000) {}\n" + " int y = 0xFFFF;\n" + " if ((wchar_t)y == 0xFFFF) {}\n" + " if (w > 65535) {}\n" + "}\n", settingsWin64); + ASSERT_EQUALS("[test.cpp:8:11]: (style) Comparing expression of type 'unsigned wchar_t' against value 65535. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:7:18]: (style) Condition '(wchar_t)y==0xFFFF' is always true [knownConditionTrueFalse]\n", + errout_str()); check("void f(unsigned char c) {\n" " if (c == 256) {}\n" @@ -6670,6 +6746,68 @@ class TestCondition : public TestFixture { ASSERT_EQUALS("[test.cpp:2:14]: (style) Comparing expression of type 'bool' against value 2. Condition is always true. [compareValueOutOfTypeRangeError]\n", errout_str()); + const Settings settingsUnspecified = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unspecified).build(); + check("void f(unsigned int u, short s) {\n" + " if (u > 4294967295u) {}\n" + " if (s == 65536) {}\n" + "}\n", settingsUnspecified); + ASSERT_EQUALS("", errout_str()); + + check("void f(unsigned int u, short s) {\n" + " if (u > 4294967295u) {}\n" + " if (s == 65536) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:13]: (style) Comparing expression of type 'unsigned int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:3:14]: (style) Comparing expression of type 'signed short' against value 65536. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("void f(short s) {\n" + " if (s == 0xFFFFFFFFu) {}\n" + " if (s == 0xFFFF8000u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("enum Flags { F_NONE = 0, F_HIGH = 0x80000000 };\n" + "void a(Flags f) { if (f == F_HIGH) {} }\n" + "enum G { G1 = 0xFFFFFFFFu };\n" + "void b(G g) { if (g == G1) {} }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("enum Flags { F_NONE = 0, F_HIGH = 0x80000000 };\n" + "void a(enum Flags f) { if (f == F_HIGH) {} }\n" + "enum G { G1 = 0xFFFFFFFFu };\n" + "void b(enum G g) { if (g == G1) {} }\n", settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + check("enum Values { E_HIGH = 200 };\n" + "void f(signed char c) { if (c == E_HIGH) {} }\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:34]: (style) Comparing expression of type 'signed char' against value 200. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("struct Unknown;\n" + "void one_bound(Unknown* p) {\n" + " if (p->type >= 0) {\n" + " if ((int)p->type < 0) {}\n" + " }\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("struct Unknown;\n" + "void alternative_paths(Unknown* p, bool choose) {\n" + " if (choose) {\n" + " if (p->type < 0) return;\n" + " } else {\n" + " if (p->type >= 20) return;\n" + " }\n" + " if ((int)p->type == 20) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("struct Unknown;\n" + "void excluded_point(Unknown* p) {\n" + " if (p->type != 1) {\n" + " if ((int)p->type == 1) {}\n" + " }\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:17] -> [test.cpp:4:26]: (style) Condition '(int)p->type==1' is always false [knownConditionTrueFalse]\n", errout_str()); + check("void f(const std::uint32_t& u) {\n" // #9078 " if (u >= UINT32_MAX) {}\n" " if (u <= UINT32_MAX) {}\n" @@ -6679,6 +6817,129 @@ class TestCondition : public TestFixture { "[test.cpp:4:13]: (style) Comparing expression of type 'const unsigned int &' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n", errout_str()); + // no false positive when unsigned arithmetic wraps around + check("void f(int x) {\n" + " if ((unsigned int)x - 1u == 0xFFFFFFFFu) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void f(int x) {\n" + " if ((unsigned short)x - 1u == 0xFFFFFFFFu) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + // ~ is decreasing: cast range bounds must be mirrored, not kept + check("void use(int);\n" + "void f(int x) { if (~(unsigned int)x == 0xFFFFFFFFu) use(2); }\n" + "void g(int x) { unsigned int m = ~(unsigned int)x; if (m == 0xFFFFFFFFu) use(1); }\n" + "void h(int x) { if (~(unsigned char)x == -256) use(1); }\n" + "void k(long long x) { if (~(int)x == 2147483647) use(7); }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + // no false positive when narrow signed types wrap on in-place increment/decrement + check("void use(int);\n" + "void d1(int x) { signed char i = (signed char)x; i++; if (i == -128) use(1); }\n" + "void d2(int x) { short i = (short)x; i++; if (i == -32768) use(2); }\n" + "void d3(int x) { short i = (short)x; i += 1; if (i == -32768) use(3); }\n" + "void d4(int x) { short i = (short)x; i--; if (i == 32767) use(4); }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void f(int x) {\n" + " if (~(unsigned char)x == -257) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:25]: (style) Condition '~(unsigned char)x==-257' is always false [knownConditionTrueFalse]\n", errout_str()); + + // Signed result type after integer promotion must still warn + check("void f(int x) {\n" + " if ((unsigned short)x + 1 == 0) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:29]: (style) Condition '(unsigned short)x+1==0' is always false [knownConditionTrueFalse]\n", + errout_str()); + + // Direct cast bounds are preserved + check("void f(int x) {\n" + " if ((unsigned int)x > 4294967295ULL) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:25]: (style) Comparing expression of type 'unsigned int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + // Reproduce the original typedef-heavy Simulink-generated pattern from #15000. + check("void f(unsigned int x) {\n" + " unsigned long long tmp = ((unsigned long long)x) + 1ULL;\n" + " if (tmp > 4294967295ULL)\n" + " tmp = 4294967295ULL;\n" + " if ((((long long)((unsigned int)tmp)) - 1LL) < 0LL) {}\n" + " if ((((long long)((unsigned int)tmp)) - 1LL) > 4294967295LL) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:6:50]: (style) Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false [knownConditionTrueFalse]\n", + errout_str()); + check("void f(unsigned int x) {\n" + " unsigned long long tmp = ((unsigned long long)x) + 1ULL;\n" + " if (tmp > 4294967295ULL)\n" + " tmp = 4294967295ULL;\n" + " if ((((long long)((unsigned int)tmp)) - 1LL) < 0LL) {}\n" + " if ((((long long)((unsigned int)tmp)) - 1LL) > 4294967295LL) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:6:50]: (style) Condition '(((long long)((unsigned int)tmp))-1LL)>4294967295LL' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("void f(unsigned long long tmp) {\n" + " if (tmp > 4294967295ULL)\n" + " tmp = 4294967295ULL;\n" + " if (static_cast(static_cast(tmp)) - 1LL > 4294967295LL) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:70]: (style) Condition 'static_cast(static_cast(tmp))-1LL>4294967295LL' is always false [knownConditionTrueFalse]\n", + errout_str()); + + // cast directly around variable: both the range-based and the declared-type + // analysis can prove the condition invariant; diag() must prevent duplicates + check("void f(unsigned char c) {\n" + " if ((unsigned char)c > 255) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:28]: (style) Comparing expression of type 'unsigned char' against value 255. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("void f(unsigned char c) {\n" + " if ((unsigned char)c == 256) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:29]: (style) Comparing expression of type 'unsigned char' against value 256. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("void f(unsigned int u) {\n" + " if ((unsigned int)u > 4294967295ULL) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:27]: (style) Comparing expression of type 'unsigned int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + check("void f(unsigned short s) {\n" + " if ((unsigned int)s > 4294967295ULL) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:27]: (style) Comparing expression of type 'unsigned int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n", + errout_str()); + + // wchar_t range is derived through ValueType::getSizeOf() + check("void f(wchar_t c) {\n" + " if ((wchar_t)c > 0x7fffffff) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:20]: (style) Condition '(wchar_t)c>0x7fffffff' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("void f(unsigned int x) {\n" + " if (-(signed char)x < -129) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:25]: (style) Condition '-(char)x<-129' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("void f(int x) {\n" + " if ((x) > 0) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void f(unsigned int x) {\n" + " if ((unsigned int)x > 0) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("void f() {\n" " long long ll = 1024 * 1024 * 1024;\n" " if (ll * 8 < INT_MAX) {}\n" @@ -6704,8 +6965,210 @@ class TestCondition : public TestFixture { "}\n", settingsUnix64); ASSERT_EQUALS("[test.cpp:2:14]: (style) Comparing expression of type 'char' against value 128. Condition is always false. [compareValueOutOfTypeRangeError]\n", errout_str()); + + // #15000: bounds that only prove a range together must survive a narrowing conversion, whichever + // order value flow creates them. + const char narrowAfterClamp[] = + "typedef signed char int8_t;\n" + "typedef unsigned char uint8_t;\n" + "void f(int x) {\n" + " if (x < 0 || x > 100) return;\n" + " if ((uint8_t)x > 200) {}\n" + " if ((int8_t)x < 0) {}\n" + " if ((short)x > 200) {}\n" + " if ((char)x < 0) {}\n" + "}\n"; + check(narrowAfterClamp, settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:20] -> [test.cpp:5:20]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:4:11] -> [test.cpp:6:19]: (style) Condition '(int8_t)x<0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:4:20] -> [test.cpp:7:18]: (style) Condition '(short)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:4:11] -> [test.cpp:8:17]: (style) Condition '(char)x<0' is always false [knownConditionTrueFalse]\n", + errout_str()); + + // Same bounds, reversed condition order and an implicit narrowing conversion. + const char narrowAfterClampReversed[] = + "typedef signed char int8_t;\n" + "typedef unsigned char uint8_t;\n" + "void f(int x) {\n" + " if (x > 100 || x < 0) return;\n" + " if ((uint8_t)x > 200) {}\n" + " if ((int8_t)x < 0) {}\n" + "}\n" + "void g(int x) {\n" + " if (x < 0 || x > 100) return;\n" + " uint8_t c = x;\n" + " if (c > 200) {}\n" + "}\n"; + check(narrowAfterClampReversed, settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:5:20]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:4:22] -> [test.cpp:6:19]: (style) Condition '(int8_t)x<0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:9:20] -> [test.cpp:11:11]: (style) Condition 'c>200' is always false [knownConditionTrueFalse]\n", + errout_str()); + + // The narrowing cast is used inside the condition that holds the range facts, not in a + // separate statement: the operands to the left of `&&`, `||` and `?:` are already evaluated. + const char narrowInsideCondition[] = + "typedef signed char int8_t;\n" + "typedef unsigned char uint8_t;\n" + "void f(int x) {\n" + " if (x >= 0 && x <= 100 && (uint8_t)x > 200) {}\n" + " if (x >= 0 && x <= 100 && (int8_t)x < 0) {}\n" + " if (x >= 0 && x <= 100 && (short)x > 200) {}\n" + " if (x < 0 || x > 100 || (uint8_t)x > 200) {}\n" + " while (x >= 0 && x <= 100 && (uint8_t)x > 200) x++;\n" + " int t = (x >= 0 && x <= 100) ? (uint8_t)x > 200 : 0;\n" + " int r = x >= 0 && x <= 100 && (uint8_t)x > 200;\n" + "}\n"; + check(narrowInsideCondition, settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:21] -> [test.cpp:4:42]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:5:11] -> [test.cpp:5:41]: (style) Condition '(int8_t)x<0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:6:21] -> [test.cpp:6:40]: (style) Condition '(short)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:7:20] -> [test.cpp:7:40]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:8:24] -> [test.cpp:8:45]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n" + "[test.cpp:10:25] -> [test.cpp:10:46]: (style) Condition '(unsigned char)x>200' is always false [knownConditionTrueFalse]\n", + errout_str()); + + const char signedToUnsigned[] = + "void gtkpod(void *p) {\n" + " unsigned int position = (int)(long)p;\n" + " if (position == -1) {}\n" + " if (position == 4294967295u) {}\n" + "}\n"; + check(signedToUnsigned, settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check(signedToUnsigned, settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + + // A signed variable compared against an unsigned constant of the same rank is converted to + // unsigned, so the constant does not bound the variable: 0xFFFFFFFFu is -1 for 'int' and + // 4294967295 cannot be reached at all. + const char signedVariableUnsignedConstant[] = + "void use(int);\n" + "void f1(int x) { if (x >= 0x80000000u) { if (x < 0) use(1); } }\n" + "void f2(int x) { if (x < 0x80000000u) return; if (x == -5) use(2); }\n" + "void f3(int x) { if (x == 0xFFFFFFFFu) { if (x == -1) use(3); } }\n" + "void f4(int x) { if (x < 4294967295u) return; if (x == -1) use(4); }\n" + "void f5(int x) { if (x < 4294967295u) return; if (x == -2) use(5); }\n"; + check(signedVariableUnsignedConstant, settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:24] -> [test.cpp:2:48]: (style) Condition 'x<0' is always true [knownConditionTrueFalse]\n" + "[test.cpp:4:24] -> [test.cpp:4:48]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:5:24] -> [test.cpp:5:53]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:6:24] -> [test.cpp:6:53]: (style) Condition 'x==-2' is always false [knownConditionTrueFalse]\n", + errout_str()); + + // A relational comparison in the unsigned domain selects a union of intervals in the signed + // operand's own order, since '(unsigned)x >= 1' also holds for every negative x. A branch is + // therefore bounded only when its set maps onto a single interval of the signed range, and a set + // of one excluded point is kept as an impossible value rather than as a bound. + const char unsignedDomainRelational[] = + "void use(int);\n" + "void m2(int x) { if (x < 1u || x >= 4294967295u) return; if (~x != 1) use(1); }\n" + "void m3(int x) { if (x < 1u) return; if (x == 0) use(2); }\n" + "void m4(int x) { if (x < 1u) return; if (x == 5) use(3); }\n" + "void m9(int x) { if (x < 4294967295u) return; if (x == -1) use(4); }\n"; + check(unsignedDomainRelational, settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:24] -> [test.cpp:3:44]: (style) Condition 'x==0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:5:24] -> [test.cpp:5:53]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n", + errout_str()); + + // The unsigned constant need not be a literal: a variable, a const, a cast or a complement + // expression carries the same unsigned-domain value and must be read in the operand's type. + const char signedVariableNonLiteralUnsigned[] = + "void use(int);\n" + "void f1(int x) { unsigned u = 0xFFFFFFFFu; if (x == u) { if (x == -1) use(1); } }\n" + "void f2(int x) { const unsigned M = 0xFFFFFFFFu; if (x == M) { if (x == -1) use(2); } }\n" + "void f3(int x) { if (x == (unsigned)-1) { if (x == -1) use(3); } }\n" + "void f4(int x) { if (x == ~0u) { if (x == -1) use(4); } }\n" + "void f5(int x) { unsigned u = 0xFFFFFFFFu; if (x != u) return; if (x == -1) use(5); }\n" + "int f6(int x) { unsigned u = 0xFFFFFFFFu; if (x == u) { return 10 / (x + 1); } return 0; }\n"; + check(signedVariableNonLiteralUnsigned, settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:50] -> [test.cpp:2:64]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:3:56] -> [test.cpp:3:70]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:4:24] -> [test.cpp:4:49]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:5:24] -> [test.cpp:5:40]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:6:50] -> [test.cpp:6:70]: (style) Condition 'x==-1' is always true [knownConditionTrueFalse]\n", + errout_str()); + + // The comparison uses the common type, which is at least 'int' and at least as wide as the + // constant. A narrower signed operand is sign-extended first, so 0xFFFFu is not -1 for a + // 'short' and no 'short' value equals it. + const char signedOperandNarrowerThanConstant[] = + "void use(int);\n" + "void f1(short s) { if (s == 0xFFFFu) return; if (s == -1) use(1); }\n" + "void f2(int x) { if (x == 0xFFFFFFFFul) return; if (x == -1) use(2); }\n" + "void f3(signed char c) { if (c != 0xFFu) { if (c == -1) use(3); } }\n" + "void f4(short s) { if (s >= 0x8000u) return; if (s == -1) use(4); }\n"; + check(signedOperandNarrowerThanConstant, settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:29]: (style) Comparing expression of type 'signed short' against value 65535. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:3:27]: (style) Comparing expression of type 'signed int' against value 4294967295. Condition is always false. [compareValueOutOfTypeRangeError]\n" + "[test.cpp:4:35]: (style) Comparing expression of type 'signed char' against value 255. Condition is always true. [compareValueOutOfTypeRangeError]\n" + // 's >= 0x8000u' holds exactly for the negative s, so the fall-through knows s >= 0. + "[test.cpp:5:26] -> [test.cpp:5:52]: (style) Condition 's==-1' is always false [knownConditionTrueFalse]\n", + errout_str()); + + const char narrowingSize[] = + "typedef unsigned long size_t;\n" + "void f(size_t len) {\n" + " if (len > 1) {\n" + " unsigned int end = (unsigned int)(len - 1);\n" + " if (end > 0) {}\n" + " }\n" + "}\n"; + check(narrowingSize, settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check(narrowingSize, settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + + const char wideningUnsigned[] = + "void f(unsigned int input) {\n" + " if (input == 0) return;\n" + " long long widened = (long long)input;\n" + " if (widened == 0) {}\n" + "}\n"; + check(wideningUnsigned, settingsUnix64); + const std::string wideningCpp = errout_str(); + ASSERT(wideningCpp.find("[test.cpp:2:15] -> [test.cpp:4:17]") != std::string::npos); + ASSERT(wideningCpp.find("Condition 'widened==0' is always false [knownConditionTrueFalse]") != std::string::npos); + check(wideningUnsigned, settingsUnix64, false); + const std::string wideningC = errout_str(); + ASSERT(wideningC.find("[test.c:2:15] -> [test.c:4:17]") != std::string::npos); + ASSERT(wideningC.find("Condition 'widened==0' is always false [knownConditionTrueFalse]") != std::string::npos); } + void sizelessPodtypeConversions() + { + const Settings posixSettings = settingsBuilder().library("posix.cfg").severity(Severity::style) + .platform(Platform::Type::Unix64).build(); + check("static long shim_enosys(long a) { return -1; }\n" + "void f(void) {\n" + " pid_t ret = (pid_t)shim_enosys(0);\n" + " if (ret >= 0) {}\n" + " off_t o = (off_t)0;\n" + " if (o > 0) {}\n" + "}\n", posixSettings); + ASSERT_EQUALS("[test.cpp:4:13]: (style) Condition 'ret>=0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:6:11]: (style) Condition 'o>0' is always false [knownConditionTrueFalse]\n", + errout_str()); + + const char podtypeXml[] = "\n\n" + " \n" + " \n" + ""; + const Settings gtkSettings = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64) + .libraryxml(podtypeXml).build(); + check("static gssize get(gsize len) { return len; }\n" + "void f(void) {\n" + " gssize length = get(3);\n" + " if (length < 0) {}\n" + "}\n", gtkSettings); + ASSERT_EQUALS("[test.cpp:4:16]: (style) Condition 'length<0' is always false [knownConditionTrueFalse]\n", errout_str()); + check("void f(gsize n) {\n" + " if (n == -1) {}\n" + "}\n", gtkSettings); + ASSERT_EQUALS("", errout_str()); + } + + void knownConditionCast() { check("void f(int i) {\n" // #9976 " if (i < 0 || (unsigned)i > 5) {}\n" @@ -6768,6 +7231,297 @@ class TestCondition : public TestFixture { ASSERT_EQUALS("[test.cpp:13:11] -> [test.cpp:18:13]: (style) Condition 'mS.b' is always false [knownConditionTrueFalse]\n", errout_str()); } + void conditionInferenceProvenance() { + const Settings settingsUnix64 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build(); + const Settings settingsUnix32 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix32).build(); + + check("void poplast(); void use(unsigned);\n" + "struct Array {\n" + " unsigned length;\n" + " void remove(unsigned index) {\n" + " if (index == length - 1) poplast();\n" + " else if (index < length) use(index);\n" + " }\n" + "};\n" + "void call_remove(Array &a) { a.remove(0); }\n" + "void call_remove_any(Array &a, unsigned index) { a.remove(index); }\n" + "void call_remove_last(Array &a) { a.length = 1; a.remove(0); }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("#define UINT_MAX 4294967295U\n" + "void gtkpod(void *p) {\n" + " unsigned int position = (int)(long)p;\n" + " if (position == -1) {}\n" + " if (position == UINT_MAX) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("#define UINT_MAX 4294967295U\n" + "void gtkpod(void *p) {\n" + " unsigned int position = (int)(long)p;\n" + " if (position == -1) {}\n" + " if (position == UINT_MAX) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + check("#define UINT_MAX 4294967295U\n" + "void gtkpod32(void *p) {\n" + " unsigned int position = (int)(long)p;\n" + " if (position == -1) {}\n" + " if (position == UINT_MAX) {}\n" + "}\n", settingsUnix32); + ASSERT_EQUALS("", errout_str()); + check("#define UINT_MAX 4294967295U\n" + "void gtkpod32_c(void *p) {\n" + " unsigned int position = (int)(long)p;\n" + " if (position == -1) {}\n" + " if (position == UINT_MAX) {}\n" + "}\n", settingsUnix32, false); + ASSERT_EQUALS("", errout_str()); + check("void known_sentinel32() {\n" + " unsigned int position = (int)(long)-1;\n" + " if (position == -1) {}\n" + "}\n", settingsUnix32); + ASSERT_EQUALS("[test.cpp:3:18]: (style) Condition 'position==-1' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void known_sentinel() {\n" + " unsigned int position = (int)(long)-1;\n" + " if (position == -1) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:18]: (style) Condition 'position==-1' is always true [knownConditionTrueFalse]\n", errout_str()); + check("void known_sentinel_c() {\n" + " unsigned int position = (int)(long)-1;\n" + " if (position == -1) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:3:18]: (style) Condition 'position==-1' is always true [knownConditionTrueFalse]\n", errout_str()); + const char pointExclusionCode[] = + "void excluded_signed_point(int value) {\n" + " if (value != -1) {\n" + " unsigned int converted = (unsigned int)value;\n" + " if (converted == 4294967295U) {}\n" + " }\n" + "}\n" + "void noninjective_exclusion(int value) {\n" + " if (value != -1) {\n" + " unsigned char narrowed = (unsigned char)value;\n" + " if (narrowed == 255) {}\n" + " }\n" + "}\n"; + check(pointExclusionCode, settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:15] -> [test.cpp:4:23]: (style) Condition 'converted==4294967295U' is always false [knownConditionTrueFalse]\n", errout_str()); + check(pointExclusionCode, settingsUnix64, false); + ASSERT_EQUALS("[test.c:2:15] -> [test.c:4:23]: (style) Condition 'converted==4294967295U' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("typedef unsigned long size_t;\n" + "void narrowed_size() {\n" + " size_t len = 4294967297ULL;\n" + " unsigned int position = (unsigned int)(len - 1);\n" + " if (position > 0) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:5:18]: (style) Condition 'position>0' is always false [knownConditionTrueFalse]\n", errout_str()); + check("typedef unsigned long size_t;\n" + "void narrowed_size_c() {\n" + " size_t len = 4294967297ULL;\n" + " unsigned int position = (unsigned int)(len - 1);\n" + " if (position > 0) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:5:18]: (style) Condition 'position>0' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("typedef unsigned long size_t;\n" + "void unknown_narrowed_size(size_t len) {\n" + " unsigned int position = (unsigned int)(len - 1);\n" + " if (position > 0) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("typedef unsigned long size_t;\n" + "void unknown_narrowed_size_c(size_t len) {\n" + " unsigned int position = (unsigned int)(len - 1);\n" + " if (position > 0) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + + check("void compare_ternary_lhs(int result) {\n" + " if (result == ((0) ? 315 : (-1-1u))) {}\n" + "}\n" + "void compare_ternary_rhs(int result) {\n" + " if (((0) ? 315 : (-1-1u)) == result) {}\n" + "}\n" + "void compare_ternary_swapped_lhs(int result) {\n" + " if (result == ((0) ? (-1-1u) : 315)) {}\n" + "}\n" + "void compare_ternary_swapped_rhs(int result) {\n" + " if (((0) ? (-1-1u) : 315) == result) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void compare_ternary_c_lhs(int result) {\n" + " if (result == ((0) ? 315 : (-1-1u))) {}\n" + "}\n" + "void compare_ternary_c_rhs(int result) {\n" + " if (((0) ? 315 : (-1-1u)) == result) {}\n" + "}\n" + "void compare_ternary_c_swapped_lhs(int result) {\n" + " if (result == ((0) ? (-1-1u) : 315)) {}\n" + "}\n" + "void compare_ternary_c_swapped_rhs(int result) {\n" + " if (((0) ? (-1-1u) : 315) == result) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + + check("void compare_known_ternary() {\n" + " int result = -2;\n" + " if (result != ((0) ? 315 : (-1-1u))) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:3:16]: (style) Condition 'result!=((0)?315:(-1-1u))' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("void compare_known_ternary_c() {\n" + " int result = -2;\n" + " if (result != ((0) ? 315 : (-1-1u))) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:3:16]: (style) Condition 'result!=((0)?315:(-1-1u))' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("void plain_unsigned_expression() {\n" + " if (-1-1u == 4294967294U) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:15]: (style) Condition '-1-1u==4294967294U' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void plain_unsigned_expression_c() {\n" + " if (-1-1u == 4294967294U) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:2:15]: (style) Condition '-1-1u==4294967294U' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void s3backer_guard() {\n" + " if ((unsigned int)(4294967295U*.666666)==2863308666U) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:44]: (style) Condition '(unsigned int)(4294967295U*0.666666)==2863308666U' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void s3backer_guard_c() {\n" + " if ((unsigned int)(4294967295U*.666666)==2863308666U) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:2:44]: (style) Condition '(unsigned int)(4294967295U*0.666666)==2863308666U' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("extern unsigned long getlength(); extern void use(int);\n" + "void f() {\n" + " int length = (int)getlength();\n" + " if (length != 1)\n" + " if (length == 1) use(length);\n" + "}\n" + "void g() {\n" + " int length = (int)getlength();\n" + " if (length != 1)\n" + " if (1 == length) use(length);\n" + "}\n" + "void h() {\n" + " int length = (int)getlength();\n" + " if (length != 1)\n" + " if (length != 1) use(length);\n" + "}\n" + "void j() {\n" + " int length = (int)getlength();\n" + " if (length != 1)\n" + " if (1 != length) use(length);\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:16] -> [test.cpp:5:20]: (style) Condition 'length==1' is always false [knownConditionTrueFalse]\n" + "[test.cpp:9:16] -> [test.cpp:10:15]: (style) Condition '1==length' is always false [knownConditionTrueFalse]\n" + "[test.cpp:14:16] -> [test.cpp:15:20]: (style) Condition 'length!=1' is always true [knownConditionTrueFalse]\n" + "[test.cpp:19:16] -> [test.cpp:20:15]: (style) Condition '1!=length' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("extern unsigned long getlength(); extern void use(int);\n" + "void oce() {\n" + " int length = (int)getlength();\n" + " if (length!=1)\n" + " if (getlength()!=0)\n" + " if ((length==1 && getlength()) || (length==2 && getlength()))\n" + " use(length);\n" + "}\n", settingsUnix64); + const std::string oceOutput = errout_str(); + ASSERT(oceOutput.find("Condition 'length==1' is always false [knownConditionTrueFalse]") != std::string::npos); + ASSERT(oceOutput.find("[test.cpp:4:") != std::string::npos); + ASSERT(oceOutput.find(" -> ") != std::string::npos); + check("extern unsigned long getlength(); extern void use(int);\n" + "void oce_reversed_exclusion() {\n" + " int length = (int)getlength();\n" + " if (length != 1) {\n" + " if (1 == length) use(length);\n" + " if (1 != length) use(length);\n" + " }\n" + "}\n", settingsUnix64); + const std::string reversedExclusionOutput = errout_str(); + ASSERT(reversedExclusionOutput.find("Condition '1==length' is always false [knownConditionTrueFalse]") != std::string::npos); + ASSERT(reversedExclusionOutput.find("Condition '1!=length' is always true [knownConditionTrueFalse]") != std::string::npos); + ASSERT(reversedExclusionOutput.find("[test.cpp:4:") != std::string::npos); + ASSERT(reversedExclusionOutput.find(" -> ") != std::string::npos); + + check("extern unsigned long getlength(); extern void use(int);\n" + "void range_without_exclusion() {\n" + " int length = (int)getlength();\n" + " if (length >= 0)\n" + " if (length == 1) use(length);\n" + "}\n" + "void exclude_a_different_point() {\n" + " int length = (int)getlength();\n" + " if (length != 2)\n" + " if (length == 1) use(length);\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("extern unsigned long getlength(); extern void use(int);\n" + "void mutation_invalidates_exclusion() {\n" + " int length = (int)getlength();\n" + " if (length != 1) {\n" + " length = 1;\n" + " if (length == 1) use(length);\n" + " }\n" + "}\n", settingsUnix64); + const std::string mutationOutput = errout_str(); + ASSERT(mutationOutput.find("Condition 'length==1' is always true [knownConditionTrueFalse]") != std::string::npos); + ASSERT_EQUALS(std::string::npos, mutationOutput.find("[test.cpp:4:16] ->")); + + check("extern unsigned long getlength(); extern void use(int);\n" + "void incompatible_paths(bool selector) {\n" + " int length = (int)getlength();\n" + " if (selector && length != 1) use(0);\n" + " if (!selector && length == 1) use(length);\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void use(int);\n" + "struct Scope { unsigned short sp; };\n" + "void pop_n(Scope *s, int n) {\n" + " if ((int)s->sp-n < 0) use(1);\n" + " s->sp -= n;\n" + "}\n" + "void call_pop(Scope *s, int n) {\n" + " pop_n(s, n);\n" + " if (n == 0) use(0);\n" + "}\n" + "void caller_n0(Scope *s) { call_pop(s, 0); }\n" + "void caller_n1(Scope *s) { call_pop(s, 1); }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("struct Scope { unsigned short sp; };\n" + "void use(int);\n" + "void local_n0(Scope *s, int n) {\n" + " if (n == 0)\n" + " if ((int)s->sp - n < 0) use(1);\n" + "}\n" + "void local_sp0_n1(Scope *s) {\n" + " s->sp = 0;\n" + " if ((int)s->sp - 1 < 0) use(1);\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:5:28]: (style) Condition '(int)s->sp-n<0' is always false [knownConditionTrueFalse]\n" + "[test.cpp:9:24]: (style) Condition '(int)s->sp-1<0' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void use(int);\n" + "struct Scope { unsigned short sp; };\n" + "void pop_n(Scope *s, int n) {\n" + " if ((int)s->sp-n < 0) use(1);\n" + "}\n" + "void caller_underflow(Scope *s) {\n" + " s->sp = 0;\n" + " pop_n(s, 1);\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + } + void knownConditionIncDecOperator() { check( "void f() {\n" @@ -6904,7 +7658,6 @@ class TestCondition : public TestFixture { ASSERT_EQUALS( "[test.cpp:3:12]: (style) Condition 'nf>+1.0' is always false [knownConditionTrueFalse]\n", errout_str()); - check("void foo() {\n" // #11200 " float f = 1.0;\n" " if (f > -1.0) {}\n" @@ -7044,6 +7797,206 @@ class TestCondition : public TestFixture { "[test.cpp:2:36] -> [test.cpp:9:29]: (style) Condition '(z-1)>=0' is always true [knownConditionTrueFalse]\n", errout_str()); } + + void knownConditionUnrelatedAssumptionNote() { + // The error path must not pick up an assumption from an unrelated condition that happened to + // be assumed while following the value. Only the note for the value's own condition belongs. + setMultiline(); + Settings s = settings0; + s.templateLocation = "{file}:{line}:note:{info}\n"; + + check("void* g(void* data, int length);\n" + "void* f(void* data, int length) {\n" + " if (data == NULL) return 0;\n" + " if (length + 40 > 65535) return 0;\n" + " if (data != NULL) return data;\n" + " return 0;\n" + "}\n", s); + ASSERT_EQUALS("[test.cpp:5:14]: style: Condition 'data!=NULL' is always true [knownConditionTrueFalse]\n" + "[test.cpp:3:14]: note: Assuming that condition 'data==NULL' is not redundant\n" + "[test.cpp:5:14]: note: Condition 'data!=NULL' is always true\n", + errout_str()); + } + + void unsignedArithmeticNoWrap() + { + const Settings settingsUnix64 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix64).build(); + const Settings settingsUnix32 = settingsBuilder().severity(Severity::style).platform(Platform::Type::Unix32).build(); + const Settings settingsUnix64Std = settingsBuilder().library("std.cfg").severity(Severity::style) + .platform(Platform::Type::Unix64).build(); + + check("int safe_subtraction(unsigned int count) {\n" + " if (count < 2) return 0;\n" + " if (count - 1 > 0) return 1;\n" + " return 0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:15] -> [test.cpp:3:19]: (style) Condition 'count-1>0' is always true [knownConditionTrueFalse]\n", errout_str()); + check("void safe_subtraction_boundary(unsigned int x) {\n" + " if (x < 1u) return;\n" + " if (x - 1u == 4294967295u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void compound_after_cast(int x) {\n" + " unsigned y = (unsigned char)x;\n" + " y -= 1;\n" + " if (y > 255) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("void decrement_after_cast(int x) {\n" + " unsigned y = (unsigned char)x;\n" + " y--;\n" + " if (y > 255) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("unsigned long compound_after_cast_ge(unsigned short n) {\n" + " unsigned long r = (unsigned short)n;\n" + " r -= 1;\n" + " if (r >= 65535) return 0;\n" + " return r;\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("void compound_after_condition(unsigned y) {\n" + " if (y > 255) return;\n" + " y -= 1;\n" + " if (y > 255) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void wrapping_subtraction_boundary(unsigned int x) {\n" + " if (x - 1u == 4294967295u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("void possible_upper_zero_wrap(unsigned int len) {\n" + " if (len > 0) return;\n" + " if (len - 1u > 100u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + check("void possible_upper_zero_wrap_c(unsigned int len) {\n" + " if (len > 0) return;\n" + " if (len - 1u > 100u) {}\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("", errout_str()); + check("void non_dominating_guard(bool flag, unsigned int x) {\n" + " if (flag) {\n" + " if (x < 1u) return;\n" + " }\n" + " if (x - 1u == 4294967295u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("int safe_addition(unsigned int value) {\n" + " if (value < 10) {\n" + " if (value + 1 > 10) return 1;\n" + " }\n" + " return 0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:15] -> [test.cpp:3:23]: (style) Condition 'value+1>10' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("int tinyexr_range(unsigned long size) {\n" + " if (size < 6) return 0;\n" + " unsigned long offset = 2;\n" + " if (size - offset < 4) return 1;\n" + " return 0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:14] -> [test.cpp:4:23]: (style) Condition 'size-offset<4' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("void use(int);\n" + "void f6(unsigned char c) {\n" + " unsigned s = c;\n" + " if (s + 1u == 0u) use(4);\n" + "}\n" + "void f4(unsigned long n) {\n" + " for (unsigned long i = 0; i < n; i++) {\n" + " if (i + 1 == 0) use(3);\n" + " }\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:16]: (style) Condition 's+1u==0u' is always false [knownConditionTrueFalse]\n" + "[test.cpp:8:19]: (style) Condition 'i+1==0' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("void use(int);\n" + "void unguarded_assignment_wrap(unsigned long n) {\n" + " unsigned long i = n - 1;\n" + " if (i + 1 == 0) use(3);\n" + "}\n" + "void full_range_wrap(unsigned u) {\n" + " if (u + 1u == 0u) use(1);\n" + "}\n" + "void possible_subtraction_wrap(unsigned x, unsigned y) {\n" + " if (x < 10u && y < 20u && x - y > 100u) use(2);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("void wrap_cases(int value) {\n" + " if ((unsigned int)value - 1u == 4294967295u) {}\n" + " if ((unsigned int)value + 1u == 0u) {}\n" + " if ((unsigned int)value * 2u > 1u) {}\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + check("void wrap_check_less_than_addend(unsigned x) {\n" + " if (x + 1u < 1u) {}\n" + " if (x + 2u < 2u) {}\n" + " if (x + 1u <= 1u) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("typedef unsigned long size_t;\n" + "int smenu(size_t len, char *str) {\n" + " size_t start = 0;\n" + " if (len > 1) {\n" + " while (start <= len-1 && (str[start]=='{' || str[start]=='}')) start++;\n" + " size_t end = len-1;\n" + " if (end > 0) return 1;\n" + " }\n" + " return 0;\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:4:13] -> [test.c:7:17]: (style) Condition 'end>0' is always true [knownConditionTrueFalse]\n", errout_str()); + check("typedef unsigned long size_t;\n" + "int smenu32(size_t len, char *str) {\n" + " size_t start = 0;\n" + " if (len > 1) {\n" + " while (start <= len-1 && (str[start]=='{' || str[start]=='}')) start++;\n" + " size_t end = len-1;\n" + " if (end > 0) return 1;\n" + " }\n" + " return 0;\n" + "}\n", settingsUnix32, false); + ASSERT_EQUALS("[test.c:4:13] -> [test.c:7:17]: (style) Condition 'end>0' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("typedef unsigned long size_t;\n" + "int no_loop(size_t len) {\n" + " if (len > 1) {\n" + " size_t end = len-1;\n" + " if (end > 0) return 1;\n" + " }\n" + " return 0;\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:3:13] -> [test.c:5:17]: (style) Condition 'end>0' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("typedef unsigned long size_t;\n" + "int narrow_size() {\n" + " size_t len = 4294967297ULL;\n" + " unsigned int end = (unsigned int)(len-1);\n" + " if (end > 0) return 1;\n" + " return 0;\n" + "}\n", settingsUnix64, false); + ASSERT_EQUALS("[test.c:5:13]: (style) Condition 'end>0' is always false [knownConditionTrueFalse]\n", errout_str()); + + check("void f(const char* text) {\n" + " size_t len = strlen(text) + 1;\n" + " if (len > 0) {}\n" + "}\n", settingsUnix64Std, false); + ASSERT_EQUALS("[test.c:3:13]: (style) Condition 'len>0' is always true [knownConditionTrueFalse]\n", errout_str()); + + check("void f(unsigned x, unsigned k) { if (x * k + 1U == 0U) {} }\n", settingsUnix64); + ASSERT_EQUALS("", errout_str()); + + check("void known_unsigned_point_wrap() {\n" + " if (0u - 1u == 4294967295U) {}\n" + "}\n", settingsUnix64); + ASSERT_EQUALS("[test.cpp:2:17]: (style) Condition '0u-1u==4294967295U' is always true [knownConditionTrueFalse]\n", errout_str()); + } }; REGISTER_TEST(TestCondition) diff --git a/test/testfunctions.cpp b/test/testfunctions.cpp index 58228b58b07..853e8d0c19a 100644 --- a/test/testfunctions.cpp +++ b/test/testfunctions.cpp @@ -64,6 +64,8 @@ class TestFunctions : public TestFixture { // Math function usage TEST_CASE(mathfunctionCall_fmod); TEST_CASE(mathfunctionCall_sqrt); + TEST_CASE(mathfunctionCall_log_garli_reduction); + TEST_CASE(mathfunctionCall_log_guarded); TEST_CASE(mathfunctionCall_log); TEST_CASE(mathfunctionCall_acos); TEST_CASE(mathfunctionCall_asin); @@ -840,6 +842,90 @@ class TestFunctions : public TestFixture { ASSERT_EQUALS("", errout_str()); } + void mathfunctionCall_log_guarded() { + check("double guarded_return(double x) {\n" + " if (x <= 0.0)\n" + " return 0.0;\n" + " return log(x);\n" + "}\n" + "double guarded_else(double x) {\n" + " if (x <= 0.0) {\n" + " return 0.0;\n" + " } else {\n" + " return log(x);\n" + " }\n" + "}\n" + "double guarded_short_circuit(double x) {\n" + " if (x <= 0.0 || x >= 2.0) return 0.0;\n" + " return log(x);\n" + "}\n" + "double guarded_subtract_short_circuit(double x) {\n" + " if (x >= 0.5 || x <= -1.0) return 0.0;\n" + " return log(0.5 - x);\n" + "}\n" + "double guarded_subtract(double x) {\n" + " if (x >= 0.5)\n" + " return 0.0;\n" + " return log(0.5 - x);\n" + "}\n" + "float guarded_float(float x) {\n" + " if (x <= 0.0f)\n" + " return 0.0f;\n" + " return logf(x);\n" + "}\n" + "float guarded_float_subtract(float x) {\n" + " if (x >= 0.5f)\n" + " return 0.0f;\n" + " return logf(0.5f - x);\n" + "}\n" + "long double guarded_long_double(long double x) {\n" + " if (x <= 0.0L)\n" + " return 0.0L;\n" + " return logl(x);\n" + "}\n" + "double guarded_after_assignment(double x) {\n" + " if (x <= 0.0)\n" + " x = 1.0;\n" + " return log(x);\n" + "}\n" + "double guarded_after_loop(double x) {\n" + " while (x <= 0.0)\n" + " x = 1.0;\n" + " return log(x);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("double invalid_true_branch(double x) {\n" + " if (x <= 0.0)\n" + " return log(x);\n" + " return 0.0;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:11] -> [test.cpp:3:20]: (warning) Either the condition 'x<=0.0' is redundant or log() argument nr 1 can have invalid value. The value is 0 but the valid values are '4.94066e-324:'. [invalidFunctionArg]\n", + errout_str()); + } + + void mathfunctionCall_log_garli_reduction() { + check("inline double LnGamma(double alp) {\n" + " double x = alp, f = 0.0, z;\n" + " if (x < 7) {\n" + " f = 1.0;\n" + " z = x - 1.0;\n" + " while (++z < 7.0)\n" + " f *= z;\n" + " x = z;\n" + " f = -log(f);\n" + " }\n" + " return f + (x - 0.5) * log(x) - x + 0.918938533204673;\n" + "}\n" + "double PointChi2(double p, double v) {\n" + " if (p < 0.000002 || p > 0.999998 || v <= 0.0)\n" + " return -1.0;\n" + " return LnGamma(v * 0.5);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + } + void mathfunctionCall_log() { // log,log10,logf,logl,log10f,log10l,log2,log2f,log2l,log1p,log1pf,log1pl check("void foo()\n" diff --git a/test/testother.cpp b/test/testother.cpp index 085b39cfffb..85bdd538d31 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -232,6 +232,7 @@ class TestOther : public TestFixture { TEST_CASE(checkNegativeShift); TEST_CASE(checkNegativeShiftErrorPath); + TEST_CASE(checkNegativeShiftDeadBranchArgument); TEST_CASE(incompleteArrayFill); @@ -441,6 +442,15 @@ class TestOther : public TestFixture { " cout<> 2;\n"); ASSERT_EQUALS("[test.cpp:1:18]: (portability) Shifting a negative value is technically undefined behaviour [shiftNegativeLHS]\n", errout_str()); + check("int negative_lhs(int value) {\n" + " if (value < -16 || value > 15) return 0;\n" + " return value << 10;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:2:15] -> [test.cpp:3:18]: (portability) Shifting a negative value is technically undefined behaviour [shiftNegativeLHS]\n", errout_str()); + // #6383 - unsigned type check("const int x = (unsigned int)(-1) >> 2;\n"); ASSERT_EQUALS("", errout_str()); @@ -10632,6 +10648,20 @@ class TestOther : public TestFixture { errout_str()); } + void checkNegativeShiftDeadBranchArgument() { + // The 'else' is unreachable for the g<1> instantiation, so its call cannot pass shift=7. + check("int f(int src, int shift) {\n" + " return src >> (8 - 2 * shift);\n" + "}\n" + "template\n" + "void g(int *out, int rgba) {\n" + " if (alphabits == 1) { out[0] = rgba; }\n" + " else { out[0] = f(rgba, 8 - alphabits); }\n" + "}\n" + "void inst(int *out, int rgba) { g<1>(out, rgba); g<4>(out, rgba); }\n"); + ASSERT_EQUALS("", errout_str()); + } + void incompleteArrayFill() { check("void f() {\n" " int a[5];\n" @@ -14290,7 +14320,7 @@ class TestOther : public TestFixture { " }\n" " return false;\n" "}\n"); - ASSERT_EQUALS("[test.cpp:4:17]: (style) Pointer expression 'a.x' converted to bool is always true. [knownPointerToBool]\n", errout_str()); + ASSERT_EQUALS("[test.cpp:3:10] -> [test.cpp:4:17]: (style) Pointer expression 'a.x' converted to bool is always true. [knownPointerToBool]\n", errout_str()); check("void f(bool* b) { if (b) *b = true; }\n"); ASSERT_EQUALS("", errout_str()); diff --git a/test/teststl.cpp b/test/teststl.cpp index a6a133af13f..d60c90e170b 100644 --- a/test/teststl.cpp +++ b/test/teststl.cpp @@ -529,6 +529,42 @@ class TestStl : public TestFixture { "}\n"); ASSERT_EQUALS("", errout_str()); + checkNormal("void f(void) {\n" + " std::vector v;\n" + " unsigned entries = 0xfffffffeU;\n" + " if (v.size() < entries + 2U)\n" + " v.resize(entries + 2U);\n" + " v[0] = 1;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:6:6]: error: Out of bounds access in expression 'v[0]' because 'v' is empty. [containerOutOfBounds]\n", errout_str()); + + checkNormal("void f(void) {\n" + " std::vector v;\n" + " unsigned entries = 0xffffffffU;\n" + " if (v.size() < entries + 2U)\n" + " v.resize(entries + 2U);\n" + " v[0] = 1;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + checkNormal("void f(void) {\n" + " std::vector v;\n" + " unsigned entries = 4;\n" + " if (v.size() < entries + 2U)\n" + " v.resize(entries + 2U);\n" + " v[0] = 1;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + checkNormal("void f(unsigned entries) {\n" + " if (entries > 1000U) return;\n" + " std::vector v;\n" + " if (v.size() < entries + 2U)\n" + " v.resize(entries + 2U);\n" + " v[0] = 1;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + checkNormal("void f(size_t entries) {\n" " std::vector v;\n" " if (v.size() < entries)\n" diff --git a/test/testsymboldatabase.cpp b/test/testsymboldatabase.cpp index 6175b76e393..1d0a548990e 100644 --- a/test/testsymboldatabase.cpp +++ b/test/testsymboldatabase.cpp @@ -9920,6 +9920,8 @@ class TestSymbolDatabase : public TestFixture { $.platform.int_bit = 32, $.platform.long_bit = 64, $.platform.long_long_bit = 64); + const Settings settingsUnix64 = settingsBuilder().platform(Platform::Type::Unix64).build(); + const Settings settingsWin64 = settingsBuilder().platform(Platform::Type::Win64).build(); // numbers ASSERT_EQUALS("signed int", typeOf("1;\n", "1", false, &s)); @@ -10010,7 +10012,8 @@ class TestSymbolDatabase : public TestFixture { ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (unsigned char)2;\n", "+")); ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (signed int)2;\n", "+")); ASSERT_EQUALS("unsigned int", typeOf("(unsigned int)1 + (unsigned int)2;\n", "+")); - ASSERT_EQUALS("signed long", typeOf("(signed long)1 + (unsigned int)2;\n", "+")); + ASSERT_EQUALS("signed long", typeOf("(signed long)1 + (unsigned int)2;\n", "+", true, &settingsUnix64)); + ASSERT_EQUALS("unsigned long", typeOf("(signed long)1 + (unsigned int)2;\n", "+", true, &settingsWin64)); ASSERT_EQUALS("unsigned long", typeOf("(unsigned long)1 + (signed int)2;\n", "+")); // char @@ -10219,19 +10222,19 @@ class TestSymbolDatabase : public TestFixture { " \n" " \n" ""; - const Settings settingsWin64 = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata).build(); + const Settings settingsWin64PodType = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata).build(); ValueType vt; - ASSERT_EQUALS(true, vt.fromLibraryType("u32", settingsWin64)); - ASSERT_EQUALS(true, vt.fromLibraryType("xyz::x", settingsWin64)); + ASSERT_EQUALS(true, vt.fromLibraryType("u32", settingsWin64PodType)); + ASSERT_EQUALS(true, vt.fromLibraryType("xyz::x", settingsWin64PodType)); ASSERT_EQUALS(ValueType::Type::INT, vt.type); ValueType vt2; - ASSERT_EQUALS(true, vt2.fromLibraryType("podtype2", settingsWin64)); + ASSERT_EQUALS(true, vt2.fromLibraryType("podtype2", settingsWin64PodType)); ASSERT_EQUALS(ValueType::Type::INT, vt2.type); - ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new u32[10];\n", "new", true, &settingsWin64)); - ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new xyz::x[10];\n", "new", true, &settingsWin64)); - ASSERT_EQUALS("unsigned int", typeOf("; x = (xyz::x)12;\n", "(", true, &settingsWin64)); - ASSERT_EQUALS("unsigned int", typeOf(";u32(12);\n", "(", true, &settingsWin64)); - ASSERT_EQUALS("unsigned int", typeOf("x = u32(y[i]);\n", "(", true, &settingsWin64)); + ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new u32[10];\n", "new", true, &settingsWin64PodType)); + ASSERT_EQUALS("unsigned int *", typeOf(";void *data = new xyz::x[10];\n", "new", true, &settingsWin64PodType)); + ASSERT_EQUALS("unsigned int", typeOf("; x = (xyz::x)12;\n", "(", true, &settingsWin64PodType)); + ASSERT_EQUALS("unsigned int", typeOf(";u32(12);\n", "(", true, &settingsWin64PodType)); + ASSERT_EQUALS("unsigned int", typeOf("x = u32(y[i]);\n", "(", true, &settingsWin64PodType)); } { // PlatformType @@ -10254,9 +10257,9 @@ class TestSymbolDatabase : public TestFixture { " \n" " \n" ""; - const Settings settingsWin64 = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata).build(); + const Settings settingsWin64PlatformType = settingsBuilder().platform(Platform::Type::Win64).libraryxml(xmldata).build(); ValueType vt; - ASSERT_EQUALS(true, vt.fromLibraryType("LPCTSTR", settingsWin64)); + ASSERT_EQUALS(true, vt.fromLibraryType("LPCTSTR", settingsWin64PlatformType)); ASSERT_EQUALS(ValueType::Type::WCHAR_T, vt.type); } { diff --git a/test/testtype.cpp b/test/testtype.cpp index 6f98efbda9e..021838eae51 100644 --- a/test/testtype.cpp +++ b/test/testtype.cpp @@ -43,6 +43,7 @@ class TestType : public TestFixture { TEST_CASE(longCastReturn); TEST_CASE(checkFloatToIntegerOverflow); TEST_CASE(integerOverflow); // #11794 + TEST_CASE(integerOverflowEnumConstant); TEST_CASE(shiftTooManyBits); // #11496 } @@ -612,6 +613,88 @@ class TestType : public TestFixture { "}\n", dinit(CheckPOptions, $.cpp = false)); ASSERT_EQUALS("[test.c:4:24]: (error) Undefined behaviour: float () to integer conversion overflow. [floatConversionOverflow]\n", removeFloat(errout_str())); + check("void f(double rr) {\n" + " if (!(rr >= 0.0) || rr > 1.0e308)\n" + " return;\n" + " while (rr >= 1.0e119L)\n" + " rr *= 1.0e-100L;\n" + " while (rr >= 1.0e29L)\n" + " rr *= 1.0e-10L;\n" + " while (rr >= 1.0e19L)\n" + " rr *= 1.0e-1L;\n" + " unsigned long long value = (unsigned long long)rr;\n" + " (void)value;\n" + "}\n"); + ASSERT_EQUALS("", removeFloat(errout_str())); + + { + const Settings unix64 = settingsBuilder().platform(Platform::Type::Unix64).c(Standards::C11).cpp(Standards::CPP14).build(); + checkP("int f(double d) { if (d >= 1e10) return 0; if (d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", errout_str()); + checkP("int f(double d) { if (d >= 1e10) return 0; if (d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("int f(double d) { if (d >= 1e10 || d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", errout_str()); + checkP("int f(double d) { if (d >= 1e10 || d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("int f(double d) { if (1e10 <= d || d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", errout_str()); + checkP("int f(double d) { if (1e10 <= d || d > 100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("int f(double d) { if (d <= -1e30) return 0; if (d < -100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", errout_str()); + checkP("int f(double d) { if (d <= -1e30) return 0; if (d < -100.0) return 0; return (int)d; }\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("int f(double d) { if (d >= 1e10) return 0; if (d > 100.0) return 0; return d; }\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", errout_str()); + checkP("int f(double d) { if (d >= 1e10) return 0; if (d > 100.0) return 0; return d; }\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("int f(double d) { if (d >= 1e100) return (int)d; return 0; }\n", + dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("[test.cpp:1:25] -> [test.cpp:1:42]: (warning) Undefined behaviour: float () to integer conversion overflow. [floatConversionOverflow]\n", removeFloat(errout_str())); + checkP("int f(double d) { if (d <= -1e100) return (int)d; return 0; }\n", + dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("[test.cpp:1:25] -> [test.cpp:1:43]: (warning) Undefined behaviour: float () to integer conversion overflow. [floatConversionOverflow]\n", removeFloat(errout_str())); + checkP("unsigned int s3backer(unsigned int maxkeys) {\n" + " if (maxkeys >= (unsigned int)(4294967295U*.666666)-1) return 0;\n" + " return (unsigned int)(maxkeys/.666666)+1;\n" + "}\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", removeFloat(errout_str())); + checkP("unsigned int s3backer(unsigned int maxkeys) {\n" + " if (maxkeys >= (unsigned int)(4294967295U*.666666)-1) return 0;\n" + " return (unsigned int)(maxkeys/.666666)+1;\n" + "}\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", removeFloat(errout_str())); + const Settings unix32 = settingsBuilder().platform(Platform::Type::Unix32).c(Standards::C11).cpp(Standards::CPP14).build(); + checkP("unsigned int s3backer(unsigned int maxkeys) {\n" + " if (maxkeys >= (unsigned int)(4294967295U*.666666)-1) return 0;\n" + " return (unsigned int)(maxkeys/.666666)+1;\n" + "}\n", dinit(CheckPOptions, $.settings = &unix32, $.cpp = false)); + ASSERT_EQUALS("", removeFloat(errout_str())); + checkP("unsigned int s3backer_literal(unsigned int maxkeys) {\n" + " if (maxkeys >= 2863308665U) return 0;\n" + " return (unsigned int)(maxkeys/.666666)+1;\n" + "}\n", dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", removeFloat(errout_str())); + checkP("unsigned int s3backer_literal(unsigned int maxkeys) {\n" + " if (maxkeys >= 2863308665U) return 0;\n" + " return (unsigned int)(maxkeys/.666666)+1;\n" + "}\n", dinit(CheckPOptions, $.settings = &unix64, $.cpp = false)); + ASSERT_EQUALS("", removeFloat(errout_str())); + checkP("unsigned int f(double d) { if (d >= 2863308665U) return 0; return (unsigned int)d; }\n", + dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("", removeFloat(errout_str())); + + checkP("unsigned int f(void) { return (unsigned int)6442457383.46; }\n", + dinit(CheckPOptions, $.settings = &unix64)); + ASSERT_EQUALS("[test.cpp:1:31]: (error) Undefined behaviour: float () to integer conversion overflow. [floatConversionOverflow]\n", removeFloat(errout_str())); + } + } void integerOverflow() { // #11794 @@ -645,6 +728,53 @@ class TestType : public TestFixture { ASSERT_EQUALS("[test.cpp:2:21]: (error) Signed integer overflow for expression '2147483647+a'. [integerOverflow]\n", errout_str()); } + void integerOverflowEnumConstant() { + // An enumerator without an explicit base type gets the type that can represent its value, + // per the C rules for the compatible type of an enumeration. + const Settings s = settingsBuilder().severity(Severity::warning).platform(Platform::Type::Unix64).build(); + + // 1U << 31 exceeds the signed int range: unsigned int, no signed overflow + check("enum m { A = 0, B = 1U << 31, C = 1 << 20 };\n" + "unsigned g(void) { return B; }\n" + "unsigned g2(void) { return C; }\n" + "unsigned g3(void) { return B + 0; }\n" + "unsigned long long g4(void) { return B + C; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("", errout_str()); + + // shift of a signed literal; the value still does not fit in int. The shift itself is + // undefined behaviour (reported), but the enumerator must not be signed int. + check("enum cs_mode { CS_MODE_LITTLE_ENDIAN = 0, CS_MODE_BIG_ENDIAN = 1 << 31, CS_MODE_QPX = 1 << 20 };\n" + "int f(void) { return CS_MODE_BIG_ENDIAN + CS_MODE_QPX; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("[test.cpp:1:66]: (error) Shifting signed 32-bit value by 31 bits is undefined behaviour [shiftTooManyBitsSigned]\n", errout_str()); + + // values built from bitwise-or and sum of literals + check("enum e { A = 1U << 20, B = 1U << 31 | 1 };\n" + "unsigned f(void) { return A + B; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("", errout_str()); + + check("enum e { A = 0x40000000, B = A + A };\n" + "unsigned f(void) { return B; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("", errout_str()); + + // beyond unsigned int -> long/long long + check("enum e { A = 4294967296LL };\n" + "long long f(void) { return A; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("", errout_str()); + + // a value that does fit in int keeps the signed int type; no overflow for `a + A` since the + // enumerator is only a constant here (base does not report it either) + check("enum e { A = 2147483647 };\n" + "int f(int a) { return a + A; }\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("", errout_str()); + + // genuine signed overflow still reports + check("int f(void) {\n" + " int a = 2147483647;\n" + " return a + 1;\n" + "}\n", dinit(CheckOptions, $.settings = &s)); + ASSERT_EQUALS("[test.cpp:3:14]: (error) Signed integer overflow for expression 'a+1'. [integerOverflow]\n", errout_str()); + } + void shiftTooManyBits() { // #11496 check("template struct B {\n" " unsigned long long f(unsigned int n) const {\n" @@ -655,6 +785,72 @@ class TestType : public TestFixture { "};\n" "static B<64> b;\n"); ASSERT_EQUALS("", errout_str()); + + // FP shiftTooManyBits: guarded shift where the shift amount is + // conditionally derived from an unsigned subtraction; a possible value + // from an interprocedural caller must not collapse the interval + // inference on the unsigned arithmetic result + { + const Settings settings = settingsBuilder().platform(Platform::Type::Unix64).build(); + check("static unsigned int l[16];\n" + "void scalar_shift(unsigned int shift) {\n" + " unsigned int shiftlimbs = shift >> 5;\n" + " unsigned int shiftlow = shift & 0x1Fu;\n" + " unsigned int shifthigh = 32u - shiftlow;\n" + " unsigned int r = 0u;\n" + " r |= (shift < 448u && shiftlow ? (l[1 + shiftlimbs] << shifthigh) : 0u);\n" + " r |= (shift < 416u && shiftlow ? (l[2 + shiftlimbs] << shifthigh) : 0u);\n" + " (void)r;\n" + "}\n" + "int main(void) { scalar_shift(384u); return 0; }\n", + dinit(CheckOptions, $.settings = &settings)); + ASSERT_EQUALS("", errout_str()); + } + + check("int guarded_shift(int delta, unsigned int lag_depth, unsigned int lag_mask) {\n" + " if (lag_depth > 20) return 0;\n" + " if (delta < -100) return 0;\n" + " if (delta < -(int)lag_depth) return 0;\n" + " if (delta < 0) return lag_mask >> -delta;\n" + " return 0;\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + { + const Settings c11unix64 = settingsBuilder().platform(Platform::Type::Unix64).c(Standards::C11).build(); + checkP("unsigned long f(unsigned long i) {\n" + " if (i < 64) return 0;\n" + " if (i < 96) return 1 << (i - 64);\n" + " return 0;\n" + "}\n", dinit(CheckPOptions, $.settings = &c11unix64, $.cpp = false)); + ASSERT_EQUALS("[test.c:3:11] -> [test.c:3:26]: (warning) Shifting signed 32-bit value by 31 bits is undefined behaviour. See condition at line 3. [shiftTooManyBitsSigned]\n", errout_str()); + + checkP("unsigned long f(unsigned long i) {\n" + " if (i < 64) return 0;\n" + " if (i < 96) return 1u << (i - 64);\n" + " return 0;\n" + "}\n", dinit(CheckPOptions, $.settings = &c11unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + + checkP("unsigned long f(unsigned long i) {\n" + " if (i < 64) return 0;\n" + " if (i < 95) return 1 << (i - 64);\n" + " return 0;\n" + "}\n", dinit(CheckPOptions, $.settings = &c11unix64, $.cpp = false)); + ASSERT_EQUALS("", errout_str()); + } + const Settings cpp14unix64 = settingsBuilder().platform(Platform::Type::Unix64).cpp(Standards::CPP14).build(); + checkP("unsigned long f(unsigned long i) {\n" + " if (i < 64) return 0;\n" + " if (i < 96) return 1 << (i - 64);\n" + " return 0;\n" + "}\n", dinit(CheckPOptions, $.settings = &cpp14unix64)); + ASSERT_EQUALS("[test.cpp:3:11] -> [test.cpp:3:26]: (portability) Shifting signed 32-bit value by 31 bits is implementation-defined behaviour. See condition at line 3. [shiftTooManyBitsSigned]\n", errout_str()); + + check("unsigned int oversized_shift(unsigned int value) {\n" + " return value >> 32;\n" + "}\n"); + ASSERT(errout_str().find("[shiftTooManyBits]") != std::string::npos); } }; diff --git a/test/testuninitvar.cpp b/test/testuninitvar.cpp index 787ede556ea..726d0900413 100644 --- a/test/testuninitvar.cpp +++ b/test/testuninitvar.cpp @@ -65,6 +65,7 @@ class TestUninitVar : public TestFixture { TEST_CASE(valueFlowUninit2_value); TEST_CASE(valueFlowUninit_uninitvar2); TEST_CASE(valueFlowUninit_functioncall); + TEST_CASE(valueFlowUninitFloatingPositiveControl); TEST_CASE(uninitStructMember); // struct members TEST_CASE(uninitvar2_while); TEST_CASE(uninitvar2_4494); // #4494 @@ -3742,6 +3743,15 @@ class TestUninitVar : public TestFixture { (checkuninitvar.valueFlowUninit)(); } + void valueFlowUninitFloatingPositiveControl() { + valueFlowUninit("float initialized(float x) { if (x <= 0.0f) return 0.0f; return x; }\n", false); + ASSERT_EQUALS("", errout_str()); + valueFlowUninit("float uninitialized() { float x; return x; }\n", false); + ASSERT_EQUALS( + "[test.c:1:41]: (error) Uninitialized variable: x [uninitvar]\n", + errout_str()); + } + void uninitvar15() { // #13685 const char code[] = "int f() {\n" " int x;\n" diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index 60807e49bf8..b134c2d0d98 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -19,16 +19,20 @@ #include "errortypes.h" #include "fixture.h" #include "helpers.h" +#include "infer.h" #include "mathlib.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "token.h" +#include "valueptr.h" +#include "vf_common.h" #include "vfvalue.h" #include #include #include +#include #include #include #include @@ -162,6 +166,8 @@ class TestValueFlow : public TestFixture { TEST_CASE(valueFlowSymbolicStrlen); TEST_CASE(valueFlowSmartPointer); TEST_CASE(valueFlowImpossibleMinMax); + TEST_CASE(inferPathCompatibility); + TEST_CASE(valueFlowPlainCharCast); TEST_CASE(valueFlowImpossibleIncDec); TEST_CASE(valueFlowImpossibleUnknownConstant); TEST_CASE(valueFlowContainerEqual); @@ -5212,6 +5218,14 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(true, testValueOfX(code, 4U, 10)); + code = "int g();\n" + "int f() {\n" + " int x;\n" + " for (x = 20; x < 10 || g(); x++) {}\n" + " return x;\n" + "}\n"; + ASSERT_EQUALS(false, testValueOfX(code, 5U, 10)); + code = "void foo() {\n" // related with #887 " int x;\n" " for (x = 0; x < 20; x++) {}\n" @@ -5489,6 +5503,28 @@ class TestValueFlow : public TestFixture { "}\n"; values = tokenValues(code, "i ]"); ASSERT(values.empty()); + ValueFlow::Value excludedUpper(0, ValueFlow::Value::Bound::Upper); + excludedUpper.setImpossible(); + excludedUpper.path = 7; + ValueFlow::Value unrelatedPoint(5); + unrelatedPoint.setPossible(); + const std::list initializerValues{excludedUpper, unrelatedPoint}; + const ValueFlow::Value* const minSource = getMinValueSource(makeIntegralInferModel(), initializerValues); + const std::vector minimum = getMinValue(makeIntegralInferModel(), initializerValues); + ASSERT_EQUALS(1U, minimum.size()); + ASSERT_EQUALS(1, minimum.front()); + ASSERT(minSource); + ASSERT(minSource == &initializerValues.front()); + ASSERT(minSource->isImpossible()); + ASSERT_EQUALS_ENUM(ValueFlow::Value::Bound::Upper, minSource->bound); + ASSERT_EQUALS(7, minSource->path); + ValueFlow::Value maxUpper(std::numeric_limits::max(), ValueFlow::Value::Bound::Upper); + maxUpper.setImpossible(); + ASSERT(getMinValue(makeIntegralInferModel(), {maxUpper}).empty()); + ValueFlow::Value minLower(std::numeric_limits::min(), ValueFlow::Value::Bound::Lower); + minLower.setImpossible(); + ASSERT(getMaxValue(makeIntegralInferModel(), {minLower}).empty()); + } void valueFlowSubFunction() { @@ -6672,14 +6708,15 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(1, values.size()); ASSERT_EQUALS(true, values.front().isUninitValue()); - code = "void f(int x) {\n" - " int i;\n" - " if (x > 0) {\n" - " int y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated - " if (y != 0) return;\n" - " i++;\n" - " }\n" - "}\n"; + code = + "void f(int x) {\n" + " int i;\n" + " if (x > 0) {\n" + " int y = -ENOMEM;\n" // assume constant ENOMEM is nonzero since it's negated + " if (y != 0) return;\n" + " i++;\n" + " }\n" + "}\n"; values = tokenValues(code, "i ++", ValueFlow::Value::ValueType::UNINIT); ASSERT_EQUALS(0, values.size()); @@ -8355,6 +8392,31 @@ class TestValueFlow : public TestFixture { " S(std::max_align_t T::* p) : m(p) {}\n" "};\n"; (void)valueOfTok(code, ":"); // don't crash + + const char libraryXml[] = "" + "" + "" + ""; + Settings charSettings = settingsBuilder().libraryxml(libraryXml).platform(Platform::Type::Unspecified).build(); + charSettings.checkUnknownFunctionReturn.insert("unknown_char"); + charSettings.checkUnknownFunctionReturn.insert("signed_char"); + const std::list signedReturnValues = tokenValues("x = signed_char();\n", "(", &charSettings); + ASSERT_EQUALS(2, signedReturnValues.size()); + ASSERT_EQUALS(-128, signedReturnValues.front().intvalue); + ASSERT_EQUALS(127, signedReturnValues.back().intvalue); + const std::list unknownReturnValues = tokenValues("x = unknown_char();\n", "(", &charSettings); + ASSERT(unknownReturnValues.empty() || + std::any_of(unknownReturnValues.cbegin(), unknownReturnValues.cend(), [](const ValueFlow::Value& value) { + return value.isIntValue() && value.intvalue >= 200; + })); + const char charCode[] = "char unknown_char(void);\n" + "void f() {\n" + " if (unknown_char() == 200) {}\n" + "}\n"; + const std::list comparisonValues = tokenValues(charCode, "==", &charSettings); + ASSERT(std::none_of(comparisonValues.cbegin(), comparisonValues.cend(), [](const ValueFlow::Value& value) { + return value.isKnown() && value.isIntValue() && value.intvalue == 0; + })); } void valueFlowUnknownFunctionReturnRand() { @@ -9358,6 +9420,40 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 2)); ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1)); + + code = "int f() {\n" + " unsigned int source = 4294967295u;\n" + " unsigned int x = (source + 1u) % 16u;\n" + " return x;\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfXKnown(code, 4U, 0)); + + code = "auto f(unsigned int i) {\n" + " auto x = (int)i;\n" + " return x;\n" + "}\n"; + SimpleTokenizer narrowingTokenizer(settings, *this); + ASSERT(narrowingTokenizer.tokenize(code)); + const Token* narrowingReturn = Token::findmatch(narrowingTokenizer.tokens(), "return x"); + ASSERT(narrowingReturn && narrowingReturn->next()); + const std::list& narrowedValues = narrowingReturn->next()->values(); + // Narrowing may add signed-destination bounds; it must not invent an excluded point. + ASSERT(std::none_of(narrowedValues.cbegin(), narrowedValues.cend(), [](const ValueFlow::Value& value) { + return value.isImpossible() && value.bound == ValueFlow::Value::Bound::Point; + })); + + code = "auto f(unsigned int i) {\n" + " auto x = (long long)i;\n" + " return x;\n" + "}\n"; + SimpleTokenizer wideningTokenizer(settings, *this); + ASSERT(wideningTokenizer.tokenize(code)); + const Token* wideningReturn = Token::findmatch(wideningTokenizer.tokens(), "return x"); + ASSERT(wideningReturn && wideningReturn->next()); + const std::list& widenedValues = wideningReturn->next()->values(); + ASSERT(std::any_of(widenedValues.cbegin(), widenedValues.cend(), [](const ValueFlow::Value& value) { + return value.isImpossible() && value.bound == ValueFlow::Value::Bound::Upper && value.intvalue == -1; + })); } void valueFlowMod() { @@ -9409,6 +9505,15 @@ class TestValueFlow : public TestFixture { values = tokenValues(code, "--"); ASSERT_EQUALS(1U, values.size()); ASSERT_EQUALS(127LLU, values.back().intvalue); + + code = "int f() {\n" + " const int a[128] = {};\n" + " signed char b = -128;\n" + " return a[--b];\n" + "}\n"; + values = tokenValues(code, "--"); + ASSERT_EQUALS(1U, values.size()); + ASSERT_EQUALS(127LLU, values.back().intvalue); } void valueFlowNotNull() @@ -9416,13 +9521,20 @@ class TestValueFlow : public TestFixture { const char* code; code = "int f(const std::string &str) {\n" - " int x = str.c_str();\n" + " bool x = str.c_str();\n" + " return x;\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfXKnown(code, 3U, 1)); + // Preserve non-nullness when the integer conversion is at least pointer-sized. + code = "long long f(const std::string &str) {\n" + " long long x = (long long)str.c_str();\n" " return x;\n" "}\n"; ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, 0)); + code = "int f(const std::string_view &str) {\n" - " int x = str.c_str();\n" + " bool x = str.data();\n" " return x;\n" "}\n"; ASSERT_EQUALS(false, testValueOfXImpossible(code, 3U, 0)); @@ -10058,6 +10170,200 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, "a", -1)); ASSERT_EQUALS(true, testValueOfXImpossible(code, 3U, -1)); + + const Settings settingsUnix64 = settingsBuilder().platform(Platform::Type::Unix64).build(); + code = "void f(unsigned long long x) {\n" + " return (unsigned int)x;\n" + "}\n"; + SimpleTokenizer tokenizer(settingsUnix64, *this); + ASSERT(tokenizer.tokenize(code)); + const Token* returnTok = Token::findmatch(tokenizer.tokens(), "return ("); + ASSERT(returnTok && returnTok->next()); + const std::list& castValues = returnTok->next()->values(); + ASSERT(std::any_of(castValues.cbegin(), castValues.cend(), [](const ValueFlow::Value& value) { + return value.isImpossible() && value.intvalue == -1; + })); + ASSERT(std::any_of(castValues.cbegin(), castValues.cend(), [](const ValueFlow::Value& value) { + return value.isImpossible() && value.intvalue == 4294967296; + })); + + // Impossible bounds on a cast must not be propagated through + // arithmetic with unsigned result type, since wrap-around invalidates the bound + code = "void f(int x) {\n" + " return (unsigned int)x - 1u;\n" + "}\n"; + SimpleTokenizer tokenizer2(settingsUnix64, *this); + ASSERT(tokenizer2.tokenize(code)); + const Token* minusTok = Token::findsimplematch(tokenizer2.tokens(), "-"); + ASSERT(minusTok); + for (const ValueFlow::Value& value : minusTok->values()) { + ASSERT(!(value.isImpossible() && value.isIntValue() && + value.bound != ValueFlow::Value::Bound::Point && value.intvalue == 4294967295)); + } + + // Known values are still propagated through unsigned arithmetic + code = "void f(int x) {\n" + " unsigned int y = 5u;\n" + " return y - 1u;\n" + "}\n"; + SimpleTokenizer tokenizer3(settingsUnix64, *this); + ASSERT(tokenizer3.tokenize(code)); + const Token* minusTok3 = Token::findsimplematch(tokenizer3.tokens(), "-"); + ASSERT(minusTok3); + ASSERT(std::any_of(minusTok3->values().cbegin(), minusTok3->values().cend(), [](const ValueFlow::Value& value) { + return value.isKnown() && value.isIntValue() && value.intvalue == 4; + })); + + ValueType charType(ValueType::Sign::SIGNED, ValueType::Type::CHAR, 0); + MathLib::bigint minValue; + MathLib::bigint maxValue; + ASSERT(ValueFlow::getMinMaxValues(&charType, settingsUnix64.platform, minValue, maxValue)); + ASSERT_EQUALS(-128, minValue); + ASSERT_EQUALS(127, maxValue); + const ValueFlow::Value castInput(255); + const ValueFlow::ConvertedValue signedCast = ValueFlow::castValue(castInput, ValueType::Sign::SIGNED, 8); + ASSERT(signedCast.valid); + ASSERT_EQUALS(-1, signedCast.value.intvalue); + + charType.sign = ValueType::Sign::UNSIGNED; + ASSERT(ValueFlow::getMinMaxValues(&charType, settingsUnix64.platform, minValue, maxValue)); + ASSERT_EQUALS(0, minValue); + ASSERT_EQUALS(255, maxValue); + const ValueFlow::ConvertedValue unsignedCast = ValueFlow::castValue(castInput, ValueType::Sign::UNSIGNED, 8); + ASSERT(unsignedCast.valid); + ASSERT_EQUALS(255, unsignedCast.value.intvalue); + + const ValueFlow::Value unsignedModulo(-1); + const ValueFlow::ConvertedValue unsignedModuloCast = ValueFlow::castValue(unsignedModulo, ValueType::Sign::UNSIGNED, 8); + ASSERT(unsignedModuloCast.valid); + ASSERT_EQUALS(255, unsignedModuloCast.value.intvalue); + const ValueFlow::Value unrepresentableUnsigned64(-1); + ASSERT_EQUALS(false, ValueFlow::castValue(unrepresentableUnsigned64, ValueType::Sign::UNSIGNED, 64).valid); + + ValueFlow::Value validFloat; + validFloat.valueType = ValueFlow::Value::ValueType::FLOAT; + validFloat.floatValue = 2863308666.68847; + const ValueFlow::ConvertedValue validFloatCast = ValueFlow::castValue(validFloat, ValueType::Sign::UNSIGNED, 32); + ASSERT(validFloatCast.valid); + ASSERT_EQUALS(2863308666LL, validFloatCast.value.intvalue); + + ValueFlow::Value negativeFraction; + negativeFraction.valueType = ValueFlow::Value::ValueType::FLOAT; + negativeFraction.floatValue = -0.5; + const ValueFlow::ConvertedValue negativeFractionCast = ValueFlow::castValue(negativeFraction, ValueType::Sign::UNSIGNED, 32); + ASSERT(negativeFractionCast.valid); + ASSERT_EQUALS(0, negativeFractionCast.value.intvalue); + + ValueFlow::Value unsignedLimit; + unsignedLimit.valueType = ValueFlow::Value::ValueType::FLOAT; + unsignedLimit.floatValue = 4294967295.9; + const ValueFlow::ConvertedValue unsignedLimitCast = ValueFlow::castValue(unsignedLimit, ValueType::Sign::UNSIGNED, 32); + ASSERT(unsignedLimitCast.valid); + ASSERT_EQUALS(4294967295LL, unsignedLimitCast.value.intvalue); + + ValueFlow::Value signedMaximum; + signedMaximum.valueType = ValueFlow::Value::ValueType::FLOAT; + signedMaximum.floatValue = 2147483647.9; + const ValueFlow::ConvertedValue signedMaximumCast = ValueFlow::castValue(signedMaximum, ValueType::Sign::SIGNED, 32); + ASSERT(signedMaximumCast.valid); + ASSERT_EQUALS(2147483647LL, signedMaximumCast.value.intvalue); + + ValueFlow::Value unsignedBelow; + unsignedBelow.valueType = ValueFlow::Value::ValueType::FLOAT; + unsignedBelow.floatValue = -1.0; + ASSERT_EQUALS(false, ValueFlow::castValue(unsignedBelow, ValueType::Sign::UNSIGNED, 32).valid); + + ValueFlow::Value signedBelow; + signedBelow.valueType = ValueFlow::Value::ValueType::FLOAT; + signedBelow.floatValue = -2147483649.0; + ASSERT_EQUALS(false, ValueFlow::castValue(signedBelow, ValueType::Sign::SIGNED, 32).valid); + + ValueFlow::Value unsignedOverflow; + unsignedOverflow.valueType = ValueFlow::Value::ValueType::FLOAT; + unsignedOverflow.floatValue = 4294967296.0; + ASSERT_EQUALS(false, ValueFlow::castValue(unsignedOverflow, ValueType::Sign::UNSIGNED, 32).valid); + + ValueFlow::Value signedMinimum; + signedMinimum.valueType = ValueFlow::Value::ValueType::FLOAT; + signedMinimum.floatValue = -2147483648.9; + const ValueFlow::ConvertedValue signedMinimumCast = ValueFlow::castValue(signedMinimum, ValueType::Sign::SIGNED, 32); + ASSERT(signedMinimumCast.valid); + ASSERT_EQUALS(-2147483648LL, signedMinimumCast.value.intvalue); + + ValueFlow::Value signedOverflow; + signedOverflow.valueType = ValueFlow::Value::ValueType::FLOAT; + signedOverflow.floatValue = 2147483648.0; + ASSERT_EQUALS(false, ValueFlow::castValue(signedOverflow, ValueType::Sign::SIGNED, 32).valid); + + ValueFlow::Value infinite; + infinite.valueType = ValueFlow::Value::ValueType::FLOAT; + infinite.floatValue = std::numeric_limits::infinity(); + ASSERT_EQUALS(false, ValueFlow::castValue(infinite, ValueType::Sign::UNSIGNED, 32).valid); + + ValueFlow::Value notANumber; + notANumber.valueType = ValueFlow::Value::ValueType::FLOAT; + notANumber.floatValue = std::numeric_limits::quiet_NaN(); + ASSERT_EQUALS(false, ValueFlow::castValue(notANumber, ValueType::Sign::UNSIGNED, 32).valid); + + ValueType doubleType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::DOUBLE, 0); + ValueType intType(ValueType::Sign::SIGNED, ValueType::Type::INT, 0); + // A representable float endpoint maps monotonically and retains its bound kind. + ValueFlow::Value floatLower; + floatLower.valueType = ValueFlow::Value::ValueType::FLOAT; + floatLower.floatValue = 1.0; + floatLower.bound = ValueFlow::Value::Bound::Lower; + floatLower.setPossible(); + ASSERT(ValueFlow::isValueRangePreservingConversion(&doubleType, &intType, settingsUnix64, floatLower)); + const ValueFlow::ConvertedValue floatLowerCast = ValueFlow::castValue(floatLower, ValueType::Sign::SIGNED, 32); + ASSERT(floatLowerCast.valid); + ASSERT(floatLowerCast.value.isPossible()); + ASSERT(floatLowerCast.value.isIntValue()); + ASSERT(floatLowerCast.value.bound == ValueFlow::Value::Bound::Lower); + ASSERT_EQUALS(1, floatLowerCast.value.intvalue); + + ValueFlow::Value excludedFloatLower; + excludedFloatLower.valueType = ValueFlow::Value::ValueType::FLOAT; + excludedFloatLower.floatValue = 1.0; + excludedFloatLower.bound = ValueFlow::Value::Bound::Lower; + excludedFloatLower.setImpossible(); + ASSERT_EQUALS(false, ValueFlow::isValueRangePreservingConversion(&doubleType, &intType, settingsUnix64, excludedFloatLower)); + ASSERT_EQUALS(false, ValueFlow::castValue(excludedFloatLower, ValueType::Sign::SIGNED, 32).valid); + ValueType unsignedIntType(ValueType::Sign::UNSIGNED, ValueType::Type::INT, 0); + ValueFlow::Value negativeUpper(-1, ValueFlow::Value::Bound::Upper); + negativeUpper.setPossible(); + const ValueFlow::ConvertedValue negativeUpperConverted = + ValueFlow::convertValueRange(negativeUpper, &intType, &unsignedIntType, settingsUnix64, nullptr, nullptr); + ASSERT(negativeUpperConverted.valid); + ASSERT(negativeUpperConverted.value.isPossible()); + ASSERT(negativeUpperConverted.value.bound == ValueFlow::Value::Bound::Lower); + ASSERT_EQUALS(2147483648LL, negativeUpperConverted.value.intvalue); + + ValueType unsignedLongType(ValueType::Sign::UNSIGNED, ValueType::Type::LONG, 0); + ValueFlow::Value negativeUpper64(-1, ValueFlow::Value::Bound::Upper); + negativeUpper64.setPossible(); + const ValueFlow::ConvertedValue negativeUpper64Converted = + ValueFlow::convertValueRange(negativeUpper64, &intType, &unsignedLongType, settingsUnix64, nullptr, nullptr); + ASSERT(negativeUpper64Converted.valid); + ASSERT(negativeUpper64Converted.value.bound == ValueFlow::Value::Bound::Lower); + ASSERT_EQUALS(std::numeric_limits::max(), negativeUpper64Converted.value.intvalue); + + ValueFlow::Value crossesZero(-1, ValueFlow::Value::Bound::Lower); + crossesZero.setPossible(); + ASSERT_EQUALS(false, ValueFlow::convertValueRange(crossesZero, &intType, &unsignedIntType, settingsUnix64, nullptr, nullptr).valid); + + ValueFlow::Value excludedUpper(-1, ValueFlow::Value::Bound::Upper); + excludedUpper.setImpossible(); + const ValueFlow::ConvertedValue excludedUpperConverted = + ValueFlow::convertValueRange(excludedUpper, &intType, &unsignedIntType, settingsUnix64, nullptr, nullptr); + ASSERT(excludedUpperConverted.valid); + ASSERT(excludedUpperConverted.value.isImpossible()); + ASSERT_EQUALS(-1, excludedUpperConverted.value.intvalue); + const MathLib::bigint outsideSignedMaximum = maxValue + 1; + ValueFlow::Value excludedUpperLimit(outsideSignedMaximum, ValueFlow::Value::Bound::Lower); + excludedUpperLimit.setImpossible(); + ASSERT_EQUALS(false, ValueFlow::convertValueRange(excludedUpperLimit, &intType, &unsignedIntType, settingsUnix64, nullptr, nullptr).valid); + charType.sign = ValueType::UNKNOWN_SIGN; + ASSERT_EQUALS(false, ValueFlow::getMinMaxValues(&charType, settingsUnix64.platform, minValue, maxValue)); } void valueFlowImpossibleIncDec() @@ -10083,6 +10389,243 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(true, testValueOfXImpossible(code, 7U, -1)); ASSERT_EQUALS(false, testValueOfXKnown(code, 7U, -1)); + + code = "int guarded_predecrement(unsigned int x) {\n" + " if (x > 0) {\n" + " --x;\n" + " if (x == 0) return 1;\n" + " }\n" + " return 0;\n" + "}\n"; + ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0)); + + code = "int guarded_postdecrement(unsigned int x) {\n" + " if (x > 0) {\n" + " x--;\n" + " if (x == 0) return 1;\n" + " }\n" + " return 0;\n" + "}\n"; + ASSERT_EQUALS(false, testValueOfXImpossible(code, 4U, 0)); + + code = "int decimal_dot(const char* current, const char* first, int dot) {\n" + " unsigned int digits = (unsigned int)(current - first);\n" + " if (digits > 0) {\n" + " if (dot) {\n" + " digits--;\n" + " if (digits == 0) return 1;\n" + " }\n" + " }\n" + " return 0;\n" + "}\n"; + ASSERT_EQUALS(false, testValueOfXImpossible(code, 6U, 0)); + + code = "int wrap_decrement(unsigned int x) {\n" + " x--;\n" + " if (x == 4294967295u) return 1;\n" + " return 0;\n" + "}\n"; + SimpleTokenizer wrapTokenizer(settings, *this); + ASSERT(wrapTokenizer.tokenize(code)); + const Token* wrappedValue = nullptr; + for (const Token* tok = wrapTokenizer.tokens(); tok; tok = tok->next()) { + if (tok->str() == "x" && tok->linenr() == 3) { + wrappedValue = tok; + break; + } + } + if (wrappedValue == nullptr) { + ASSERT(wrappedValue); + return; + } + ASSERT(std::none_of(wrappedValue->values().cbegin(), + wrappedValue->values().cend(), + [](const ValueFlow::Value& value) { + return value.isImpossible() && value.isIntValue() && value.intvalue == 4294967295LL; + })); + } + + void valueFlowPlainCharCast() + { + // Values that fit in both signed and unsigned char are kept on a cast to plain char. + ASSERT_EQUALS(true, testValueOfXKnown("int f() {\n" + " int i = 65;\n" + " int x = (char)i;\n" + " return x;\n" + "}\n", + 4, + 65)); + ASSERT_EQUALS(true, testValueOfXKnown("int f() {\n" + " int x = static_cast(0);\n" + " return x;\n" + "}\n", + 3, + 0)); + ASSERT_EQUALS(true, testValueOfX("int f(int i) {\n" + " if (i == 0) {}\n" + " int x = (char)i;\n" + " return x;\n" + "}\n", + 4, + 0)); + } + + void inferPathCompatibility() + { + SimpleTokenizer tokenizer(settings, *this); + ASSERT(tokenizer.tokenize("int f(int x) { if (x) return 0; if (x > 0) return 2; return 1; }\n")); + const Token* const condition = Token::findmatch(tokenizer.tokens(), "if"); + ASSERT(condition); + const Token* exclusionCondition = nullptr; + for (const Token* tok = condition->next(); tok; tok = tok->next()) { + if (tok->str() == "if") { + exclusionCondition = tok; + break; + } + } + ASSERT(exclusionCondition); + + ValueFlow::Value lhs(384); + lhs.setPossible(); + lhs.condition = condition; + lhs.path = 7; + lhs.conditional = true; + lhs.varId = 1; + lhs.varvalue = 384; + ValueFlow::Value rhs(32); + rhs.setKnown(); + + std::vector inferred = infer(makeIntegralInferModel(), "-", {lhs}, {rhs}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isPossible()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT(inferred.front().condition == condition); + ASSERT(inferred.front().conditional); + ASSERT_EQUALS(1, inferred.front().varId); + ASSERT_EQUALS(384, inferred.front().varvalue); + std::list arithmeticValue{inferred.front()}; + + ValueFlow::Value rhsSamePath(32); + rhsSamePath.setPossible(); + rhsSamePath.condition = condition; + rhsSamePath.path = 7; + inferred = infer(makeIntegralInferModel(), "-", {lhs}, {rhsSamePath}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT(inferred.front().condition == condition); + + ValueFlow::Value rhsDifferentPath(32); + rhsDifferentPath.setPossible(); + rhsDifferentPath.path = 8; + inferred = infer(makeIntegralInferModel(), "-", {lhs}, {rhsDifferentPath}); + ASSERT(inferred.empty()); + + ValueFlow::Value knownLhs(9); + knownLhs.setKnown(); + ValueFlow::Value knownRhs(4); + knownRhs.setKnown(); + inferred = infer(makeIntegralInferModel(), "-", {knownLhs}, {knownRhs}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isKnown()); + ASSERT_EQUALS(0, inferred.front().path); + ASSERT_EQUALS(5, inferred.front().intvalue); + ValueFlow::Value arithmeticExpected(352); + arithmeticExpected.setKnown(); + inferred = infer(makeIntegralInferModel(), "==", arithmeticValue, {arithmeticExpected}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isPossible()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT_EQUALS(1, inferred.front().intvalue); + + ValueFlow::Value rhsLower(1); + rhsLower.setPossible(); + rhsLower.bound = ValueFlow::Value::Bound::Lower; + rhsLower.condition = condition; + rhsLower.path = 7; + ValueFlow::Value rhsUpper(10); + rhsUpper.setPossible(); + rhsUpper.bound = ValueFlow::Value::Bound::Upper; + rhsUpper.condition = condition; + rhsUpper.path = 7; + std::vector derivedBounds = infer(makeIntegralInferModel(), "-", {lhs}, {rhsLower, rhsUpper}); + ASSERT_EQUALS(2U, derivedBounds.size()); + ASSERT(std::all_of(derivedBounds.cbegin(), derivedBounds.cend(), [](const ValueFlow::Value& value) { + return value.isImpossible() && value.bound != ValueFlow::Value::Bound::Point && value.path == 7; + })); + ASSERT(std::any_of(derivedBounds.cbegin(), derivedBounds.cend(), [](const ValueFlow::Value& value) { + return value.bound == ValueFlow::Value::Bound::Upper; + })); + ASSERT(std::any_of(derivedBounds.cbegin(), derivedBounds.cend(), [](const ValueFlow::Value& value) { + return value.bound == ValueFlow::Value::Bound::Lower; + })); + std::list derivedValues(derivedBounds.begin(), derivedBounds.end()); + ValueFlow::Value intervalBoundary(384); + intervalBoundary.setKnown(); + inferred = infer(makeIntegralInferModel(), "==", derivedValues, {intervalBoundary}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isPossible()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT_EQUALS(0, inferred.front().intvalue); + + lhs.path = 0; + rhsLower.path = 0; + rhsUpper.path = 0; + derivedBounds = infer(makeIntegralInferModel(), "-", {lhs}, {rhsLower, rhsUpper}); + std::list localDerivedValues(derivedBounds.begin(), derivedBounds.end()); + inferred = infer(makeIntegralInferModel(), "==", localDerivedValues, {intervalBoundary}); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isKnown()); + ASSERT_EQUALS(0, inferred.front().path); + ASSERT_EQUALS(0, inferred.front().intvalue); + + ValueFlow::Value scalarSupport(23); + scalarSupport.setPossible(); + scalarSupport.path = 7; + scalarSupport.condition = condition; + scalarSupport.errorPath.emplace_back(condition, "scalar support"); + ValueFlow::Value excludedPoint(23); + excludedPoint.setImpossible(); + excludedPoint.bound = ValueFlow::Value::Bound::Point; + excludedPoint.path = 7; + excludedPoint.condition = exclusionCondition; + excludedPoint.errorPath.emplace_back(exclusionCondition, "excluded point"); + ValueFlow::Value castLower(100); + castLower.setImpossible(); + castLower.bound = ValueFlow::Value::Bound::Lower; + castLower.path = 7; + ValueFlow::Value castUpper(0); + castUpper.setImpossible(); + castUpper.bound = ValueFlow::Value::Bound::Upper; + castUpper.path = 7; + const std::list castAndExclusionValues{castLower, excludedPoint, castUpper}; + inferred = infer(makeIntegralInferModel(), "==", {scalarSupport}, castAndExclusionValues); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isPossible()); + ASSERT(!inferred.front().isKnown()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT_EQUALS(0, inferred.front().intvalue); + ASSERT(inferred.front().condition == condition); + ASSERT(std::any_of(inferred.front().errorPath.cbegin(), inferred.front().errorPath.cend(), [&](const std::pair& item) { + return item.first == condition; + })); + ASSERT(std::any_of(inferred.front().errorPath.cbegin(), inferred.front().errorPath.cend(), [&](const std::pair& item) { + return item.first == exclusionCondition; + })); + + inferred = infer(makeIntegralInferModel(), "!=", {scalarSupport}, castAndExclusionValues); + ASSERT_EQUALS(1U, inferred.size()); + ASSERT(inferred.front().isPossible()); + ASSERT(!inferred.front().isKnown()); + ASSERT_EQUALS(7, inferred.front().path); + ASSERT_EQUALS(1, inferred.front().intvalue); + + scalarSupport.path = 7; + excludedPoint.path = 8; + castLower.path = 8; + castUpper.path = 8; + const std::list incompatibleValues{castLower, excludedPoint, castUpper}; + inferred = infer(makeIntegralInferModel(), "==", {scalarSupport}, incompatibleValues); + ASSERT(inferred.empty()); } void valueFlowImpossibleUnknownConstant()