diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 46330f41e9d..eb64d8c6e0d 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -38,6 +38,8 @@ #include #include #include +#include +#include #include #include #include @@ -45,11 +47,83 @@ #include namespace { + // A traversal walks one path through the code: the tracked value with the state assumed on the + // way. Where the paths part, another path is walked on a fork(). struct ForwardTraversal { enum class Progress : std::uint8_t { Continue, Break, Skip }; ForwardTraversal(const ValuePtr& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) : analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) {} + + // What became of the paths through a range + struct Outcome { + Analyzer::Action action = Analyzer::Action::None; + int reached = 0; + // How each path that did not reach the end stopped + std::vector stops; + + void reach(Analyzer::Action a) { + action |= a; + ++reached; + } + void stop(Analyzer::Action a, Analyzer::Terminate t) { + action |= a; + stops.push_back(t); + } + // The paths that stopped in a block of the range stopped in the range. If another path + // covers the code they did not walk, only an escape or a changed value counts. + void add(const Outcome& block, bool covered) { + action |= block.action; + for (Analyzer::Terminate t : block.stops) { + if (covered && t != Analyzer::Terminate::Escape && t != Analyzer::Terminate::Modified) + t = Analyzer::Terminate::None; + stops.push_back(t); + } + } + // Paths that were followed to the end of the same range + void join(const Outcome& paths) { + add(paths, false); + reached += paths.reached; + } + bool hasEscape() const { + return contains(stops, Analyzer::Terminate::Escape); + } + bool allEscape() const { + return reached == 0 && !stops.empty() && std::all_of(stops.cbegin(), stops.cend(), [](Analyzer::Terminate t) { + return t == Analyzer::Terminate::Escape; + }); + } + Analyzer::Terminate worst() const { + Analyzer::Terminate result = Analyzer::Terminate::None; + for (Analyzer::Terminate t : stops) { + if (rank(t) > rank(result)) + result = t; + } + return result; + } + // A path stopped without walking the rest of the range + bool unwalked() const { + const Analyzer::Terminate t = worst(); + return t != Analyzer::Terminate::None && t != Analyzer::Terminate::Modified; + } + static int rank(Analyzer::Terminate t) { + switch (t) { + case Analyzer::Terminate::None: + case Analyzer::Terminate::Escape: + return 0; + case Analyzer::Terminate::Modified: + return 1; + case Analyzer::Terminate::Conditional: + return 2; + case Analyzer::Terminate::Inconclusive: + return 3; + case Analyzer::Terminate::Bail: + return 4; + } + cppcheck::unreachable(); + } + }; + ValuePtr analyzer; RefThunk tokenList; RefThunk errorLogger; @@ -64,6 +138,8 @@ namespace { int forkDepth = 0; // Total forks of the traversal (shared via the fork() copy); backstop past the depth bound. std::shared_ptr forkBudget = std::make_shared(0); + // The paths that parted from this one in the range being walked and do not go on with it + Outcome parted; Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) @@ -73,11 +149,19 @@ namespace { struct Branch { explicit Branch(Token* tok = nullptr) : endBlock(tok) {} + // nullptr if there is nothing to walk, e.g. an if without else Token* endBlock = nullptr; Analyzer::Action action = Analyzer::Action::None; - bool check = false; bool escape = false; bool escapeUnknown = false; + // The path that walked the block is at its end + bool reachesEnd = true; + // The traversal that walked the block + ForwardTraversal* traversal = nullptr; + // The condition that holds on it, if it is a fork + const Token* condTok = nullptr; + // The paths that stopped in the block, if it was walked on a fork + Outcome stoppedPaths; bool isEscape() const { return escape || escapeUnknown; } @@ -96,11 +180,6 @@ namespace { bool hasGoto() const { return endBlock ? ForwardTraversal::hasGoto(endBlock) : false; } - Progress progress = Progress::Continue; - // The path through this branch continues past the if - bool continues() const { - return progress != Progress::Break && !isEscape(); - } }; bool stopUpdates() { @@ -135,6 +214,11 @@ namespace { return evalCond(tok, ctx).first; } + bool isConditionFalse(const Token* tok, const Token* ctx = nullptr) const { + const std::pair check = evalCond(tok, ctx); + return !check.first && check.second; + } + template )> Progress traverseTok(T* tok, const F &f, bool traverseUnknown, T** out = nullptr) { if (Token::Match(tok, "asm|goto")) @@ -334,6 +418,7 @@ namespace { ft.analyzeTerminate = true; } ft.actions = Analyzer::Action::None; + ft.parted = Outcome{}; return ft; } @@ -346,12 +431,13 @@ namespace { return (depthLimit < 0 || forkDepth < depthLimit) && (budgetLimit < 0 || *forkBudget < budgetLimit); } - // A value changed in either branch is only possible past the if, on both paths. False if - // it cannot be lowered. - static bool lowerAfterBranches(Analyzer& a, const Branch& thenBranch, const Branch& elseBranch) { - if ((thenBranch.isModified() || elseBranch.isModified()) && !a.lowerToPossible()) + // A value changed in one of the branches is only possible past them, on every path. False + // if it cannot be lowered. + static bool lowerAfterBranches(Analyzer& a, const std::vector& branches) { + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isModified)) && !a.lowerToPossible()) return false; - if ((thenBranch.isInconclusive() || elseBranch.isInconclusive()) && !a.lowerToInconclusive()) + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isInconclusive)) && + !a.lowerToInconclusive()) return false; return true; } @@ -367,7 +453,7 @@ namespace { std::vector tryForkUpdateScope(Token* endBlock, bool isModified = false) const { std::vector result = tryForkScope(endBlock, isModified); for (ForwardTraversal& ft : result) - ft.updateScope(endBlock); + ft.updateAllScopePaths(endBlock); return result; } @@ -402,53 +488,72 @@ namespace { return a; } - Progress updateBranch(Branch& branch, int depth) + // What became of this path and of the paths that parted from it + Outcome outcome(Progress p) const { - // Save and reset actions - Analyzer::Action prevActions = actions; + Outcome paths = parted; + if (p == Progress::Break) + paths.stop(actions, terminate); + else + paths.reach(actions); + return paths; + } + + // Walk a block on this traversal. The paths do not part for good inside it: each one would + // have to be followed past the block to the end of the range, which costs too much. + Branch updateBranch(Token* endBlock, int depth) + { + const Analyzer::Action outerActions = actions; actions = Analyzer::Action::None; - Progress p = updateRange(branch.endBlock->link(), branch.endBlock, depth); - branch.action |= actions; - // Restore actions - actions |= prevActions; + Outcome outer = std::move(parted); + parted = Outcome{}; + const Progress p = updateRange(endBlock->link(), endBlock, false, depth); + const Outcome paths = outcome(p); + outer.add(parted, false); + parted = std::move(outer); + actions |= outerActions; - if (terminate == Analyzer::Terminate::Escape) { + Branch branch{endBlock}; + branch.action = paths.action; + branch.reachesEnd = paths.reached > 0; + if (paths.allEscape()) { branch.escape = true; - // The traversal followed an escaping path, but if the scope does not structurally - // always escape then another path (e.g. a modified fork) falls through, so the escape - // is only conditional - keep isModified() meaningful by not treating it as conclusive. + // The paths can miss a way through the block: a call is taken to return what an + // earlier call of the same function returned. Unless the block structurally always + // escapes, it may fall through and change the value on the way. bool structuralUnknown = false; - const bool structuralEscape = isEscapeScope(branch.endBlock, structuralUnknown); + const bool structuralEscape = isEscapeScope(endBlock, structuralUnknown); branch.escapeUnknown = !structuralEscape || structuralUnknown; - // The traversal stopped at the escape, so the rest of the scope was not walked; a - // fall-through path could still modify the value there - include the whole scope's - // actions so isModified() sees it. if (branch.escapeUnknown) - branch.action |= analyzeScope(branch.endBlock); + branch.action |= analyzeScope(endBlock); } else { - // Detect an escape the traversal did not flag (e.g. an unknown noreturn call); + // Detect an escape the paths did not flag (e.g. an unknown noreturn call); // escapeUnknown reports a possible (unknown) escape. - branch.escape = isEscapeScope(branch.endBlock, branch.escapeUnknown); - if (terminate != Analyzer::Terminate::None && terminate != Analyzer::Terminate::Modified) { - branch.action |= analyzeScope(branch.endBlock); - } + branch.escape = isEscapeScope(endBlock, branch.escapeUnknown); + if (paths.unwalked()) + branch.action |= analyzeScope(endBlock); } - - return p; + return branch; } - // Update the branch that the evaluated condition takes - Progress updateTakenBranch(Branch& branch, const Token* skippedBlock, const Token* condTok, int depth) + // The condition was evaluated: walk the one block of the if that it selects + Progress updateSingleIfBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, int depth) { // The condition is only "known" because of an earlier assumption, so the // skipped block could still modify the value -> lower to possible if (!condTok->hasKnownIntValue() && skippedBlock && analyzeScope(skippedBlock).isModified() && !analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); - if (!branch.endBlock) + if (!endBlock) { + // Record the state past the skipped block, so that the conditions evaluated later do + // not each look for changes in it + if (skippedBlock->next()) + analyzer->updateState(skippedBlock->next()); return Progress::Continue; - updateScopeState(branch.endBlock); - if (updateBranch(branch, depth - 1) == Progress::Break) + } + updateScopeState(endBlock); + const Branch branch = updateBranch(endBlock, depth - 1); + if (!branch.reachesEnd) return Progress::Break; // The branch was entered because of the tracked value; if it might not // return (it ends in a call to an unknown, possibly noreturn function) @@ -458,6 +563,147 @@ namespace { return Progress::Continue; } + // A path that parted from this one stops + void stopFork(ForwardTraversal& ft, Analyzer::Terminate t = Analyzer::Terminate::None) + { + ft.Break(t); + parted.stop(ft.actions, ft.terminate); + } + + // This path stopped; the path of a fork goes on in its place + void replaceWith(ForwardTraversal ft) + { + Outcome paths = std::move(parted); + paths.stop(actions, terminate); + *this = std::move(ft); + parted = std::move(paths); + } + + // Walk a block on a fork of this traversal, on which the condition holds + Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, bool split, int depth) const + { + ft.actions = actions; + if (split) { + ++(*forkBudget); + ++ft.forkDepth; + } + ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); + Branch branch = ft.updateBranch(endBlock, depth); + branch.traversal = &ft; + branch.condTok = condTok; + // The branch limit counts the branches on the way past the block, as it does for this path + ft.branchCount = branchCount; + // A fork that does not split uses up the fork limit as well. Otherwise the whole limit is + // left for the forks that walk to the end of the range, which are the expensive ones. + if (!split && branch.reachesEnd && canFork()) + ++(*forkBudget); + branch.stoppedPaths = std::move(ft.parted); + ft.parted = Outcome{}; + if (!branch.reachesEnd) + branch.stoppedPaths.stop(ft.actions, ft.terminate); + return branch; + } + + // Neither outcome of the condition is known: the then block is walked on a fork, the else + // block on this traversal. + Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, bool conditional, bool split, int depth) + { + Token* ifEnd = elseEnd ? elseEnd : thenEnd; + // The value only flows into the then block when the condition can split it; for an opaque + // or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the + // block's effect is still tracked but nothing is reported in it. + ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false)); + const Branch thenBranch = updateForkedBranch(ft, condTok, thenEnd, split, depth - 1); + + // The condition is an assumption on this path if the then path drops the value. If the + // then path goes on past the if, the value is the same with and without it. Otherwise + // this path stands for the then path as well and records that the condition is false + // only if that holds on both (e.g. 'if (x > 5) x = 5;'). With an else block the state is + // recorded after it. + const unsigned int pending = elseEnd ? Analyzer::Assume::Pending : Analyzer::Assume::None; + bool assumed = true; + if (thenBranch.isDead()) + analyzer->assume(condTok, false, pending); + else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous()))) + analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending); + else + assumed = false; + Branch elseBranch; + if (elseEnd) { + if (!assumed) + updateScopeState(elseEnd); + elseBranch = updateBranch(elseEnd, depth - 1); + if (elseBranch.reachesEnd) + analyzer->updateState(elseEnd->previous()); + } else if (!assumed && ifEnd->next()) { + // An assumption records the state where the path goes on. Without one the state stays + // at an earlier token, and every condition evaluated later looks for changes from there. + analyzer->updateState(ifEnd->next()); + } + elseBranch.traversal = this; + return continueAfterBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, split, depth); + } + + // The blocks of a branching statement were walked, each on a fork or on this traversal. + // Decide which of the paths go on past the statement. split: every path goes on to the end + // of the range on its own. Otherwise one path goes on for all of them. + Progress continueAfterBranches(const std::vector& branches, bool conditional, Token* next, const Token* end, bool split, int depth) + { + const Analyzer::Action action = + std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{}, [](Analyzer::Action a, const Branch& branch) { + return a | branch.action; + }); + actions |= action; + const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto)); + const bool reachesEnd = std::all_of(branches.cbegin(), branches.cend(), [this](const Branch& branch) { + return branch.traversal != this || branch.reachesEnd; + }); + Progress progress = reachesEnd ? Progress::Continue : Progress::Break; + if (reachesEnd) { + if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isDead)) && conditional && stopUpdates()) + progress = Break(Analyzer::Terminate::Conditional); + else if (!lowerAfterBranches(*analyzer, branches) || jumps) + progress = Break(Analyzer::Terminate::Bail); + } + // Without a split this path goes on for the forks. If it stopped, a fork goes on in its place. + const bool forksGoOn = split || progress == Progress::Break; + std::vector successors; + for (const Branch& branch : branches) { + if (branch.traversal == this || !branch.reachesEnd) + continue; + ForwardTraversal& ft = *branch.traversal; + ft.actions |= action; + if (jumps) { + stopFork(ft, Analyzer::Terminate::Bail); + } else if (branch.isEscape()) { + stopFork(ft, Analyzer::Terminate::Escape); + } else if (forksGoOn && !lowerAfterBranches(*ft.analyzer, branches)) { + stopFork(ft); + } else if (forksGoOn) { + // Anchor the state (and the block's assignments) at the block end + ft.analyzer->assume(branch.condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); + if (split) + parted.join(ft.updatePaths(next, end, depth - 1)); + else + successors.push_back(&ft); + } + } + // Each fork holds its own condition, so one of several cannot go on for the others + const bool replaced = successors.size() == 1; + // A path that stopped in a block is covered only if a path goes on for it past the + // statement. Otherwise nothing walks the code that follows on its way. + const bool covered = !split && (replaced || progress == Progress::Continue); + for (const Branch& branch : branches) + parted.add(branch.stoppedPaths, covered); + if (replaced) { + replaceWith(std::move(*successors.front())); + return Progress::Continue; + } + for (ForwardTraversal* ft : successors) + stopFork(*ft, Analyzer::Terminate::Bail); + return progress; + } + bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const { if (!condTok) return true; @@ -587,7 +833,7 @@ namespace { if (forkContinue) { for (ForwardTraversal& ft : ftv) { if (!ft.actions.isIncremental()) - ft.updateRange(endBlock, endToken); + ft.updateAllPaths(endBlock, endToken); } } if (allAnalysis.isIncremental()) @@ -624,13 +870,42 @@ namespace { if (!endBlock) return Break(); updateScopeState(endBlock); - return updateRange(endBlock->link(), endBlock, depth); + return updateRange(endBlock->link(), endBlock, false, depth); + } + + void updateAllScopePaths(Token* endBlock, int depth = 20) + { + if (!endBlock) + return; + updateScopeState(endBlock); + updateAllPaths(endBlock->link(), endBlock, depth); + } + + // Walk this path and every path that parts from it to the end of the range + Outcome updatePaths(Token* start, const Token* end, int depth) + { + return outcome(updateRange(start, end, true, depth)); + } + + // As updatePaths(), and this traversal gets the joint result of the paths. It must not go on + // after the range. + void updateAllPaths(Token* start, const Token* end, int depth = 20) { + const Outcome paths = updatePaths(start, end, depth); + // A path that stopped without an escape was not followed to one, but the code can show + // that there is no way to the end of the range + const bool escapes = paths.allEscape() || + (paths.reached == 0 && paths.hasEscape() && isReturnScope(end, settings().library)); + actions = paths.action; + terminate = escapes ? Analyzer::Terminate::Escape : paths.worst(); } /** + * Walk this path from start to end. + * @param split the paths may part for good at an undecided if: nothing goes on after the + * range on this traversal. Otherwise one path has to stand for all of them at its end. * @throws InternalError thrown on cyclic analysis */ - Progress updateRange(Token* start, const Token* end, int depth = 20) { + Progress updateRange(Token* start, const Token* end, bool split, int depth = 20) { if (depth < 0) return Break(Analyzer::Terminate::Bail); std::size_t i = 0; @@ -785,73 +1060,28 @@ namespace { // Traverse condition if (updateRecursive(condTok) == Progress::Break) return Break(); - Branch thenBranch{endBlock}; - Branch elseBranch{endBlock->tokAt(2) ? endBlock->linkAt(2) : nullptr}; // Check if condition is true or false - std::tie(thenBranch.check, elseBranch.check) = evalCond(condTok); - if (!thenBranch.check && !elseBranch.check && stopOnCondition(condTok) && stopUpdates()) + bool checkThen, checkElse; + std::tie(checkThen, checkElse) = evalCond(condTok); + const bool conditional = !checkThen && !checkElse && stopOnCondition(condTok); + if (conditional && stopUpdates()) return Break(Analyzer::Terminate::Conditional); - const bool hasElse = Token::simpleMatch(endBlock, "} else {"); - tok = hasElse ? endBlock->linkAt(2) : endBlock; - if (thenBranch.check) { - if (updateTakenBranch(thenBranch, hasElse ? elseBranch.endBlock : nullptr, condTok, depth) == - Progress::Break) + Token* elseEnd = Token::simpleMatch(endBlock, "} else {") ? endBlock->linkAt(2) : nullptr; + tok = elseEnd ? elseEnd : endBlock; + if (checkThen) { + if (updateSingleIfBranch(endBlock, elseEnd, condTok, depth) == Progress::Break) return Break(); - } else if (elseBranch.check) { - if (updateTakenBranch(elseBranch, thenBranch.endBlock, condTok, depth) == Progress::Break) + } else if (checkElse) { + if (updateSingleIfBranch(elseEnd, endBlock, condTok, depth) == Progress::Break) return Break(); - } else { - const bool conditional = stopOnCondition(condTok); - // The then-path runs on a fork, the else-path on this traversal. The value only - // flows into the then-branch when the condition can split it; for an opaque or - // correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: - // the branch's effect is still tracked but nothing is reported in it. - ForwardTraversal ft = fork(!analyzer->updateScope(thenBranch.endBlock, false)); - ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending); - thenBranch.progress = ft.updateBranch(thenBranch, depth - 1); - actions |= thenBranch.action; - // The condition is an assumption on the else-path only if the then-path drops - // the value. With an else block the state is recorded after it. - analyzer->assume(condTok, - false, - (thenBranch.isDead() ? Analyzer::Assume::None - : Analyzer::Assume::Quiet | Analyzer::Assume::Absolute) | - (hasElse ? Analyzer::Assume::Pending : Analyzer::Assume::None)); - if (hasElse) { - elseBranch.progress = updateBranch(elseBranch, depth - 1); - if (elseBranch.progress != Progress::Break) - analyzer->updateState(elseBranch.endBlock->previous()); - } - if ((thenBranch.isDead() || elseBranch.isDead()) && conditional && stopUpdates()) - elseBranch.progress = Break(Analyzer::Terminate::Conditional); - if (!lowerAfterBranches(*ft.analyzer, thenBranch, elseBranch)) - thenBranch.progress = Progress::Break; - if (elseBranch.progress != Progress::Break && !lowerAfterBranches(*analyzer, thenBranch, elseBranch)) - elseBranch.progress = Break(Analyzer::Terminate::Bail); - if (thenBranch.hasGoto() || elseBranch.hasGoto()) - return Break(Analyzer::Terminate::Bail); - // Carry the then-path past the if. Skip the closing brace, whose handler is for - // traversals that start inside the block; re-assume to anchor the state (and the - // block's assignments) at the block end. - if (thenBranch.continues() && canFork()) { - ++(*forkBudget); - ++ft.forkDepth; - ft.analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); - ft.updateRange(tok->next(), end, depth - 1); - } - if (elseBranch.progress == Progress::Break) { - // Only the else branch escaped; the then branch falls through, so - // the scope as a whole does not always escape. - if (terminate == Analyzer::Terminate::Escape && !thenBranch.isEscape()) - terminate = Analyzer::Terminate::None; - return Break(); - } + } else if (updateIfBranches(condTok, endBlock, elseEnd, end, conditional, split && canFork(), depth) == Progress::Break) { + return Break(); } } } else if (Token::simpleMatch(tok, "try {")) { Token* endBlock = tok->linkAt(1); ForwardTraversal tryTraversal = fork(); - tryTraversal.updateScope(endBlock, depth - 1); + tryTraversal.updateAllScopePaths(endBlock, depth - 1); bool bail = tryTraversal.actions.isModified(); if (bail) { actions = tryTraversal.actions; @@ -865,7 +1095,7 @@ namespace { return Break(); endBlock = endCatch->linkAt(1); ForwardTraversal ft = fork(); - ft.updateScope(endBlock, depth - 1); + ft.updateAllScopePaths(endBlock, depth - 1); bail |= ft.terminate != Analyzer::Terminate::None || ft.actions.isModified(); } if (bail) @@ -899,7 +1129,7 @@ namespace { return Break(); // Since the call could be an unknown macro, traverse the tokens as a range instead of recursively if (!Token::simpleMatch(callTok, "( )") && - updateRange(callTok->next(), callTok->link(), depth - 1) == Progress::Break) + updateRange(callTok->next(), callTok->link(), false, depth - 1) == Progress::Break) return Break(); if (updateTok(callTok) == Progress::Break) return Break(); @@ -994,7 +1224,7 @@ Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const V ForwardTraversal ft{a, tokenList, errorLogger, settings}; if (start) ft.analyzer->updateState(start); - ft.updateRange(start, end); + ft.updateAllPaths(start, end); return Analyzer::Result{ ft.actions, ft.terminate }; } diff --git a/test/testcondition.cpp b/test/testcondition.cpp index 5961dca21a9..39b9c466c0e 100644 --- a/test/testcondition.cpp +++ b/test/testcondition.cpp @@ -5005,6 +5005,262 @@ class TestCondition : public TestFixture { "}\n"); ASSERT_EQUALS("", errout_str()); + check("bool g();\n" // only the path that skips 'w = true' returns + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w || !b)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path is split inside a block that is always entered + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (a) {\n" + " if (g())\n" + " w = true;\n" + " }\n" + " if (!w)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:6:13]: (warning) Identical inner 'if' condition is always true. [identicalInnerCondition]\n", + errout_str()); + + check("bool g();\n" // x is assigned on the path that sets w + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" + "void use();\n" + "void f(bool c) {\n" + " int x = 0;\n" + " if (c) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // every path returns + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:12:14]: (style) Condition 'a' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("bool g();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (g())\n" + " x = 1;\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:9:11]: (style) Condition 'x==0' is always false [knownConditionTrueFalse]\n", + errout_str()); + + check("bool g();\n" // the path that leaves the else block assigns x afterwards + "bool c();\n" + "int h();\n" + "void use(int);\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (c()) {\n" + " } else {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " x = h();\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use(x);\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the same in a block that is always entered + "int h();\n" + "void use(int);\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " x = h();\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use(x);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:5:11] -> [test.cpp:6:15]: (warning) Identical inner 'if' condition is always true. [identicalInnerCondition]\n", + errout_str()); + + check("bool g();\n" // #15264 - the split is in the then block of another unknown condition + "bool h();\n" + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " if (h()) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " } else {\n" + " return;\n" + " }\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // #15264 - the split is in a loop + "void use();\n" + "void f(bool a, bool b, bool c) {\n" + " if (a) {\n" + " bool w = false;\n" + " while (g()) {\n" + " if (c)\n" + " w = true;\n" + " }\n" + " if (!w)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path that leaves the else block assigns x in a later block + "bool c();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (c()) {\n" + " } else {\n" + " if (g())\n" + " w = true;\n" + " }\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // the path that leaves the loop assigns x in a later block + "void use();\n" + "void f(int x, bool c) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " while (g()) {\n" + " if (c)\n" + " w = true;\n" + " }\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n"); + ASSERT_EQUALS("", errout_str()); + + { + // Without splitting, the path past 'if (g())' stands for both outcomes + /*const*/ Settings s = settings0; + s.vfOptions.maxForwardConditionForkDepth = 0; + check("bool g();\n" + "void use();\n" + "void f(int x) {\n" + " if (x == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (w)\n" + " x = 1;\n" + " } else {\n" + " return;\n" + " }\n" + " if (x == 0)\n" + " use();\n" + "}\n", s); + ASSERT_EQUALS("", errout_str()); + + check("bool g();\n" // #15264 + "void use();\n" + "void f(bool a, bool b) {\n" + " if (a) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w || !b)\n" + " return;\n" + " }\n" + " if (b && a)\n" + " use();\n" + "}\n", s); + ASSERT_EQUALS("", errout_str()); + } + check("void f() {\n" " if (42) {}\n" " if (42U) {}\n" diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp index cecbb27ca09..9873a391e2b 100644 --- a/test/testnullpointer.cpp +++ b/test/testnullpointer.cpp @@ -154,6 +154,7 @@ class TestNullPointer : public TestFixture { TEST_CASE(nullpointer113); // a variable is clamped before the check TEST_CASE(nullpointer114); // the else block changes the value TEST_CASE(nullpointer115); // a range condition overlapping the assumed one + TEST_CASE(nullpointer116); // #15264 TEST_CASE(nullpointer_addressOf); // address of TEST_CASE(nullpointerSwitch); // #2626 TEST_CASE(nullpointer_cast); // #4692 @@ -3375,6 +3376,41 @@ class TestNullPointer : public TestFixture { ASSERT_EQUALS("[test.cpp:4:24]: (warning) Possible null pointer dereference: p [nullPointer]\n", errout_str()); } + void nullpointer116() { // #15264 - only the path that skips 'w = true' returns + check("bool g();\n" + "void use(int);\n" + "void f(const int *p) {\n" + " if (!p) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " use(*p);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:11:10]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p. [nullPointerRedundantCheck]\n", + errout_str()); + + check("bool g();\n" // the path leaves an else block + "void use(int);\n" + "void f(const int *p, bool c) {\n" + " if (!p) {\n" + " if (c) {\n" + " } else {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return;\n" + " }\n" + " }\n" + " use(*p);\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:9] -> [test.cpp:14:10]: (warning) Either the condition '!p' is redundant or there is possible null pointer dereference: p. [nullPointerRedundantCheck]\n", + errout_str()); + } + void nullpointer_addressOf() { // address of check("void f() {\n" " struct X *x = 0;\n" diff --git a/test/testother.cpp b/test/testother.cpp index 085b39cfffb..5c91927f9ec 100644 --- a/test/testother.cpp +++ b/test/testother.cpp @@ -936,6 +936,43 @@ class TestOther : public TestFixture { " return 0;\n" "}\n"); ASSERT_EQUALS("[test.cpp:4:26]: (warning) Division by zero. [zerodivcond]\n", errout_str()); + + // #15264 - only the path that sets both flags leaves the block + check("bool g();\n" + "bool h();\n" + "int f(int a) {\n" + " if (a == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " bool v = false;\n" + " if (h())\n" + " v = true;\n" + " if (!w || !v)\n" + " return 0;\n" + " }\n" + " return 10 / a;\n" + "}\n"); + ASSERT_EQUALS("[test.cpp:4:11] -> [test.cpp:14:15]: (warning) Either the condition 'a==0' is redundant or there is division by zero at line 14. [zerodivcond]\n", + errout_str()); + + // TODO #15264: the second call of g() is assumed to return what the first call returned + check("bool g();\n" + "int f(int a) {\n" + " if (a == 0) {\n" + " bool w = false;\n" + " if (g())\n" + " w = true;\n" + " if (!w)\n" + " return 0;\n" + " if (g())\n" + " return 1;\n" + " }\n" + " return 10 / a;\n" + "}\n"); + TODO_ASSERT_EQUALS("[test.cpp:3:11] -> [test.cpp:12:15]: (warning) Either the condition 'a==0' is redundant or there is division by zero at line 12. [zerodivcond]\n", + "", + errout_str()); } void zeroDivErrorPath() { diff --git a/test/testvalueflow.cpp b/test/testvalueflow.cpp index d7fc9933214..4c81b9130f0 100644 --- a/test/testvalueflow.cpp +++ b/test/testvalueflow.cpp @@ -4662,6 +4662,30 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(true, testValueOfX(code, 4U, 1)); ASSERT_EQUALS(false, testValueOfX(code, 5U, 1)); + // inside a block one path goes on past the if: the then path, as the else path stopped + code = "void f(int n, bool d) {\n" + " int x = 1;\n" + " if (d) {\n" + " if (n > 5) { n = 5; } else { return; }\n" + " if (n == 5) { int a = x; }\n" + " if (n != 5) { int b = x; }\n" + " }\n" + " int c = x;\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 5U, 1)); + ASSERT_EQUALS(false, testValueOfX(code, 6U, 1)); + ASSERT_EQUALS(true, testValueOfXKnown(code, 8U, 1)); + + code = "void f(int n, bool d) {\n" + " int x = 1;\n" + " while (d) {\n" + " if (n > 5) {} else { return; }\n" + " int a = x;\n" + " d = g();\n" + " }\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 5U, 1)); + // the main path continues with the else block's assignments (then escapes) code = "void f(int n) {\n" " int x = 1;\n" @@ -4801,7 +4825,7 @@ class TestValueFlow : public TestFixture { ASSERT_EQUALS(true, testValueOfX(code, 5U, 5)); ASSERT_EQUALS(false, testValueOfX(code, 6U, 5)); - // no fork: the main path still knows the condition is false + // no fork: the then block makes the condition false, so it is false on both outcomes /*const*/ Settings s(settings); s.vfOptions.maxForwardConditionForkDepth = 0; code = "void f(int n) {\n" @@ -4812,6 +4836,39 @@ class TestValueFlow : public TestFixture { "}\n"; ASSERT_EQUALS(false, testValueOfX(code, 4U, 1, &s)); ASSERT_EQUALS(true, testValueOfX(code, 5U, 1, &s)); + + // no fork: a condition that is false on one outcome only is not recorded + code = "bool g();\n" + "void f() {\n" + " int x = 1;\n" + " bool w = false;\n" + " if (g()) w = true;\n" + " if (w) { int a = x; }\n" + "}\n"; + ASSERT_EQUALS(true, testValueOfX(code, 6U, 1, &s)); + + // the path through 'if (c)' stops at the branch limit and the other path returns, so no + // path walks 'x = 5' + const Settings normal = settingsBuilder(settings).checkLevel(Settings::CheckLevel::normal).build(); + code = "void use();\n" + "void f(bool o, bool c, bool d1, bool d2, bool d3, bool d4) {\n" + " int x = 0;\n" + " if (o) {\n" + " if (c) {\n" + " if (d1) { use(); }\n" + " if (d2) { use(); }\n" + " if (d3) { use(); }\n" + " if (d4) { use(); }\n" + " } else {\n" + " return;\n" + " }\n" + " x = 5;\n" + " }\n" + " if (x == 0) {}\n" + "}\n"; + const ValueFlow::Value value = valueOfTok(code, "x ==", &normal); + ASSERT_EQUALS(0, value.intvalue); + ASSERT(value.isPossible()); } void valueFlowForwardAfterCondition()