| 40 | static const CWE CWE398(398U); // Indicator of Poor Code Quality |
| 41 | |
| 42 | void CheckAssertImpl::assertWithSideEffects() |
| 43 | { |
| 44 | if (!mSettings.severity.isEnabled(Severity::warning)) |
| 45 | return; |
| 46 | |
| 47 | logChecker("CheckAssert::assertWithSideEffects"); // warning |
| 48 | |
| 49 | for (const Token* tok = mTokenizer->list.front(); tok; tok = tok->next()) { |
| 50 | if (!Token::simpleMatch(tok, "assert (")) |
| 51 | continue; |
| 52 | |
| 53 | const Token *endTok = tok->linkAt(1); |
| 54 | for (const Token* tmp = tok->next(); tmp != endTok; tmp = tmp->next()) { |
| 55 | if (Token::simpleMatch(tmp, "sizeof (")) |
| 56 | tmp = tmp->linkAt(1); |
| 57 | |
| 58 | checkVariableAssignment(tmp, tok->scope()); |
| 59 | |
| 60 | if (tmp->tokType() != Token::eFunction) { |
| 61 | if (const Library::Function* f = mSettings.library.getFunction(tmp)) { |
| 62 | if (f->isconst || f->ispure) |
| 63 | continue; |
| 64 | if (Library::getContainerYield(tmp->next()) != Library::Container::Yield::NO_YIELD) // bailout, assume read access |
| 65 | continue; |
| 66 | if (std::any_of(f->argumentChecks.begin(), f->argumentChecks.end(), [](const std::pair<int, Library::ArgumentChecks>& ac) { |
| 67 | return ac.second.iteratorInfo.container > 0; // bailout, takes iterators -> assume read access |
| 68 | })) |
| 69 | continue; |
| 70 | if (tmp->str() == "get" && Token::simpleMatch(tmp->astParent(), ".") && astIsSmartPointer(tmp->astParent()->astOperand1())) |
| 71 | continue; |
| 72 | if (f->containerYield == Library::Container::Yield::START_ITERATOR || // bailout for std::begin/end/prev/next |
| 73 | f->containerYield == Library::Container::Yield::END_ITERATOR || |
| 74 | f->containerYield == Library::Container::Yield::ITERATOR) |
| 75 | continue; |
| 76 | sideEffectInAssertError(tmp, mSettings.library.getFunctionName(tmp)); |
| 77 | } |
| 78 | continue; |
| 79 | } |
| 80 | |
| 81 | const Function* f = tmp->function(); |
| 82 | const Scope* scope = f->functionScope; |
| 83 | if (!scope) { |
| 84 | // guess that const method doesn't have side effects |
| 85 | if (f->nestedIn->isClassOrStruct() && !f->isConst() && !f->isStatic()) |
| 86 | sideEffectInAssertError(tmp, f->name()); // Non-const member function called, assume it has side effects |
| 87 | continue; |
| 88 | } |
| 89 | |
| 90 | for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) { |
| 91 | if (!tok2->isAssignmentOp() && tok2->tokType() != Token::eIncDecOp) |
| 92 | continue; |
| 93 | |
| 94 | const Variable* var = tok2->previous()->variable(); |
| 95 | if (!var || var->isLocal() || (var->isArgument() && !var->isReference() && !var->isPointer())) |
| 96 | continue; // See ticket #4937. Assigning function arguments not passed by reference is ok. |
| 97 | if (var->isArgument() && var->isPointer() && tok2->strAt(-2) != "*") |
| 98 | continue; // Pointers need to be dereferenced, otherwise there is no error |
| 99 |
no test coverage detected