From 68a7c4cee81235503c62e9565427f4b90cb45071 Mon Sep 17 00:00:00 2001 From: tnixeu <4436784+tnixeu@users.noreply.github.com> Date: Sat, 9 Mar 2024 01:32:03 +0100 Subject: [PATCH] refactor: move and rename code in order to support a CMAKE_UNITY_BUILD --- gui/filelist.cpp | 6 +- .../testcppchecklibrarydata.h | 2 + gui/test/filelist/testfilelist.h | 2 + gui/test/projectfile/testprojectfile.h | 2 + .../testtranslationhandler.h | 2 + gui/test/xmlreportv2/testxmlreportv2.h | 2 + gui/xmlreport.cpp | 10 +-- lib/check64bit.cpp | 4 +- lib/checkassert.cpp | 4 +- lib/checkautovariables.cpp | 5 +- lib/checkbool.cpp | 6 +- lib/checkboost.cpp | 3 +- lib/checkbufferoverrun.cpp | 21 ++---- lib/checkclass.cpp | 33 ++++------ lib/checkcondition.cpp | 7 +- lib/checkexceptionsafety.cpp | 5 +- lib/checkfunctions.cpp | 9 +-- lib/checkinternal.cpp | 2 +- lib/checkio.cpp | 11 +--- lib/checkleakautovar.cpp | 48 +++++++------- lib/checkmemoryleak.cpp | 5 -- lib/checknullpointer.cpp | 15 ++--- lib/checkother.cpp | 24 +------ lib/checkpostfixoperator.cpp | 4 +- lib/checksizeof.cpp | 5 +- lib/checkstl.cpp | 19 +----- lib/checkstring.cpp | 9 +-- lib/checktype.cpp | 7 +- lib/checkuninitvar.cpp | 14 ++-- lib/checkunusedfunctions.cpp | 5 +- lib/checkunusedvar.cpp | 4 +- lib/checkvaarg.cpp | 6 +- lib/cppcheck.cpp | 2 - lib/errortypes.cpp | 64 ++++++++++++++++++ lib/errortypes.h | 65 +++++++++++++++++++ lib/forwardanalyzer.cpp | 6 +- lib/token.cpp | 4 +- lib/valueflow.cpp | 4 +- test/CMakeLists.txt | 2 + tools/matchcompiler.py | 8 +-- 40 files changed, 239 insertions(+), 217 deletions(-) diff --git a/gui/filelist.cpp b/gui/filelist.cpp index 3115967c451..852cca0c7ab 100644 --- a/gui/filelist.cpp +++ b/gui/filelist.cpp @@ -108,7 +108,7 @@ void FileList::addExcludeList(const QStringList &paths) mExcludedPaths = paths; } -static std::vector toStdStringList(const QStringList &stringList) +static std::vector toStdStringList2(const QStringList &stringList) { std::vector ret; std::transform(stringList.cbegin(), stringList.cend(), std::back_inserter(ret), [](const QString& s) { @@ -120,9 +120,9 @@ static std::vector toStdStringList(const QStringList &stringList) QStringList FileList::applyExcludeList() const { #ifdef _WIN32 - const PathMatch pathMatch(toStdStringList(mExcludedPaths), true); + const PathMatch pathMatch(toStdStringList2(mExcludedPaths), true); #else - const PathMatch pathMatch(toStdStringList(mExcludedPaths), false); + const PathMatch pathMatch(toStdStringList2(mExcludedPaths), false); #endif QStringList paths; diff --git a/gui/test/cppchecklibrarydata/testcppchecklibrarydata.h b/gui/test/cppchecklibrarydata/testcppchecklibrarydata.h index 079436f5509..873b95e67f3 100644 --- a/gui/test/cppchecklibrarydata/testcppchecklibrarydata.h +++ b/gui/test/cppchecklibrarydata/testcppchecklibrarydata.h @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +#pragma once + #include "cppchecklibrarydata.h" #include diff --git a/gui/test/filelist/testfilelist.h b/gui/test/filelist/testfilelist.h index 1089499932a..fa2018a0de8 100644 --- a/gui/test/filelist/testfilelist.h +++ b/gui/test/filelist/testfilelist.h @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +#pragma once + #include #include diff --git a/gui/test/projectfile/testprojectfile.h b/gui/test/projectfile/testprojectfile.h index 47ed517f412..ca2dd8b8a67 100644 --- a/gui/test/projectfile/testprojectfile.h +++ b/gui/test/projectfile/testprojectfile.h @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +#pragma once + #include #include diff --git a/gui/test/translationhandler/testtranslationhandler.h b/gui/test/translationhandler/testtranslationhandler.h index 45bd1ae5186..a7497af98c8 100644 --- a/gui/test/translationhandler/testtranslationhandler.h +++ b/gui/test/translationhandler/testtranslationhandler.h @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +#pragma once + #include #include diff --git a/gui/test/xmlreportv2/testxmlreportv2.h b/gui/test/xmlreportv2/testxmlreportv2.h index d5d0f659f93..988952a884a 100644 --- a/gui/test/xmlreportv2/testxmlreportv2.h +++ b/gui/test/xmlreportv2/testxmlreportv2.h @@ -16,6 +16,8 @@ * along with this program. If not, see . */ +#pragma once + #include #include diff --git a/gui/xmlreport.cpp b/gui/xmlreport.cpp index 3e432d62380..595e7986371 100644 --- a/gui/xmlreport.cpp +++ b/gui/xmlreport.cpp @@ -29,8 +29,8 @@ #include #endif -static constexpr char ResultElementName[] = "results"; -static constexpr char VersionAttribute[] = "version"; +static constexpr char ResultElementName2[] = "results"; +static constexpr char VersionAttribute2[] = "version"; XmlReport::XmlReport(const QString &filename) : Report(filename) @@ -70,10 +70,10 @@ int XmlReport::determineVersion(const QString &filename) while (!reader.atEnd()) { switch (reader.readNext()) { case QXmlStreamReader::StartElement: - if (reader.name() == QString(ResultElementName)) { + if (reader.name() == QString(ResultElementName2)) { QXmlStreamAttributes attribs = reader.attributes(); - if (attribs.hasAttribute(QString(VersionAttribute))) { - const int ver = attribs.value(QString(), VersionAttribute).toString().toInt(); + if (attribs.hasAttribute(QString(VersionAttribute2))) { + const int ver = attribs.value(QString(), VersionAttribute2).toString().toInt(); return ver; } return 1; diff --git a/lib/check64bit.cpp b/lib/check64bit.cpp index 02196cfc043..ae92a82af4b 100644 --- a/lib/check64bit.cpp +++ b/lib/check64bit.cpp @@ -32,12 +32,10 @@ //--------------------------------------------------------------------------- -// CWE ids used -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior // Register this check class (by creating a static instance of it) namespace { - Check64BitPortability instance; + Check64BitPortability instance64BitPortability; } void Check64BitPortability::pointerassignment() diff --git a/lib/checkassert.cpp b/lib/checkassert.cpp index a96191288c2..439b6865657 100644 --- a/lib/checkassert.cpp +++ b/lib/checkassert.cpp @@ -31,12 +31,10 @@ //--------------------------------------------------------------------------- -// CWE ids used -static const CWE CWE398(398U); // Indicator of Poor Code Quality // Register this check class (by creating a static instance of it) namespace { - CheckAssert instance; + CheckAssert instanceAssert; } void CheckAssert::assertWithSideEffects() diff --git a/lib/checkautovariables.cpp b/lib/checkautovariables.cpp index 766cc185ade..a1e1ddcf259 100644 --- a/lib/checkautovariables.cpp +++ b/lib/checkautovariables.cpp @@ -42,12 +42,9 @@ // Register this check class into cppcheck by creating a static instance of it.. namespace { - CheckAutoVariables instance; + CheckAutoVariables instanceAutoVariables; } -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE562(562U); // Return of Stack Variable Address -static const CWE CWE590(590U); // Free of Memory not on the Heap static bool isPtrArg(const Token *tok) { diff --git a/lib/checkbool.cpp b/lib/checkbool.cpp index 16e1471db07..15a8a942a1e 100644 --- a/lib/checkbool.cpp +++ b/lib/checkbool.cpp @@ -34,13 +34,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckBool instance; + CheckBool instanceBool; } -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE571(571U); // Expression is Always True -static const CWE CWE587(587U); // Assignment of a Fixed Address to a Pointer -static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static bool isBool(const Variable* var) { diff --git a/lib/checkboost.cpp b/lib/checkboost.cpp index 4913a691fba..bfdb2127ff3 100644 --- a/lib/checkboost.cpp +++ b/lib/checkboost.cpp @@ -26,10 +26,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckBoost instance; + CheckBoost instanceBoost; } -static const CWE CWE664(664); void CheckBoost::checkBoostForeachModification() { diff --git a/lib/checkbufferoverrun.cpp b/lib/checkbufferoverrun.cpp index 49cb2036ff3..78b7b49540e 100644 --- a/lib/checkbufferoverrun.cpp +++ b/lib/checkbufferoverrun.cpp @@ -48,20 +48,11 @@ // Register this check class (by creating a static instance of it) namespace { - CheckBufferOverrun instance; + CheckBufferOverrun instanceBufferOverrun; } //--------------------------------------------------------------------------- -// CWE ids used: -static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size -static const CWE CWE170(170U); // Improper Null Termination -static const CWE CWE_ARGUMENT_SIZE(398U); // Indicator of Poor Code Quality -static const CWE CWE_ARRAY_INDEX_THEN_CHECK(398U); // Indicator of Poor Code Quality -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE_POINTER_ARITHMETIC_OVERFLOW(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE_BUFFER_UNDERRUN(786U); // Access of Memory Location Before Start of Buffer -static const CWE CWE_BUFFER_OVERRUN(788U); // Access of Memory Location After End of Buffer //--------------------------------------------------------------------------- @@ -885,7 +876,7 @@ void CheckBufferOverrun::argumentSizeError(const Token *tok, const std::string & // CTU.. //--------------------------------------------------------------------------- -// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now +// a Clang-built executable will crash when using the anonymous MyFileInfoBufferOverrun later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckBufferOverrun_internal @@ -894,7 +885,7 @@ namespace #endif { /** data for multifile checking */ - class MyFileInfo : public Check::FileInfo { + class MyFileInfoBufferOverrun : public Check::FileInfo { public: /** unsafe array index usage */ std::list unsafeArrayIndex; @@ -954,7 +945,7 @@ Check::FileInfo *CheckBufferOverrun::getFileInfo(const Tokenizer *tokenizer, con if (unsafeArrayIndex.empty() && unsafePointerArith.empty()) { return nullptr; } - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoBufferOverrun; fileInfo->unsafeArrayIndex = unsafeArrayIndex; fileInfo->unsafePointerArith = unsafePointerArith; return fileInfo; @@ -966,7 +957,7 @@ Check::FileInfo * CheckBufferOverrun::loadFileInfoFromXml(const tinyxml2::XMLEle const std::string arrayIndex("array-index"); const std::string pointerArith("pointer-arith"); - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoBufferOverrun; for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) { if (e->Name() == arrayIndex) fileInfo->unsafeArrayIndex = CTU::loadUnsafeUsageListFromXml(e); @@ -997,7 +988,7 @@ bool CheckBufferOverrun::analyseWholeProgram(const CTU::FileInfo *ctu, const std const std::map> callsMap = ctu->getCallsMap(); for (const Check::FileInfo* fi1 : fileInfo) { - const MyFileInfo *fi = dynamic_cast(fi1); + const MyFileInfoBufferOverrun *fi = dynamic_cast(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeArrayIndex) diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp index 7e4d4adc443..279626856ca 100644 --- a/lib/checkclass.cpp +++ b/lib/checkclass.cpp @@ -48,16 +48,9 @@ namespace CTU { // Register CheckClass.. namespace { - CheckClass instance; + CheckClass instanceClass; } -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE404(404U); // Improper Resource Shutdown or Release -static const CWE CWE665(665U); // Improper Initialization -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE762(762U); // Mismatched Memory Management Routines - -static const CWE CWE_ONE_DEFINITION_RULE(758U); static const char * getFunctionTypeName(Function::Type type) { @@ -2632,7 +2625,7 @@ void CheckClass::checkConstError2(const Token *tok1, const Token *tok2, const st // ClassCheck: Check that initializer list is in declared order. //--------------------------------------------------------------------------- -namespace { // avoid one-definition-rule violation +namespace internal { // avoid one-definition-rule violation struct VarInfo { VarInfo(const Variable *_var, const Token *_tok) : var(_var), tok(_tok) {} @@ -2666,7 +2659,7 @@ void CheckClass::initializerListOrder() const Token *tok = func->arg->link()->next(); if (tok->str() == ":") { - std::vector vars; + std::vector vars; tok = tok->next(); // find all variable initializations in list @@ -3436,7 +3429,7 @@ void CheckClass::unsafeClassRefMemberError(const Token *tok, const std::string & CWE(0), Certainty::normal); } -// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now +// a Clang-built executable will crash when using the anonymous MyFileInfoClass later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckClass_internal @@ -3445,7 +3438,7 @@ namespace #endif { /* multifile checking; one definition rule violations */ - class MyFileInfo : public Check::FileInfo { + class MyFileInfoClass : public Check::FileInfo { public: struct NameLoc { std::string className; @@ -3485,7 +3478,7 @@ Check::FileInfo *CheckClass::getFileInfo(const Tokenizer *tokenizer, const Setti return nullptr; (void)settings; // One definition rule - std::vector classDefinitions; + std::vector classDefinitions; for (const Scope * classScope : tokenizer->getSymbolDatabase()->classAndStructScopes) { if (classScope->isAnonymous()) continue; @@ -3519,7 +3512,7 @@ Check::FileInfo *CheckClass::getFileInfo(const Tokenizer *tokenizer, const Setti if (scope->type != Scope::ScopeType::eGlobal) continue; - MyFileInfo::NameLoc nameLoc; + MyFileInfoClass::NameLoc nameLoc; nameLoc.className = std::move(name); nameLoc.fileName = tokenizer->list.file(classScope->classDef); nameLoc.lineNumber = classScope->classDef->linenr(); @@ -3543,14 +3536,14 @@ Check::FileInfo *CheckClass::getFileInfo(const Tokenizer *tokenizer, const Setti if (classDefinitions.empty()) return nullptr; - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoClass; fileInfo->classDefinitions.swap(classDefinitions); return fileInfo; } Check::FileInfo * CheckClass::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const { - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoClass; for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "class") != 0) continue; @@ -3560,7 +3553,7 @@ Check::FileInfo * CheckClass::loadFileInfoFromXml(const tinyxml2::XMLElement *xm const char *col = e->Attribute("col"); const char *hash = e->Attribute("hash"); if (name && file && line && col && hash) { - MyFileInfo::NameLoc nameLoc; + MyFileInfoClass::NameLoc nameLoc; nameLoc.className = name; nameLoc.fileName = file; nameLoc.lineNumber = strToInt(line); @@ -3582,17 +3575,17 @@ bool CheckClass::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list all; + std::unordered_map all; CheckClass dummy(nullptr, &settings, &errorLogger); dummy. logChecker("CheckClass::analyseWholeProgram"); for (const Check::FileInfo* fi1 : fileInfo) { - const MyFileInfo *fi = dynamic_cast(fi1); + const MyFileInfoClass *fi = dynamic_cast(fi1); if (!fi) continue; - for (const MyFileInfo::NameLoc &nameLoc : fi->classDefinitions) { + for (const MyFileInfoClass::NameLoc &nameLoc : fi->classDefinitions) { auto it = all.find(nameLoc.className); if (it == all.end()) { all[nameLoc.className] = nameLoc; diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp index b39b69cbd40..1d548635659 100644 --- a/lib/checkcondition.cpp +++ b/lib/checkcondition.cpp @@ -42,17 +42,12 @@ #include #include -// CWE ids used -static const CWE uncheckedErrorConditionCWE(391U); -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE570(570U); // Expression is Always False -static const CWE CWE571(571U); // Expression is Always True //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { - CheckCondition instance; + CheckCondition instanceCondition; } bool CheckCondition::diag(const Token* tok, bool insert) diff --git a/lib/checkexceptionsafety.cpp b/lib/checkexceptionsafety.cpp index bd217d8c545..0f1b6d123f7 100644 --- a/lib/checkexceptionsafety.cpp +++ b/lib/checkexceptionsafety.cpp @@ -34,12 +34,9 @@ // Register CheckExceptionSafety.. namespace { - CheckExceptionSafety instance; + CheckExceptionSafety instanceExceptionSafety; } -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE703(703U); // Improper Check or Handling of Exceptional Conditions -static const CWE CWE480(480U); // Use of Incorrect Operator //--------------------------------------------------------------------------- diff --git a/lib/checkfunctions.cpp b/lib/checkfunctions.cpp index 7c2a58eb0d4..67da35f2b5c 100644 --- a/lib/checkfunctions.cpp +++ b/lib/checkfunctions.cpp @@ -43,16 +43,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckFunctions instance; + CheckFunctions instanceFunctions; } -static const CWE CWE252(252U); // Unchecked Return Value -static const CWE CWE477(477U); // Use of Obsolete Functions -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments -static const CWE CWE686(686U); // Function Call With Incorrect Argument Type -static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value -static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument void CheckFunctions::checkProhibitedFunctions() { diff --git a/lib/checkinternal.cpp b/lib/checkinternal.cpp index b152389bad5..4d96f3136cb 100644 --- a/lib/checkinternal.cpp +++ b/lib/checkinternal.cpp @@ -32,7 +32,7 @@ // Register this check class (by creating a static instance of it). // Disabled in release builds namespace { - CheckInternal instance; + CheckInternal instanceInternal; } void CheckInternal::checkTokenMatchPatterns() diff --git a/lib/checkio.cpp b/lib/checkio.cpp index b4fc0a4abb6..d5bf6b082e1 100644 --- a/lib/checkio.cpp +++ b/lib/checkio.cpp @@ -47,18 +47,9 @@ // Register CheckIO.. namespace { - CheckIO instance; + CheckIO instanceIO; } -// CVE ID used: -static const CWE CWE119(119U); // Improper Restriction of Operations within the Bounds of a Memory Buffer -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime -static const CWE CWE685(685U); // Function Call With Incorrect Number of Arguments -static const CWE CWE686(686U); // Function Call With Incorrect Argument Type -static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value -static const CWE CWE704(704U); // Incorrect Type Conversion or Cast -static const CWE CWE910(910U); // Use of Expired File Descriptor //--------------------------------------------------------------------------- // std::cout << std::cout; diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp index 7ac325ac567..110c914b43b 100644 --- a/lib/checkleakautovar.cpp +++ b/lib/checkleakautovar.cpp @@ -47,12 +47,10 @@ // Register this check class (by creating a static instance of it) namespace { - CheckLeakAutoVar instance; + CheckLeakAutoVar instanceLeakAutoVar; } -static const CWE CWE672(672U); -static const CWE CWE415(415U); - +namespace leakAutoVar{ // Hardcoded allocation types (not from library) static constexpr int NEW_ARRAY = -2; static constexpr int NEW = -1; @@ -101,7 +99,7 @@ static bool isVarTokComparison(const Token * tok, const Token ** vartok, return astIsVariableComparison(tok, op.first, op.second, vartok); }); } - +} //--------------------------------------------------------------------------- void VarInfo::print() @@ -230,6 +228,7 @@ void CheckLeakAutoVar::check() } } +namespace leakAutoVar { static bool isVarUsedInTree(const Token *tok, nonneg int varid) { if (!tok) @@ -303,7 +302,7 @@ static const Token * isFunctionCall(const Token * nameToken) } return nullptr; } - +} bool CheckLeakAutoVar::checkScope(const Token * const startToken, VarInfo &varInfo, std::set notzero, @@ -424,7 +423,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, tokRightAstOperand = tokRightAstOperand->astOperand2() ? tokRightAstOperand->astOperand2() : tokRightAstOperand->astOperand1(); // is variable used in rhs? - if (isVarUsedInTree(tokRightAstOperand, varTok->varId())) + if (leakAutoVar::isVarUsedInTree(tokRightAstOperand, varTok->varId())) continue; // Variable has already been allocated => error @@ -432,7 +431,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, leakIfAllocated(varTok, varInfo); varInfo.erase(varTok->varId()); - if (!isLocalVarNoAutoDealloc(varTok, mTokenizer->isCPP())) + if (!leakAutoVar::isLocalVarNoAutoDealloc(varTok, mTokenizer->isCPP())) continue; // allocation? @@ -451,7 +450,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, const Token* tok2 = varTok->tokAt(2)->astOperand1(); const bool arrayNew = (tok2 && (tok2->str() == "[" || (Token::Match(tok2, "(|{") && tok2->astOperand1() && tok2->astOperand1()->str() == "["))); VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()]; - varAlloc.type = arrayNew ? NEW_ARRAY : NEW; + varAlloc.type = arrayNew ? leakAutoVar::NEW_ARRAY : leakAutoVar::NEW; varAlloc.status = VarInfo::ALLOC; varAlloc.allocTok = varTok->tokAt(2); } @@ -477,11 +476,11 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, continue; } // TODO: replace with checkTokenInsideExpression() - const Token* const openingPar = isFunctionCall(innerTok); + const Token* const openingPar = leakAutoVar::isFunctionCall(innerTok); if (!openingPar) checkTokenInsideExpression(innerTok, varInfo); - if (!isLocalVarNoAutoDealloc(innerTok, mTokenizer->isCPP())) + if (!leakAutoVar::isLocalVarNoAutoDealloc(innerTok, mTokenizer->isCPP())) continue; // Check assignments in the if-statement. Skip multiple assignments since we don't track those @@ -509,7 +508,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, const Token* tok2 = innerTok->tokAt(2)->astOperand1(); const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "["))); VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()]; - varAlloc.type = arrayNew ? NEW_ARRAY : NEW; + varAlloc.type = arrayNew ? leakAutoVar::NEW_ARRAY : leakAutoVar::NEW; varAlloc.status = VarInfo::ALLOC; varAlloc.allocTok = innerTok->tokAt(2); } @@ -551,8 +550,8 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, if (!par->isComparisonOp()) continue; const Token *vartok = nullptr; - if (isVarTokComparison(par, &vartok, alloc_success_conds) || - (isVarTokComparison(par, &vartok, alloc_failed_conds))) { + if (leakAutoVar::isVarTokComparison(par, &vartok, leakAutoVar::alloc_success_conds) || + (leakAutoVar::isVarTokComparison(par, &vartok, leakAutoVar::alloc_failed_conds))) { varInfo1.erase(vartok->varId()); varInfo2.erase(vartok->varId()); } @@ -561,13 +560,13 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, } const Token *vartok = nullptr; - if (isVarTokComparison(tok3, &vartok, alloc_success_conds)) { + if (leakAutoVar::isVarTokComparison(tok3, &vartok, leakAutoVar::alloc_success_conds)) { varInfo2.reallocToAlloc(vartok->varId()); varInfo2.erase(vartok->varId()); if (astIsVariableComparison(tok3, "!=", "0", &vartok) && (notzero.find(vartok->varId()) != notzero.end())) varInfo2.clear(); - } else if (isVarTokComparison(tok3, &vartok, alloc_failed_conds)) { + } else if (leakAutoVar::isVarTokComparison(tok3, &vartok, leakAutoVar::alloc_failed_conds)) { varInfo1.reallocToAlloc(vartok->varId()); varInfo1.erase(vartok->varId()); } @@ -686,13 +685,13 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, tok = tok->tokAt(2); const bool isnull = tok->hasKnownIntValue() && tok->values().front().intvalue == 0; if (!isnull && tok->varId() && tok->strAt(1) != "[") { - const VarInfo::AllocInfo allocation(arrayDelete ? NEW_ARRAY : NEW, VarInfo::DEALLOC, delTok); + const VarInfo::AllocInfo allocation(arrayDelete ? leakAutoVar::NEW_ARRAY : leakAutoVar::NEW, VarInfo::DEALLOC, delTok); changeAllocStatus(varInfo, allocation, tok, tok); } } // Function call.. - else if (const Token* openingPar = isFunctionCall(ftok)) { + else if (const Token* openingPar = leakAutoVar::isFunctionCall(ftok)) { const Library::AllocFunc* af = mSettings->library.getDeallocFuncInfo(ftok); VarInfo::AllocInfo allocation(af ? af->groupId : 0, VarInfo::DEALLOC, ftok); if (allocation.type == 0) @@ -747,7 +746,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, tok = typeEndTok->linkAt(2); const int varid = typeEndTok->next()->varId(); - if (isPointerReleased(typeEndTok->tokAt(2), endToken, varid)) + if (leakAutoVar::isPointerReleased(typeEndTok->tokAt(2), endToken, varid)) continue; bool arrayDelete = false; @@ -816,7 +815,7 @@ bool CheckLeakAutoVar::checkScope(const Token * const startToken, } const Token * vtok = typeEndTok->tokAt(3); - const VarInfo::AllocInfo allocation(af ? af->groupId : (arrayDelete ? NEW_ARRAY : NEW), VarInfo::OWNED, ftok); + const VarInfo::AllocInfo allocation(af ? af->groupId : (arrayDelete ? leakAutoVar::NEW_ARRAY : leakAutoVar::NEW), VarInfo::OWNED, ftok); changeAllocStatus(varInfo, allocation, vtok, vtok); } else if (Token::Match(tok, "%var% .")) checkTokenInsideExpression(tok, varInfo); @@ -876,7 +875,7 @@ const Token * CheckLeakAutoVar::checkTokenInsideExpression(const Token * const t } // check for function call - const Token * const openingPar = inFuncCall ? nullptr : isFunctionCall(tok); + const Token * const openingPar = inFuncCall ? nullptr : leakAutoVar::isFunctionCall(tok); if (openingPar) { const Library::AllocFunc* allocFunc = mSettings->library.getDeallocFuncInfo(tok); VarInfo::AllocInfo alloc(allocFunc ? allocFunc->groupId : 0, VarInfo::DEALLOC, tok); @@ -1058,7 +1057,7 @@ void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpenin } const Token * vtok = typeEndTok->tokAt(2); - const VarInfo::AllocInfo sp_allocation(sp_af ? sp_af->groupId : (arrayDelete ? NEW_ARRAY : NEW), VarInfo::OWNED, allocTok); + const VarInfo::AllocInfo sp_allocation(sp_af ? sp_af->groupId : (arrayDelete ? leakAutoVar::NEW_ARRAY : leakAutoVar::NEW), VarInfo::OWNED, allocTok); changeAllocStatus(varInfo, sp_allocation, vtok, vtok); } else { const Token* const nextArg = funcArg->nextArgument(); @@ -1093,6 +1092,7 @@ void CheckLeakAutoVar::leakIfAllocated(const Token *vartok, } } +namespace leakAutoVar{ static const Token* getOutparamAllocation(const Token* tok, const Settings* settings) { if (!tok) @@ -1107,7 +1107,7 @@ static const Token* getOutparamAllocation(const Token* tok, const Settings* sett } return nullptr; } - +} void CheckLeakAutoVar::ret(const Token *tok, VarInfo &varInfo, const bool isEndOfScope) { const std::map &alloctype = varInfo.alloctype; @@ -1164,7 +1164,7 @@ void CheckLeakAutoVar::ret(const Token *tok, VarInfo &varInfo, const bool isEndO // don't warn when returning after checking return value of outparam allocation const Token* outparamFunc{}; if ((tok->scope()->type == Scope::ScopeType::eIf || tok->scope()->type== Scope::ScopeType::eElse) && - (outparamFunc = getOutparamAllocation(it->second.allocTok, mSettings))) { + (outparamFunc = leakAutoVar::getOutparamAllocation(it->second.allocTok, mSettings))) { const Scope* scope = tok->scope(); if (scope->type == Scope::ScopeType::eElse) { scope = scope->bodyStart->tokAt(-2)->scope(); diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp index 28542238444..373463d2f10 100644 --- a/lib/checkmemoryleak.cpp +++ b/lib/checkmemoryleak.cpp @@ -44,11 +44,6 @@ namespace { CheckMemoryLeakNoVar instance4; } -// CWE ID used: -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE401(401U); // Improper Release of Memory Before Removing Last Reference ('Memory Leak') -static const CWE CWE771(771U); // Missing Reference to Active Allocated Resource -static const CWE CWE772(772U); // Missing Release of Resource after Effective Lifetime //--------------------------------------------------------------------------- diff --git a/lib/checknullpointer.cpp b/lib/checknullpointer.cpp index cec36ee06dd..ef3d40c6ce3 100644 --- a/lib/checknullpointer.cpp +++ b/lib/checknullpointer.cpp @@ -40,13 +40,10 @@ //--------------------------------------------------------------------------- -// CWE ids used: -static const CWE CWE_NULL_POINTER_DEREFERENCE(476U); -static const CWE CWE_INCORRECT_CALCULATION(682U); // Register this check class (by creating a static instance of it) namespace { - CheckNullPointer instance; + CheckNullPointer instanceNullPointer; } //--------------------------------------------------------------------------- @@ -558,7 +555,7 @@ static bool isUnsafeUsage(const Settings *settings, const Token *vartok, MathLib return CheckNullPointer::isPointerDeRef(vartok, unknown, settings); } -// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now +// a Clang-built executable will crash when using the anonymous MyFileInfoNullPointer later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckNullPointer_internal @@ -567,7 +564,7 @@ namespace #endif { /* data for multifile checking */ - class MyFileInfo : public Check::FileInfo { + class MyFileInfoNullPointer : public Check::FileInfo { public: /** function arguments that are dereferenced without checking if they are null */ std::list unsafeUsage; @@ -586,7 +583,7 @@ Check::FileInfo *CheckNullPointer::getFileInfo(const Tokenizer *tokenizer, const if (unsafeUsage.empty()) return nullptr; - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoNullPointer; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } @@ -597,7 +594,7 @@ Check::FileInfo * CheckNullPointer::loadFileInfoFromXml(const tinyxml2::XMLEleme if (unsafeUsage.empty()) return nullptr; - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoNullPointer; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } @@ -616,7 +613,7 @@ bool CheckNullPointer::analyseWholeProgram(const CTU::FileInfo *ctu, const std:: const std::map> callsMap = ctu->getCallsMap(); for (const Check::FileInfo* fi1 : fileInfo) { - const MyFileInfo *fi = dynamic_cast(fi1); + const MyFileInfoNullPointer *fi = dynamic_cast(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) { diff --git a/lib/checkother.cpp b/lib/checkother.cpp index 6eb877a6b70..4b5ee6dcd81 100644 --- a/lib/checkother.cpp +++ b/lib/checkother.cpp @@ -48,27 +48,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckOther instance; -} - -static const CWE CWE128(128U); // Wrap-around Error -static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size -static const CWE CWE197(197U); // Numeric Truncation Error -static const CWE CWE362(362U); // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') -static const CWE CWE369(369U); // Divide By Zero -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE475(475U); // Undefined Behavior for Input to API -static const CWE CWE561(561U); // Dead Code -static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable') -static const CWE CWE570(570U); // Expression is Always False -static const CWE CWE571(571U); // Expression is Always True -static const CWE CWE672(672U); // Operation on a Resource after Expiration or Release -static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments -static const CWE CWE683(683U); // Function Call With Incorrect Order of Arguments -static const CWE CWE704(704U); // Incorrect Type Conversion or Cast -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation -static const CWE CWE783(783U); // Operator Precedence Logic Error + CheckOther instanceOther; +} + //---------------------------------------------------------------------------------- // The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value. diff --git a/lib/checkpostfixoperator.cpp b/lib/checkpostfixoperator.cpp index eb8d57a39e2..b400cfebaa8 100644 --- a/lib/checkpostfixoperator.cpp +++ b/lib/checkpostfixoperator.cpp @@ -35,12 +35,10 @@ // Register this check class (by creating a static instance of it) namespace { - CheckPostfixOperator instance; + CheckPostfixOperator instancePostfixOperator; } -// CWE ids used -static const CWE CWE398(398U); // Indicator of Poor Code Quality void CheckPostfixOperator::postfixOperator() diff --git a/lib/checksizeof.cpp b/lib/checksizeof.cpp index 848b8946cbe..54c5bd2ce49 100644 --- a/lib/checksizeof.cpp +++ b/lib/checksizeof.cpp @@ -36,12 +36,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckSizeof instance; + CheckSizeof instanceSizeof; } -// CWE IDs used: -static const CWE CWE467(467U); // Use of sizeof() on a Pointer Type -static const CWE CWE682(682U); // Incorrect Calculation //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- void CheckSizeof::checkSizeofForNumericParameter() diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp index 3f740c2a98f..027c9e2ff31 100644 --- a/lib/checkstl.cpp +++ b/lib/checkstl.cpp @@ -47,22 +47,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckStl instance; -} - -// CWE IDs used: -static const CWE CWE398(398U); // Indicator of Poor Code Quality -static const CWE CWE597(597U); // Use of Wrong Operator in String Comparison -static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments -static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime -static const CWE CWE667(667U); // Improper Locking -static const CWE CWE704(704U); // Incorrect Type Conversion or Cast -static const CWE CWE762(762U); // Mismatched Memory Management Routines -static const CWE CWE786(786U); // Access of Memory Location Before Start of Buffer -static const CWE CWE788(788U); // Access of Memory Location After End of Buffer -static const CWE CWE825(825U); // Expired Pointer Dereference -static const CWE CWE833(833U); // Deadlock -static const CWE CWE834(834U); // Excessive Iteration + CheckStl instanceStl; +} + static bool isElementAccessYield(Library::Container::Yield yield) { diff --git a/lib/checkstring.cpp b/lib/checkstring.cpp index cc9a5939896..c634cd9b3d3 100644 --- a/lib/checkstring.cpp +++ b/lib/checkstring.cpp @@ -38,16 +38,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckString instance; + CheckString instanceString; } -// CWE ids used: -static const CWE CWE570(570U); // Expression is Always False -static const CWE CWE571(571U); // Expression is Always True -static const CWE CWE595(595U); // Comparison of Object References Instead of Object Contents -static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments -static const CWE CWE665(665U); // Improper Initialization -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior //--------------------------------------------------------------------------- // Writing string literal is UB diff --git a/lib/checktype.cpp b/lib/checktype.cpp index 344f752f96d..2524076c00b 100644 --- a/lib/checktype.cpp +++ b/lib/checktype.cpp @@ -43,7 +43,7 @@ // Register this check class (by creating a static instance of it) namespace { - CheckType instance; + CheckType instanceType; } //--------------------------------------------------------------------------- @@ -51,11 +51,6 @@ namespace { //--------------------------------------------------------------------------- // -// CWE ids used: -static const CWE CWE195(195U); // Signed to Unsigned Conversion Error -static const CWE CWE197(197U); // Numeric Truncation Error -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior -static const CWE CWE190(190U); // Integer Overflow or Wraparound void CheckType::checkTooBigBitwiseShift() diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp index e12e8047ed9..6dbea17f855 100644 --- a/lib/checkuninitvar.cpp +++ b/lib/checkuninitvar.cpp @@ -48,12 +48,10 @@ namespace tinyxml2 { //--------------------------------------------------------------------------- -// CWE ids used: -static const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE(457U); // Register this check class (by creating a static instance of it) namespace { - CheckUninitVar instance; + CheckUninitVar instanceUninitVar; } //--------------------------------------------------------------------------- @@ -1679,7 +1677,7 @@ static bool isVariableUsage(const Settings *settings, const Token *vartok, MathL return CheckUninitVar::isVariableUsage(vartok, settings->library, true, CheckUninitVar::Alloc::ARRAY); } -// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now +// a Clang-built executable will crash when using the anonymous MyFileInfoUninitVar later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckUninitVar_internal @@ -1688,7 +1686,7 @@ namespace #endif { /* data for multifile checking */ - class MyFileInfo : public Check::FileInfo { + class MyFileInfoUninitVar : public Check::FileInfo { public: /** function arguments that data are unconditionally read */ std::list unsafeUsage; @@ -1707,7 +1705,7 @@ Check::FileInfo *CheckUninitVar::getFileInfo(const Tokenizer *tokenizer, const S if (unsafeUsage.empty()) return nullptr; - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoUninitVar; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } @@ -1718,7 +1716,7 @@ Check::FileInfo * CheckUninitVar::loadFileInfoFromXml(const tinyxml2::XMLElement if (unsafeUsage.empty()) return nullptr; - auto *fileInfo = new MyFileInfo; + auto *fileInfo = new MyFileInfoUninitVar; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } @@ -1733,7 +1731,7 @@ bool CheckUninitVar::analyseWholeProgram(const CTU::FileInfo *ctu, const std::li const std::map> callsMap = ctu->getCallsMap(); for (const Check::FileInfo* fi1 : fileInfo) { - const MyFileInfo *fi = dynamic_cast(fi1); + const MyFileInfoUninitVar *fi = dynamic_cast(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) { diff --git a/lib/checkunusedfunctions.cpp b/lib/checkunusedfunctions.cpp index fdc2789d321..26af0efb7ed 100644 --- a/lib/checkunusedfunctions.cpp +++ b/lib/checkunusedfunctions.cpp @@ -45,7 +45,6 @@ //--------------------------------------------------------------------------- -static const CWE CWE561(561U); // Dead Code static std::string stripTemplateParameters(const std::string& funcName) { std::string name = funcName; @@ -307,7 +306,7 @@ static bool isOperatorFunction(const std::string & funcName) return std::find(additionalOperators.cbegin(), additionalOperators.cend(), funcName.substr(operatorPrefix.length())) != additionalOperators.cend(); } -#define logChecker(id) \ +#define logChecker_macro(id) \ do { \ const ErrorMessage errmsg({}, nullptr, Severity::internal, "logChecker", (id), CWE(0U), Certainty::normal); \ errorLogger.reportErr(errmsg); \ @@ -315,7 +314,7 @@ static bool isOperatorFunction(const std::string & funcName) bool CheckUnusedFunctions::check(const Settings& settings, ErrorLogger& errorLogger) const { - logChecker("CheckUnusedFunctions::check"); // unusedFunction + logChecker_macro("CheckUnusedFunctions::check"); // unusedFunction using ErrorParams = std::tuple; std::vector errors; // ensure well-defined order diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp index d7e4f4bf55e..62fd1693e7f 100644 --- a/lib/checkunusedvar.cpp +++ b/lib/checkunusedvar.cpp @@ -40,11 +40,9 @@ // Register this check class (by creating a static instance of it) namespace { - CheckUnusedVar instance; + CheckUnusedVar instanceUnusedVar; } -static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable') -static const CWE CWE665(665U); // Improper Initialization /** Is scope a raii class scope */ static bool isRaiiClassScope(const Scope *classScope) diff --git a/lib/checkvaarg.cpp b/lib/checkvaarg.cpp index 3606a4f3432..8a64848eeda 100644 --- a/lib/checkvaarg.cpp +++ b/lib/checkvaarg.cpp @@ -34,7 +34,7 @@ // Register this check class (by creating a static instance of it) namespace { - CheckVaarg instance; + CheckVaarg instanceVaarg; } @@ -42,10 +42,6 @@ namespace { // Ensure that correct parameter is passed to va_start() //--------------------------------------------------------------------------- -// CWE ids used: -static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime -static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument -static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior void CheckVaarg::va_start_argument() { diff --git a/lib/cppcheck.cpp b/lib/cppcheck.cpp index 224c5a3b74e..e189d8197d9 100644 --- a/lib/cppcheck.cpp +++ b/lib/cppcheck.cpp @@ -88,8 +88,6 @@ static constexpr char FILELIST[] = "cppcheck-addon-ctu-file-list"; static TimerResults s_timerResults; -// CWE ids used -static const CWE CWE398(398U); // Indicator of Poor Code Quality // File deleter namespace { diff --git a/lib/errortypes.cpp b/lib/errortypes.cpp index 00345a59f3b..f22c2e7c903 100644 --- a/lib/errortypes.cpp +++ b/lib/errortypes.cpp @@ -96,3 +96,67 @@ Severity severityFromString(const std::string& severity) return Severity::internal; return Severity::none; } + +const CWE CWE119(119U); // Improper Restriction of Operations within the Bounds of a Memory Buffer +const CWE CWE128(128U); // Wrap-around Error +const CWE CWE131(131U); // Incorrect Calculation of Buffer Size +const CWE CWE170(170U); // Improper Null Termination +const CWE CWE190(190U); // Integer Overflow or Wraparound +const CWE CWE195(195U); // Signed to Unsigned Conversion Error +const CWE CWE197(197U); // Numeric Truncation Error +const CWE CWE252(252U); // Unchecked Return Value +const CWE CWE362(362U); // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') +const CWE CWE369(369U); // Divide By Zero +const CWE CWE398(398U); // Indicator of Poor Code Quality +const CWE CWE401(401U); // Improper Release of Memory Before Removing Last Reference ('Memory Leak') +const CWE CWE404(404U); // Improper Resource Shutdown or Release +const CWE CWE415(415U); +const CWE CWE467(467U); // Use of sizeof() on a Pointer Type +const CWE CWE475(475U); // Undefined Behavior for Input to API +const CWE CWE477(477U); // Use of Obsolete Functions +const CWE CWE480(480U); // Use of Incorrect Operator +const CWE CWE561(561U); // Dead Code +const CWE CWE562(562U); // Return of Stack Variable Address +const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable') +const CWE CWE570(570U); // Expression is Always False +const CWE CWE571(571U); // Expression is Always True +const CWE CWE587(587U); // Assignment of a Fixed Address to a Pointer +const CWE CWE590(590U); // Free of Memory not on the Heap +const CWE CWE595(595U); // Comparison of Object References Instead of Object Contents +const CWE CWE597(597U); // Use of Wrong Operator in String Comparison +const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments +const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime +const CWE CWE665(665U); // Improper Initialization +const CWE CWE667(667U); // Improper Locking +const CWE CWE672(672U); // Operation on a Resource after Expiration or Release +const CWE CWE682(682U); // Incorrect Calculation +const CWE CWE683(683U); // Function Call With Incorrect Order of Arguments +const CWE CWE685(685U); // Function Call With Incorrect Number of Arguments +const CWE CWE686(686U); // Function Call With Incorrect Argument Type +const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value +const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument +const CWE CWE703(703U); // Improper Check or Handling of Exceptional Conditions +const CWE CWE704(704U); // Incorrect Type Conversion or Cast +const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior +const CWE CWE762(762U); // Mismatched Memory Management Routines +const CWE CWE768(768U); // Incorrect Short Circuit Evaluation +const CWE CWE771(771U); // Missing Reference to Active Allocated Resource +const CWE CWE772(772U); // Missing Release of Resource after Effective Lifetime +const CWE CWE783(783U); // Operator Precedence Logic Error +const CWE CWE786(786U); // Access of Memory Location Before Start of Buffer +const CWE CWE788(788U); // Access of Memory Location After End of Buffer +const CWE CWE825(825U); // Expired Pointer Dereference +const CWE CWE833(833U); // Deadlock +const CWE CWE834(834U); // Excessive Iteration +const CWE CWE910(910U); // Use of Expired File Descriptor + +const CWE CWE_ARGUMENT_SIZE(398U); // Indicator of Poor Code Quality +const CWE CWE_ARRAY_INDEX_THEN_CHECK(398U); // Indicator of Poor Code Quality +const CWE CWE_BUFFER_OVERRUN(788U); // Access of Memory Location After End of Buffer +const CWE CWE_BUFFER_UNDERRUN(786U); // Access of Memory Location Before Start of Buffer +const CWE CWE_INCORRECT_CALCULATION(682U); +const CWE CWE_NULL_POINTER_DEREFERENCE(476U); +const CWE CWE_ONE_DEFINITION_RULE(758U); +const CWE CWE_POINTER_ARITHMETIC_OVERFLOW(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior +const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE(457U); +const CWE uncheckedErrorConditionCWE(391U); diff --git a/lib/errortypes.h b/lib/errortypes.h index 3e9a6a41426..d7d4006582e 100644 --- a/lib/errortypes.h +++ b/lib/errortypes.h @@ -126,6 +126,71 @@ struct CWE { unsigned short id; }; +extern const CWE CWE119; // Improper Restriction of Operations within the Bounds of a Memory Buffer +extern const CWE CWE128; // Wrap-around Error +extern const CWE CWE131; // Incorrect Calculation of Buffer Size +extern const CWE CWE170; // Improper Null Termination +extern const CWE CWE190; // Integer Overflow or Wraparound +extern const CWE CWE195; // Signed to Unsigned Conversion Error +extern const CWE CWE197; // Numeric Truncation Error +extern const CWE CWE252; // Unchecked Return Value +extern const CWE CWE362; // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') +extern const CWE CWE369; // Divide By Zero +extern const CWE CWE398; // Indicator of Poor Code Quality +extern const CWE CWE401; // Improper Release of Memory Before Removing Last Reference ('Memory Leak') +extern const CWE CWE404; // Improper Resource Shutdown or Release +extern const CWE CWE415; +extern const CWE CWE467; // Use of sizeof() on a Pointer Type +extern const CWE CWE475; // Undefined Behavior for Input to API +extern const CWE CWE477; // Use of Obsolete Functions +extern const CWE CWE480; // Use of Incorrect Operator +extern const CWE CWE561; // Dead Code +extern const CWE CWE562; // Return of Stack Variable Address +extern const CWE CWE563; // Assignment to Variable without Use ('Unused Variable') +extern const CWE CWE570; // Expression is Always False +extern const CWE CWE571; // Expression is Always True +extern const CWE CWE587; // Assignment of a Fixed Address to a Pointer +extern const CWE CWE590; // Free of Memory not on the Heap +extern const CWE CWE595; // Comparison of Object References Instead of Object Contents +extern const CWE CWE597; // Use of Wrong Operator in String Comparison +extern const CWE CWE628; // Function Call with Incorrectly Specified Arguments +extern const CWE CWE664; // Improper Control of a Resource Through its Lifetime +extern const CWE CWE665; // Improper Initialization +extern const CWE CWE667; // Improper Locking +extern const CWE CWE672; // Operation on a Resource after Expiration or Release +extern const CWE CWE682; // Incorrect Calculation +extern const CWE CWE683; // Function Call With Incorrect Order of Arguments +extern const CWE CWE685; // Function Call With Incorrect Number of Arguments +extern const CWE CWE686; // Function Call With Incorrect Argument Type +extern const CWE CWE687; // Function Call With Incorrectly Specified Argument Value +extern const CWE CWE688; // Function Call With Incorrect Variable or Reference as Argument +extern const CWE CWE703; // Improper Check or Handling of Exceptional Conditions +extern const CWE CWE704; // Incorrect Type Conversion or Cast +extern const CWE CWE758; // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior +extern const CWE CWE762; // Mismatched Memory Management Routines +extern const CWE CWE768; // Incorrect Short Circuit Evaluation +extern const CWE CWE771; // Missing Reference to Active Allocated Resource +extern const CWE CWE772; // Missing Release of Resource after Effective Lifetime +extern const CWE CWE783; // Operator Precedence Logic Error +extern const CWE CWE786; // Access of Memory Location Before Start of Buffer +extern const CWE CWE788; // Access of Memory Location After End of Buffer +extern const CWE CWE825; // Expired Pointer Dereference +extern const CWE CWE833; // Deadlock +extern const CWE CWE834; // Excessive Iteration +extern const CWE CWE910; // Use of Expired File Descriptor + +extern const CWE CWE_ARGUMENT_SIZE; // Indicator of Poor Code Quality +extern const CWE CWE_ARRAY_INDEX_THEN_CHECK; // Indicator of Poor Code Quality +extern const CWE CWE_BUFFER_OVERRUN; // Access of Memory Location After End of Buffer +extern const CWE CWE_BUFFER_UNDERRUN; // Access of Memory Location Before Start of Buffer +extern const CWE CWE_INCORRECT_CALCULATION; +extern const CWE CWE_NULL_POINTER_DEREFERENCE; +extern const CWE CWE_ONE_DEFINITION_RULE; +extern const CWE CWE_POINTER_ARITHMETIC_OVERFLOW; // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior +extern const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE; +extern const CWE uncheckedErrorConditionCWE; + + using ErrorPathItem = std::pair; using ErrorPath = std::list; diff --git a/lib/forwardanalyzer.cpp b/lib/forwardanalyzer.cpp index 0dfe80895f8..a27afc715b8 100644 --- a/lib/forwardanalyzer.cpp +++ b/lib/forwardanalyzer.cpp @@ -43,7 +43,7 @@ #include #include -namespace { +namespace forwardAnalyzer{ struct ForwardTraversal { enum class Progress { Continue, Break, Skip }; enum class Terminate { None, Bail, Inconclusive }; @@ -908,7 +908,7 @@ Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const V { if (a->invalid()) return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail}; - ForwardTraversal ft{a, tokenList, errorLogger, settings}; + forwardAnalyzer::ForwardTraversal ft{a, tokenList, errorLogger, settings}; if (start) ft.analyzer->updateState(start); ft.updateRange(start, end); @@ -921,7 +921,7 @@ Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr& throw TerminateException(); if (a->invalid()) return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail}; - ForwardTraversal ft{a, tokenList, errorLogger, settings}; + forwardAnalyzer::ForwardTraversal ft{a, tokenList, errorLogger, settings}; ft.updateRecursive(start); return Analyzer::Result{ ft.actions, ft.terminate }; } diff --git a/lib/token.cpp b/lib/token.cpp index 0a2024aee76..f465362d273 100644 --- a/lib/token.cpp +++ b/lib/token.cpp @@ -940,7 +940,7 @@ const Token* Token::nextTemplateArgument() const return nullptr; } -static bool isOperator(const Token *tok) +static bool isOperator2(const Token *tok) { if (tok->link()) tok = tok->link(); @@ -985,7 +985,7 @@ const Token * Token::findClosingBracket() const return nullptr; // we can make some guesses for template parameters else if (closing->str() == "<" && closing->previous() && - (closing->previous()->isName() || Token::simpleMatch(closing->previous(), "]") || isOperator(closing->previous())) && + (closing->previous()->isName() || Token::simpleMatch(closing->previous(), "]") || isOperator2(closing->previous())) && (templateParameter ? templateParameters.find(closing->strAt(-1)) == templateParameters.end() : true)) ++depth; else if (closing->str() == ">") { diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp index 2c734df9925..39b8969b306 100644 --- a/lib/valueflow.cpp +++ b/lib/valueflow.cpp @@ -2242,7 +2242,7 @@ static const std::string& invertAssign(const std::string& assign) return it->second; } -static std::string removeAssign(const std::string& assign) { +static std::string removeAssign2(const std::string& assign) { return std::string{assign.cbegin(), assign.cend() - 1}; } @@ -2256,7 +2256,7 @@ static T calculateAssign(const std::string& assign, const T& x, const U& y, bool } if (assign == "=") return y; - return calculate(removeAssign(assign), x, y, error); + return calculate(removeAssign2(assign), x, y, error); } template diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 4ec673ba152..9abf8d9c1a0 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -12,6 +12,8 @@ if (BUILD_TESTS) endif() add_executable(testrunner ${testrunner_SOURCES}) + # disable unity build for tests because some macros conflict with macros + set_target_properties(testrunner PROPERTIES UNITY_BUILD OFF) target_include_directories(testrunner PRIVATE ${PROJECT_SOURCE_DIR}/lib/ ${PROJECT_SOURCE_DIR}/cli/) if(USE_BUNDLED_TINYXML2) target_externals_include_directories(testrunner PRIVATE ${PROJECT_SOURCE_DIR}/externals/tinyxml2) diff --git a/tools/matchcompiler.py b/tools/matchcompiler.py index 2544366965a..06218af55a4 100755 --- a/tools/matchcompiler.py +++ b/tools/matchcompiler.py @@ -206,7 +206,7 @@ def _compilePattern(self, pattern, nr, varid, arg2 = ', const int varid' ret = '// pattern: ' + pattern + '\n' - ret += 'static inline bool match' + \ + ret += 'static inline bool match' + str(abs(hash(pattern))) + \ str(nr) + '(' + tokenType + '* tok' + arg2 + ') {\n' returnStatement = 'return false;\n' @@ -290,7 +290,7 @@ def _compileFindPattern(self, pattern, findmatchnr, endToken, varId): more_args += ', int varid' ret = '// pattern: ' + pattern + '\n' - ret += 'template static inline T * findmatch' + \ + ret += 'template static inline T * findmatch'+ str(abs(hash(pattern))) + \ str(findmatchnr) + '(T * start_tok' + more_args + ') {\n' ret += ' for (; start_tok' + endCondition + \ '; start_tok = start_tok->next()) {\n' @@ -432,7 +432,7 @@ def _replaceSpecificTokenMatch( self._rawMatchFunctions.append( self._compilePattern(pattern, patternNumber, varId)) - functionName = "match" + functionName = "match"+ str(abs(hash(pattern))) if self._verifyMode: verifyNumber = len(self._rawMatchFunctions) + 1 self._rawMatchFunctions.append( @@ -572,7 +572,7 @@ def _replaceSpecificFindTokenMatch( endToken, varId)) - functionName = "findmatch" + functionName = "findmatch"+ str(abs(hash(pattern))) if self._verifyMode: verifyNumber = len(self._rawMatchFunctions) + 1 self._rawMatchFunctions.append(