From 6c588cc3efe4bf14f7c4d4dd503dceef8b26f16a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 28 Jun 2020 21:00:50 +0200
Subject: [PATCH 001/116] Library: Refactoring init attribute
---
lib/checkuninitvar.cpp | 31 ++++++++++++++++++-------------
lib/library.cpp | 4 +++-
lib/library.h | 2 +-
test/testlibrary.cpp | 4 +---
4 files changed, 23 insertions(+), 18 deletions(-)
diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp
index 03323abfc..e46f94304 100644
--- a/lib/checkuninitvar.cpp
+++ b/lib/checkuninitvar.cpp
@@ -173,15 +173,18 @@ void CheckUninitVar::checkScope(const Scope* scope, const std::set
if (arg.declarationId() && Token::Match(arg.typeStartToken(), "%type% * %name% [,)]")) {
// Treat the pointer as initialized until it is assigned by malloc
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
- if (Token::Match(tok, "[;{}] %varid% = %name% (", arg.declarationId()) &&
- mSettings->library.returnuninitdata.count(tok->strAt(3)) == 1U) {
- if (arg.typeStartToken()->strAt(-1) == "struct" || (arg.type() && arg.type()->isStructType()))
- checkStruct(tok, arg);
- else if (arg.typeStartToken()->isStandardType() || arg.typeStartToken()->isEnumType()) {
- Alloc alloc = NO_ALLOC;
- const std::map variableValue;
- checkScopeForVariable(tok->next(), arg, nullptr, nullptr, &alloc, emptyString, variableValue);
- }
+ if (!Token::Match(tok, "[;{}] %varid% = %name% (", arg.declarationId()))
+ continue;
+ const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(tok->tokAt(3));
+ if (!allocFunc || allocFunc->initData)
+ continue;
+
+ if (arg.typeStartToken()->strAt(-1) == "struct" || (arg.type() && arg.type()->isStructType()))
+ checkStruct(tok, arg);
+ else if (arg.typeStartToken()->isStandardType() || arg.typeStartToken()->isEnumType()) {
+ Alloc alloc = NO_ALLOC;
+ const std::map variableValue;
+ checkScopeForVariable(tok->next(), arg, nullptr, nullptr, &alloc, emptyString, variableValue);
}
}
}
@@ -716,10 +719,12 @@ bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var
const Token *rhs = tok->next()->astOperand2();
while (rhs && rhs->isCast())
rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1();
- if (rhs && Token::Match(rhs->previous(), "%name% (") &&
- mSettings->library.returnuninitdata.count(rhs->previous()->str()) > 0U) {
- *alloc = NO_CTOR_CALL;
- continue;
+ if (rhs && Token::Match(rhs->previous(), "%name% (")) {
+ const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(rhs->astOperand1());
+ if (allocFunc && !allocFunc->initData) {
+ *alloc = NO_CTOR_CALL;
+ continue;
+ }
}
}
if (mTokenizer->isCPP() && var.isPointer() && (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType() || (var.type() && var.type()->needInitialization == Type::NeedInitialization::True)) && Token::simpleMatch(tok->next(), "= new")) {
diff --git a/lib/library.cpp b/lib/library.cpp
index f5192a0ca..5d4da2949 100644
--- a/lib/library.cpp
+++ b/lib/library.cpp
@@ -194,7 +194,9 @@ Library::Error Library::load(const tinyxml2::XMLDocument &doc)
temp.groupId = allocationId;
if (memorynode->Attribute("init", "false"))
- returnuninitdata.insert(memorynode->GetText());
+ temp.initData = false;
+ else
+ temp.initData = true;
const char *arg = memorynode->Attribute("arg");
if (arg)
diff --git a/lib/library.h b/lib/library.h
index f7975faa9..53bdbfe6d 100644
--- a/lib/library.h
+++ b/lib/library.h
@@ -78,6 +78,7 @@ public:
int bufferSizeArg1;
int bufferSizeArg2;
int reallocArg;
+ bool initData;
};
/** get allocation info for function */
@@ -418,7 +419,6 @@ public:
return -1;
}
- std::set returnuninitdata;
std::vector defines; // to provide some library defines
std::set smartPointers;
diff --git a/test/testlibrary.cpp b/test/testlibrary.cpp
index 606149599..d34d4d88f 100644
--- a/test/testlibrary.cpp
+++ b/test/testlibrary.cpp
@@ -686,11 +686,9 @@ private:
ASSERT(library.functions.empty());
const Library::AllocFunc* af = library.getAllocFuncInfo("CreateX");
- ASSERT(af && af->arg == 5);
+ ASSERT(af && af->arg == 5 && !af->initData);
const Library::AllocFunc* df = library.getDeallocFuncInfo("DeleteX");
ASSERT(df && df->arg == 2);
-
- ASSERT(library.returnuninitdata.find("CreateX") != library.returnuninitdata.cend());
}
void resource() const {
From ad5e4fef1f0dacb83ec50153b3af12da3efdc5a8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 28 Jun 2020 21:20:59 +0200
Subject: [PATCH 002/116] Bug hunting; improved handling of 'malloc' in uninit
checker
---
lib/exprengine.cpp | 12 ++++++++++++
test/testbughuntingchecks.cpp | 12 ++++++++++--
2 files changed, 22 insertions(+), 2 deletions(-)
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index b47b16ea2..65b928f5e 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -1887,6 +1887,18 @@ static ExprEngine::ValuePtr executeFunctionCall(const Token *tok, Data &data)
}
}
+ else if (const auto *f = data.settings->library.getAllocFuncInfo(tok->astOperand1())) {
+ if (!f->initData) {
+ const std::string name = data.getNewSymbolName();
+ auto size = std::make_shared(data.getNewSymbolName(), 1, ~0U);
+ auto val = std::make_shared();
+ auto result = std::make_shared(name, size, val, false, false, false);
+ call(data.callbacks, tok, result, &data);
+ data.functionCall();
+ return result;
+ }
+ }
+
auto val = getValueRangeFromValueType(tok->valueType(), data);
call(data.callbacks, tok, val, &data);
data.functionCall();
diff --git a/test/testbughuntingchecks.cpp b/test/testbughuntingchecks.cpp
index 8055033b4..9b1f35c71 100644
--- a/test/testbughuntingchecks.cpp
+++ b/test/testbughuntingchecks.cpp
@@ -25,21 +25,24 @@
class TestBughuntingChecks : public TestFixture {
public:
TestBughuntingChecks() : TestFixture("TestBughuntingChecks") {
+ settings.platform(cppcheck::Platform::Unix64);
}
private:
+ Settings settings;
+
void run() OVERRIDE {
#ifdef USE_Z3
+ LOAD_LIB_2(settings.library, "std.cfg");
TEST_CASE(uninit);
TEST_CASE(uninit_array);
TEST_CASE(uninit_function_par);
+ TEST_CASE(uninit_malloc);
TEST_CASE(ctu);
#endif
}
void check(const char code[]) {
- Settings settings;
- settings.platform(cppcheck::Platform::Unix64);
Tokenizer tokenizer(&settings, this);
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
@@ -89,6 +92,11 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void uninit_malloc() {
+ check("void foo() { char *p = malloc(10); return *p; }");
+ ASSERT_EQUALS("[test.cpp:1]: (error) Cannot determine that '*p' is initialized\n", errout.str());
+ }
+
void ctu() {
check("void init(int &x) {\n"
" x = 1;\n"
From b5cd96cbda855e0741fbba32e56b0d66e7480bff Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 28 Jun 2020 21:36:56 +0200
Subject: [PATCH 003/116] ExprEngine; Rename variable
---
lib/exprengine.cpp | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index 65b928f5e..b1d9d81bf 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -1899,10 +1899,10 @@ static ExprEngine::ValuePtr executeFunctionCall(const Token *tok, Data &data)
}
}
- auto val = getValueRangeFromValueType(tok->valueType(), data);
- call(data.callbacks, tok, val, &data);
+ auto result = getValueRangeFromValueType(tok->valueType(), data);
+ call(data.callbacks, tok, result, &data);
data.functionCall();
- return val;
+ return result;
}
static ExprEngine::ValuePtr executeArrayIndex(const Token *tok, Data &data)
From 5164d87a2e5099c6435f97049dd80bdd9aaa4e1e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 28 Jun 2020 22:49:51 +0200
Subject: [PATCH 004/116] Bug hunting; Fixed false positives for containers
---
lib/bughuntingchecks.cpp | 23 +++++++++++++++++++++++
1 file changed, 23 insertions(+)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index c97a3172d..c674d50c4 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -185,6 +185,29 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
return;
}
+ // container is not uninitialized
+ if (tok->valueType() && tok->valueType()->pointer==0 && tok->valueType()->container)
+ return;
+
+ // container element is not uninitialized
+ if (tok->str() == "[" &&
+ tok->astOperand1() &&
+ tok->astOperand1()->valueType() &&
+ tok->astOperand1()->valueType()->pointer==0 &&
+ tok->astOperand1()->valueType()->container) {
+ if (tok->astOperand1()->valueType()->container->stdStringLike)
+ return;
+ bool pointerType = false;
+ for (const Token *typeTok = tok->astOperand1()->valueType()->containerTypeToken; Token::Match(typeTok, "%name%|*|::|<"); typeTok = typeTok->next()) {
+ if (typeTok->str() == "<" && typeTok->link())
+ typeTok = typeTok->link();
+ if (typeTok->str() == "*")
+ pointerType = true;
+ }
+ if (!pointerType)
+ return;
+ }
+
// lhs in assignment
if (tok->astParent()->str() == "=" && tok == tok->astParent()->astOperand1())
return;
From a49d277e0da99f6585c0b94baee1c51afad69496 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 29 Jun 2020 13:09:01 +0200
Subject: [PATCH 005/116] Fixed #6471 (FP functionConst - member function
modifying member variable after cast (inconclusive))
---
lib/checkclass.cpp | 3 +++
test/testclass.cpp | 12 ++++++++++++
2 files changed, 15 insertions(+)
diff --git a/lib/checkclass.cpp b/lib/checkclass.cpp
index 049c020bf..7300b8e29 100644
--- a/lib/checkclass.cpp
+++ b/lib/checkclass.cpp
@@ -1991,6 +1991,9 @@ bool CheckClass::checkConstFunc(const Scope *scope, const Function *func, bool&
if (tok1->str() == "this" && tok1->previous()->isAssignmentOp())
return false;
+ // non const pointer cast
+ if (tok1->valueType() && tok1->valueType()->pointer > 0 && tok1->astParent() && tok1->astParent()->isCast() && !Token::simpleMatch(tok1->astParent(), "( const"))
+ return false;
const Token* lhs = tok1->previous();
if (lhs->str() == "&") {
diff --git a/test/testclass.cpp b/test/testclass.cpp
index 82d559000..a5db98b02 100644
--- a/test/testclass.cpp
+++ b/test/testclass.cpp
@@ -170,6 +170,7 @@ private:
TEST_CASE(const65); // ticket #8693
TEST_CASE(const66); // ticket #7714
TEST_CASE(const67); // ticket #9193
+ TEST_CASE(const68); // ticket #6471
TEST_CASE(const_handleDefaultParameters);
TEST_CASE(const_passThisToMemberOfOtherClass);
TEST_CASE(assigningPointerToPointerIsNotAConstOperation);
@@ -5514,6 +5515,17 @@ private:
ASSERT_EQUALS("[test.cpp:8]: (style, inconclusive) Technically the member function 'Test::get' can be const.\n", errout.str());
}
+ void const68() { // #6471
+ checkConst("class MyClass {\n"
+ " void clear() {\n"
+ " SVecPtr v = (SVecPtr) m_data;\n"
+ " v->clear();\n"
+ " }\n"
+ " void* m_data;\n"
+ "};\n");
+ ASSERT_EQUALS("", errout.str());
+ }
+
void const_handleDefaultParameters() {
checkConst("struct Foo {\n"
" void foo1(int i, int j = 0) {\n"
From 7c66dabce19215891a69d182c82227017e11b5e6 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Mon, 29 Jun 2020 15:25:32 +0200
Subject: [PATCH 006/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 12 ++++++++++++
1 file changed, 12 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 5d07266bf..093becc74 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -14241,4 +14241,16 @@
+
+
+
+
+
+
+ false
+
+
+
+
+
From 7d9220e96cd33451bd142ced03cae9be9bb98442 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Mon, 29 Jun 2020 15:31:03 +0200
Subject: [PATCH 007/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 19 +++++++++++++++++++
1 file changed, 19 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 093becc74..0e4ab863a 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -7387,6 +7387,25 @@
+
+
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
false
From 07d8cb4f01b1eabbe7db45b0e44be7f43dffbdc8 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 29 Jun 2020 11:55:59 -0500
Subject: [PATCH 008/116] Extend scope of afterCondition until end of function
---
lib/valueflow.cpp | 5 ++++-
test/testnullpointer.cpp | 2 +-
2 files changed, 5 insertions(+), 2 deletions(-)
diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp
index 8b10c6ba2..c0ed8f2ef 100644
--- a/lib/valueflow.cpp
+++ b/lib/valueflow.cpp
@@ -4232,7 +4232,10 @@ struct ValueFlowConditionHandler {
// TODO: constValue could be true if there are no assignments in the conditional blocks and
// perhaps if there are no && and no || in the condition
bool constValue = false;
- forward(after, top->scope()->bodyEnd, cond.vartok, values, constValue);
+ const Scope* scope = top->scope();
+ while(scope->nestedIn && scope->type != Scope::eFunction)
+ scope = scope->nestedIn;
+ forward(after, scope->bodyEnd, cond.vartok, values, constValue);
}
}
}
diff --git a/test/testnullpointer.cpp b/test/testnullpointer.cpp
index a6f496127..c27b785cc 100644
--- a/test/testnullpointer.cpp
+++ b/test/testnullpointer.cpp
@@ -262,7 +262,7 @@ private:
" }\n"
" tok->str();\n"
"}\n");
- TODO_ASSERT_EQUALS("[test.cpp:5] -> [test.cpp:3]: (warning, inconclusive) Possible null pointer dereference: tok - otherwise it is redundant to check it against null.\n", "", errout.str());
+ ASSERT_EQUALS("[test.cpp:3] -> [test.cpp:5]: (warning) Either the condition 'tok' is redundant or there is possible null pointer dereference: tok.\n", errout.str());
check("int foo(const Token *tok)\n"
"{\n"
From a0770f05e185ca146e5bd793954f7e2c2efa2203 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 29 Jun 2020 21:01:43 +0200
Subject: [PATCH 009/116] Reuse 'extractForLoopValues' in ValueFlow
---
lib/astutils.cpp | 6 +++--
lib/astutils.h | 1 +
lib/exprengine.cpp | 3 ++-
lib/valueflow.cpp | 59 ++++++++++------------------------------------
4 files changed, 19 insertions(+), 50 deletions(-)
diff --git a/lib/astutils.cpp b/lib/astutils.cpp
index 712847e46..a4ed885b5 100644
--- a/lib/astutils.cpp
+++ b/lib/astutils.cpp
@@ -438,6 +438,7 @@ const Token* getCondTokFromEnd(const Token* endBlock)
bool extractForLoopValues(const Token *forToken,
nonneg int * const varid,
+ bool * const knownInitValue,
MathLib::bigint * const initValue,
MathLib::bigint * const stepValue,
MathLib::bigint * const lastValue)
@@ -447,10 +448,11 @@ bool extractForLoopValues(const Token *forToken,
const Token *initExpr = forToken->next()->astOperand2()->astOperand1();
const Token *condExpr = forToken->next()->astOperand2()->astOperand2()->astOperand1();
const Token *incExpr = forToken->next()->astOperand2()->astOperand2()->astOperand2();
- if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%") || !initExpr->astOperand2()->hasKnownIntValue())
+ if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%"))
return false;
*varid = initExpr->astOperand1()->varId();
- *initValue = initExpr->astOperand2()->getKnownIntValue();
+ *knownInitValue = initExpr->astOperand2()->hasKnownIntValue();
+ *initValue = (*knownInitValue) ? initExpr->astOperand2()->getKnownIntValue() : 0;
if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != *varid || !condExpr->astOperand2()->hasKnownIntValue())
return false;
if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != *varid)
diff --git a/lib/astutils.h b/lib/astutils.h
index 3cd883f4d..b9f88e251 100644
--- a/lib/astutils.h
+++ b/lib/astutils.h
@@ -113,6 +113,7 @@ const Token* getCondTokFromEnd(const Token* endBlock);
*/
bool extractForLoopValues(const Token *forToken,
nonneg int * const varid,
+ bool * const knownInitValue,
long long * const initValue,
long long * const stepValue,
long long * const lastValue);
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index b1d9d81bf..7991cebb4 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -2371,8 +2371,9 @@ static std::string execute(const Token *start, const Token *end, Data &data)
if (Token::simpleMatch(tok, "for (")) {
nonneg int varid;
+ bool hasKnownInitValue;
MathLib::bigint initValue, stepValue, lastValue;
- if (extractForLoopValues(tok, &varid, &initValue, &stepValue, &lastValue)) {
+ if (extractForLoopValues(tok, &varid, &hasKnownInitValue, &initValue, &stepValue, &lastValue) && hasKnownInitValue) {
auto loopValues = std::make_shared(data.getNewSymbolName(), initValue, lastValue);
data.assignValue(tok, varid, loopValues);
tok = tok->linkAt(1);
diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp
index 8b10c6ba2..0faa10ef5 100644
--- a/lib/valueflow.cpp
+++ b/lib/valueflow.cpp
@@ -4444,44 +4444,6 @@ static void valueFlowInferCondition(TokenList* tokenlist,
}
}
-static bool valueFlowForLoop1(const Token *tok, int * const varid, MathLib::bigint * const num1, MathLib::bigint * const num2, MathLib::bigint * const numAfter)
-{
- tok = tok->tokAt(2);
- if (!Token::Match(tok, "%type%| %var% ="))
- return false;
- const Token * const vartok = Token::Match(tok, "%var% =") ? tok : tok->next();
- *varid = vartok->varId();
- tok = vartok->tokAt(2);
- const Token * const num1tok = Token::Match(tok, "%num% ;") ? tok : nullptr;
- if (num1tok)
- *num1 = MathLib::toLongNumber(num1tok->str());
- while (Token::Match(tok, "%name%|%num%|%or%|+|-|*|/|&|[|]|("))
- tok = (tok->str() == "(") ? tok->link()->next() : tok->next();
- if (!tok || tok->str() != ";")
- return false;
- tok = tok->next();
- const Token *num2tok = nullptr;
- if (Token::Match(tok, "%varid% <|<=|!=", vartok->varId())) {
- tok = tok->next();
- num2tok = tok->astOperand2();
- if (num2tok && num2tok->str() == "(" && !num2tok->astOperand2())
- num2tok = num2tok->astOperand1();
- if (!Token::Match(num2tok, "%num% ;|%oror%")) // TODO: || enlarges the scope of the condition, so it should not cause FP, but it should no lnger be part of this pattern as soon as valueFlowForLoop2 can handle an unknown RHS of || better
- num2tok = nullptr;
- }
- if (!num2tok)
- return false;
- *num2 = MathLib::toLongNumber(num2tok->str()) - ((tok->str()=="<=") ? 0 : 1);
- *numAfter = *num2 + 1;
- if (!num1tok)
- *num1 = *num2;
- while (tok && tok->str() != ";")
- tok = tok->next();
- if (!Token::Match(tok, "; %varid% ++ ) {", vartok->varId()) && !Token::Match(tok, "; ++ %varid% ) {", vartok->varId()))
- return false;
- return true;
-}
-
static bool valueFlowForLoop2(const Token *tok,
ProgramMemory *memory1,
ProgramMemory *memory2,
@@ -4663,16 +4625,19 @@ static void valueFlowForLoop(TokenList *tokenlist, SymbolDatabase* symboldatabas
!Token::simpleMatch(tok->next()->astOperand2()->astOperand2(), ";"))
continue;
- int varid(0);
- MathLib::bigint num1(0), num2(0), numAfter(0);
+ nonneg int varid;
+ bool knownInitValue;
+ MathLib::bigint initValue, stepValue, lastValue;
- if (valueFlowForLoop1(tok, &varid, &num1, &num2, &numAfter)) {
- if (num1 <= num2) {
- valueFlowForLoopSimplify(bodyStart, varid, false, num1, tokenlist, errorLogger, settings);
- valueFlowForLoopSimplify(bodyStart, varid, false, num2, tokenlist, errorLogger, settings);
- valueFlowForLoopSimplifyAfter(tok, varid, numAfter, tokenlist, errorLogger, settings);
- } else
- valueFlowForLoopSimplifyAfter(tok, varid, num1, tokenlist, errorLogger, settings);
+ if (extractForLoopValues(tok, &varid, &knownInitValue, &initValue, &stepValue, &lastValue)) {
+ const bool executeBody = !knownInitValue || initValue <= lastValue;
+ if (executeBody) {
+ valueFlowForLoopSimplify(bodyStart, varid, false, initValue, tokenlist, errorLogger, settings);
+ if (stepValue == 1)
+ valueFlowForLoopSimplify(bodyStart, varid, false, lastValue, tokenlist, errorLogger, settings);
+ }
+ const MathLib::bigint afterValue = executeBody ? lastValue + stepValue : initValue;
+ valueFlowForLoopSimplifyAfter(tok, varid, afterValue, tokenlist, errorLogger, settings);
} else {
ProgramMemory mem1, mem2, memAfter;
if (valueFlowForLoop2(tok, &mem1, &mem2, &memAfter)) {
From f34ff9325ae00dc2ee82ff9841471edf28274ce8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 29 Jun 2020 21:53:14 +0200
Subject: [PATCH 010/116] Fixed testrunner
---
lib/astutils.cpp | 11 +++++++++++
lib/astutils.h | 1 +
lib/exprengine.cpp | 4 ++--
lib/valueflow.cpp | 4 ++--
4 files changed, 16 insertions(+), 4 deletions(-)
diff --git a/lib/astutils.cpp b/lib/astutils.cpp
index a4ed885b5..f1a13f961 100644
--- a/lib/astutils.cpp
+++ b/lib/astutils.cpp
@@ -440,6 +440,7 @@ bool extractForLoopValues(const Token *forToken,
nonneg int * const varid,
bool * const knownInitValue,
MathLib::bigint * const initValue,
+ bool * const partialCond,
MathLib::bigint * const stepValue,
MathLib::bigint * const lastValue)
{
@@ -453,6 +454,16 @@ bool extractForLoopValues(const Token *forToken,
*varid = initExpr->astOperand1()->varId();
*knownInitValue = initExpr->astOperand2()->hasKnownIntValue();
*initValue = (*knownInitValue) ? initExpr->astOperand2()->getKnownIntValue() : 0;
+ *partialCond = Token::Match(condExpr, "%oror%|&&");
+ visitAstNodes(condExpr, [varid, &condExpr](const Token *tok) {
+ if (Token::Match(tok, "%oror%|&&"))
+ return ChildrenToVisit::op1_and_op2;
+ if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == *varid && tok->astOperand2()->hasKnownIntValue()) {
+ if (Token::Match(condExpr, "%oror%|&&") || tok->astOperand2()->getKnownIntValue() < condExpr->astOperand2()->getKnownIntValue())
+ condExpr = tok;
+ }
+ return ChildrenToVisit::none;
+ });
if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != *varid || !condExpr->astOperand2()->hasKnownIntValue())
return false;
if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != *varid)
diff --git a/lib/astutils.h b/lib/astutils.h
index b9f88e251..a3545d3d7 100644
--- a/lib/astutils.h
+++ b/lib/astutils.h
@@ -115,6 +115,7 @@ bool extractForLoopValues(const Token *forToken,
nonneg int * const varid,
bool * const knownInitValue,
long long * const initValue,
+ bool * const partialCond,
long long * const stepValue,
long long * const lastValue);
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index 7991cebb4..0e96a97fb 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -2371,9 +2371,9 @@ static std::string execute(const Token *start, const Token *end, Data &data)
if (Token::simpleMatch(tok, "for (")) {
nonneg int varid;
- bool hasKnownInitValue;
+ bool hasKnownInitValue, partialCond;
MathLib::bigint initValue, stepValue, lastValue;
- if (extractForLoopValues(tok, &varid, &hasKnownInitValue, &initValue, &stepValue, &lastValue) && hasKnownInitValue) {
+ if (extractForLoopValues(tok, &varid, &hasKnownInitValue, &initValue, &partialCond, &stepValue, &lastValue) && hasKnownInitValue && !partialCond) {
auto loopValues = std::make_shared(data.getNewSymbolName(), initValue, lastValue);
data.assignValue(tok, varid, loopValues);
tok = tok->linkAt(1);
diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp
index 0faa10ef5..60e644c14 100644
--- a/lib/valueflow.cpp
+++ b/lib/valueflow.cpp
@@ -4626,10 +4626,10 @@ static void valueFlowForLoop(TokenList *tokenlist, SymbolDatabase* symboldatabas
continue;
nonneg int varid;
- bool knownInitValue;
+ bool knownInitValue, partialCond;
MathLib::bigint initValue, stepValue, lastValue;
- if (extractForLoopValues(tok, &varid, &knownInitValue, &initValue, &stepValue, &lastValue)) {
+ if (extractForLoopValues(tok, &varid, &knownInitValue, &initValue, &partialCond, &stepValue, &lastValue)) {
const bool executeBody = !knownInitValue || initValue <= lastValue;
if (executeBody) {
valueFlowForLoopSimplify(bodyStart, varid, false, initValue, tokenlist, errorLogger, settings);
From 600919f624426f1ffafe8d068d8bd307669c3c24 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 29 Jun 2020 15:13:06 -0500
Subject: [PATCH 011/116] Remove redundant conditions
---
lib/templatesimplifier.cpp | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/lib/templatesimplifier.cpp b/lib/templatesimplifier.cpp
index 64697a786..a045cd69d 100644
--- a/lib/templatesimplifier.cpp
+++ b/lib/templatesimplifier.cpp
@@ -1352,7 +1352,7 @@ bool TemplateSimplifier::getTemplateNamePositionTemplateFunction(const Token *to
// skip decltype(...)
else if (Token::simpleMatch(tok->next(), "decltype (")) {
const Token * end = tok->linkAt(2)->previous();
- while (tok && tok->next() && tok != end) {
+ while (tok->next() && tok != end) {
tok = tok->next();
namepos++;
}
@@ -1361,7 +1361,7 @@ bool TemplateSimplifier::getTemplateNamePositionTemplateFunction(const Token *to
if (closing) {
if (closing->strAt(1) == "(" && Tokenizer::isFunctionHead(closing->next(), ";|{|:", true))
return true;
- while (tok && tok->next() && tok->next() != closing) {
+ while (tok->next() && tok->next() != closing) {
tok = tok->next();
namepos++;
}
@@ -1384,7 +1384,7 @@ bool TemplateSimplifier::getTemplateNamePositionTemplateVariable(const Token *to
// skip decltype(...)
else if (Token::simpleMatch(tok->next(), "decltype (")) {
const Token * end = tok->linkAt(2);
- while (tok && tok->next() && tok != end) {
+ while (tok->next() && tok != end) {
tok = tok->next();
namepos++;
}
@@ -1393,7 +1393,7 @@ bool TemplateSimplifier::getTemplateNamePositionTemplateVariable(const Token *to
if (closing) {
if (Token::Match(closing->next(), "=|;"))
return true;
- while (tok && tok->next() && tok->next() != closing) {
+ while (tok->next() && tok->next() != closing) {
tok = tok->next();
namepos++;
}
From a412e3e1f16982585a4b58ca05ddbb1e3b2206b4 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 29 Jun 2020 15:33:25 -0500
Subject: [PATCH 012/116] Mark syntax error functions as noreturn
---
lib/symboldatabase.cpp | 1 -
lib/tokenize.h | 8 ++++----
2 files changed, 4 insertions(+), 5 deletions(-)
diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp
index 601a82f38..07af526d9 100644
--- a/lib/symboldatabase.cpp
+++ b/lib/symboldatabase.cpp
@@ -3560,7 +3560,6 @@ void Function::addArguments(const SymbolDatabase *symbolDatabase, const Scope *s
typeTok = typeTok->next();
if (Token::Match(typeTok, ",|)")) { // #8333
symbolDatabase->mTokenizer->syntaxError(typeTok);
- return;
}
// skip over qualification
while (Token::Match(typeTok, "%type% ::"))
diff --git a/lib/tokenize.h b/lib/tokenize.h
index da236ecf4..950efb296 100644
--- a/lib/tokenize.h
+++ b/lib/tokenize.h
@@ -607,16 +607,16 @@ private:
public:
/** Syntax error */
- void syntaxError(const Token *tok, const std::string &code = "") const;
+ [[noreturn]] void syntaxError(const Token *tok, const std::string &code = "") const;
/** Syntax error. Unmatched character. */
- void unmatchedToken(const Token *tok) const;
+ [[noreturn]] void unmatchedToken(const Token *tok) const;
/** Syntax error. C++ code in C file. */
- void syntaxErrorC(const Token *tok, const std::string &what) const;
+ [[noreturn]] void syntaxErrorC(const Token *tok, const std::string &what) const;
/** Warn about unknown macro(s), configuration is recommended */
- void unknownMacroError(const Token *tok1) const;
+ [[noreturn]] void unknownMacroError(const Token *tok1) const;
private:
From 67e06c18a981a31d8659f1ea46b7cd47d0411779 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 29 Jun 2020 15:36:01 -0500
Subject: [PATCH 013/116] Use the already available function scope
---
lib/valueflow.cpp | 3 ---
1 file changed, 3 deletions(-)
diff --git a/lib/valueflow.cpp b/lib/valueflow.cpp
index c0ed8f2ef..158fbf41b 100644
--- a/lib/valueflow.cpp
+++ b/lib/valueflow.cpp
@@ -4232,9 +4232,6 @@ struct ValueFlowConditionHandler {
// TODO: constValue could be true if there are no assignments in the conditional blocks and
// perhaps if there are no && and no || in the condition
bool constValue = false;
- const Scope* scope = top->scope();
- while(scope->nestedIn && scope->type != Scope::eFunction)
- scope = scope->nestedIn;
forward(after, scope->bodyEnd, cond.vartok, values, constValue);
}
}
From c76c03c7111e02aa6e1d9db3e08c5c753956789b Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 29 Jun 2020 15:54:51 -0500
Subject: [PATCH 014/116] Replace noreturn with macro
---
lib/config.h | 9 +++++++++
lib/tokenize.h | 8 ++++----
2 files changed, 13 insertions(+), 4 deletions(-)
diff --git a/lib/config.h b/lib/config.h
index 0d549b9ca..4bbb80359 100644
--- a/lib/config.h
+++ b/lib/config.h
@@ -37,6 +37,15 @@
# define NOEXCEPT
#endif
+// C++11 noreturn
+#if (defined(__GNUC__) && (__GNUC__ >= 5)) \
+ || (defined(__clang__) && (defined (__cplusplus)) && (__cplusplus >= 201103L)) \
+ || defined(__CPPCHECK__)
+# define NORETURN [[noreturn]]
+#else
+# define NORETURN
+#endif
+
#define REQUIRES(msg, ...) class=typename std::enable_if<__VA_ARGS__::value>::type
#include
diff --git a/lib/tokenize.h b/lib/tokenize.h
index 950efb296..36ea66bd5 100644
--- a/lib/tokenize.h
+++ b/lib/tokenize.h
@@ -607,16 +607,16 @@ private:
public:
/** Syntax error */
- [[noreturn]] void syntaxError(const Token *tok, const std::string &code = "") const;
+ NORETURN void syntaxError(const Token *tok, const std::string &code = "") const;
/** Syntax error. Unmatched character. */
- [[noreturn]] void unmatchedToken(const Token *tok) const;
+ NORETURN void unmatchedToken(const Token *tok) const;
/** Syntax error. C++ code in C file. */
- [[noreturn]] void syntaxErrorC(const Token *tok, const std::string &what) const;
+ NORETURN void syntaxErrorC(const Token *tok, const std::string &what) const;
/** Warn about unknown macro(s), configuration is recommended */
- [[noreturn]] void unknownMacroError(const Token *tok1) const;
+ NORETURN void unknownMacroError(const Token *tok1) const;
private:
From 0bd44995aaca9ec034289f844afb6eb4caa4e18f Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Tue, 30 Jun 2020 10:15:44 +0200
Subject: [PATCH 015/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 0e4ab863a..1182322d8 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -6189,6 +6189,7 @@
+
@@ -6201,7 +6202,7 @@
-
+
false
From f5d3e6fad17de83f02b0bf39f5943d570da609d3 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Tue, 30 Jun 2020 10:21:52 +0200
Subject: [PATCH 016/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 1182322d8..42372afd1 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -13077,6 +13077,17 @@
+
+
+
+
+ false
+
+
+
+
+
+
From 0f205060638df654170fe1dfe9c24f32c410005e Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Tue, 30 Jun 2020 10:28:09 +0200
Subject: [PATCH 017/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 11 +++++++++++
1 file changed, 11 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 42372afd1..b48fa5049 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -5139,6 +5139,17 @@
+
+
+
+ false
+
+
+
+ 0:
+
+
+
From 0583763cc606cdb7b0389c37361b558881140b2a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 30 Jun 2020 10:59:57 +0200
Subject: [PATCH 018/116] Fixed #3088 (False positive: Dont report "struct or
union member is never used" for structs with __attribute__((packed)) or
#pragma pack(push))
---
lib/checkunusedvar.cpp | 12 ++++++++++++
lib/cppcheck.cpp | 31 ++++++++++++++++---------------
lib/preprocessor.h | 3 +++
lib/tokenize.cpp | 4 +++-
lib/tokenize.h | 10 ++++++++++
test/testunusedvar.cpp | 16 +++++++++++++++-
6 files changed, 59 insertions(+), 17 deletions(-)
diff --git a/lib/checkunusedvar.cpp b/lib/checkunusedvar.cpp
index 3951b9e87..d54d29f98 100644
--- a/lib/checkunusedvar.cpp
+++ b/lib/checkunusedvar.cpp
@@ -21,6 +21,7 @@
#include "checkunusedvar.h"
#include "astutils.h"
+#include "preprocessor.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
@@ -1340,6 +1341,17 @@ void CheckUnusedVar::checkStructMemberUsage()
// Packed struct => possibly used by lowlevel code. Struct members might be required by hardware.
if (scope.bodyEnd->isAttributePacked())
continue;
+ if (const Preprocessor *preprocessor = mTokenizer->getPreprocessor()) {
+ bool isPacked = false;
+ for (const Directive &d: preprocessor->getDirectives()) {
+ if (d.str == "#pragma pack(1)" && d.file == mTokenizer->list.getFiles().front() && d.linenr < scope.bodyStart->linenr()) {
+ isPacked=true;
+ break;
+ }
+ }
+ if (isPacked)
+ continue;
+ }
// Bail out if struct/union contains any functions
if (!scope.functionList.empty())
diff --git a/lib/cppcheck.cpp b/lib/cppcheck.cpp
index 0b4349eb8..f948e8b78 100644
--- a/lib/cppcheck.cpp
+++ b/lib/cppcheck.cpp
@@ -688,16 +688,17 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
continue;
}
- Tokenizer mTokenizer(&mSettings, this);
+ Tokenizer tokenizer(&mSettings, this);
+ tokenizer.setPreprocessor(&preprocessor);
if (mSettings.showtime != SHOWTIME_MODES::SHOWTIME_NONE)
- mTokenizer.setTimerResults(&s_timerResults);
+ tokenizer.setTimerResults(&s_timerResults);
try {
// Create tokens, skip rest of iteration if failed
{
Timer timer("Tokenizer::createTokens", mSettings.showtime, &s_timerResults);
simplecpp::TokenList tokensP = preprocessor.preprocess(tokens1, mCurrentConfig, files, true);
- mTokenizer.createTokens(std::move(tokensP));
+ tokenizer.createTokens(std::move(tokensP));
}
hasValidConfig = true;
@@ -708,7 +709,7 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
mErrorLogger.reportOut("Checking " + fixedpath + ": " + mCurrentConfig + "...");
}
- if (!mTokenizer.tokens())
+ if (!tokenizer.tokens())
continue;
// skip rest of iteration if just checking configuration
@@ -716,11 +717,11 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
continue;
// Check raw tokens
- checkRawTokens(mTokenizer);
+ checkRawTokens(tokenizer);
// Simplify tokens into normal form, skip rest of iteration if failed
Timer timer2("Tokenizer::simplifyTokens1", mSettings.showtime, &s_timerResults);
- bool result = mTokenizer.simplifyTokens1(mCurrentConfig);
+ bool result = tokenizer.simplifyTokens1(mCurrentConfig);
timer2.stop();
if (!result)
continue;
@@ -733,13 +734,13 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
fdump << " " << std::endl;
fdump << " " << std::endl;
preprocessor.dump(fdump);
- mTokenizer.dump(fdump);
+ tokenizer.dump(fdump);
fdump << "" << std::endl;
}
// Skip if we already met the same simplified token list
if (mSettings.force || mSettings.maxConfigs > 1) {
- const unsigned long long checksum = mTokenizer.list.calculateChecksum();
+ const unsigned long long checksum = tokenizer.list.calculateChecksum();
if (checksums.find(checksum) != checksums.end()) {
if (mSettings.debugwarnings)
purgedConfigurationMessage(filename, mCurrentConfig);
@@ -749,11 +750,11 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
}
// Check normal tokens
- checkNormalTokens(mTokenizer);
+ checkNormalTokens(tokenizer);
// Analyze info..
if (!mSettings.buildDir.empty())
- checkUnusedFunctions.parseTokens(mTokenizer, filename.c_str(), &mSettings);
+ checkUnusedFunctions.parseTokens(tokenizer, filename.c_str(), &mSettings);
// simplify more if required, skip rest of iteration if failed
if (mSimplify && hasRule("simple")) {
@@ -761,13 +762,13 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
// if further simplification fails then skip rest of iteration
Timer timer3("Tokenizer::simplifyTokenList2", mSettings.showtime, &s_timerResults);
- result = mTokenizer.simplifyTokenList2();
+ result = tokenizer.simplifyTokenList2();
timer3.stop();
if (!result)
continue;
if (!Settings::terminated())
- executeRules("simple", mTokenizer);
+ executeRules("simple", tokenizer);
}
} catch (const simplecpp::Output &o) {
@@ -779,16 +780,16 @@ unsigned int CppCheck::checkFile(const std::string& filename, const std::string
} catch (const InternalError &e) {
std::list locationList;
if (e.token) {
- ErrorMessage::FileLocation loc(e.token, &mTokenizer.list);
+ ErrorMessage::FileLocation loc(e.token, &tokenizer.list);
locationList.push_back(loc);
} else {
- ErrorMessage::FileLocation loc(mTokenizer.list.getSourceFilePath(), 0, 0);
+ ErrorMessage::FileLocation loc(tokenizer.list.getSourceFilePath(), 0, 0);
ErrorMessage::FileLocation loc2(filename, 0, 0);
locationList.push_back(loc2);
locationList.push_back(loc);
}
ErrorMessage errmsg(locationList,
- mTokenizer.list.getSourceFilePath(),
+ tokenizer.list.getSourceFilePath(),
Severity::error,
e.errorMessage,
e.id,
diff --git a/lib/preprocessor.h b/lib/preprocessor.h
index 8a0dfd888..71b88dd50 100644
--- a/lib/preprocessor.h
+++ b/lib/preprocessor.h
@@ -91,6 +91,9 @@ public:
void inlineSuppressions(const simplecpp::TokenList &tokens);
void setDirectives(const simplecpp::TokenList &tokens);
+ void setDirectives(const std::list &directives) {
+ mDirectives = directives;
+ }
/** list of all directives met while preprocessing file */
const std::list &getDirectives() const {
diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp
index b72ba5225..a92301a78 100644
--- a/lib/tokenize.cpp
+++ b/lib/tokenize.cpp
@@ -157,8 +157,9 @@ Tokenizer::Tokenizer() :
mCodeWithTemplates(false), //is there any templates?
mTimerResults(nullptr)
#ifdef MAXTIME
- ,mMaxTime(std::time(0) + MAXTIME)
+ , mMaxTime(std::time(0) + MAXTIME)
#endif
+ , mPreprocessor(nullptr)
{
}
@@ -175,6 +176,7 @@ Tokenizer::Tokenizer(const Settings *settings, ErrorLogger *errorLogger) :
#ifdef MAXTIME
,mMaxTime(std::time(0) + MAXTIME)
#endif
+ , mPreprocessor(nullptr)
{
// make sure settings are specified
assert(mSettings);
diff --git a/lib/tokenize.h b/lib/tokenize.h
index 36ea66bd5..628628ae6 100644
--- a/lib/tokenize.h
+++ b/lib/tokenize.h
@@ -37,6 +37,7 @@ class TimerResults;
class Token;
class TemplateSimplifier;
class ErrorLogger;
+class Preprocessor;
namespace simplecpp {
class TokenList;
@@ -560,6 +561,13 @@ public:
*/
static const Token * isFunctionHead(const Token *tok, const std::string &endsWith, bool cpp);
+ void setPreprocessor(const Preprocessor *preprocessor) {
+ mPreprocessor = preprocessor;
+ }
+ const Preprocessor *getPreprocessor() const {
+ return mPreprocessor;
+ }
+
private:
/**
@@ -956,6 +964,8 @@ private:
/** Tokenizer maxtime */
const std::time_t mMaxTime;
#endif
+
+ const Preprocessor *mPreprocessor;
};
/// @}
diff --git a/test/testunusedvar.cpp b/test/testunusedvar.cpp
index c2cfb1f3b..7450c38fd 100644
--- a/test/testunusedvar.cpp
+++ b/test/testunusedvar.cpp
@@ -17,6 +17,7 @@
*/
#include "checkunusedvar.h"
+#include "preprocessor.h"
#include "settings.h"
#include "testsuite.h"
#include "tokenize.h"
@@ -55,6 +56,7 @@ private:
TEST_CASE(structmember12); // #7179 - FP unused structmember
TEST_CASE(structmember13); // #3088 - __attribute__((packed))
TEST_CASE(structmember14); // #6508 - (struct x){1,2,..}
+ TEST_CASE(structmember15); // #3088 - #pragma pack(1)
TEST_CASE(structmember_sizeof);
TEST_CASE(localvar1);
@@ -211,12 +213,17 @@ private:
TEST_CASE(volatileData); // #9280
}
- void checkStructMemberUsage(const char code[]) {
+ void checkStructMemberUsage(const char code[], const std::list *directives=nullptr) {
// Clear the error buffer..
errout.str("");
+ Preprocessor preprocessor(settings, nullptr);
+ if (directives)
+ preprocessor.setDirectives(*directives);
+
// Tokenize..
Tokenizer tokenizer(&settings, this);
+ tokenizer.setPreprocessor(&preprocessor);
std::istringstream istr(code);
tokenizer.tokenize(istr, "test.cpp");
@@ -473,6 +480,13 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void structmember15() { // #3088
+ std::list directives;
+ directives.emplace_back("test.cpp", 1, "#pragma pack(1)");
+ checkStructMemberUsage("\nstruct Foo { int x; int y; };", &directives);
+ ASSERT_EQUALS("", errout.str());
+ }
+
void structmember_extern() {
// extern struct => no false positive
checkStructMemberUsage("extern struct AB\n"
From ddd21a260f5567d1c94a805b7430ae4869aeae9e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 30 Jun 2020 18:26:24 +0200
Subject: [PATCH 019/116] Fixed #6978 (False positive: unusedLabel shown for
labels that are used in some preprocessor configurations)
---
lib/checkother.cpp | 37 ++++++++++++++++++++++++-------------
lib/checkother.h | 8 +++++---
lib/tokenize.cpp | 17 +++++++++++++++++
lib/tokenize.h | 2 ++
4 files changed, 48 insertions(+), 16 deletions(-)
diff --git a/lib/checkother.cpp b/lib/checkother.cpp
index c48e6b735..c3a492fa9 100644
--- a/lib/checkother.cpp
+++ b/lib/checkother.cpp
@@ -2637,6 +2637,7 @@ void CheckOther::checkUnusedLabel()
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
+ const bool hasIfdef = mTokenizer->hasIfdef(scope->bodyStart, scope->bodyEnd);
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->scope()->isExecutable())
tok = tok->scope()->bodyEnd;
@@ -2644,25 +2645,35 @@ void CheckOther::checkUnusedLabel()
if (Token::Match(tok, "{|}|; %name% :") && tok->strAt(1) != "default") {
const std::string tmp("goto " + tok->strAt(1));
if (!Token::findsimplematch(scope->bodyStart->next(), tmp.c_str(), tmp.size(), scope->bodyEnd->previous()))
- unusedLabelError(tok->next(), tok->next()->scope()->type == Scope::eSwitch);
+ unusedLabelError(tok->next(), tok->next()->scope()->type == Scope::eSwitch, hasIfdef);
}
}
}
}
-void CheckOther::unusedLabelError(const Token* tok, bool inSwitch)
+void CheckOther::unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef)
{
- if (inSwitch) {
- if (!tok || mSettings->isEnabled(Settings::WARNING))
- reportError(tok, Severity::warning, "unusedLabelSwitch",
- "$symbol:" + (tok ? tok->str() : emptyString) + "\n"
- "Label '$symbol' is not used. Should this be a 'case' of the enclosing switch()?", CWE398, false);
- } else {
- if (!tok || mSettings->isEnabled(Settings::STYLE))
- reportError(tok, Severity::style, "unusedLabel",
- "$symbol:" + (tok ? tok->str() : emptyString) + "\n"
- "Label '$symbol' is not used.", CWE398, false);
- }
+ if (tok && !mSettings->isEnabled(inSwitch ? Settings::WARNING : Settings::STYLE))
+ return;
+
+ std::string id = "unusedLabel";
+ if (inSwitch)
+ id += "Switch";
+ if (hasIfdef)
+ id += "Configuration";
+
+ std::string msg = "$symbol:" + (tok ? tok->str() : emptyString) + "\nLabel '$symbol' is not used.";
+ if (hasIfdef)
+ msg += " There is #if in function body so the label might be used in code that is removed by the preprocessor.";
+ if (inSwitch)
+ msg += " Should this be a 'case' of the enclosing switch()?";
+
+ reportError(tok,
+ inSwitch ? Severity::warning : Severity::style,
+ id,
+ msg,
+ CWE398,
+ false);
}
diff --git a/lib/checkother.h b/lib/checkother.h
index 0d1e1a323..4dc418986 100644
--- a/lib/checkother.h
+++ b/lib/checkother.h
@@ -266,7 +266,7 @@ private:
void commaSeparatedReturnError(const Token *tok);
void redundantPointerOpError(const Token* tok, const std::string& varname, bool inconclusive);
void raceAfterInterlockedDecrementError(const Token* tok);
- void unusedLabelError(const Token* tok, bool inSwitch);
+ void unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef);
void unknownEvaluationOrder(const Token* tok);
static bool isMovedParameterAllowedForInconclusiveFunction(const Token * tok);
void accessMovedError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive);
@@ -331,8 +331,10 @@ private:
c.nanInArithmeticExpressionError(nullptr);
c.commaSeparatedReturnError(nullptr);
c.redundantPointerOpError(nullptr, "varname", false);
- c.unusedLabelError(nullptr, true);
- c.unusedLabelError(nullptr, false);
+ c.unusedLabelError(nullptr, false, false);
+ c.unusedLabelError(nullptr, false, true);
+ c.unusedLabelError(nullptr, true, false);
+ c.unusedLabelError(nullptr, true, true);
c.unknownEvaluationOrder(nullptr);
c.accessMovedError(nullptr, "v", nullptr, false);
c.funcArgNamesDifferent("function", 1, nullptr, nullptr);
diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp
index a92301a78..a9fa35bea 100644
--- a/lib/tokenize.cpp
+++ b/lib/tokenize.cpp
@@ -24,6 +24,7 @@
#include "library.h"
#include "mathlib.h"
#include "platform.h"
+#include "preprocessor.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
@@ -11773,3 +11774,19 @@ bool Tokenizer::VariableMap::hasVariable(const std::string &varname) const
{
return mVariableId.find(varname) != mVariableId.end();
}
+
+bool Tokenizer::hasIfdef(const Token *start, const Token *end) const
+{
+ if (!mPreprocessor)
+ return false;
+ for (const Directive &d: mPreprocessor->getDirectives()) {
+ if (d.str.compare(0,3,"#if") == 0 &&
+ d.linenr >= start->linenr() &&
+ d.linenr <= end->linenr() &&
+ start->fileIndex() < list.getFiles().size() &&
+ d.file == list.getFiles()[start->fileIndex()])
+ return true;
+ }
+ return false;
+}
+
diff --git a/lib/tokenize.h b/lib/tokenize.h
index 628628ae6..543a6cb74 100644
--- a/lib/tokenize.h
+++ b/lib/tokenize.h
@@ -568,6 +568,8 @@ public:
return mPreprocessor;
}
+ bool hasIfdef(const Token *start, const Token *end) const;
+
private:
/**
From f56a17bf3dc9d545cd6dc69a9de0897b0712be3d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 1 Jul 2020 07:48:32 +0200
Subject: [PATCH 020/116] Fixed #8858 (FP: identicalConditionAfterEarlyExit
when there is #if)
---
lib/checkcondition.cpp | 25 +++++++++++--------------
test/testcondition.cpp | 17 +++++++++++++++++
2 files changed, 28 insertions(+), 14 deletions(-)
diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp
index ec9b33c39..e15a09a06 100644
--- a/lib/checkcondition.cpp
+++ b/lib/checkcondition.cpp
@@ -702,22 +702,19 @@ void CheckCondition::multiCondition2()
}
}
} else {
- std::stack tokens2;
- tokens2.push(cond2);
- while (!tokens2.empty()) {
- const Token *secondCondition = tokens2.top();
- tokens2.pop();
- if (!secondCondition)
- continue;
- if (secondCondition->str() == "||" || secondCondition->str() == "&&") {
- tokens2.push(secondCondition->astOperand1());
- tokens2.push(secondCondition->astOperand2());
- } else if ((!cond1->hasKnownIntValue() || !secondCondition->hasKnownIntValue()) &&
- isSameExpression(mTokenizer->isCPP(), true, cond1, secondCondition, mSettings->library, true, true, &errorPath)) {
- if (!isAliased(vars))
+ visitAstNodes(cond2, [&](const Token *secondCondition) {
+ if (secondCondition->str() == "||" || secondCondition->str() == "&&")
+ return ChildrenToVisit::op1_and_op2;
+
+ if ((!cond1->hasKnownIntValue() || !secondCondition->hasKnownIntValue()) &&
+ isSameExpression(mTokenizer->isCPP(), true, cond1, secondCondition, mSettings->library, true, true, &errorPath)) {
+ if (!isAliased(vars) && !mTokenizer->hasIfdef(cond1, secondCondition)) {
identicalConditionAfterEarlyExitError(cond1, secondCondition, errorPath);
+ return ChildrenToVisit::done;
+ }
}
- }
+ return ChildrenToVisit::none;
+ });
}
}
if (Token::Match(tok, "%name% (") && isVariablesChanged(tok, tok->linkAt(1), true, varsInCond, mSettings, mTokenizer->isCPP())) {
diff --git a/test/testcondition.cpp b/test/testcondition.cpp
index d02abd8ad..f93c5b386 100644
--- a/test/testcondition.cpp
+++ b/test/testcondition.cpp
@@ -18,6 +18,7 @@
#include "checkcondition.h"
#include "library.h"
+#include "preprocessor.h"
#include "settings.h"
#include "testsuite.h"
#include "tokenize.h"
@@ -136,10 +137,14 @@ private:
std::map filedata;
simplecpp::preprocess(tokens2, tokens1, files, filedata, simplecpp::DUI());
+ Preprocessor preprocessor(settings0, nullptr);
+ preprocessor.setDirectives(tokens1);
+
// Tokenizer..
Tokenizer tokenizer(&settings0, this);
tokenizer.createTokens(std::move(tokens2));
tokenizer.simplifyTokens1("");
+ tokenizer.setPreprocessor(&preprocessor);
// Run checks..
CheckCondition checkCondition;
@@ -2570,6 +2575,18 @@ private:
" int FileIndex; \n"
"};\n");
ASSERT_EQUALS("", errout.str());
+
+ // #8858 - #if
+ check("short Do() {\n"
+ " short ret = bar1();\n"
+ " if ( ret )\n"
+ " return ret;\n"
+ "#ifdef FEATURE\n"
+ " ret = bar2();\n"
+ "#endif\n"
+ " return ret;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
}
void innerConditionModified() {
From d2b2bae7bf85f916a3c98fdbb71be61e9285a84c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 1 Jul 2020 08:24:52 +0200
Subject: [PATCH 021/116] Fixed #7733 (False positive: scope of the variable
can be reduced (variable is used in hidden code))
---
lib/checkother.cpp | 3 +++
test/testother.cpp | 24 ++++++++++++++++++++++++
2 files changed, 27 insertions(+)
diff --git a/lib/checkother.cpp b/lib/checkother.cpp
index c3a492fa9..d39daaa19 100644
--- a/lib/checkother.cpp
+++ b/lib/checkother.cpp
@@ -882,6 +882,9 @@ void CheckOther::checkVariableScope()
if (var->isConst())
continue;
+ if (mTokenizer->hasIfdef(var->nameToken(), var->scope()->bodyEnd))
+ continue;
+
// reference of range for loop variable..
if (Token::Match(var->nameToken()->previous(), "& %var% = %var% .")) {
const Token *otherVarToken = var->nameToken()->tokAt(2);
diff --git a/test/testother.cpp b/test/testother.cpp
index 3b80943d1..773c20a8a 100644
--- a/test/testother.cpp
+++ b/test/testother.cpp
@@ -19,6 +19,7 @@
#include "checkother.h"
#include "library.h"
#include "platform.h"
+#include "preprocessor.h"
#include "settings.h"
#include "standards.h"
#include "testsuite.h"
@@ -86,6 +87,7 @@ private:
TEST_CASE(varScope24); // pointer / reference
TEST_CASE(varScope25); // time_t
TEST_CASE(varScope26); // range for loop, map
+ TEST_CASE(varScope27); // #7733 - #if
TEST_CASE(oldStylePointerCast);
TEST_CASE(invalidPointerCast);
@@ -300,10 +302,14 @@ private:
std::map filedata;
simplecpp::preprocess(tokens2, tokens1, files, filedata, simplecpp::DUI());
+ Preprocessor preprocessor(*settings, nullptr);
+ preprocessor.setDirectives(tokens1);
+
// Tokenizer..
Tokenizer tokenizer(settings, this);
tokenizer.createTokens(std::move(tokens2));
tokenizer.simplifyTokens1("");
+ tokenizer.setPreprocessor(&preprocessor);
// Check..
CheckOther checkOther(&tokenizer, settings, this);
@@ -1229,6 +1235,24 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void varScope27() {
+ checkP("void f() {\n"
+ " int x = 0;\n"
+ "#ifdef X\n"
+ "#endif\n"
+ " if (id == ABC) { return x; }\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+
+ checkP("void f() {\n"
+ "#ifdef X\n"
+ "#endif\n"
+ " int x = 0;\n"
+ " if (id == ABC) { return x; }\n"
+ "}");
+ ASSERT_EQUALS("[test.cpp:4]: (style) The scope of the variable 'x' can be reduced.\n", errout.str());
+ }
+
void checkOldStylePointerCast(const char code[]) {
// Clear the error buffer..
errout.str("");
From 4f191e455e3a4b35fa2a9718a39ae0bde9dae545 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 1 Jul 2020 11:11:47 +0200
Subject: [PATCH 022/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 20 ++++++++++++++++++++
1 file changed, 20 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index b48fa5049..0dee41ecd 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -14295,4 +14295,24 @@
+
+
+ false
+
+
+
+ 0:
+
+
+
+ 0:
+
+
+
+
+
+
+ 0:
+
+
From 27d6b9a57d120a282255322da21fd5a3c7d16ac6 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 1 Jul 2020 11:12:22 +0200
Subject: [PATCH 023/116] std.cfg: Formatted comments, there are no functional
changes [ci skip]
---
cfg/std.cfg | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/cfg/std.cfg b/cfg/std.cfg
index eb9a0f5a7..5840d26d9 100644
--- a/cfg/std.cfg
+++ b/cfg/std.cfg
@@ -3755,8 +3755,8 @@ The obsolete function 'gets' is called. With 'gets' you'll get a buffer overrun
0:
-
-
+
+
From 0770a6fe6286c4efcbc1d3b409ae05aa201c15e1 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 1 Jul 2020 14:43:17 +0200
Subject: [PATCH 024/116] std.cfg: Added support for std::at_quick_exit()
---
cfg/std.cfg | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/cfg/std.cfg b/cfg/std.cfg
index 5840d26d9..f9c0430a0 100644
--- a/cfg/std.cfg
+++ b/cfg/std.cfg
@@ -1475,6 +1475,16 @@
+
+
+ false
+
+
+
+
+
+
+
From 8ab02ed97aec5e445bc43cc2b1e2ccc47f0064ed Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 1 Jul 2020 15:06:00 +0200
Subject: [PATCH 025/116] std.cfg: Improved bsearch() configuration
---
cfg/std.cfg | 1 +
1 file changed, 1 insertion(+)
diff --git a/cfg/std.cfg b/cfg/std.cfg
index f9c0430a0..27866875f 100644
--- a/cfg/std.cfg
+++ b/cfg/std.cfg
@@ -4232,6 +4232,7 @@ The obsolete function 'gets' is called. With 'gets' you'll get a buffer overrun
+
From cabafca5ae495e7105c989c3d8763bdedfa9b81c Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 1 Jul 2020 16:14:59 +0200
Subject: [PATCH 026/116] windows.cfg: Added some constants from WinUser.h
---
cfg/windows.cfg | 141 +++++++++++++++++++++++++++++++++++++++++++++++
test/cfg/std.cpp | 13 +++++
2 files changed, 154 insertions(+)
diff --git a/cfg/windows.cfg b/cfg/windows.cfg
index df39e3fde..f50a253e6 100644
--- a/cfg/windows.cfg
+++ b/cfg/windows.cfg
@@ -12645,6 +12645,147 @@ HFONT CreateFont(
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/test/cfg/std.cpp b/test/cfg/std.cpp
index 5019c887d..9247a1e1c 100644
--- a/test/cfg/std.cpp
+++ b/test/cfg/std.cpp
@@ -2040,6 +2040,19 @@ void uninivar_bsearch(void)
(void)std::bsearch(key,base,num,size,(int(*)(const void*,const void*)) strcmp);
}
+void minsize_bsearch(const void* key, const void* base,
+ size_t num, size_t size,
+ int (*compar)(const void*,const void*))
+{
+ int Base [3] = {42, 43, 44};
+
+ (void)std::bsearch(key,Base,2,size,(int(*)(const void*,const void*)) strcmp);
+ (void)std::bsearch(key,Base,3,size,(int(*)(const void*,const void*)) strcmp);
+ (void)std::bsearch(key,Base,4,size,(int(*)(const void*,const void*)) strcmp);
+
+ (void)std::bsearch(key,base,2,size,(int(*)(const void*,const void*)) strcmp);
+}
+
void uninitvar_qsort(void)
{
void *base;
From 25055cec626c8b10ca22ae9735384ecfe1f77b06 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Thu, 2 Jul 2020 08:31:27 +0200
Subject: [PATCH 027/116] windows.cfg: Added support for SystemParametersInfo()
---
cfg/windows.cfg | 16 ++++++++++++++++
1 file changed, 16 insertions(+)
diff --git a/cfg/windows.cfg b/cfg/windows.cfg
index f50a253e6..b9cfec2dd 100644
--- a/cfg/windows.cfg
+++ b/cfg/windows.cfg
@@ -6113,6 +6113,22 @@ HFONT CreateFont(
+
+
+ false
+
+
+
+
+
+
+
+
+
+
+
+
+
From eec622b515649575ef267b9af6e1954a38a5b10a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 2 Jul 2020 18:18:30 +0200
Subject: [PATCH 028/116] Bump simplecpp
---
externals/simplecpp/simplecpp.cpp | 119 +++++++++++++++++-------------
1 file changed, 67 insertions(+), 52 deletions(-)
diff --git a/externals/simplecpp/simplecpp.cpp b/externals/simplecpp/simplecpp.cpp
index 6de395055..900e07c6e 100644
--- a/externals/simplecpp/simplecpp.cpp
+++ b/externals/simplecpp/simplecpp.cpp
@@ -1026,15 +1026,15 @@ void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
- const std::string* altop;
+ const std::string* alternativeOp;
if (*op == '&')
- altop = &BITAND;
+ alternativeOp = &BITAND;
else if (*op == '|')
- altop = &BITOR;
+ alternativeOp = &BITOR;
else
- altop = &XOR;
+ alternativeOp = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
- if (tok->op != *op && !isAlternativeBinaryOp(tok, *altop))
+ if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
continue;
if (!tok->previous || !tok->previous->number)
continue;
@@ -1472,6 +1472,7 @@ namespace simplecpp {
}
const Token *appendTokens(TokenList *tokens,
+ const Location &rawloc,
const Token *lpar,
const std::map ¯os,
const std::set &expandedmacros,
@@ -1483,17 +1484,17 @@ namespace simplecpp {
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
- tok = expandHashHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
+ tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
- tok = expandHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
+ tok = expandHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else {
- if (!expandArg(tokens, tok, tok->location, macros, expandedmacros, parametertokens)) {
+ if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
bool expanded = false;
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
const Macro &m = it->second;
if (!m.functionLike()) {
- m.expand(tokens, tok->location, tok, macros, expandedmacros);
+ m.expand(tokens, rawloc, tok, macros, expandedmacros);
expanded = true;
}
}
@@ -1612,13 +1613,19 @@ namespace simplecpp {
hashToken = hashToken->next;
++numberOfHash;
}
- if (numberOfHash == 4) {
+ if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
+ if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
+ output->push_back(new Token(*tok));
+ tok = tok->next;
+ continue;
+ }
+
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
@@ -1645,6 +1652,41 @@ namespace simplecpp {
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
+ const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
+ if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ if (!sameline(tok, tok->next)) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const std::map::const_iterator it = macros.find(temp.cback()->str());
+ if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const Macro &calledMacro = it->second;
+ if (!calledMacro.functionLike()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ TokenList temp2(files);
+ temp2.push_back(new Token(temp.cback()->str(), tok->location));
+
+ const Token *tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
+ if (!tok2)
+ return tok->next;
+ output->takeTokens(temp);
+ output->deleteToken(output->back());
+ calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
+ return tok2->next;
+ }
+
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
// Not name..
if (!tok->name) {
@@ -1655,63 +1697,36 @@ namespace simplecpp {
// Macro parameter..
{
TokenList temp(files);
- if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
- if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- if (!sameline(tok, tok->next)) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const std::map::const_iterator it = macros.find(temp.cback()->str());
- if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- TokenList temp2(files);
- temp2.push_back(new Token(temp.cback()->str(), tok->location));
-
- const Token *tok2 = appendTokens(&temp2, tok->next, macros, expandedmacros, parametertokens);
- if (!tok2)
- return tok->next;
-
- output->takeTokens(temp);
- output->deleteToken(output->back());
- calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
-
- return tok2->next;
- }
+ if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens))
+ return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
}
// Macro..
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
+ std::set expandedmacros2(expandedmacros);
+ expandedmacros2.insert(tok->str());
+
const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike())
- return calledMacro.expand(output, loc, tok, macros, expandedmacros);
+ if (!calledMacro.functionLike()) {
+ TokenList temp(files);
+ calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
+ return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
+ }
if (!sameline(tok, tok->next) || tok->next->op != '(') {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
- const Token *tok2 = appendTokens(&tokens, tok->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
- calledMacro.expand(output, loc, tokens.cfront(), macros, expandedmacros);
- return tok2->next;
+ TokenList temp(files);
+ calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
+ return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros2, parametertokens);
}
else if (tok->str() == DEFINED) {
@@ -1879,7 +1894,7 @@ namespace simplecpp {
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const std::map::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
- const Token *tok2 = appendTokens(&tokens, B->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
From 8ab305d3c9aa5e638d9b44dd8be35e71463f53fe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 2 Jul 2020 21:31:23 +0200
Subject: [PATCH 029/116] Revert "Bump simplecpp"
This reverts commit eec622b515649575ef267b9af6e1954a38a5b10a.
---
externals/simplecpp/simplecpp.cpp | 119 +++++++++++++-----------------
1 file changed, 52 insertions(+), 67 deletions(-)
diff --git a/externals/simplecpp/simplecpp.cpp b/externals/simplecpp/simplecpp.cpp
index 900e07c6e..6de395055 100644
--- a/externals/simplecpp/simplecpp.cpp
+++ b/externals/simplecpp/simplecpp.cpp
@@ -1026,15 +1026,15 @@ void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
- const std::string* alternativeOp;
+ const std::string* altop;
if (*op == '&')
- alternativeOp = &BITAND;
+ altop = &BITAND;
else if (*op == '|')
- alternativeOp = &BITOR;
+ altop = &BITOR;
else
- alternativeOp = &XOR;
+ altop = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
- if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
+ if (tok->op != *op && !isAlternativeBinaryOp(tok, *altop))
continue;
if (!tok->previous || !tok->previous->number)
continue;
@@ -1472,7 +1472,6 @@ namespace simplecpp {
}
const Token *appendTokens(TokenList *tokens,
- const Location &rawloc,
const Token *lpar,
const std::map ¯os,
const std::set &expandedmacros,
@@ -1484,17 +1483,17 @@ namespace simplecpp {
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
- tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
+ tok = expandHashHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
- tok = expandHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
+ tok = expandHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
} else {
- if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
+ if (!expandArg(tokens, tok, tok->location, macros, expandedmacros, parametertokens)) {
bool expanded = false;
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
const Macro &m = it->second;
if (!m.functionLike()) {
- m.expand(tokens, rawloc, tok, macros, expandedmacros);
+ m.expand(tokens, tok->location, tok, macros, expandedmacros);
expanded = true;
}
}
@@ -1613,19 +1612,13 @@ namespace simplecpp {
hashToken = hashToken->next;
++numberOfHash;
}
- if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
+ if (numberOfHash == 4) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
- if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
- output->push_back(new Token(*tok));
- tok = tok->next;
- continue;
- }
-
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
@@ -1652,41 +1645,6 @@ namespace simplecpp {
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
- const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
- if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- if (!sameline(tok, tok->next)) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const std::map::const_iterator it = macros.find(temp.cback()->str());
- if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- TokenList temp2(files);
- temp2.push_back(new Token(temp.cback()->str(), tok->location));
-
- const Token *tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
- if (!tok2)
- return tok->next;
- output->takeTokens(temp);
- output->deleteToken(output->back());
- calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
- return tok2->next;
- }
-
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
// Not name..
if (!tok->name) {
@@ -1697,36 +1655,63 @@ namespace simplecpp {
// Macro parameter..
{
TokenList temp(files);
- if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens))
- return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
+ if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
+ if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ if (!sameline(tok, tok->next)) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const std::map::const_iterator it = macros.find(temp.cback()->str());
+ if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const Macro &calledMacro = it->second;
+ if (!calledMacro.functionLike()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ TokenList temp2(files);
+ temp2.push_back(new Token(temp.cback()->str(), tok->location));
+
+ const Token *tok2 = appendTokens(&temp2, tok->next, macros, expandedmacros, parametertokens);
+ if (!tok2)
+ return tok->next;
+
+ output->takeTokens(temp);
+ output->deleteToken(output->back());
+ calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
+
+ return tok2->next;
+ }
}
// Macro..
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
- std::set expandedmacros2(expandedmacros);
- expandedmacros2.insert(tok->str());
-
const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike()) {
- TokenList temp(files);
- calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
- return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
- }
+ if (!calledMacro.functionLike())
+ return calledMacro.expand(output, loc, tok, macros, expandedmacros);
if (!sameline(tok, tok->next) || tok->next->op != '(') {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
- const Token *tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, tok->next, macros, expandedmacros, parametertokens);
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
- TokenList temp(files);
- calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
- return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros2, parametertokens);
+ calledMacro.expand(output, loc, tokens.cfront(), macros, expandedmacros);
+ return tok2->next;
}
else if (tok->str() == DEFINED) {
@@ -1894,7 +1879,7 @@ namespace simplecpp {
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const std::map::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
- const Token *tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
From d606eb5ed907b393015737308bf39e1b5642e931 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 3 Jul 2020 11:42:58 +0200
Subject: [PATCH 030/116] Bump simplecpp
---
externals/simplecpp/simplecpp.cpp | 123 +++++++++++++++++-------------
1 file changed, 70 insertions(+), 53 deletions(-)
diff --git a/externals/simplecpp/simplecpp.cpp b/externals/simplecpp/simplecpp.cpp
index 6de395055..c78bc8746 100644
--- a/externals/simplecpp/simplecpp.cpp
+++ b/externals/simplecpp/simplecpp.cpp
@@ -1026,15 +1026,15 @@ void simplecpp::TokenList::constFoldBitwise(Token *tok)
{
Token * const tok1 = tok;
for (const char *op = "&^|"; *op; op++) {
- const std::string* altop;
+ const std::string* alternativeOp;
if (*op == '&')
- altop = &BITAND;
+ alternativeOp = &BITAND;
else if (*op == '|')
- altop = &BITOR;
+ alternativeOp = &BITOR;
else
- altop = &XOR;
+ alternativeOp = &XOR;
for (tok = tok1; tok && tok->op != ')'; tok = tok->next) {
- if (tok->op != *op && !isAlternativeBinaryOp(tok, *altop))
+ if (tok->op != *op && !isAlternativeBinaryOp(tok, *alternativeOp))
continue;
if (!tok->previous || !tok->previous->number)
continue;
@@ -1472,7 +1472,8 @@ namespace simplecpp {
}
const Token *appendTokens(TokenList *tokens,
- const Token *lpar,
+ const Location &rawloc,
+ const Token * const lpar,
const std::map ¯os,
const std::set &expandedmacros,
const std::vector ¶metertokens) const {
@@ -1483,17 +1484,17 @@ namespace simplecpp {
while (sameline(lpar, tok)) {
if (tok->op == '#' && sameline(tok,tok->next) && tok->next->op == '#' && sameline(tok,tok->next->next)) {
// A##B => AB
- tok = expandHashHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
+ tok = expandHashHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else if (tok->op == '#' && sameline(tok, tok->next) && tok->next->op != '#') {
- tok = expandHash(tokens, tok->location, tok, macros, expandedmacros, parametertokens);
+ tok = expandHash(tokens, rawloc, tok, macros, expandedmacros, parametertokens);
} else {
- if (!expandArg(tokens, tok, tok->location, macros, expandedmacros, parametertokens)) {
+ if (!expandArg(tokens, tok, rawloc, macros, expandedmacros, parametertokens)) {
bool expanded = false;
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
const Macro &m = it->second;
if (!m.functionLike()) {
- m.expand(tokens, tok->location, tok, macros, expandedmacros);
+ m.expand(tokens, rawloc, tok, macros, expandedmacros);
expanded = true;
}
}
@@ -1511,6 +1512,8 @@ namespace simplecpp {
tok = tok->next;
}
}
+ for (Token *tok2 = tokens->front(); tok2; tok2 = tok2->next)
+ tok2->location = lpar->location;
return sameline(lpar,tok) ? tok : NULL;
}
@@ -1612,13 +1615,19 @@ namespace simplecpp {
hashToken = hashToken->next;
++numberOfHash;
}
- if (numberOfHash == 4) {
+ if (numberOfHash == 4 && tok->next->location.col + 1 == tok->next->next->location.col) {
// # ## # => ##
output->push_back(newMacroToken("##", loc, isReplaced(expandedmacros)));
tok = hashToken;
continue;
}
+ if (numberOfHash >= 2 && tok->location.col + 1 < tok->next->location.col) {
+ output->push_back(new Token(*tok));
+ tok = tok->next;
+ continue;
+ }
+
tok = tok->next;
if (tok == endToken) {
output->push_back(new Token(*tok->previous));
@@ -1645,6 +1654,41 @@ namespace simplecpp {
return functionLike() ? parametertokens2.back()->next : nameTokInst->next;
}
+ const Token *recursiveExpandToken(TokenList *output, TokenList &temp, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
+ if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ if (!sameline(tok, tok->next)) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const std::map::const_iterator it = macros.find(temp.cback()->str());
+ if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ const Macro &calledMacro = it->second;
+ if (!calledMacro.functionLike()) {
+ output->takeTokens(temp);
+ return tok->next;
+ }
+
+ TokenList temp2(files);
+ temp2.push_back(new Token(temp.cback()->str(), tok->location));
+
+ const Token *tok2 = appendTokens(&temp2, loc, tok->next, macros, expandedmacros, parametertokens);
+ if (!tok2)
+ return tok->next;
+ output->takeTokens(temp);
+ output->deleteToken(output->back());
+ calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
+ return tok2->next;
+ }
+
const Token *expandToken(TokenList *output, const Location &loc, const Token *tok, const std::map ¯os, const std::set &expandedmacros, const std::vector ¶metertokens) const {
// Not name..
if (!tok->name) {
@@ -1655,63 +1699,36 @@ namespace simplecpp {
// Macro parameter..
{
TokenList temp(files);
- if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens)) {
- if (!(temp.cback() && temp.cback()->name && tok->next && tok->next->op == '(')) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- if (!sameline(tok, tok->next)) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const std::map::const_iterator it = macros.find(temp.cback()->str());
- if (it == macros.end() || expandedmacros.find(temp.cback()->str()) != expandedmacros.end()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike()) {
- output->takeTokens(temp);
- return tok->next;
- }
-
- TokenList temp2(files);
- temp2.push_back(new Token(temp.cback()->str(), tok->location));
-
- const Token *tok2 = appendTokens(&temp2, tok->next, macros, expandedmacros, parametertokens);
- if (!tok2)
- return tok->next;
-
- output->takeTokens(temp);
- output->deleteToken(output->back());
- calledMacro.expand(output, loc, temp2.cfront(), macros, expandedmacros);
-
- return tok2->next;
- }
+ if (expandArg(&temp, tok, loc, macros, expandedmacros, parametertokens))
+ return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros, parametertokens);
}
// Macro..
const std::map::const_iterator it = macros.find(tok->str());
if (it != macros.end() && expandedmacros.find(tok->str()) == expandedmacros.end()) {
+ std::set expandedmacros2(expandedmacros);
+ expandedmacros2.insert(tok->str());
+
const Macro &calledMacro = it->second;
- if (!calledMacro.functionLike())
- return calledMacro.expand(output, loc, tok, macros, expandedmacros);
+ if (!calledMacro.functionLike()) {
+ TokenList temp(files);
+ calledMacro.expand(&temp, loc, tok, macros, expandedmacros);
+ return recursiveExpandToken(output, temp, loc, tok, macros, expandedmacros2, parametertokens);
+ }
if (!sameline(tok, tok->next) || tok->next->op != '(') {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
TokenList tokens(files);
tokens.push_back(new Token(*tok));
- const Token *tok2 = appendTokens(&tokens, tok->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, loc, tok->next, macros, expandedmacros, parametertokens);
if (!tok2) {
output->push_back(newMacroToken(tok->str(), loc, true));
return tok->next;
}
- calledMacro.expand(output, loc, tokens.cfront(), macros, expandedmacros);
- return tok2->next;
+ TokenList temp(files);
+ calledMacro.expand(&temp, loc, tokens.cfront(), macros, expandedmacros);
+ return recursiveExpandToken(output, temp, loc, tok2, macros, expandedmacros2, parametertokens);
}
else if (tok->str() == DEFINED) {
@@ -1879,7 +1896,7 @@ namespace simplecpp {
if (tokensB.empty() && sameline(B,B->next) && B->next->op=='(') {
const std::map::const_iterator it = macros.find(strAB);
if (it != macros.end() && expandedmacros.find(strAB) == expandedmacros.end() && it->second.functionLike()) {
- const Token *tok2 = appendTokens(&tokens, B->next, macros, expandedmacros, parametertokens);
+ const Token *tok2 = appendTokens(&tokens, loc, B->next, macros, expandedmacros, parametertokens);
if (tok2)
nextTok = tok2->next;
}
From 921997c9e90909fd82b38034bada578eaba64349 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 3 Jul 2020 17:50:56 +0200
Subject: [PATCH 031/116] itc.py; false negative is fixed
---
test/bug-hunting/itc.py | 2 --
1 file changed, 2 deletions(-)
diff --git a/test/bug-hunting/itc.py b/test/bug-hunting/itc.py
index df9c79abb..bd77e1780 100644
--- a/test/bug-hunting/itc.py
+++ b/test/bug-hunting/itc.py
@@ -38,8 +38,6 @@ def get_error_lines(filename):
linenr = 176
elif linenr == 241:
linenr = 242 # warn about usage
- elif linenr == 266:
- continue # no warning should be written
ret.append(linenr)
return ret
From 686a6c7862975a0bc4cac20dee79ca662875bc5c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 3 Jul 2020 17:54:55 +0200
Subject: [PATCH 032/116] Fixed compiler warning
---
lib/astutils.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/astutils.cpp b/lib/astutils.cpp
index f1a13f961..bbf0a64a4 100644
--- a/lib/astutils.cpp
+++ b/lib/astutils.cpp
@@ -1306,7 +1306,7 @@ const Token * getTokenArgumentFunction(const Token * tok, int& argn)
return tok;
}
-const Variable* getArgumentVar(const Token* tok, int argnr)
+static const Variable* getArgumentVar(const Token* tok, int argnr)
{
if (!tok)
return nullptr;
From 14df79a53f21cc5e59d7b79599ca72615e05fba2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 3 Jul 2020 19:23:29 +0200
Subject: [PATCH 033/116] Travis: Use json.tool instead of jsonlint as there
was some installation issues
---
.travis.yml | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/.travis.yml b/.travis.yml
index 104f94c51..1552c56a5 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -35,7 +35,6 @@ before_install:
- travis_retry python3 -m pip install --user pexpect # imported by tools/ci.py
- travis_retry python3 -m pip install --user requests # imported by tools/pr.py
- travis_retry python3 -m pip install --user pygments
- - travis_retry sudo python3 -m pip install demjson # installs jsonlint => sudo required
- travis_retry python3 -m pip install --user natsort
- cp externals/z3_version_old.h externals/z3_version.h # because travis z3 version is old
@@ -183,7 +182,7 @@ matrix:
- make -s -j2 CXXFLAGS=-funsigned-char testrunner
- ./testrunner TestSymbolDatabase
# check .json files
- - find . -name '*.json' -not -path '*/\.*' | xargs jsonlint -s
+ - find . -name '*.json' | xargs -n 1 python3 -m json.tool > /dev/null
# build fuzz client
- make -s -j2 CXXFLAGS="-fsanitize=address" -C oss-fuzz fuzz-client
From 5cb3aacf5a72febbd6fcd0ecb782dd9016404578 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Sat, 4 Jul 2020 22:33:34 +0200
Subject: [PATCH 034/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 0dee41ecd..e4cef2575 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -9919,7 +9919,8 @@
-
+
+
false
From 24299544d4c043218a231974163be41ce6ae0f62 Mon Sep 17 00:00:00 2001
From: anoy
Date: Mon, 6 Jul 2020 07:10:20 +0200
Subject: [PATCH 035/116] qt.cfg: added namespace macros
---
cfg/qt.cfg | 3 +++
1 file changed, 3 insertions(+)
diff --git a/cfg/qt.cfg b/cfg/qt.cfg
index bcfa237fd..e18a3bea7 100644
--- a/cfg/qt.cfg
+++ b/cfg/qt.cfg
@@ -5047,11 +5047,14 @@
+
+
+
From d5345052ab84d4910b09b5795b8f7be29b915e3d Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Tue, 7 Jul 2020 21:36:14 +0200
Subject: [PATCH 036/116] Fix #9793 (false positive, memleak with lambda)
Skip scopes with lambdas (similar to how checkleakautovar does). In
order to fix this when the lambda is inside a for loop, make
hasInlineOrLambdaFunction() recursive. This should be what all existing
users want.
---
lib/checkmemoryleak.cpp | 2 ++
lib/symboldatabase.cpp | 2 ++
test/testmemleak.cpp | 18 ++++++++++++++++++
3 files changed, 22 insertions(+)
diff --git a/lib/checkmemoryleak.cpp b/lib/checkmemoryleak.cpp
index a4dc0ee4d..43c0664e2 100644
--- a/lib/checkmemoryleak.cpp
+++ b/lib/checkmemoryleak.cpp
@@ -764,6 +764,8 @@ void CheckMemoryLeakStructMember::check()
continue;
if (var->typeEndToken()->isStandardType())
continue;
+ if (var->scope()->hasInlineOrLambdaFunction())
+ continue;
checkStructVariable(var);
}
}
diff --git a/lib/symboldatabase.cpp b/lib/symboldatabase.cpp
index 07af526d9..0dcceb21d 100644
--- a/lib/symboldatabase.cpp
+++ b/lib/symboldatabase.cpp
@@ -4447,6 +4447,8 @@ bool Scope::hasInlineOrLambdaFunction() const
// Lambda function
if (s->type == Scope::eLambda)
return true;
+ if (s->hasInlineOrLambdaFunction())
+ return true;
}
return false;
}
diff --git a/test/testmemleak.cpp b/test/testmemleak.cpp
index f77661372..b70b35921 100644
--- a/test/testmemleak.cpp
+++ b/test/testmemleak.cpp
@@ -1677,6 +1677,8 @@ private:
TEST_CASE(varid_2); // #5315: Analysis confused by ((variable).attribute) notation
TEST_CASE(customAllocation);
+
+ TEST_CASE(lambdaInForLoop); // #9793
}
void err() {
@@ -2062,6 +2064,22 @@ private:
"}", false);
ASSERT_EQUALS("[test.c:7]: (error) Memory leak: abc.a\n", errout.str());
}
+
+ void lambdaInForLoop() { // #9793
+ check(
+ "struct S { int * p{nullptr}; };\n"
+ "int main()\n"
+ "{\n"
+ " S s;\n"
+ " s.p = new int[10];\n"
+ " for (int i = 0; i < 10; ++i) {\n"
+ " s.p[i] = []() { return 1; }();\n"
+ " }\n"
+ " delete[] s.p;\n"
+ " return 0;\n"
+ "}", true);
+ ASSERT_EQUALS("", errout.str());
+ }
};
REGISTER_TEST(TestMemleakStructMember)
From 4996ec190ecf27a4bf018eb0dcd12e2a51fd550e Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Tue, 7 Jul 2020 23:46:24 +0200
Subject: [PATCH 037/116] Fix #9652 (fp memleak with function call with cast)
When the first argument was (void *)(1), at the start of the second
iteration, arg was pointing to the "1", which caused problems for
nextArgument(), which saw the ")" as the next token and returned
nullptr, signalling that there are no more arguments.
Instead, save the first token in the argument, which makes
nextArgument() do the right thing.
---
lib/checkleakautovar.cpp | 3 ++-
test/testleakautovar.cpp | 43 ++++++++++++++++++++++++++++++++++++++++
2 files changed, 45 insertions(+), 1 deletion(-)
diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp
index 7400f39b4..551e475ce 100644
--- a/lib/checkleakautovar.cpp
+++ b/lib/checkleakautovar.cpp
@@ -856,7 +856,8 @@ void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpenin
}
int argNr = 1;
- for (const Token *arg = tokFirstArg; arg; arg = arg->nextArgument()) {
+ for (const Token *funcArg = tokFirstArg; funcArg; funcArg = funcArg->nextArgument()) {
+ const Token* arg = funcArg;
if (mTokenizer->isCPP() && arg->str() == "new") {
arg = arg->next();
if (Token::simpleMatch(arg, "( std :: nothrow )"))
diff --git a/test/testleakautovar.cpp b/test/testleakautovar.cpp
index 28a6fa532..7aea76b06 100644
--- a/test/testleakautovar.cpp
+++ b/test/testleakautovar.cpp
@@ -184,6 +184,8 @@ private:
TEST_CASE(smartPtrInContainer); // #8262
TEST_CASE(recursiveCountLimit); // #5872 #6157 #9097
+
+ TEST_CASE(functionCallCastConfig); // #9652
}
void check(const char code[], bool cpp = false) {
@@ -202,6 +204,22 @@ private:
c.runChecks(&tokenizer, &settings, this);
}
+ void check(const char code[], Settings & settings) {
+ // Clear the error buffer..
+ errout.str("");
+
+ // Tokenize..
+ Tokenizer tokenizer(&settings, this);
+ std::istringstream istr(code);
+ tokenizer.tokenize(istr, "test.cpp");
+
+ // Check for leaks..
+ CheckLeakAutoVar c;
+ settings.checkLibrary = true;
+ settings.addEnabled("information");
+ c.runChecks(&tokenizer, &settings, this);
+ }
+
void checkP(const char code[], bool cpp = false) {
// Clear the error buffer..
errout.str("");
@@ -2023,6 +2041,31 @@ private:
"}"));
}
+ void functionCallCastConfig() { // #9652
+ Settings settingsFunctionCall = settings;
+
+ const char xmldata[] = "\n"
+ "\n"
+ " \n"
+ " false\n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ " \n"
+ "";
+ tinyxml2::XMLDocument doc;
+ doc.Parse(xmldata, sizeof(xmldata));
+ settingsFunctionCall.library.load(doc);
+ check("void test_func()\n"
+ "{\n"
+ " char * buf = malloc(4);\n"
+ " free_func((void *)(1), buf);\n"
+ "}", settingsFunctionCall);
+ ASSERT_EQUALS("[test.cpp:5]: (information) --check-library: Function free_func() should have
+
+
+ false
+
+
+
+
+ 0:
+
+
+
+
false
From 9b98ee4be5bd70b0b2c27fab2c55623a128da603 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 8 Jul 2020 13:25:16 +0200
Subject: [PATCH 039/116] wxwidgets.cfg: Added missing cont attribute
---
cfg/wxwidgets.cfg | 1 +
1 file changed, 1 insertion(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 08184475b..c444d153e 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -5544,6 +5544,7 @@
false
+
0:
From 12033a33dc6c1ff9d09f9a67cac2890aee552ea3 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 8 Jul 2020 13:35:47 +0200
Subject: [PATCH 040/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 15 +++++++++++++++
1 file changed, 15 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index c444d153e..6bdb96c43 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -11203,6 +11203,21 @@
+
+
+
+ false
+
+
+
+
+
+
+
+
+
+
From 1e679cc5d1a9a24f886f621ef946f7f91c526681 Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Thu, 9 Jul 2020 21:13:54 +0200
Subject: [PATCH 041/116] Fix #9635 (FP: Memory leak with comma operator in
if-statement)
When checking for comparisons in if-statements, if there are comma
operators in the if-statement, skip until after the last comma.
---
lib/checkleakautovar.cpp | 6 +++++-
test/testleakautovar.cpp | 21 +++++++++++++++++++++
2 files changed, 26 insertions(+), 1 deletion(-)
diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp
index 551e475ce..0991bfdf0 100644
--- a/lib/checkleakautovar.cpp
+++ b/lib/checkleakautovar.cpp
@@ -465,7 +465,11 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
// Recursively scan variable comparisons in condition
std::stack tokens;
- tokens.push(tok->next()->astOperand2());
+ // Skip expressions before commas
+ const Token * astOperand2AfterCommas = tok->next()->astOperand2();
+ while (Token::simpleMatch(astOperand2AfterCommas, ","))
+ astOperand2AfterCommas = astOperand2AfterCommas->astOperand2();
+ tokens.push(astOperand2AfterCommas);
while (!tokens.empty()) {
const Token *tok3 = tokens.top();
tokens.pop();
diff --git a/test/testleakautovar.cpp b/test/testleakautovar.cpp
index 7aea76b06..90d5d14ec 100644
--- a/test/testleakautovar.cpp
+++ b/test/testleakautovar.cpp
@@ -134,6 +134,7 @@ private:
TEST_CASE(ifelse13); // #8392
TEST_CASE(ifelse14); // #9130 - if (x == (char*)NULL)
TEST_CASE(ifelse15); // #9206 - if (global_ptr = malloc(1))
+ TEST_CASE(ifelse16); // #9635 - if (p = malloc(4), p == NULL)
// switch
TEST_CASE(switch1);
@@ -1484,6 +1485,26 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void ifelse16() { // #9635
+ check("void f(void) {\n"
+ " char *p;\n"
+ " if(p = malloc(4), p == NULL)\n"
+ " return;\n"
+ " free(p);\n"
+ " return;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+
+ check("void f(void) {\n"
+ " char *p, q;\n"
+ " if(p = malloc(4), q = 1, p == NULL)\n"
+ " return;\n"
+ " free(p);\n"
+ " return;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+ }
+
void switch1() {
check("void f() {\n"
" char *p = 0;\n"
From 5fa3d5304bbe4c506cbc93e42bdfd91ad26504f1 Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Fri, 10 Jul 2020 08:20:38 +0200
Subject: [PATCH 042/116] Run dmake (#2705)
---
Makefile | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
diff --git a/Makefile b/Makefile
index 71651e37e..327915764 100644
--- a/Makefile
+++ b/Makefile
@@ -484,7 +484,7 @@ $(libcppdir)/checkuninitvar.o: lib/checkuninitvar.cpp lib/astutils.h lib/check.h
$(libcppdir)/checkunusedfunctions.o: lib/checkunusedfunctions.cpp externals/tinyxml/tinyxml2.h lib/astutils.h lib/check.h lib/checkunusedfunctions.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o $(libcppdir)/checkunusedfunctions.o $(libcppdir)/checkunusedfunctions.cpp
-$(libcppdir)/checkunusedvar.o: lib/checkunusedvar.cpp lib/astutils.h lib/check.h lib/checkunusedvar.h lib/config.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
+$(libcppdir)/checkunusedvar.o: lib/checkunusedvar.cpp externals/simplecpp/simplecpp.h lib/astutils.h lib/check.h lib/checkunusedvar.h lib/config.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/preprocessor.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o $(libcppdir)/checkunusedvar.o $(libcppdir)/checkunusedvar.cpp
$(libcppdir)/checkvaarg.o: lib/checkvaarg.cpp lib/astutils.h lib/check.h lib/checkvaarg.h lib/config.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
@@ -556,7 +556,7 @@ $(libcppdir)/timer.o: lib/timer.cpp lib/config.h lib/timer.h
$(libcppdir)/token.o: lib/token.cpp lib/astutils.h lib/config.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenlist.h lib/utils.h lib/valueflow.h
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o $(libcppdir)/token.o $(libcppdir)/token.cpp
-$(libcppdir)/tokenize.o: lib/tokenize.cpp lib/check.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
+$(libcppdir)/tokenize.o: lib/tokenize.cpp externals/simplecpp/simplecpp.h lib/check.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/preprocessor.h lib/settings.h lib/standards.h lib/suppressions.h lib/symboldatabase.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h
$(CXX) ${INCLUDE_FOR_LIB} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o $(libcppdir)/tokenize.o $(libcppdir)/tokenize.cpp
$(libcppdir)/tokenlist.o: lib/tokenlist.cpp externals/simplecpp/simplecpp.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenlist.h lib/utils.h lib/valueflow.h
@@ -622,7 +622,7 @@ test/testclass.o: test/testclass.cpp externals/tinyxml/tinyxml2.h lib/check.h li
test/testcmdlineparser.o: test/testcmdlineparser.cpp cli/cmdlineparser.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/timer.h lib/utils.h test/redirect.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testcmdlineparser.o test/testcmdlineparser.cpp
-test/testcondition.o: test/testcondition.cpp externals/simplecpp/simplecpp.h externals/tinyxml/tinyxml2.h lib/check.h lib/checkcondition.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
+test/testcondition.o: test/testcondition.cpp externals/simplecpp/simplecpp.h externals/tinyxml/tinyxml2.h lib/check.h lib/checkcondition.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/preprocessor.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testcondition.o test/testcondition.cpp
test/testconstructors.o: test/testconstructors.cpp lib/check.h lib/checkclass.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
@@ -679,7 +679,7 @@ test/testnullpointer.o: test/testnullpointer.cpp externals/simplecpp/simplecpp.h
test/testoptions.o: test/testoptions.cpp lib/config.h lib/errorlogger.h lib/errortypes.h lib/suppressions.h test/options.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testoptions.o test/testoptions.cpp
-test/testother.o: test/testother.cpp externals/simplecpp/simplecpp.h externals/tinyxml/tinyxml2.h lib/check.h lib/checkother.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
+test/testother.o: test/testother.cpp externals/simplecpp/simplecpp.h externals/tinyxml/tinyxml2.h lib/check.h lib/checkother.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/preprocessor.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testother.o test/testother.cpp
test/testpath.o: test/testpath.cpp lib/config.h lib/errorlogger.h lib/errortypes.h lib/path.h lib/suppressions.h test/testsuite.h
@@ -760,7 +760,7 @@ test/testunusedfunctions.o: test/testunusedfunctions.cpp lib/check.h lib/checkun
test/testunusedprivfunc.o: test/testunusedprivfunc.cpp externals/simplecpp/simplecpp.h lib/check.h lib/checkclass.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testunusedprivfunc.o test/testunusedprivfunc.cpp
-test/testunusedvar.o: test/testunusedvar.cpp lib/check.h lib/checkunusedvar.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
+test/testunusedvar.o: test/testunusedvar.cpp externals/simplecpp/simplecpp.h lib/check.h lib/checkunusedvar.h lib/config.h lib/errorlogger.h lib/errortypes.h lib/importproject.h lib/library.h lib/mathlib.h lib/platform.h lib/preprocessor.h lib/settings.h lib/standards.h lib/suppressions.h lib/templatesimplifier.h lib/timer.h lib/token.h lib/tokenize.h lib/tokenlist.h lib/utils.h lib/valueflow.h test/testsuite.h
$(CXX) ${INCLUDE_FOR_TEST} $(CPPFLAGS) $(CPPFILESDIR) $(CXXFLAGS) $(UNDEF_STRICT_ANSI) -c -o test/testunusedvar.o test/testunusedvar.cpp
test/testutils.o: test/testutils.cpp lib/config.h lib/errorlogger.h lib/errortypes.h lib/suppressions.h lib/utils.h test/testsuite.h
From 27841d6b811a9a7537efe943af23f99f5afb68ce Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 10 Jul 2020 19:24:45 +0200
Subject: [PATCH 043/116] Fixed #9795 (False positive: Local lock is not
ineffective, mutex is locked in thread also.)
---
lib/checkstl.cpp | 29 +--------------------------
lib/checkstl.h | 2 --
test/teststl.cpp | 51 ------------------------------------------------
3 files changed, 1 insertion(+), 81 deletions(-)
diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp
index ebeb7f44f..58706e2ae 100644
--- a/lib/checkstl.cpp
+++ b/lib/checkstl.cpp
@@ -2394,25 +2394,12 @@ void CheckStl::useStlAlgorithm()
}
}
-static bool isMutex(const Variable* var)
-{
- const Token* tok = Token::typeDecl(var->nameToken()).first;
- return Token::Match(tok, "std :: mutex|recursive_mutex|timed_mutex|recursive_timed_mutex|shared_mutex");
-}
-
static bool isLockGuard(const Variable* var)
{
const Token* tok = Token::typeDecl(var->nameToken()).first;
return Token::Match(tok, "std :: lock_guard|unique_lock|scoped_lock");
}
-static bool isLocalMutex(const Variable* var, const Scope* scope)
-{
- if (!var)
- return false;
- return !var->isReference() && !var->isRValueReference() && !var->isStatic() && var->scope() == scope;
-}
-
void CheckStl::globalLockGuardError(const Token* tok)
{
reportError(tok, Severity::warning,
@@ -2420,13 +2407,6 @@ void CheckStl::globalLockGuardError(const Token* tok)
"Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.", CWE833, false);
}
-void CheckStl::localMutexError(const Token* tok)
-{
- reportError(tok, Severity::warning,
- "localMutex",
- "The lock is ineffective because the mutex is locked at the same scope as the mutex itself.", CWE667, false);
-}
-
void CheckStl::checkMutexes()
{
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
@@ -2434,19 +2414,12 @@ void CheckStl::checkMutexes()
const Variable* var = tok->variable();
if (!var)
continue;
- if (Token::Match(tok, "%var% . lock ( )")) {
- if (!isMutex(var))
- continue;
- if (isLocalMutex(var, tok->scope()))
- localMutexError(tok);
- } else if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
+ if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
if (!isLockGuard(var))
continue;
const Variable* mvar = tok->tokAt(2)->variable();
if (var->isStatic() || var->isGlobal())
globalLockGuardError(tok);
- else if (isLocalMutex(mvar, tok->scope()))
- localMutexError(tok);
}
}
}
diff --git a/lib/checkstl.h b/lib/checkstl.h
index 9dd5e07d5..a0ae7d1e5 100644
--- a/lib/checkstl.h
+++ b/lib/checkstl.h
@@ -233,7 +233,6 @@ private:
void useStlAlgorithmError(const Token *tok, const std::string &algoName);
void globalLockGuardError(const Token *tok);
- void localMutexError(const Token *tok);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const OVERRIDE {
ErrorPath errorPath;
@@ -272,7 +271,6 @@ private:
c.readingEmptyStlContainerError(nullptr);
c.useStlAlgorithmError(nullptr, "");
c.globalLockGuardError(nullptr);
- c.localMutexError(nullptr);
}
static std::string myName() {
diff --git a/test/teststl.cpp b/test/teststl.cpp
index 240e20709..e9e929a92 100644
--- a/test/teststl.cpp
+++ b/test/teststl.cpp
@@ -4445,28 +4445,6 @@ private:
true);
ASSERT_EQUALS("", errout.str());
- check("void f() {\n"
- " std::mutex m;\n"
- " std::lock_guard g(m);\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
-
- check("void f() {\n"
- " std::mutex m;\n"
- " std::unique_lock g(m);\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
-
- check("void f() {\n"
- " std::mutex m;\n"
- " std::unique_lock g(m, std::defer_lock);\n"
- " std::lock(g);\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
-
check("void g();\n"
"void f() {\n"
" static std::mutex m;\n"
@@ -4477,16 +4455,6 @@ private:
true);
ASSERT_EQUALS("", errout.str());
- check("void g();\n"
- "void f() {\n"
- " std::mutex m;\n"
- " m.lock();\n"
- " g();\n"
- " m.unlock();\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
-
check("class A {\n"
" std::mutex m;\n"
" void f() {\n"
@@ -4535,25 +4503,6 @@ private:
"}\n",
true);
ASSERT_EQUALS("", errout.str());
-
- check("std::mutex& h();\n"
- "void f() {\n"
- " auto m = h();\n"
- " std::lock_guard g(m);\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
-
- check("void g();\n"
- "std::mutex& h();\n"
- "void f() {\n"
- " auto m = h();\n"
- " m.lock();\n"
- " g();\n"
- " m.unlock();\n"
- "}\n",
- true);
- ASSERT_EQUALS("[test.cpp:5]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
}
};
From d8e7e9176b08261d749b2b76a957fa0a5e83adad Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Fri, 10 Jul 2020 23:33:43 +0200
Subject: [PATCH 044/116] Fix FN with known condition and sizeof
cppcheck behaved differently if sizeof was to the left or right of the
comparison. In order to fix this, we cannot break the while loop until
all operands have been processed.
---
lib/checkcondition.cpp | 5 +++--
test/testcondition.cpp | 5 ++++-
2 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp
index e15a09a06..4a5de6828 100644
--- a/lib/checkcondition.cpp
+++ b/lib/checkcondition.cpp
@@ -1457,6 +1457,7 @@ void CheckCondition::alwaysTrueFalse()
// don't warn when condition checks sizeof result
bool hasSizeof = false;
+ bool hasNonNumber = false;
tokens.push(tok);
while (!tokens.empty()) {
const Token *tok2 = tokens.top();
@@ -1473,9 +1474,9 @@ void CheckCondition::alwaysTrueFalse()
tokens.push(tok2->astOperand1());
tokens.push(tok2->astOperand2());
} else
- break;
+ hasNonNumber = true;
}
- if (tokens.empty() && hasSizeof)
+ if (!hasNonNumber && hasSizeof)
continue;
alwaysTrueFalseError(tok, &tok->values().front());
diff --git a/test/testcondition.cpp b/test/testcondition.cpp
index f93c5b386..a9a62f7ba 100644
--- a/test/testcondition.cpp
+++ b/test/testcondition.cpp
@@ -2987,14 +2987,17 @@ private:
// Avoid FP for sizeof condition
check("void f() {\n"
" if (sizeof(char) != 123) {}\n"
+ " if (123 != sizeof(char)) {}\n"
"}");
ASSERT_EQUALS("", errout.str());
check("void f() {\n"
" int x = 123;\n"
" if (sizeof(char) != x) {}\n"
+ " if (x != sizeof(char)) {}\n"
"}");
- ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'sizeof(char)!=x' is always true\n", errout.str());
+ ASSERT_EQUALS("[test.cpp:3]: (style) Condition 'sizeof(char)!=x' is always true\n"
+ "[test.cpp:4]: (style) Condition 'x!=sizeof(char)' is always true\n", errout.str());
// Don't warn in assertions. Condition is often 'always true' by intention.
// If platform,defines,etc cause an 'always false' assertion then that is not very dangerous neither
From 61ccf888b31f84da6fc7495b2cdf1845e6c23b00 Mon Sep 17 00:00:00 2001
From: Ken-Patrick Lehrmann
Date: Sat, 11 Jul 2020 13:42:57 +0200
Subject: [PATCH 045/116] Fix some false positives when the same expression at
different places does not have the same value
Typically with
```
int F(int *f);
void F2(int *a, int *b) {
int c = *a;
F(a); // modifies *a
if (b && c != *a) {}
}
```
we would get the following FP:
```
[test.cpp:3] -> [test.cpp:5]: (style) The comparison 'c != *a' is always false because 'c' and '*a' represent the same value.\n
```
I guess it boils down to isSameExpression only checking that the
expression is the same (in the above case, "*a" and "*a" are indeed the
same), but there's not real check on the values.
So the patch here is a bit hackish, and we still have false negatives in
cases with dereferenced pointers.
---
lib/checkother.cpp | 4 +++-
test/testother.cpp | 29 +++++++++++++++++++++++++++++
2 files changed, 32 insertions(+), 1 deletion(-)
diff --git a/lib/checkother.cpp b/lib/checkother.cpp
index d39daaa19..96ed875ee 100644
--- a/lib/checkother.cpp
+++ b/lib/checkother.cpp
@@ -2014,7 +2014,9 @@ void CheckOther::checkDuplicateExpression()
if (tok->isOp() && tok->astOperand1() && !Token::Match(tok, "+|*|<<|>>|+=|*=|<<=|>>=")) {
if (Token::Match(tok, "==|!=|-") && astIsFloat(tok->astOperand1(), true))
continue;
- const bool followVar = !isConstVarExpression(tok) || Token::Match(tok, "%comp%|%oror%|&&");
+ const bool pointerDereference = (tok->astOperand1() && tok->astOperand1()->isUnaryOp("*")) ||
+ (tok->astOperand2() && tok->astOperand2()->isUnaryOp("*"));
+ const bool followVar = (!isConstVarExpression(tok) || Token::Match(tok, "%comp%|%oror%|&&")) && !pointerDereference;
if (isSameExpression(mTokenizer->isCPP(),
true,
tok->astOperand1(),
diff --git a/test/testother.cpp b/test/testother.cpp
index 773c20a8a..b6463cbac 100644
--- a/test/testother.cpp
+++ b/test/testother.cpp
@@ -243,6 +243,8 @@ private:
TEST_CASE(unusedVariableValueTemplate); // #8994
TEST_CASE(moduloOfOne);
+
+ TEST_CASE(sameExpressionPointers);
}
void check(const char code[], const char *filename = nullptr, bool experimental = false, bool inconclusive = true, bool runSimpleChecks=true, bool verbose=false, Settings* settings = nullptr) {
@@ -5484,6 +5486,24 @@ private:
ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison 'val < 0' is always false.\n"
"[test.cpp:2] -> [test.cpp:4]: (style) The comparison 'val > 0' is always false.\n", errout.str());
+ check("void f() {\n"
+ " int val = 0;\n"
+ " int *p = &val;n"
+ " val = 1;\n"
+ " if (*p < 0) continue;\n"
+ " if ((*p > 0)) {}\n"
+ "}\n");
+ ASSERT_EQUALS("", errout.str());
+
+ check("void f() {\n"
+ " int val = 0;\n"
+ " int *p = &val;n"
+ " if (*p < 0) continue;\n"
+ " if ((*p > 0)) {}\n"
+ "}\n");
+ TODO_ASSERT_EQUALS("[test.cpp:2] -> [test.cpp:3]: (style) The comparison '*p < 0' is always false.\n"
+ "[test.cpp:2] -> [test.cpp:4]: (style) The comparison '*p > 0' is always false.\n", "", errout.str());
+
check("void f() {\n"
" int val = 0;\n"
" if (val < 0) {\n"
@@ -8701,6 +8721,15 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void sameExpressionPointers() {
+ check("int f(int *i);\n"
+ "void g(int *a, int *b) {\n"
+ " int c = *a;\n"
+ " f(a);\n"
+ " if (b && c != *a) {}\n"
+ "}\n");
+ ASSERT_EQUALS("", errout.str());
+ }
};
REGISTER_TEST(TestOther)
From caabe56f14ad1daf2fa8eadeb61629d3a1d1c939 Mon Sep 17 00:00:00 2001
From: Paul
Date: Sun, 12 Jul 2020 21:31:53 -0500
Subject: [PATCH 046/116] Handle FPs: mutexes being locked at different scopes
---
lib/checkstl.cpp | 9 +++++++++
test/teststl.cpp | 30 ++++++++++++++++++++++++++++++
2 files changed, 39 insertions(+)
diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp
index ebeb7f44f..15bf0ac70 100644
--- a/lib/checkstl.cpp
+++ b/lib/checkstl.cpp
@@ -2430,19 +2430,28 @@ void CheckStl::localMutexError(const Token* tok)
void CheckStl::checkMutexes()
{
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
+ std::set checkedVars;
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
+ if (!Token::Match(tok, "%var%"))
+ continue;
const Variable* var = tok->variable();
if (!var)
continue;
if (Token::Match(tok, "%var% . lock ( )")) {
if (!isMutex(var))
continue;
+ if (!checkedVars.insert(var->declarationId()).second)
+ continue;
if (isLocalMutex(var, tok->scope()))
localMutexError(tok);
} else if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
if (!isLockGuard(var))
continue;
const Variable* mvar = tok->tokAt(2)->variable();
+ if (!mvar)
+ continue;
+ if (!checkedVars.insert(mvar->declarationId()).second)
+ continue;
if (var->isStatic() || var->isGlobal())
globalLockGuardError(tok);
else if (isLocalMutex(mvar, tok->scope()))
diff --git a/test/teststl.cpp b/test/teststl.cpp
index 240e20709..931fdc73f 100644
--- a/test/teststl.cpp
+++ b/test/teststl.cpp
@@ -4554,6 +4554,36 @@ private:
"}\n",
true);
ASSERT_EQUALS("[test.cpp:5]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
+ check("void foo();\n"
+ "void bar();\n"
+ "void f() {\n"
+ " std::mutex m;\n"
+ " std::thread t([&m](){\n"
+ " m.lock();\n"
+ " foo();\n"
+ " m.unlock();\n"
+ " });\n"
+ " m.lock();\n"
+ " bar();\n"
+ " m.unlock();\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("", errout.str());
+
+ check("void foo();\n"
+ "void bar();\n"
+ "void f() {\n"
+ " std::mutex m;\n"
+ " std::thread t([&m](){\n"
+ " std::unique_lock g{m};\n"
+ " foo();\n"
+ " });\n"
+ " std::unique_lock g{m};\n"
+ " bar();\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("", errout.str());
}
};
From 0009b4c8af16f500073d7a9ed88aba78534bca05 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 13 Jul 2020 11:18:51 +0200
Subject: [PATCH 047/116] test/bug-hunting/cve.py: Add --slow argument to check
slow packages
---
test/bug-hunting/cve.py | 27 ++++++++++++++++++++++-----
1 file changed, 22 insertions(+), 5 deletions(-)
diff --git a/test/bug-hunting/cve.py b/test/bug-hunting/cve.py
index 18c524358..b2fa0f032 100644
--- a/test/bug-hunting/cve.py
+++ b/test/bug-hunting/cve.py
@@ -1,6 +1,7 @@
# Test if --bug-hunting works using cve tests
import glob
+import logging
import os
import re
import shutil
@@ -14,26 +15,32 @@ else:
CPPCHECK_PATH = '../../cppcheck'
TEST_SUITE = 'cve'
+slow = '--slow' in sys.argv
+
+logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')
+
def test(test_folder):
- print(test_folder)
+ logging.info(test_folder)
cmd_file = os.path.join(test_folder, 'cmd.txt')
expected_file = os.path.join(test_folder, 'expected.txt')
- cmd = [CPPCHECK_PATH,
+ cmd = ['nice',
+ CPPCHECK_PATH,
'-D__GNUC__',
'--bug-hunting',
'--inconclusive',
'--platform=unix64',
'--template={file}:{line}:{id}',
- '-rp=' + test_folder,
- test_folder]
+ '-rp=' + test_folder]
if os.path.isfile(cmd_file):
for line in open(cmd_file, 'rt'):
if len(line) > 1:
cmd.append(line.strip())
+ cmd.append(test_folder)
+
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
comm = p.communicate()
stdout = comm[0].decode(encoding='utf-8', errors='ignore')
@@ -49,10 +56,20 @@ def test(test_folder):
print(stderr)
sys.exit(1)
-if len(sys.argv) > 1:
+if (slow is False) and len(sys.argv) > 1:
test(sys.argv[1])
sys.exit(0)
+SLOW = []
+
for test_folder in sorted(glob.glob(TEST_SUITE + '/CVE*')):
+ if slow is False:
+ check = False
+ for s in SLOW:
+ if s in test_folder:
+ check = True
+ if check is True:
+ logging.info('skipping %s', test_folder)
+ continue
test(test_folder)
From 4465d033f6602b55436f255cab24f2fe28517d0c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 13 Jul 2020 11:43:11 +0200
Subject: [PATCH 048/116] Bug hunting; When passing uninitialized data to
unknown function it is inconclusive if that would be a problem for the
function or not
---
lib/bughuntingchecks.cpp | 28 ++++++++++++++++++++--------
test/testbughuntingchecks.cpp | 3 ++-
2 files changed, 22 insertions(+), 9 deletions(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index c674d50c4..87ca9ee34 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -254,6 +254,7 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
}
// Uninitialized function argument
+ bool inconclusive = false;
if (Token::Match(tok->astParent(), "[,(]")) {
const Token *parent = tok->astParent();
int count = 0;
@@ -271,10 +272,16 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
const Variable *argvar = parent->astOperand1()->function()->getArgumentVar(count);
if (argvar && argvar->isReference() && !argvar->isConst())
return;
- if (uninitData && argvar && !argvar->isConst())
- return;
- if (!uninitStructMember.empty() && dataBase->isC() && argvar && !argvar->isConst())
- return;
+ if (uninitData && argvar && !argvar->isConst()) {
+ if (parent->astOperand1()->function()->hasBody())
+ return;
+ inconclusive = true;
+ }
+ if (!uninitStructMember.empty() && dataBase->isC() && argvar && !argvar->isConst()) {
+ if (parent->astOperand1()->function()->hasBody())
+ return;
+ inconclusive = true;
+ }
} else if (uninitData) {
if (dataBase->settings->library.getFunction(parent->astOperand1()))
return;
@@ -285,6 +292,9 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
return;
}
+ if (inconclusive && !dataBase->settings->inconclusive)
+ return;
+
// Avoid FP for array declaration
const Token *parent = tok->astParent();
while (parent && parent->str() == "[")
@@ -292,13 +302,15 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (!parent)
return;
+ const std::string inconclusiveMessage(inconclusive ? ". It is inconclusive if there would be a problem in the function call." : "");
+
if (!uninitStructMember.empty()) {
dataBase->reportError(tok,
Severity::SeverityType::error,
"bughuntingUninitStructMember",
- "Cannot determine that '" + tok->expressionString() + "." + uninitStructMember + "' is initialized",
+ "Cannot determine that '" + tok->expressionString() + "." + uninitStructMember + "' is initialized" + inconclusiveMessage,
CWE_USE_OF_UNINITIALIZED_VARIABLE,
- false,
+ inconclusive,
value.type == ExprEngine::ValueType::BailoutValue);
return;
}
@@ -310,9 +322,9 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
dataBase->reportError(tok,
Severity::SeverityType::error,
"bughuntingUninit",
- "Cannot determine that '" + uninitexpr + "' is initialized",
+ "Cannot determine that '" + uninitexpr + "' is initialized" + inconclusiveMessage,
CWE_USE_OF_UNINITIALIZED_VARIABLE,
- false,
+ inconclusive,
value.type == ExprEngine::ValueType::BailoutValue);
}
diff --git a/test/testbughuntingchecks.cpp b/test/testbughuntingchecks.cpp
index 9b1f35c71..bfb62e985 100644
--- a/test/testbughuntingchecks.cpp
+++ b/test/testbughuntingchecks.cpp
@@ -33,6 +33,7 @@ private:
void run() OVERRIDE {
#ifdef USE_Z3
+ settings.inconclusive = true;
LOAD_LIB_2(settings.library, "std.cfg");
TEST_CASE(uninit);
TEST_CASE(uninit_array);
@@ -86,7 +87,7 @@ private:
check("char foo(char id[]);\n"
"void bar() { char data[10]; foo(data); }");
- ASSERT_EQUALS("", errout.str());
+ ASSERT_EQUALS("[test.cpp:2]: (error, inconclusive) Cannot determine that 'data[0]' is initialized. It is inconclusive if there would be a problem in the function call.\n", errout.str());
check("void foo(int *p) { if (p) *p=0; }");
ASSERT_EQUALS("", errout.str());
From 9ff8adcc40c618df5f0561fb52f1aa53850f9874 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 13 Jul 2020 12:31:59 +0200
Subject: [PATCH 049/116] GUI: Remove message box when saving results even
though there are no results, to prevent problems with autosave
---
gui/resultsview.cpp | 7 -------
1 file changed, 7 deletions(-)
diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp
index eae38141d..1dc0a294c 100644
--- a/gui/resultsview.cpp
+++ b/gui/resultsview.cpp
@@ -171,13 +171,6 @@ void ResultsView::updateFromOldReport(const QString &filename) const
void ResultsView::save(const QString &filename, Report::Type type) const
{
- if (!hasResults()) {
- QMessageBox msgBox;
- msgBox.setText(tr("No errors found, nothing to save."));
- msgBox.setIcon(QMessageBox::Critical);
- msgBox.exec();
- }
-
Report *report = nullptr;
switch (type) {
From 450bdfedf3fe0773fd666bfd91226211d8fb8d47 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 13 Jul 2020 12:40:01 -0500
Subject: [PATCH 050/116] Fix FP of duplicateCondition when modifying the this
variable
---
lib/astutils.cpp | 31 ++++++++++++++++++++++++++-
lib/astutils.h | 6 ++++++
lib/checkcondition.cpp | 6 ++++++
test/testcondition.cpp | 48 ++++++++++++++++++++++++++++++++++++++++++
4 files changed, 90 insertions(+), 1 deletion(-)
diff --git a/lib/astutils.cpp b/lib/astutils.cpp
index 712847e46..7d636c829 100644
--- a/lib/astutils.cpp
+++ b/lib/astutils.cpp
@@ -539,7 +539,10 @@ bool exprDependsOnThis(const Token* expr, nonneg int depth)
// calling nonstatic method?
if (Token::Match(expr->previous(), "!!:: %name% (") && expr->function() && expr->function()->nestedIn && expr->function()->nestedIn->isClassOrStruct()) {
// is it a method of this?
- const Scope *nestedIn = expr->scope()->functionOf;
+ const Scope *fScope = expr->scope();
+ while (!fScope->functionOf && fScope->nestedIn)
+ fScope = fScope->nestedIn;
+ const Scope *nestedIn = fScope->functionOf;
if (nestedIn && nestedIn->function)
nestedIn = nestedIn->function->token->scope();
while (nestedIn && nestedIn != expr->function()->nestedIn) {
@@ -1562,6 +1565,32 @@ bool isVariablesChanged(const Token* start,
return false;
}
+bool isThisChanged(const Token* start,
+ const Token* end,
+ int indirect,
+ const Settings* settings,
+ bool cpp)
+{
+ for (const Token* tok = start; tok != end; tok = tok->next()) {
+ if (!exprDependsOnThis(tok))
+ continue;
+ if (Token::Match(tok->previous(), "%name% (")) {
+ if (tok->previous()->function()) {
+ if (!tok->previous()->function()->isConst())
+ return true;
+ else
+ continue;
+ } else if (!tok->previous()->isKeyword()){
+ return true;
+ }
+
+ }
+ if (isVariableChanged(tok, indirect, settings, cpp))
+ return true;
+ }
+ return false;
+}
+
int numberOfArguments(const Token *start)
{
int arguments=0;
diff --git a/lib/astutils.h b/lib/astutils.h
index 3cd883f4d..20e402d42 100644
--- a/lib/astutils.h
+++ b/lib/astutils.h
@@ -192,6 +192,12 @@ bool isVariablesChanged(const Token* start,
const Settings* settings,
bool cpp);
+bool isThisChanged(const Token* start,
+ const Token* end,
+ int indirect,
+ const Settings* settings,
+ bool cpp);
+
const Token* findVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int varid, bool globalvar, const Settings *settings, bool cpp, int depth = 20);
Token* findVariableChanged(Token *start, const Token *end, int indirect, const nonneg int varid, bool globalvar, const Settings *settings, bool cpp, int depth = 20);
diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp
index ec9b33c39..17e3e026e 100644
--- a/lib/checkcondition.cpp
+++ b/lib/checkcondition.cpp
@@ -453,6 +453,12 @@ void CheckCondition::duplicateCondition()
bool modified = false;
visitAstNodes(cond1, [&](const Token *tok3) {
+ if (exprDependsOnThis(tok3)) {
+ if (isThisChanged(scope.classDef->next(), cond2, false, mSettings, mTokenizer->isCPP())) {
+ modified = true;
+ return ChildrenToVisit::done;
+ }
+ }
if (tok3->varId() > 0 &&
isVariableChanged(scope.classDef->next(), cond2, tok3->varId(), false, mSettings, mTokenizer->isCPP())) {
modified = true;
diff --git a/test/testcondition.cpp b/test/testcondition.cpp
index d02abd8ad..05c6ba239 100644
--- a/test/testcondition.cpp
+++ b/test/testcondition.cpp
@@ -3668,6 +3668,54 @@ private:
" if (a.b) {}\n"
"}\n");
ASSERT_EQUALS("", errout.str());
+
+ check("struct A {\n"
+ " int a;\n"
+ " void b() const {\n"
+ " return a == 1;\n"
+ " }\n"
+ " void c();\n"
+ " void d() {\n"
+ " if(b()) {\n"
+ " c();\n"
+ " }\n"
+ " if (b()) {\n"
+ " a = 3;\n"
+ " }\n"
+ " }\n"
+ "}\n");
+ ASSERT_EQUALS("", errout.str());
+
+ check("struct A {\n"
+ " int a;\n"
+ " void b() const {\n"
+ " return a == 1;\n"
+ " }\n"
+ " void d() {\n"
+ " if(b()) {\n"
+ " a = 2;\n"
+ " }\n"
+ " if (b()) {\n"
+ " a = 3;\n"
+ " }\n"
+ " }\n"
+ "}\n");
+ ASSERT_EQUALS("", errout.str());
+
+ check("struct A {\n"
+ " int a;\n"
+ " void b() const {\n"
+ " return a == 1;\n"
+ " }\n"
+ " void d() {\n"
+ " if(b()) {\n"
+ " }\n"
+ " if (b()) {\n"
+ " a = 3;\n"
+ " }\n"
+ " }\n"
+ "}\n");
+ ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) The if condition is the same as the previous if condition\n", errout.str());
}
void checkInvalidTestForOverflow() {
From 36b9e545ac26d3b8c40bd1548f54ed5ca67e84f5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 13 Jul 2020 20:23:44 +0200
Subject: [PATCH 051/116] Bug hunting; more bailout warnings in uninit check
---
lib/bughuntingchecks.cpp | 31 ++++++++++++++++++++-----------
lib/exprengine.h | 2 --
2 files changed, 20 insertions(+), 13 deletions(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 87ca9ee34..39062cfac 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -87,7 +87,7 @@ static void divByZero(const Token *tok, const ExprEngine::Value &value, ExprEngi
return;
if (tok->isImpossibleIntValue(0))
return;
- if (value.isUninit())
+ if (value.isUninit() && value.type != ExprEngine::ValueType::BailoutValue)
return;
float f = getKnownFloatValue(tok, 0.0f);
if (f > 0.0f || f < 0.0f)
@@ -216,22 +216,16 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (value.type == ExprEngine::ValueType::BailoutValue) {
if (tok->hasKnownValue())
return;
- if (tok->function())
- return;
- if (Token::Match(tok, "<<|>>|,"))
- // Only warn about the operands
+ if (!tok->variable())
+ // FIXME
return;
+
// lhs for scope operator
if (Token::Match(tok, "%name% ::"))
return;
if (tok->astParent()->str() == "::" && tok == tok->astParent()->astOperand1())
return;
- if (tok->str() == "(")
- // cast: result is not uninitialized if expression is initialized
- // function: does not return a uninitialized value
- return;
-
// Containers are not uninitialized
std::vector tokens{tok, tok->astOperand1(), tok->astOperand2()};
if (Token::Match(tok->previous(), ". %name%"))
@@ -242,15 +236,30 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
}
const Variable *var = tok->variable();
+ if (var && var->nameToken() == tok)
+ return;
+ if (var && !var->isLocal())
+ return; // FIXME
if (var && !var->isPointer()) {
if (!var->isLocal() || var->isStatic())
return;
}
- if (var && (Token::Match(var->nameToken(), "%name% =") || Token::Match(var->nameToken(), "%varid% ; %varid% =", var->declarationId())))
+ if (var && (Token::Match(var->nameToken(), "%name% [=:]") || Token::Match(var->nameToken(), "%varid% ; %varid% =", var->declarationId())))
return;
if (var && var->nameToken() == tok)
return;
+ // Are there unconditional assignment?
+ if (var && Token::Match(var->nameToken(), "%varid% ;| %varid%| =", tok->varId()))
+ return;
+ for (const Token *prev = tok->previous(); prev; prev = prev->previous()) {
+ if (!precedes(var->nameToken(), prev))
+ break;
+ if (prev->str() == "}")
+ prev = prev->link();
+ if (Token::Match(prev, "%varid% =", tok->varId()))
+ return;
+ }
}
// Uninitialized function argument
diff --git a/lib/exprengine.h b/lib/exprengine.h
index cff8d536f..46966d610 100644
--- a/lib/exprengine.h
+++ b/lib/exprengine.h
@@ -317,11 +317,9 @@ namespace ExprEngine {
bool isEqual(DataBase * /*dataBase*/, int /*value*/) const OVERRIDE {
return true;
}
- /* FIXME: This is too noisy
bool isUninit() const OVERRIDE {
return true;
}
- */
};
typedef std::function Callback;
From cb221e970d4da79f5ea6088cc46baad19e018032 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 13 Jul 2020 20:42:53 +0200
Subject: [PATCH 052/116] Bug hunting: Add test case for CVE-2019-12977.
Passing uninitialized struct to function
---
test/bug-hunting/cve/CVE-2019-12977/cmd.txt | 2 +
.../cve/CVE-2019-12977/expected.txt | 1 +
test/bug-hunting/cve/CVE-2019-12977/jp2.c | 1106 +++++++++++++++++
3 files changed, 1109 insertions(+)
create mode 100644 test/bug-hunting/cve/CVE-2019-12977/cmd.txt
create mode 100644 test/bug-hunting/cve/CVE-2019-12977/expected.txt
create mode 100644 test/bug-hunting/cve/CVE-2019-12977/jp2.c
diff --git a/test/bug-hunting/cve/CVE-2019-12977/cmd.txt b/test/bug-hunting/cve/CVE-2019-12977/cmd.txt
new file mode 100644
index 000000000..7000b0c5f
--- /dev/null
+++ b/test/bug-hunting/cve/CVE-2019-12977/cmd.txt
@@ -0,0 +1,2 @@
+-DMAGICKCORE_LIBOPENJP2_DELEGATE
+
diff --git a/test/bug-hunting/cve/CVE-2019-12977/expected.txt b/test/bug-hunting/cve/CVE-2019-12977/expected.txt
new file mode 100644
index 000000000..4e0e618ff
--- /dev/null
+++ b/test/bug-hunting/cve/CVE-2019-12977/expected.txt
@@ -0,0 +1 @@
+jp2.c:865:bughuntingUninit
diff --git a/test/bug-hunting/cve/CVE-2019-12977/jp2.c b/test/bug-hunting/cve/CVE-2019-12977/jp2.c
new file mode 100644
index 000000000..d4d68ab51
--- /dev/null
+++ b/test/bug-hunting/cve/CVE-2019-12977/jp2.c
@@ -0,0 +1,1106 @@
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% JJJ PPPP 222 %
+% J P P 2 2 %
+% J PPPP 22 %
+% J J P 2 %
+% JJ P 22222 %
+% %
+% %
+% Read/Write JPEG-2000 Image Format %
+% %
+% Cristy %
+% Nathan Brown %
+% June 2001 %
+% %
+% %
+% Copyright 1999-2019 ImageMagick Studio LLC, a non-profit organization %
+% dedicated to making software imaging solutions freely available. %
+% %
+% You may not use this file except in compliance with the License. You may %
+% obtain a copy of the License at %
+% %
+% https://imagemagick.org/script/license.php %
+% %
+% Unless required by applicable law or agreed to in writing, software %
+% distributed under the License is distributed on an "AS IS" BASIS, %
+% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
+% See the License for the specific language governing permissions and %
+% limitations under the License. %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+%
+*/
+
+/*
+ Include declarations.
+*/
+#include "MagickCore/studio.h"
+#include "MagickCore/artifact.h"
+#include "MagickCore/attribute.h"
+#include "MagickCore/blob.h"
+#include "MagickCore/blob-private.h"
+#include "MagickCore/cache.h"
+#include "MagickCore/colorspace.h"
+#include "MagickCore/colorspace-private.h"
+#include "MagickCore/color.h"
+#include "MagickCore/color-private.h"
+#include "MagickCore/exception.h"
+#include "MagickCore/exception-private.h"
+#include "MagickCore/image.h"
+#include "MagickCore/image-private.h"
+#include "MagickCore/list.h"
+#include "MagickCore/magick.h"
+#include "MagickCore/memory_.h"
+#include "MagickCore/monitor.h"
+#include "MagickCore/monitor-private.h"
+#include "MagickCore/option.h"
+#include "MagickCore/pixel-accessor.h"
+#include "MagickCore/profile.h"
+#include "MagickCore/property.h"
+#include "MagickCore/quantum-private.h"
+#include "MagickCore/resource_.h"
+#include "MagickCore/semaphore.h"
+#include "MagickCore/static.h"
+#include "MagickCore/statistic.h"
+#include "MagickCore/string_.h"
+#include "MagickCore/string-private.h"
+#include "MagickCore/module.h"
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+#include
+#endif
+
+/*
+ Forward declarations.
+*/
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+static MagickBooleanType
+ WriteJP2Image(const ImageInfo *,Image *,ExceptionInfo *);
+#endif
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% I s J 2 K %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% IsJ2K() returns MagickTrue if the image format type, identified by the
+% magick string, is J2K.
+%
+% The format of the IsJ2K method is:
+%
+% MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
+%
+% A description of each parameter follows:
+%
+% o magick: compare image format pattern against these bytes.
+%
+% o length: Specifies the length of the magick string.
+%
+*/
+static MagickBooleanType IsJ2K(const unsigned char *magick,const size_t length)
+{
+ if (length < 4)
+ return(MagickFalse);
+ if (memcmp(magick,"\xff\x4f\xff\x51",4) == 0)
+ return(MagickTrue);
+ return(MagickFalse);
+}
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% I s J P 2 %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% IsJP2() returns MagickTrue if the image format type, identified by the
+% magick string, is JP2.
+%
+% The format of the IsJP2 method is:
+%
+% MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
+%
+% A description of each parameter follows:
+%
+% o magick: compare image format pattern against these bytes.
+%
+% o length: Specifies the length of the magick string.
+%
+*/
+static MagickBooleanType IsJP2(const unsigned char *magick,const size_t length)
+{
+ if (length < 4)
+ return(MagickFalse);
+ if (memcmp(magick,"\x0d\x0a\x87\x0a",4) == 0)
+ return(MagickTrue);
+ if (length < 12)
+ return(MagickFalse);
+ if (memcmp(magick,"\x00\x00\x00\x0c\x6a\x50\x20\x20\x0d\x0a\x87\x0a",12) == 0)
+ return(MagickTrue);
+ return(MagickFalse);
+}
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% R e a d J P 2 I m a g e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% ReadJP2Image() reads a JPEG 2000 Image file (JP2) or JPEG 2000
+% codestream (JPC) image file and returns it. It allocates the memory
+% necessary for the new Image structure and returns a pointer to the new
+% image or set of images.
+%
+% JP2 support is originally written by Nathan Brown, nathanbrown@letu.edu.
+%
+% The format of the ReadJP2Image method is:
+%
+% Image *ReadJP2Image(const ImageInfo *image_info,
+% ExceptionInfo *exception)
+%
+% A description of each parameter follows:
+%
+% o image_info: the image info.
+%
+% o exception: return any errors or warnings in this structure.
+%
+*/
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+static void JP2ErrorHandler(const char *message,void *client_data)
+{
+ ExceptionInfo
+ *exception;
+
+ exception=(ExceptionInfo *) client_data;
+ (void) ThrowMagickException(exception,GetMagickModule(),CoderError,
+ message,"`%s'","OpenJP2");
+}
+
+static OPJ_SIZE_T JP2ReadHandler(void *buffer,OPJ_SIZE_T length,void *context)
+{
+ Image
+ *image;
+
+ ssize_t
+ count;
+
+ image=(Image *) context;
+ count=ReadBlob(image,(ssize_t) length,(unsigned char *) buffer);
+ if (count == 0)
+ return((OPJ_SIZE_T) -1);
+ return((OPJ_SIZE_T) count);
+}
+
+static OPJ_BOOL JP2SeekHandler(OPJ_OFF_T offset,void *context)
+{
+ Image
+ *image;
+
+ image=(Image *) context;
+ return(SeekBlob(image,offset,SEEK_SET) < 0 ? OPJ_FALSE : OPJ_TRUE);
+}
+
+static OPJ_OFF_T JP2SkipHandler(OPJ_OFF_T offset,void *context)
+{
+ Image
+ *image;
+
+ image=(Image *) context;
+ return(SeekBlob(image,offset,SEEK_CUR) < 0 ? -1 : offset);
+}
+
+static void JP2WarningHandler(const char *message,void *client_data)
+{
+ ExceptionInfo
+ *exception;
+
+ exception=(ExceptionInfo *) client_data;
+ (void) ThrowMagickException(exception,GetMagickModule(),CoderWarning,
+ message,"`%s'","OpenJP2");
+}
+
+static OPJ_SIZE_T JP2WriteHandler(void *buffer,OPJ_SIZE_T length,void *context)
+{
+ Image
+ *image;
+
+ ssize_t
+ count;
+
+ image=(Image *) context;
+ count=WriteBlob(image,(ssize_t) length,(unsigned char *) buffer);
+ return((OPJ_SIZE_T) count);
+}
+
+static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
+{
+ const char
+ *option;
+
+ Image
+ *image;
+
+ int
+ jp2_status;
+
+ MagickBooleanType
+ status;
+
+ opj_codec_t
+ *jp2_codec;
+
+ opj_dparameters_t
+ parameters;
+
+ opj_image_t
+ *jp2_image;
+
+ opj_stream_t
+ *jp2_stream;
+
+ register ssize_t
+ i;
+
+ ssize_t
+ y;
+
+ unsigned char
+ sans[4];
+
+ /*
+ Open image file.
+ */
+ assert(image_info != (const ImageInfo *) NULL);
+ assert(image_info->signature == MagickCoreSignature);
+ if (image_info->debug != MagickFalse)
+ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
+ image_info->filename);
+ assert(exception != (ExceptionInfo *) NULL);
+ assert(exception->signature == MagickCoreSignature);
+ image=AcquireImage(image_info,exception);
+ status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
+ if (status == MagickFalse)
+ {
+ image=DestroyImageList(image);
+ return((Image *) NULL);
+ }
+ /*
+ Initialize JP2 codec.
+ */
+ if (ReadBlob(image,4,sans) != 4)
+ {
+ image=DestroyImageList(image);
+ return((Image *) NULL);
+ }
+ (void) SeekBlob(image,SEEK_SET,0);
+ if (LocaleCompare(image_info->magick,"JPT") == 0)
+ jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
+ else
+ if (IsJ2K(sans,4) != MagickFalse)
+ jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
+ else
+ jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
+ opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
+ opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
+ opj_set_default_decoder_parameters(¶meters);
+ option=GetImageOption(image_info,"jp2:reduce-factor");
+ if (option != (const char *) NULL)
+ parameters.cp_reduce=StringToInteger(option);
+ option=GetImageOption(image_info,"jp2:quality-layers");
+ if (option != (const char *) NULL)
+ parameters.cp_layer=StringToInteger(option);
+ if (opj_setup_decoder(jp2_codec,¶meters) == 0)
+ {
+ opj_destroy_codec(jp2_codec);
+ ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
+ }
+ jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,1);
+ opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
+ opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
+ opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
+ opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
+ opj_stream_set_user_data(jp2_stream,image,NULL);
+ opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
+ if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
+ {
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
+ }
+ jp2_status=OPJ_TRUE;
+ if (image->ping == MagickFalse)
+ {
+ if ((image->columns != 0) && (image->rows != 0))
+ /*
+ Extract an area from the image.
+ */
+ jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
+ (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
+ (OPJ_INT32) (image->extract_info.x+(ssize_t) image->columns),
+ (OPJ_INT32) (image->extract_info.y+(ssize_t) image->rows));
+ else
+ jp2_status=opj_set_decode_area(jp2_codec,jp2_image,0,0,
+ jp2_image->comps[0].w,jp2_image->comps[0].h);
+ if (jp2_status == OPJ_FALSE)
+ {
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
+ }
+ }
+ if ((AcquireMagickResource(WidthResource,(size_t) jp2_image->comps[0].w) == MagickFalse) ||
+ (AcquireMagickResource(HeightResource,(size_t) jp2_image->comps[0].h) == MagickFalse))
+ {
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
+ }
+ if ((image_info->number_scenes != 0) && (image_info->scene != 0))
+ jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
+ (unsigned int) image_info->scene-1);
+ else
+ if (image->ping == MagickFalse)
+ {
+ jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
+ if (jp2_status != OPJ_FALSE)
+ jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
+ }
+ if (jp2_status == OPJ_FALSE)
+ {
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
+ }
+ opj_stream_destroy(jp2_stream);
+ for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
+ {
+ if ((jp2_image->comps[0].dx == 0) || (jp2_image->comps[0].dy == 0) ||
+ (jp2_image->comps[0].prec != jp2_image->comps[i].prec) ||
+ (jp2_image->comps[0].sgnd != jp2_image->comps[i].sgnd) ||
+ ((image->ping == MagickFalse) && (jp2_image->comps[i].data == NULL)))
+ {
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
+ }
+ }
+ /*
+ Convert JP2 image.
+ */
+ image->columns=(size_t) jp2_image->comps[0].w;
+ image->rows=(size_t) jp2_image->comps[0].h;
+ image->depth=jp2_image->comps[0].prec;
+ image->compression=JPEG2000Compression;
+ if (jp2_image->numcomps == 1)
+ SetImageColorspace(image,GRAYColorspace,exception);
+ else
+ if (jp2_image->color_space == 2)
+ {
+ SetImageColorspace(image,GRAYColorspace,exception);
+ if (jp2_image->numcomps > 1)
+ image->alpha_trait=BlendPixelTrait;
+ }
+ else
+ if (jp2_image->color_space == 3)
+ SetImageColorspace(image,Rec601YCbCrColorspace,exception);
+ if (jp2_image->numcomps > 3)
+ image->alpha_trait=BlendPixelTrait;
+ if (jp2_image->icc_profile_buf != (unsigned char *) NULL)
+ {
+ StringInfo
+ *profile;
+
+ profile=BlobToStringInfo(jp2_image->icc_profile_buf,
+ jp2_image->icc_profile_len);
+ if (profile != (StringInfo *) NULL)
+ {
+ SetImageProfile(image,"icc",profile,exception);
+ profile=DestroyStringInfo(profile);
+ }
+ }
+ if (image->ping != MagickFalse)
+ {
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ return(GetFirstImageInList(image));
+ }
+ status=SetImageExtent(image,image->columns,image->rows,exception);
+ if (status == MagickFalse)
+ {
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ return(DestroyImageList(image));
+ }
+ for (y=0; y < (ssize_t) image->rows; y++)
+ {
+ register Quantum
+ *magick_restrict q;
+
+ register ssize_t
+ x;
+
+ q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
+ if (q == (Quantum *) NULL)
+ break;
+ for (x=0; x < (ssize_t) image->columns; x++)
+ {
+ for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
+ {
+ double
+ pixel,
+ scale;
+
+ scale=QuantumRange/(double) ((1UL << jp2_image->comps[i].prec)-1);
+ pixel=scale*(jp2_image->comps[i].data[y/jp2_image->comps[i].dy*
+ image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx]+
+ (jp2_image->comps[i].sgnd ? 1UL << (jp2_image->comps[i].prec-1) : 0));
+ switch (i)
+ {
+ case 0:
+ {
+ if (jp2_image->numcomps == 1)
+ {
+ SetPixelGray(image,ClampToQuantum(pixel),q);
+ SetPixelAlpha(image,OpaqueAlpha,q);
+ break;
+ }
+ SetPixelRed(image,ClampToQuantum(pixel),q);
+ SetPixelGreen(image,ClampToQuantum(pixel),q);
+ SetPixelBlue(image,ClampToQuantum(pixel),q);
+ SetPixelAlpha(image,OpaqueAlpha,q);
+ break;
+ }
+ case 1:
+ {
+ if (jp2_image->numcomps == 2)
+ {
+ SetPixelAlpha(image,ClampToQuantum(pixel),q);
+ break;
+ }
+ SetPixelGreen(image,ClampToQuantum(pixel),q);
+ break;
+ }
+ case 2:
+ {
+ SetPixelBlue(image,ClampToQuantum(pixel),q);
+ break;
+ }
+ case 3:
+ {
+ SetPixelAlpha(image,ClampToQuantum(pixel),q);
+ break;
+ }
+ }
+ }
+ q+=GetPixelChannels(image);
+ }
+ if (SyncAuthenticPixels(image,exception) == MagickFalse)
+ break;
+ status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
+ image->rows);
+ if (status == MagickFalse)
+ break;
+ }
+ /*
+ Free resources.
+ */
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ (void) CloseBlob(image);
+ if ((image_info->number_scenes != 0) && (image_info->scene != 0))
+ AppendImageToList(&image,CloneImage(image,0,0,MagickTrue,exception));
+ return(GetFirstImageInList(image));
+}
+#endif
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% R e g i s t e r J P 2 I m a g e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% RegisterJP2Image() adds attributes for the JP2 image format to the list of
+% supported formats. The attributes include the image format tag, a method
+% method to read and/or write the format, whether the format supports the
+% saving of more than one frame to the same file or blob, whether the format
+% supports native in-memory I/O, and a brief description of the format.
+%
+% The format of the RegisterJP2Image method is:
+%
+% size_t RegisterJP2Image(void)
+%
+*/
+ModuleExport size_t RegisterJP2Image(void)
+{
+ char
+ version[MagickPathExtent];
+
+ MagickInfo
+ *entry;
+
+ *version='\0';
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ (void) FormatLocaleString(version,MagickPathExtent,"%s",opj_version());
+#endif
+ entry=AcquireMagickInfo("JP2","JP2","JPEG-2000 File Format Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJP2;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ entry=AcquireMagickInfo("JP2","J2C","JPEG-2000 Code Stream Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJ2K;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ entry=AcquireMagickInfo("JP2","J2K","JPEG-2000 Code Stream Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJ2K;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ entry=AcquireMagickInfo("JP2","JPM","JPEG-2000 File Format Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJP2;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ entry=AcquireMagickInfo("JP2","JPT","JPEG-2000 File Format Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJP2;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ entry=AcquireMagickInfo("JP2","JPC","JPEG-2000 Code Stream Syntax");
+ if (*version != '\0')
+ entry->version=ConstantString(version);
+ entry->mime_type=ConstantString("image/jp2");
+ entry->magick=(IsImageFormatHandler *) IsJP2;
+ entry->flags^=CoderAdjoinFlag;
+ entry->flags|=CoderDecoderSeekableStreamFlag;
+ entry->flags|=CoderEncoderSeekableStreamFlag;
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+ entry->decoder=(DecodeImageHandler *) ReadJP2Image;
+ entry->encoder=(EncodeImageHandler *) WriteJP2Image;
+#endif
+ (void) RegisterMagickInfo(entry);
+ return(MagickImageCoderSignature);
+}
+
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% U n r e g i s t e r J P 2 I m a g e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% UnregisterJP2Image() removes format registrations made by the JP2 module
+% from the list of supported formats.
+%
+% The format of the UnregisterJP2Image method is:
+%
+% UnregisterJP2Image(void)
+%
+*/
+ModuleExport void UnregisterJP2Image(void)
+{
+ (void) UnregisterMagickInfo("JPC");
+ (void) UnregisterMagickInfo("JPT");
+ (void) UnregisterMagickInfo("JPM");
+ (void) UnregisterMagickInfo("JP2");
+ (void) UnregisterMagickInfo("J2K");
+}
+
+#if defined(MAGICKCORE_LIBOPENJP2_DELEGATE)
+/*
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+% %
+% %
+% %
+% W r i t e J P 2 I m a g e %
+% %
+% %
+% %
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%
+% WriteJP2Image() writes an image in the JPEG 2000 image format.
+%
+% JP2 support originally written by Nathan Brown, nathanbrown@letu.edu
+%
+% The format of the WriteJP2Image method is:
+%
+% MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
+% ExceptionInfo *exception)
+%
+% A description of each parameter follows.
+%
+% o image_info: the image info.
+%
+% o image: The image.
+%
+*/
+
+static void CinemaProfileCompliance(const opj_image_t *jp2_image,
+ opj_cparameters_t *parameters)
+{
+ /*
+ Digital Cinema 4K profile compliant codestream.
+ */
+ parameters->tile_size_on=OPJ_FALSE;
+ parameters->cp_tdx=1;
+ parameters->cp_tdy=1;
+ parameters->tp_flag='C';
+ parameters->tp_on=1;
+ parameters->cp_tx0=0;
+ parameters->cp_ty0=0;
+ parameters->image_offset_x0=0;
+ parameters->image_offset_y0=0;
+ parameters->cblockw_init=32;
+ parameters->cblockh_init=32;
+ parameters->csty|=0x01;
+ parameters->prog_order=OPJ_CPRL;
+ parameters->roi_compno=(-1);
+ parameters->subsampling_dx=1;
+ parameters->subsampling_dy=1;
+ parameters->irreversible=1;
+ if ((jp2_image->comps[0].w == 2048) || (jp2_image->comps[0].h == 1080))
+ {
+ /*
+ Digital Cinema 2K.
+ */
+ parameters->cp_cinema=OPJ_CINEMA2K_24;
+ parameters->cp_rsiz=OPJ_CINEMA2K;
+ parameters->max_comp_size=1041666;
+ if (parameters->numresolution > 6)
+ parameters->numresolution=6;
+
+ }
+ if ((jp2_image->comps[0].w == 4096) || (jp2_image->comps[0].h == 2160))
+ {
+ /*
+ Digital Cinema 4K.
+ */
+ parameters->cp_cinema=OPJ_CINEMA4K_24;
+ parameters->cp_rsiz=OPJ_CINEMA4K;
+ parameters->max_comp_size=1041666;
+ if (parameters->numresolution < 1)
+ parameters->numresolution=1;
+ if (parameters->numresolution > 7)
+ parameters->numresolution=7;
+ parameters->numpocs=2;
+ parameters->POC[0].tile=1;
+ parameters->POC[0].resno0=0;
+ parameters->POC[0].compno0=0;
+ parameters->POC[0].layno1=1;
+ parameters->POC[0].resno1=parameters->numresolution-1;
+ parameters->POC[0].compno1=3;
+ parameters->POC[0].prg1=OPJ_CPRL;
+ parameters->POC[1].tile=1;
+ parameters->POC[1].resno0=parameters->numresolution-1;
+ parameters->POC[1].compno0=0;
+ parameters->POC[1].layno1=1;
+ parameters->POC[1].resno1=parameters->numresolution;
+ parameters->POC[1].compno1=3;
+ parameters->POC[1].prg1=OPJ_CPRL;
+ }
+ parameters->tcp_numlayers=1;
+ parameters->tcp_rates[0]=((float) (jp2_image->numcomps*jp2_image->comps[0].w*
+ jp2_image->comps[0].h*jp2_image->comps[0].prec))/(parameters->max_comp_size*
+ 8*jp2_image->comps[0].dx*jp2_image->comps[0].dy);
+ parameters->cp_disto_alloc=1;
+}
+
+static MagickBooleanType WriteJP2Image(const ImageInfo *image_info,Image *image,
+ ExceptionInfo *exception)
+{
+ const char
+ *option,
+ *property;
+
+ int
+ jp2_status;
+
+ MagickBooleanType
+ status;
+
+ opj_codec_t
+ *jp2_codec;
+
+ OPJ_COLOR_SPACE
+ jp2_colorspace;
+
+ opj_cparameters_t
+ parameters;
+
+ opj_image_cmptparm_t
+ jp2_info[5];
+
+ opj_image_t
+ *jp2_image;
+
+ opj_stream_t
+ *jp2_stream;
+
+ register ssize_t
+ i;
+
+ ssize_t
+ y;
+
+ unsigned int
+ channels;
+
+ /*
+ Open image file.
+ */
+ assert(image_info != (const ImageInfo *) NULL);
+ assert(image_info->signature == MagickCoreSignature);
+ assert(image != (Image *) NULL);
+ assert(image->signature == MagickCoreSignature);
+ if (image->debug != MagickFalse)
+ (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename);
+ assert(exception != (ExceptionInfo *) NULL);
+ assert(exception->signature == MagickCoreSignature);
+ status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception);
+ if (status == MagickFalse)
+ return(status);
+ /*
+ Initialize JPEG 2000 API.
+ */
+ opj_set_default_encoder_parameters(¶meters);
+ for (i=1; i < 6; i++)
+ if (((size_t) (1UL << (i+2)) > image->columns) &&
+ ((size_t) (1UL << (i+2)) > image->rows))
+ break;
+ parameters.numresolution=i;
+ option=GetImageOption(image_info,"jp2:number-resolutions");
+ if (option != (const char *) NULL)
+ parameters.numresolution=StringToInteger(option);
+ parameters.tcp_numlayers=1;
+ parameters.tcp_rates[0]=0; /* lossless */
+ parameters.cp_disto_alloc=1;
+ if ((image_info->quality != 0) && (image_info->quality != 100))
+ {
+ parameters.tcp_distoratio[0]=(double) image_info->quality;
+ parameters.cp_fixed_quality=OPJ_TRUE;
+ }
+ if (image_info->extract != (char *) NULL)
+ {
+ RectangleInfo
+ geometry;
+
+ int
+ flags;
+
+ /*
+ Set tile size.
+ */
+ flags=ParseAbsoluteGeometry(image_info->extract,&geometry);
+ parameters.cp_tdx=(int) geometry.width;
+ parameters.cp_tdy=(int) geometry.width;
+ if ((flags & HeightValue) != 0)
+ parameters.cp_tdy=(int) geometry.height;
+ if ((flags & XValue) != 0)
+ parameters.cp_tx0=geometry.x;
+ if ((flags & YValue) != 0)
+ parameters.cp_ty0=geometry.y;
+ parameters.tile_size_on=OPJ_TRUE;
+ }
+ option=GetImageOption(image_info,"jp2:quality");
+ if (option != (const char *) NULL)
+ {
+ register const char
+ *p;
+
+ /*
+ Set quality PSNR.
+ */
+ p=option;
+ for (i=0; sscanf(p,"%f",¶meters.tcp_distoratio[i]) == 1; i++)
+ {
+ if (i > 100)
+ break;
+ while ((*p != '\0') && (*p != ','))
+ p++;
+ if (*p == '\0')
+ break;
+ p++;
+ }
+ parameters.tcp_numlayers=i+1;
+ parameters.cp_fixed_quality=OPJ_TRUE;
+ }
+ option=GetImageOption(image_info,"jp2:progression-order");
+ if (option != (const char *) NULL)
+ {
+ if (LocaleCompare(option,"LRCP") == 0)
+ parameters.prog_order=OPJ_LRCP;
+ if (LocaleCompare(option,"RLCP") == 0)
+ parameters.prog_order=OPJ_RLCP;
+ if (LocaleCompare(option,"RPCL") == 0)
+ parameters.prog_order=OPJ_RPCL;
+ if (LocaleCompare(option,"PCRL") == 0)
+ parameters.prog_order=OPJ_PCRL;
+ if (LocaleCompare(option,"CPRL") == 0)
+ parameters.prog_order=OPJ_CPRL;
+ }
+ option=GetImageOption(image_info,"jp2:rate");
+ if (option != (const char *) NULL)
+ {
+ register const char
+ *p;
+
+ /*
+ Set compression rate.
+ */
+ p=option;
+ for (i=0; sscanf(p,"%f",¶meters.tcp_rates[i]) == 1; i++)
+ {
+ if (i >= 100)
+ break;
+ while ((*p != '\0') && (*p != ','))
+ p++;
+ if (*p == '\0')
+ break;
+ p++;
+ }
+ parameters.tcp_numlayers=i+1;
+ parameters.cp_disto_alloc=OPJ_TRUE;
+ }
+ if (image_info->sampling_factor != (const char *) NULL)
+ (void) sscanf(image_info->sampling_factor,"%d,%d",
+ ¶meters.subsampling_dx,¶meters.subsampling_dy);
+ property=GetImageProperty(image,"comment",exception);
+ if (property != (const char *) NULL)
+ parameters.cp_comment=(char *) property;
+ channels=3;
+ jp2_colorspace=OPJ_CLRSPC_SRGB;
+ if (image->colorspace == YUVColorspace)
+ {
+ jp2_colorspace=OPJ_CLRSPC_SYCC;
+ parameters.subsampling_dx=2;
+ }
+ else
+ {
+ if (IsGrayColorspace(image->colorspace) != MagickFalse)
+ {
+ channels=1;
+ jp2_colorspace=OPJ_CLRSPC_GRAY;
+ }
+ else
+ (void) TransformImageColorspace(image,sRGBColorspace,exception);
+ if (image->alpha_trait != UndefinedPixelTrait)
+ channels++;
+ }
+ parameters.tcp_mct=channels == 3 ? 1 : 0;
+ memset(jp2_info,0,sizeof(jp2_info));
+ for (i=0; i < (ssize_t) channels; i++)
+ {
+ jp2_info[i].prec=(OPJ_UINT32) image->depth;
+ jp2_info[i].bpp=(OPJ_UINT32) image->depth;
+ if ((image->depth == 1) &&
+ ((LocaleCompare(image_info->magick,"JPT") == 0) ||
+ (LocaleCompare(image_info->magick,"JP2") == 0)))
+ {
+ jp2_info[i].prec++; /* OpenJPEG returns exception for depth @ 1 */
+ jp2_info[i].bpp++;
+ }
+ jp2_info[i].sgnd=0;
+ jp2_info[i].dx=parameters.subsampling_dx;
+ jp2_info[i].dy=parameters.subsampling_dy;
+ jp2_info[i].w=(OPJ_UINT32) image->columns;
+ jp2_info[i].h=(OPJ_UINT32) image->rows;
+ }
+ jp2_image=opj_image_create((OPJ_UINT32) channels,jp2_info,jp2_colorspace);
+ if (jp2_image == (opj_image_t *) NULL)
+ ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
+ jp2_image->x0=parameters.image_offset_x0;
+ jp2_image->y0=parameters.image_offset_y0;
+ jp2_image->x1=(unsigned int) (2*parameters.image_offset_x0+(image->columns-1)*
+ parameters.subsampling_dx+1);
+ jp2_image->y1=(unsigned int) (2*parameters.image_offset_y0+(image->rows-1)*
+ parameters.subsampling_dx+1);
+ if ((image->depth == 12) &&
+ ((image->columns == 2048) || (image->rows == 1080) ||
+ (image->columns == 4096) || (image->rows == 2160)))
+ CinemaProfileCompliance(jp2_image,¶meters);
+ if (channels == 4)
+ jp2_image->comps[3].alpha=1;
+ else
+ if ((channels == 2) && (jp2_colorspace == OPJ_CLRSPC_GRAY))
+ jp2_image->comps[1].alpha=1;
+ /*
+ Convert to JP2 pixels.
+ */
+ for (y=0; y < (ssize_t) image->rows; y++)
+ {
+ register const Quantum
+ *p;
+
+ ssize_t
+ x;
+
+ p=GetVirtualPixels(image,0,y,image->columns,1,exception);
+ if (p == (const Quantum *) NULL)
+ break;
+ for (x=0; x < (ssize_t) image->columns; x++)
+ {
+ for (i=0; i < (ssize_t) channels; i++)
+ {
+ double
+ scale;
+
+ register int
+ *q;
+
+ scale=(double) ((1UL << jp2_image->comps[i].prec)-1)/QuantumRange;
+ q=jp2_image->comps[i].data+(y/jp2_image->comps[i].dy*
+ image->columns/jp2_image->comps[i].dx+x/jp2_image->comps[i].dx);
+ switch (i)
+ {
+ case 0:
+ {
+ if (jp2_colorspace == OPJ_CLRSPC_GRAY)
+ {
+ *q=(int) (scale*GetPixelGray(image,p));
+ break;
+ }
+ *q=(int) (scale*GetPixelRed(image,p));
+ break;
+ }
+ case 1:
+ {
+ if (jp2_colorspace == OPJ_CLRSPC_GRAY)
+ {
+ *q=(int) (scale*GetPixelAlpha(image,p));
+ break;
+ }
+ *q=(int) (scale*GetPixelGreen(image,p));
+ break;
+ }
+ case 2:
+ {
+ *q=(int) (scale*GetPixelBlue(image,p));
+ break;
+ }
+ case 3:
+ {
+ *q=(int) (scale*GetPixelAlpha(image,p));
+ break;
+ }
+ }
+ }
+ p+=GetPixelChannels(image);
+ }
+ status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,
+ image->rows);
+ if (status == MagickFalse)
+ break;
+ }
+ if (LocaleCompare(image_info->magick,"JPT") == 0)
+ jp2_codec=opj_create_compress(OPJ_CODEC_JPT);
+ else
+ if (LocaleCompare(image_info->magick,"J2K") == 0)
+ jp2_codec=opj_create_compress(OPJ_CODEC_J2K);
+ else
+ jp2_codec=opj_create_compress(OPJ_CODEC_JP2);
+ opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
+ opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
+ opj_setup_encoder(jp2_codec,¶meters,jp2_image);
+ jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,OPJ_FALSE);
+ if (jp2_stream == (opj_stream_t *) NULL)
+ {
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
+ }
+ opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
+ opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
+ opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
+ opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
+ opj_stream_set_user_data(jp2_stream,image,NULL);
+ jp2_status=opj_start_compress(jp2_codec,jp2_image,jp2_stream);
+ if ((jp2_status == 0) || (opj_encode(jp2_codec,jp2_stream) == 0) ||
+ (opj_end_compress(jp2_codec,jp2_stream) == 0))
+ {
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ ThrowWriterException(DelegateError,"UnableToEncodeImageFile");
+ }
+ /*
+ Free resources.
+ */
+ opj_stream_destroy(jp2_stream);
+ opj_destroy_codec(jp2_codec);
+ opj_image_destroy(jp2_image);
+ (void) CloseBlob(image);
+ return(MagickTrue);
+}
+#endif
From 519f2a537a58aafffee030facfd965acf77635d5 Mon Sep 17 00:00:00 2001
From: Paul
Date: Mon, 13 Jul 2020 13:55:45 -0500
Subject: [PATCH 053/116] Format
---
lib/astutils.cpp | 13 ++++---------
lib/astutils.h | 6 +-----
lib/checkcondition.cpp | 2 +-
test/testcondition.cpp | 3 ++-
4 files changed, 8 insertions(+), 16 deletions(-)
diff --git a/lib/astutils.cpp b/lib/astutils.cpp
index 7d636c829..293ad1dcc 100644
--- a/lib/astutils.cpp
+++ b/lib/astutils.cpp
@@ -539,10 +539,10 @@ bool exprDependsOnThis(const Token* expr, nonneg int depth)
// calling nonstatic method?
if (Token::Match(expr->previous(), "!!:: %name% (") && expr->function() && expr->function()->nestedIn && expr->function()->nestedIn->isClassOrStruct()) {
// is it a method of this?
- const Scope *fScope = expr->scope();
+ const Scope* fScope = expr->scope();
while (!fScope->functionOf && fScope->nestedIn)
fScope = fScope->nestedIn;
- const Scope *nestedIn = fScope->functionOf;
+ const Scope* nestedIn = fScope->functionOf;
if (nestedIn && nestedIn->function)
nestedIn = nestedIn->function->token->scope();
while (nestedIn && nestedIn != expr->function()->nestedIn) {
@@ -1565,11 +1565,7 @@ bool isVariablesChanged(const Token* start,
return false;
}
-bool isThisChanged(const Token* start,
- const Token* end,
- int indirect,
- const Settings* settings,
- bool cpp)
+bool isThisChanged(const Token* start, const Token* end, int indirect, const Settings* settings, bool cpp)
{
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (!exprDependsOnThis(tok))
@@ -1580,10 +1576,9 @@ bool isThisChanged(const Token* start,
return true;
else
continue;
- } else if (!tok->previous()->isKeyword()){
+ } else if (!tok->previous()->isKeyword()) {
return true;
}
-
}
if (isVariableChanged(tok, indirect, settings, cpp))
return true;
diff --git a/lib/astutils.h b/lib/astutils.h
index 20e402d42..cb453482c 100644
--- a/lib/astutils.h
+++ b/lib/astutils.h
@@ -192,11 +192,7 @@ bool isVariablesChanged(const Token* start,
const Settings* settings,
bool cpp);
-bool isThisChanged(const Token* start,
- const Token* end,
- int indirect,
- const Settings* settings,
- bool cpp);
+bool isThisChanged(const Token* start, const Token* end, int indirect, const Settings* settings, bool cpp);
const Token* findVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int varid, bool globalvar, const Settings *settings, bool cpp, int depth = 20);
Token* findVariableChanged(Token *start, const Token *end, int indirect, const nonneg int varid, bool globalvar, const Settings *settings, bool cpp, int depth = 20);
diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp
index 17e3e026e..ca086d5b1 100644
--- a/lib/checkcondition.cpp
+++ b/lib/checkcondition.cpp
@@ -452,7 +452,7 @@ void CheckCondition::duplicateCondition()
continue;
bool modified = false;
- visitAstNodes(cond1, [&](const Token *tok3) {
+ visitAstNodes(cond1, [&](const Token* tok3) {
if (exprDependsOnThis(tok3)) {
if (isThisChanged(scope.classDef->next(), cond2, false, mSettings, mTokenizer->isCPP())) {
modified = true;
diff --git a/test/testcondition.cpp b/test/testcondition.cpp
index 05c6ba239..7519a17e7 100644
--- a/test/testcondition.cpp
+++ b/test/testcondition.cpp
@@ -3715,7 +3715,8 @@ private:
" }\n"
" }\n"
"}\n");
- ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) The if condition is the same as the previous if condition\n", errout.str());
+ ASSERT_EQUALS("[test.cpp:7] -> [test.cpp:9]: (style) The if condition is the same as the previous if condition\n",
+ errout.str());
}
void checkInvalidTestForOverflow() {
From 6030ab72ab4651cd0bc5279e2b4941ddc04c4499 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 08:12:40 +0200
Subject: [PATCH 054/116] Bug hunting; Avoid some bailout false positives in
uninit checker
---
lib/bughuntingchecks.cpp | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 39062cfac..85c598062 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -226,6 +226,10 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (tok->astParent()->str() == "::" && tok == tok->astParent()->astOperand1())
return;
+ // Object allocated on the stack
+ if (tok->valueType() && tok->valueType()->pointer == 0 && Token::Match(tok, "%var% ."))
+ return;
+
// Containers are not uninitialized
std::vector tokens{tok, tok->astOperand1(), tok->astOperand2()};
if (Token::Match(tok->previous(), ". %name%"))
From fe324aea4998b411c0e450654c66d54717683e6b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 10:25:00 +0200
Subject: [PATCH 055/116] Bug hunting; Detect internal error and throw
exception
---
lib/exprengine.cpp | 2 ++
1 file changed, 2 insertions(+)
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index 0e96a97fb..4a2d66808 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -716,6 +716,8 @@ namespace {
const std::string c = line.substr(pos, end-pos);
pos = end;
d.constraints.push_back(c);
+ } else {
+ throw ExprEngineException(nullptr, "Internal Error: Data::parsestr(), line:" + line);
}
}
importData->push_back(d);
From 176826a1f5dd26b47f8a166a4cea9edf806cd604 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 11:15:26 +0200
Subject: [PATCH 056/116] Bug hunting; Avoid false positives
---
lib/bughuntingchecks.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 85c598062..46879ec04 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -227,7 +227,7 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
return;
// Object allocated on the stack
- if (tok->valueType() && tok->valueType()->pointer == 0 && Token::Match(tok, "%var% ."))
+ if (Token::Match(tok, "%var% .") && tok->next()->originalName() != "->")
return;
// Containers are not uninitialized
From 8d6fd4769b60950decda14cfda4f585502ed2c47 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 11:22:42 +0200
Subject: [PATCH 057/116] Bug hunting; Terminating analysis
---
lib/exprengine.cpp | 6 ++++++
1 file changed, 6 insertions(+)
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index 4a2d66808..388f4149c 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -154,6 +154,7 @@ namespace {
const Token *tok;
const std::string what;
};
+ struct TerminateExpression {};
}
static std::string str(ExprEngine::ValuePtr val)
@@ -2153,6 +2154,9 @@ static ExprEngine::ValuePtr executeStringLiteral(const Token *tok, Data &data)
static ExprEngine::ValuePtr executeExpression1(const Token *tok, Data &data)
{
+ if (data.settings->terminated())
+ throw TerminateExpression();
+
if (tok->str() == "return")
return executeReturn(tok, data);
@@ -2489,6 +2493,8 @@ void ExprEngine::executeAllFunctions(ErrorLogger *errorLogger, const Tokenizer *
// FIXME.. there should not be exceptions
std::string functionName = functionScope->function->name();
std::cout << "Verify: Aborted analysis of function '" << functionName << "': " << e.what() << std::endl;
+ } catch (const TerminateExpression &) {
+ break;
}
}
}
From a6d70b9022da74bc5350d6f4645910023ead1674 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 16:54:00 +0200
Subject: [PATCH 058/116] Code cleanup, __temp__ files are not needed anymore
---
lib/analyzerinfo.cpp | 6 ------
1 file changed, 6 deletions(-)
diff --git a/lib/analyzerinfo.cpp b/lib/analyzerinfo.cpp
index 460d9cf16..1d6af8537 100644
--- a/lib/analyzerinfo.cpp
+++ b/lib/analyzerinfo.cpp
@@ -59,12 +59,6 @@ void AnalyzerInformation::writeFilesTxt(const std::string &buildDir, const std::
const std::string afile = getFilename(fs.filename);
fout << afile << ".a" << (++fileCount[afile]) << ":" << fs.cfg << ":" << Path::simplifyPath(Path::fromNativeSeparators(fs.filename)) << std::endl;
}
-
- std::ofstream fc(buildDir + "/__temp__.c");
- fc << "int x;\n";
-
- std::ofstream fcpp(buildDir + "/__temp__.cpp");
- fcpp << "int x;\n";
}
void AnalyzerInformation::close()
From 62702a6816bf21671c86d7af6465e8db982f2982 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 18:19:03 +0200
Subject: [PATCH 059/116] GUI: Use const argument
---
gui/resultstree.cpp | 2 +-
gui/resultstree.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index 435412780..c3e3d4b22 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -1133,7 +1133,7 @@ void ResultsTree::saveResults(Report *report) const
report->writeFooter();
}
-void ResultsTree::saveErrors(Report *report, QStandardItem *fileItem) const
+void ResultsTree::saveErrors(Report *report, const QStandardItem *fileItem) const
{
if (!fileItem) {
return;
diff --git a/gui/resultstree.h b/gui/resultstree.h
index 71c237bb5..55b5b709e 100644
--- a/gui/resultstree.h
+++ b/gui/resultstree.h
@@ -333,7 +333,7 @@ protected:
* @param report Report that errors are saved to
* @param fileItem Item whose errors to save
*/
- void saveErrors(Report *report, QStandardItem *fileItem) const;
+ void saveErrors(Report *report, const QStandardItem *fileItem) const;
/**
* @brief Convert a severity string to a icon filename
From 4373404238a785bcb5b73d96a82afd0111086cfa Mon Sep 17 00:00:00 2001
From: Paul
Date: Tue, 14 Jul 2020 13:04:59 -0500
Subject: [PATCH 060/116] Revert "Fixed #9795 (False positive: Local lock is
not ineffective, mutex is locked in thread also.)"
This reverts commit 27841d6b811a9a7537efe943af23f99f5afb68ce.
---
lib/checkstl.cpp | 29 ++++++++++++++++++++++++++-
lib/checkstl.h | 2 ++
test/teststl.cpp | 51 ++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 81 insertions(+), 1 deletion(-)
diff --git a/lib/checkstl.cpp b/lib/checkstl.cpp
index 58706e2ae..ebeb7f44f 100644
--- a/lib/checkstl.cpp
+++ b/lib/checkstl.cpp
@@ -2394,12 +2394,25 @@ void CheckStl::useStlAlgorithm()
}
}
+static bool isMutex(const Variable* var)
+{
+ const Token* tok = Token::typeDecl(var->nameToken()).first;
+ return Token::Match(tok, "std :: mutex|recursive_mutex|timed_mutex|recursive_timed_mutex|shared_mutex");
+}
+
static bool isLockGuard(const Variable* var)
{
const Token* tok = Token::typeDecl(var->nameToken()).first;
return Token::Match(tok, "std :: lock_guard|unique_lock|scoped_lock");
}
+static bool isLocalMutex(const Variable* var, const Scope* scope)
+{
+ if (!var)
+ return false;
+ return !var->isReference() && !var->isRValueReference() && !var->isStatic() && var->scope() == scope;
+}
+
void CheckStl::globalLockGuardError(const Token* tok)
{
reportError(tok, Severity::warning,
@@ -2407,6 +2420,13 @@ void CheckStl::globalLockGuardError(const Token* tok)
"Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.", CWE833, false);
}
+void CheckStl::localMutexError(const Token* tok)
+{
+ reportError(tok, Severity::warning,
+ "localMutex",
+ "The lock is ineffective because the mutex is locked at the same scope as the mutex itself.", CWE667, false);
+}
+
void CheckStl::checkMutexes()
{
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
@@ -2414,12 +2434,19 @@ void CheckStl::checkMutexes()
const Variable* var = tok->variable();
if (!var)
continue;
- if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
+ if (Token::Match(tok, "%var% . lock ( )")) {
+ if (!isMutex(var))
+ continue;
+ if (isLocalMutex(var, tok->scope()))
+ localMutexError(tok);
+ } else if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
if (!isLockGuard(var))
continue;
const Variable* mvar = tok->tokAt(2)->variable();
if (var->isStatic() || var->isGlobal())
globalLockGuardError(tok);
+ else if (isLocalMutex(mvar, tok->scope()))
+ localMutexError(tok);
}
}
}
diff --git a/lib/checkstl.h b/lib/checkstl.h
index a0ae7d1e5..9dd5e07d5 100644
--- a/lib/checkstl.h
+++ b/lib/checkstl.h
@@ -233,6 +233,7 @@ private:
void useStlAlgorithmError(const Token *tok, const std::string &algoName);
void globalLockGuardError(const Token *tok);
+ void localMutexError(const Token *tok);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const OVERRIDE {
ErrorPath errorPath;
@@ -271,6 +272,7 @@ private:
c.readingEmptyStlContainerError(nullptr);
c.useStlAlgorithmError(nullptr, "");
c.globalLockGuardError(nullptr);
+ c.localMutexError(nullptr);
}
static std::string myName() {
diff --git a/test/teststl.cpp b/test/teststl.cpp
index e9e929a92..240e20709 100644
--- a/test/teststl.cpp
+++ b/test/teststl.cpp
@@ -4445,6 +4445,28 @@ private:
true);
ASSERT_EQUALS("", errout.str());
+ check("void f() {\n"
+ " std::mutex m;\n"
+ " std::lock_guard g(m);\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
+ check("void f() {\n"
+ " std::mutex m;\n"
+ " std::unique_lock g(m);\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
+ check("void f() {\n"
+ " std::mutex m;\n"
+ " std::unique_lock g(m, std::defer_lock);\n"
+ " std::lock(g);\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:3]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
check("void g();\n"
"void f() {\n"
" static std::mutex m;\n"
@@ -4455,6 +4477,16 @@ private:
true);
ASSERT_EQUALS("", errout.str());
+ check("void g();\n"
+ "void f() {\n"
+ " std::mutex m;\n"
+ " m.lock();\n"
+ " g();\n"
+ " m.unlock();\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
check("class A {\n"
" std::mutex m;\n"
" void f() {\n"
@@ -4503,6 +4535,25 @@ private:
"}\n",
true);
ASSERT_EQUALS("", errout.str());
+
+ check("std::mutex& h();\n"
+ "void f() {\n"
+ " auto m = h();\n"
+ " std::lock_guard g(m);\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:4]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
+
+ check("void g();\n"
+ "std::mutex& h();\n"
+ "void f() {\n"
+ " auto m = h();\n"
+ " m.lock();\n"
+ " g();\n"
+ " m.unlock();\n"
+ "}\n",
+ true);
+ ASSERT_EQUALS("[test.cpp:5]: (warning) The lock is ineffective because the mutex is locked at the same scope as the mutex itself.\n", errout.str());
}
};
From af0db3cc2176079fc752402a083ee09604cef4ec Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 14 Jul 2020 22:30:42 +0200
Subject: [PATCH 061/116] Add cppcheck-id for warnings. To start with it's a
simple id that changes when file is changed.
---
lib/errorlogger.cpp | 46 +++++++++++++++++++++++++++-------------
lib/errorlogger.h | 3 +++
test/testerrorlogger.cpp | 2 ++
3 files changed, 36 insertions(+), 15 deletions(-)
diff --git a/lib/errorlogger.cpp b/lib/errorlogger.cpp
index 97f8f5ab3..b3d25952b 100644
--- a/lib/errorlogger.cpp
+++ b/lib/errorlogger.cpp
@@ -32,6 +32,7 @@
#include
#include
#include
+#include // std::hash
InternalError::InternalError(const Token *tok, const std::string &errorMsg, Type type) :
token(tok), errorMessage(errorMsg), type(type)
@@ -58,8 +59,15 @@ InternalError::InternalError(const Token *tok, const std::string &errorMsg, Type
}
}
+static std::size_t calculateCppcheckId(const TokenList *tokenList, const std::string &msg)
+{
+ if (!tokenList)
+ return 0;
+ return std::hash {}(msg + "\n" + tokenList->front()->stringifyList(false, true, false, false, false));
+}
+
ErrorMessage::ErrorMessage()
- : incomplete(false), severity(Severity::none), cwe(0U), inconclusive(false)
+ : incomplete(false), severity(Severity::none), cwe(0U), inconclusive(false), cppcheckId(0)
{
}
@@ -70,7 +78,8 @@ ErrorMessage::ErrorMessage(const std::list &callStack, const std::
incomplete(false),
severity(severity), // severity for this error message
cwe(0U),
- inconclusive(inconclusive)
+ inconclusive(inconclusive),
+ cppcheckId(0)
{
// set the summary and verbose messages
setmsg(msg);
@@ -85,14 +94,15 @@ ErrorMessage::ErrorMessage(const std::list &callStack, const std::
incomplete(false),
severity(severity), // severity for this error message
cwe(cwe.id),
- inconclusive(inconclusive)
+ inconclusive(inconclusive),
+ cppcheckId(0)
{
// set the summary and verbose messages
setmsg(msg);
}
ErrorMessage::ErrorMessage(const std::list& callstack, const TokenList* list, Severity::SeverityType severity, const std::string& id, const std::string& msg, bool inconclusive)
- : id(id), incomplete(false), severity(severity), cwe(0U), inconclusive(inconclusive)
+ : id(id), incomplete(false), severity(severity), cwe(0U), inconclusive(inconclusive), cppcheckId(0)
{
// Format callstack
for (std::list::const_iterator it = callstack.begin(); it != callstack.end(); ++it) {
@@ -126,6 +136,8 @@ ErrorMessage::ErrorMessage(const std::list& callstack, const Token
file0 = list->getFiles()[0];
setmsg(msg);
+
+ cppcheckId = calculateCppcheckId(list, toString(false));
}
ErrorMessage::ErrorMessage(const ErrorPath &errorPath, const TokenList *tokenList, Severity::SeverityType severity, const char id[], const std::string &msg, const CWE &cwe, bool inconclusive)
@@ -145,6 +157,8 @@ ErrorMessage::ErrorMessage(const ErrorPath &errorPath, const TokenList *tokenLis
file0 = tokenList->getFiles()[0];
setmsg(msg);
+
+ cppcheckId = calculateCppcheckId(tokenList, toString(false));
}
ErrorMessage::ErrorMessage(const tinyxml2::XMLElement * const errmsg)
@@ -173,6 +187,9 @@ ErrorMessage::ErrorMessage(const tinyxml2::XMLElement * const errmsg)
attr = errmsg->Attribute("verbose");
mVerboseMessage = attr ? attr : "";
+ attr = errmsg->Attribute("cppcheck-id");
+ std::istringstream(attr ? attr : "0") >> cppcheckId;
+
for (const tinyxml2::XMLElement *e = errmsg->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(),"location")==0) {
const char *strfile = e->Attribute("file");
@@ -236,6 +253,7 @@ std::string ErrorMessage::serialize() const
oss << id.length() << " " << id;
oss << Severity::toString(severity).length() << " " << Severity::toString(severity);
oss << MathLib::toString(cwe.id).length() << " " << MathLib::toString(cwe.id);
+ oss << MathLib::toString(cppcheckId).length() << " " << MathLib::toString(cppcheckId);
if (inconclusive) {
const std::string text("inconclusive");
oss << text.length() << " " << text;
@@ -262,9 +280,9 @@ bool ErrorMessage::deserialize(const std::string &data)
inconclusive = false;
callStack.clear();
std::istringstream iss(data);
- std::array results;
+ std::array results;
std::size_t elem = 0;
- while (iss.good()) {
+ while (iss.good() && elem < 6) {
unsigned int len = 0;
if (!(iss >> len))
return false;
@@ -282,19 +300,17 @@ bool ErrorMessage::deserialize(const std::string &data)
}
results[elem++] = temp;
- if (elem == 5)
- break;
}
- if (elem != 5)
+ if (elem != 6)
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed");
id = results[0];
severity = Severity::fromString(results[1]);
- std::istringstream scwe(results[2]);
- scwe >> cwe.id;
- mShortMessage = results[3];
- mVerboseMessage = results[4];
+ std::istringstream(results[2]) >> cwe.id;
+ std::istringstream(results[3]) >> cppcheckId;
+ mShortMessage = results[4];
+ mVerboseMessage = results[5];
unsigned int stackSize = 0;
if (!(iss >> stackSize))
@@ -347,8 +363,6 @@ bool ErrorMessage::deserialize(const std::string &data)
std::string ErrorMessage::getXMLHeader()
{
- // xml_version 1 is the default xml format
-
tinyxml2::XMLPrinter printer;
// standard xml header
@@ -403,6 +417,8 @@ std::string ErrorMessage::toXML() const
printer.PushAttribute("verbose", fixInvalidChars(mVerboseMessage).c_str());
if (cwe.id)
printer.PushAttribute("cwe", cwe.id);
+ if (cppcheckId)
+ printer.PushAttribute("cppcheck-id", MathLib::toString(cppcheckId).c_str());
if (inconclusive)
printer.PushAttribute("inconclusive", "true");
diff --git a/lib/errorlogger.h b/lib/errorlogger.h
index ea03eecce..76d168be5 100644
--- a/lib/errorlogger.h
+++ b/lib/errorlogger.h
@@ -196,6 +196,9 @@ public:
CWE cwe;
bool inconclusive;
+ /** Warning ID */
+ std::size_t cppcheckId;
+
/** set short and verbose messages */
void setmsg(const std::string &msg);
diff --git a/test/testerrorlogger.cpp b/test/testerrorlogger.cpp
index 3fb718371..f827f8723 100644
--- a/test/testerrorlogger.cpp
+++ b/test/testerrorlogger.cpp
@@ -252,6 +252,7 @@ private:
ASSERT_EQUALS("7 errorId"
"5 error"
"1 0"
+ "1 0"
"12 inconclusive"
"17 Programming error"
"17 Programming error"
@@ -278,6 +279,7 @@ private:
ASSERT_EQUALS("7 errorId"
"5 error"
"1 0"
+ "1 0"
"33 Illegal character in \"foo\\001bar\""
"33 Illegal character in \"foo\\001bar\""
"0 ", msg.serialize());
From 260c53ba6f73e7395e11c6232aa78f6a1eb51639 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 15 Jul 2020 07:59:05 +0200
Subject: [PATCH 062/116] GUI: Write cppcheck-id in xml report
---
gui/erroritem.cpp | 9 +++++++--
gui/erroritem.h | 4 +++-
gui/resultstree.cpp | 4 ++++
gui/resultsview.cpp | 2 +-
gui/xmlreportv2.cpp | 7 ++++++-
5 files changed, 21 insertions(+), 5 deletions(-)
diff --git a/gui/erroritem.cpp b/gui/erroritem.cpp
index acf420204..cccc25911 100644
--- a/gui/erroritem.cpp
+++ b/gui/erroritem.cpp
@@ -37,6 +37,7 @@ ErrorItem::ErrorItem()
, incomplete(false)
, inconclusive(false)
, cwe(-1)
+ , cppcheckId(0)
{
}
@@ -50,6 +51,7 @@ ErrorItem::ErrorItem(const ErrorMessage &errmsg)
, summary(QString::fromStdString(errmsg.shortMessage()))
, message(QString::fromStdString(errmsg.verboseMessage()))
, cwe(errmsg.cwe.id)
+ , cppcheckId(errmsg.cppcheckId)
, symbolNames(QString::fromStdString(errmsg.symbolNames()))
{
for (std::list::const_iterator loc = errmsg.callStack.begin();
@@ -70,7 +72,7 @@ QString ErrorItem::tool() const
return "cppcheck";
}
-QString ErrorItem::ToString() const
+QString ErrorItem::toString() const
{
QString str = errorPath.back().file + " - " + errorId + " - ";
if (inconclusive)
@@ -86,7 +88,10 @@ QString ErrorItem::ToString() const
bool ErrorItem::sameCID(const ErrorItem &errorItem1, const ErrorItem &errorItem2)
{
- // TODO: Implement some better CID calculation
+ if (errorItem1.cppcheckId || errorItem2.cppcheckId)
+ return errorItem1.cppcheckId == errorItem2.cppcheckId;
+
+ // fallback
return errorItem1.errorId == errorItem2.errorId &&
errorItem1.errorPath == errorItem2.errorPath &&
errorItem1.file0 == errorItem2.file0 &&
diff --git a/gui/erroritem.h b/gui/erroritem.h
index 96ed90e7d..7bcb9a74f 100644
--- a/gui/erroritem.h
+++ b/gui/erroritem.h
@@ -76,7 +76,7 @@ public:
* @brief Convert error item to string.
* @return Error item as string.
*/
- QString ToString() const;
+ QString toString() const;
QString tool() const;
QString file0;
@@ -88,6 +88,7 @@ public:
QString summary;
QString message;
int cwe;
+ unsigned long long cppcheckId;
QList errorPath;
QString symbolNames;
@@ -114,6 +115,7 @@ public:
QString errorId;
bool incomplete;
int cwe;
+ unsigned long long cppcheckId;
bool inconclusive;
Severity::SeverityType severity;
QString summary;
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index c3e3d4b22..cbb1e3b93 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -168,6 +168,7 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
line.errorId = item.errorId;
line.incomplete = item.incomplete;
line.cwe = item.cwe;
+ line.cppcheckId = item.cppcheckId;
line.inconclusive = item.inconclusive;
line.summary = item.summary;
line.message = item.message;
@@ -197,6 +198,7 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
data["id"] = item.errorId;
data["incomplete"] = item.incomplete;
data["cwe"] = item.cwe;
+ data["cppcheckId"] = item.cppcheckId;
data["inconclusive"] = item.inconclusive;
data["file0"] = stripPath(item.file0, true);
data["function"] = item.function;
@@ -232,6 +234,7 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
child_data["id"] = line.errorId;
child_data["incomplete"] = line.incomplete;
child_data["cwe"] = line.cwe;
+ child_data["cppcheckId"] = line.cppcheckId;
child_data["inconclusive"] = line.inconclusive;
child_item->setData(QVariant(child_data));
}
@@ -1221,6 +1224,7 @@ void ResultsTree::readErrorItem(const QStandardItem *error, ErrorItem *item) con
item->errorId = data["id"].toString();
item->incomplete = data["incomplete"].toBool();
item->cwe = data["cwe"].toInt();
+ item->cppcheckId = data["cppcheckId"].toULongLong();
item->inconclusive = data["inconclusive"].toBool();
item->file0 = data["file0"].toString();
item->sinceDate = data["sinceDate"].toString();
diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp
index 1dc0a294c..fcc88d73b 100644
--- a/gui/resultsview.cpp
+++ b/gui/resultsview.cpp
@@ -448,7 +448,7 @@ void ResultsView::log(const QString &str)
void ResultsView::debugError(const ErrorItem &item)
{
- mUI.mListLog->addItem(item.ToString());
+ mUI.mListLog->addItem(item.toString());
}
void ResultsView::bughuntingReportLine(const QString& line)
diff --git a/gui/xmlreportv2.cpp b/gui/xmlreportv2.cpp
index f70053de5..5fac01c9e 100644
--- a/gui/xmlreportv2.cpp
+++ b/gui/xmlreportv2.cpp
@@ -34,6 +34,7 @@ static const QString ErrorElementName = "error";
static const QString ErrorsElementName = "errors";
static const QString LocationElementName = "location";
static const QString CWEAttribute = "cwe";
+static const QString CppcheckIdAttribute = "cppcheck-id";
static const QString SinceDateAttribute = "sinceDate";
static const QString TagsAttribute = "tag";
static const QString FilenameAttribute = "file";
@@ -122,6 +123,8 @@ void XmlReportV2::writeError(const ErrorItem &error)
mXmlWriter->writeAttribute(InconclusiveAttribute, "true");
if (error.cwe > 0)
mXmlWriter->writeAttribute(CWEAttribute, QString::number(error.cwe));
+ if (error.cppcheckId > 0)
+ mXmlWriter->writeAttribute(CppcheckIdAttribute, QString::number(error.cppcheckId));
if (!error.sinceDate.isEmpty())
mXmlWriter->writeAttribute(SinceDateAttribute, error.sinceDate);
if (!error.tags.isEmpty())
@@ -214,7 +217,9 @@ ErrorItem XmlReportV2::readError(QXmlStreamReader *reader)
if (attribs.hasAttribute(QString(), InconclusiveAttribute))
item.inconclusive = true;
if (attribs.hasAttribute(QString(), CWEAttribute))
- item.cwe = attribs.value(QString(), CWEAttribute).toString().toInt();
+ item.cwe = attribs.value(QString(), CWEAttribute).toInt();
+ if (attribs.hasAttribute(QString(), CppcheckIdAttribute))
+ item.cppcheckId = attribs.value(QString(), CWEAttribute).toULongLong();
if (attribs.hasAttribute(QString(), SinceDateAttribute))
item.sinceDate = attribs.value(QString(), SinceDateAttribute).toString();
if (attribs.hasAttribute(QString(), TagsAttribute))
From 6ab4f39f523f3e55a4e001a3e3468a8b2c549d4c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 15 Jul 2020 13:03:07 +0200
Subject: [PATCH 063/116] GUI: Suppress cppcheck-id
---
gui/mainwindow.cpp | 3 +++
gui/projectfile.cpp | 15 +++++++++++++++
gui/projectfile.h | 14 ++++++++++++++
gui/resultstree.cpp | 27 +++++++++++++++++++++++++++
gui/resultstree.h | 3 +++
gui/xmlreportv2.cpp | 2 +-
lib/errorlogger.cpp | 1 +
lib/suppressions.cpp | 10 ++++++++--
lib/suppressions.h | 9 +++++++--
9 files changed, 79 insertions(+), 5 deletions(-)
diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp
index 0a78fc653..e721b605c 100644
--- a/gui/mainwindow.cpp
+++ b/gui/mainwindow.cpp
@@ -341,6 +341,7 @@ void MainWindow::loadSettings()
if (inf.exists() && inf.isReadable()) {
setPath(SETTINGS_LAST_PROJECT_PATH, projectFile);
mProjectFile = new ProjectFile(this);
+ mProjectFile->setActiveProject();
mProjectFile->read(projectFile);
loadLastResults();
QDir::setCurrent(inf.absolutePath());
@@ -1508,6 +1509,7 @@ void MainWindow::loadProjectFile(const QString &filePath)
mUI.mActionEditProjectFile->setEnabled(true);
delete mProjectFile;
mProjectFile = new ProjectFile(filePath, this);
+ mProjectFile->setActiveProject();
updateContractsTab();
if (!loadLastResults())
analyzeProject(mProjectFile);
@@ -1630,6 +1632,7 @@ void MainWindow::newProjectFile()
delete mProjectFile;
mProjectFile = new ProjectFile(this);
+ mProjectFile->setActiveProject();
mProjectFile->setFilename(filepath);
mProjectFile->setBuildDir(filename.left(filename.indexOf(".")) + "-cppcheck-build-dir");
diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp
index 01bdd28fa..fce386ee8 100644
--- a/gui/projectfile.cpp
+++ b/gui/projectfile.cpp
@@ -28,6 +28,8 @@
#include "settings.h"
+ProjectFile *ProjectFile::mActiveProject;
+
ProjectFile::ProjectFile(QObject *parent) :
QObject(parent)
{
@@ -603,6 +605,8 @@ void ProjectFile::readSuppressions(QXmlStreamReader &reader)
suppression.lineNumber = reader.attributes().value(QString(),"lineNumber").toInt();
if (reader.attributes().hasAttribute(QString(),"symbolName"))
suppression.symbolName = reader.attributes().value(QString(),"symbolName").toString().toStdString();
+ if (reader.attributes().hasAttribute(QString(),"cppcheck-id"))
+ suppression.cppcheckId = reader.attributes().value(QString(),"cppcheck-id").toULongLong();
type = reader.readNext();
if (type == QXmlStreamReader::Characters) {
suppression.errorId = reader.text().toString().toStdString();
@@ -873,6 +877,8 @@ bool ProjectFile::write(const QString &filename)
xmlWriter.writeAttribute("lineNumber", QString::number(suppression.lineNumber));
if (!suppression.symbolName.empty())
xmlWriter.writeAttribute("symbolName", QString::fromStdString(suppression.symbolName));
+ if (suppression.cppcheckId > 0)
+ xmlWriter.writeAttribute("cppcheck-id", QString::number(suppression.cppcheckId));
if (!suppression.errorId.empty())
xmlWriter.writeCharacters(QString::fromStdString(suppression.errorId));
xmlWriter.writeEndElement();
@@ -1022,3 +1028,12 @@ QString ProjectFile::getAddonFilePath(QString filesDir, const QString &addon)
return QString();
}
+void ProjectFile::suppressCppcheckId(std::size_t cppcheckId)
+{
+ if (cppcheckId > 0) {
+ Suppressions::Suppression s;
+ s.cppcheckId = cppcheckId;
+ mSuppressions.append(s);
+ write();
+ }
+}
diff --git a/gui/projectfile.h b/gui/projectfile.h
index 18772dcd8..fc1effc00 100644
--- a/gui/projectfile.h
+++ b/gui/projectfile.h
@@ -44,6 +44,19 @@ class ProjectFile : public QObject {
public:
explicit ProjectFile(QObject *parent = nullptr);
explicit ProjectFile(const QString &filename, QObject *parent = nullptr);
+ ~ProjectFile() {
+ if (this == mActiveProject) mActiveProject = nullptr;
+ }
+
+ static ProjectFile* getActiveProject() {
+ return mActiveProject;
+ }
+ void setActiveProject() {
+ mActiveProject = this;
+ }
+
+ /** Suppress warning with Cppcheck-ID */
+ void suppressCppcheckId(std::size_t cppcheckId);
/**
* @brief Read the project file.
@@ -551,6 +564,7 @@ private:
QStringList mCheckUnknownFunctionReturn;
+ static ProjectFile *mActiveProject;
};
/// @}
#endif // PROJECT_FILE_H
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index cbb1e3b93..7233a4d15 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -43,6 +43,7 @@
#include "resultstree.h"
#include "report.h"
#include "application.h"
+#include "projectfile.h"
#include "showtypes.h"
#include "threadhandler.h"
#include "path.h"
@@ -638,6 +639,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
QAction *copy = new QAction(tr("Copy"), &menu);
QAction *hide = new QAction(tr("Hide"), &menu);
QAction *hideallid = new QAction(tr("Hide all with id"), &menu);
+ QAction *suppressCppcheckID = new QAction(tr("Suppress cppcheck-id"), &menu);
QAction *opencontainingfolder = new QAction(tr("Open containing folder"), &menu);
if (multipleSelection) {
@@ -655,6 +657,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
menu.addSeparator();
menu.addAction(hide);
menu.addAction(hideallid);
+ menu.addAction(suppressCppcheckID);
if (!bughunting) {
QAction *suppress = new QAction(tr("Suppress selected id(s)"), &menu);
menu.addAction(suppress);
@@ -667,6 +670,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
connect(copy, SIGNAL(triggered()), this, SLOT(copy()));
connect(hide, SIGNAL(triggered()), this, SLOT(hideResult()));
connect(hideallid, SIGNAL(triggered()), this, SLOT(hideAllIdResult()));
+ connect(suppressCppcheckID, &QAction::triggered, this, &ResultsTree::suppressCppcheckID);
connect(opencontainingfolder, SIGNAL(triggered()), this, SLOT(openContainingFolder()));
if (!mTags.isEmpty()) {
@@ -1031,12 +1035,35 @@ void ResultsTree::suppressSelectedIds()
j++;
}
}
+ if (file->rowCount() == 0)
+ mModel.removeRow(file->row());
}
emit suppressIds(selectedIds.toList());
}
+void ResultsTree::suppressCppcheckID()
+{
+ if (!mSelectionModel)
+ return;
+ ProjectFile *projectFile = ProjectFile::getActiveProject();
+ foreach (QModelIndex index, mSelectionModel->selectedRows()) {
+ QStandardItem *item = mModel.itemFromIndex(index);
+ if (!item->parent())
+ continue;
+ while (item->parent()->parent())
+ item = item->parent();
+ const QVariantMap data = item->data().toMap();
+ if (projectFile && data.contains("cppcheckId"))
+ projectFile->suppressCppcheckId(data["cppcheckId"].toULongLong());
+ QStandardItem *fileItem = item->parent();
+ fileItem->removeRow(item->row());
+ if (fileItem->rowCount() == 0)
+ mModel.removeRow(fileItem->row());
+ }
+}
+
void ResultsTree::openContainingFolder()
{
QString filePath = getFilePath(mContextItem, true);
diff --git a/gui/resultstree.h b/gui/resultstree.h
index 55b5b709e..349ea855f 100644
--- a/gui/resultstree.h
+++ b/gui/resultstree.h
@@ -285,6 +285,9 @@ protected slots:
/** Slot for context menu item to suppress all messages with the current message id */
void suppressSelectedIds();
+ /** Slot for context menu item to suppress message with cppcheck ID */
+ void suppressCppcheckID();
+
/**
* @brief Slot for context menu item to open the folder containing the current file.
*/
diff --git a/gui/xmlreportv2.cpp b/gui/xmlreportv2.cpp
index 5fac01c9e..00fd096e8 100644
--- a/gui/xmlreportv2.cpp
+++ b/gui/xmlreportv2.cpp
@@ -219,7 +219,7 @@ ErrorItem XmlReportV2::readError(QXmlStreamReader *reader)
if (attribs.hasAttribute(QString(), CWEAttribute))
item.cwe = attribs.value(QString(), CWEAttribute).toInt();
if (attribs.hasAttribute(QString(), CppcheckIdAttribute))
- item.cppcheckId = attribs.value(QString(), CWEAttribute).toULongLong();
+ item.cppcheckId = attribs.value(QString(), CppcheckIdAttribute).toULongLong();
if (attribs.hasAttribute(QString(), SinceDateAttribute))
item.sinceDate = attribs.value(QString(), SinceDateAttribute).toString();
if (attribs.hasAttribute(QString(), TagsAttribute))
diff --git a/lib/errorlogger.cpp b/lib/errorlogger.cpp
index b3d25952b..06bfbde76 100644
--- a/lib/errorlogger.cpp
+++ b/lib/errorlogger.cpp
@@ -235,6 +235,7 @@ void ErrorMessage::setmsg(const std::string &msg)
Suppressions::ErrorMessage ErrorMessage::toSuppressionsErrorMessage() const
{
Suppressions::ErrorMessage ret;
+ ret.cppcheckId = cppcheckId;
ret.errorId = id;
if (!callStack.empty()) {
ret.setFileName(callStack.back().getfile(false));
diff --git a/lib/suppressions.cpp b/lib/suppressions.cpp
index 0f307b834..93bc71531 100644
--- a/lib/suppressions.cpp
+++ b/lib/suppressions.cpp
@@ -204,9 +204,9 @@ std::string Suppressions::addSuppressionLine(const std::string &line)
std::string Suppressions::addSuppression(const Suppressions::Suppression &suppression)
{
// Check that errorId is valid..
- if (suppression.errorId.empty()) {
+ if (suppression.errorId.empty() && suppression.cppcheckId == 0)
return "Failed to add suppression. No id.";
- }
+
if (suppression.errorId != "*") {
for (std::string::size_type pos = 0; pos < suppression.errorId.length(); ++pos) {
if (suppression.errorId[pos] < 0 || !isAcceptedErrorIdChar(suppression.errorId[pos])) {
@@ -271,6 +271,8 @@ bool Suppressions::Suppression::parseComment(std::string comment, std::string *e
bool Suppressions::Suppression::isSuppressed(const Suppressions::ErrorMessage &errmsg) const
{
+ if (cppcheckId > 0 && cppcheckId != errmsg.cppcheckId)
+ return false;
if (!errorId.empty() && !matchglob(errorId, errmsg.errorId))
return false;
if (!fileName.empty() && !matchglob(fileName, errmsg.getFileName()))
@@ -371,6 +373,8 @@ std::list Suppressions::getUnmatchedLocalSuppressions
for (const Suppression &s : mSuppressions) {
if (s.matched)
continue;
+ if (s.cppcheckId > 0)
+ continue;
if (!unusedFunctionChecking && s.errorId == "unusedFunction")
continue;
if (file.empty() || !s.isLocal() || s.fileName != file)
@@ -386,6 +390,8 @@ std::list Suppressions::getUnmatchedGlobalSuppression
for (const Suppression &s : mSuppressions) {
if (s.matched)
continue;
+ if (s.cppcheckId > 0)
+ continue;
if (!unusedFunctionChecking && s.errorId == "unusedFunction")
continue;
if (s.isLocal())
diff --git a/lib/suppressions.h b/lib/suppressions.h
index 014e897df..5c9873e37 100644
--- a/lib/suppressions.h
+++ b/lib/suppressions.h
@@ -35,6 +35,7 @@ class CPPCHECKLIB Suppressions {
public:
struct CPPCHECKLIB ErrorMessage {
+ std::size_t cppcheckId;
std::string errorId;
void setFileName(const std::string &s);
const std::string &getFileName() const {
@@ -48,17 +49,18 @@ public:
};
struct CPPCHECKLIB Suppression {
- Suppression() : lineNumber(NO_LINE), matched(false) {}
+ Suppression() : lineNumber(NO_LINE), cppcheckId(0), matched(false) {}
Suppression(const Suppression &other) {
*this = other;
}
- Suppression(const std::string &id, const std::string &file, int line=NO_LINE) : errorId(id), fileName(file), lineNumber(line), matched(false) {}
+ Suppression(const std::string &id, const std::string &file, int line=NO_LINE) : errorId(id), fileName(file), lineNumber(line), cppcheckId(0), matched(false) {}
Suppression & operator=(const Suppression &other) {
errorId = other.errorId;
fileName = other.fileName;
lineNumber = other.lineNumber;
symbolName = other.symbolName;
+ cppcheckId = other.cppcheckId;
matched = other.matched;
return *this;
}
@@ -72,6 +74,8 @@ public:
return fileName < other.fileName;
if (symbolName != other.symbolName)
return symbolName < other.symbolName;
+ if (cppcheckId != other.cppcheckId)
+ return cppcheckId < other.cppcheckId;
return false;
}
@@ -96,6 +100,7 @@ public:
std::string fileName;
int lineNumber;
std::string symbolName;
+ std::size_t cppcheckId;
bool matched;
enum { NO_LINE = -1 };
From 60399b9321e37d39ec095e8c983f91a86adc275a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 15 Jul 2020 13:06:17 +0200
Subject: [PATCH 064/116] cppcheck-errors.rng: Update xml schema, cppcheck-id
attribute was added
---
cppcheck-errors.rng | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/cppcheck-errors.rng b/cppcheck-errors.rng
index 57ce4224c..6446d98ce 100644
--- a/cppcheck-errors.rng
+++ b/cppcheck-errors.rng
@@ -24,6 +24,13 @@
+
+
+
+ 1
+
+
+
From 4f83b3618c7c9012ffe61816e975537fa2852941 Mon Sep 17 00:00:00 2001
From: orbitcowboy
Date: Wed, 15 Jul 2020 13:37:01 +0200
Subject: [PATCH 065/116] wxwidgets.cfg: Added support for more interfaces
---
cfg/wxwidgets.cfg | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/cfg/wxwidgets.cfg b/cfg/wxwidgets.cfg
index 6bdb96c43..ef4014114 100644
--- a/cfg/wxwidgets.cfg
+++ b/cfg/wxwidgets.cfg
@@ -13428,6 +13428,13 @@ wxItemKind kind = wxITEM_NORMAL) -->
+
+
+ false
+
+
+
+
false
From bdb08232d7ab6c7713e89c55d1e8e8caaaaccb98 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 15 Jul 2020 20:55:04 +0200
Subject: [PATCH 066/116] GUI: Fix suppression of multiple cppcheck ids
---
gui/resultstree.cpp | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index 7233a4d15..a9202bde0 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -1047,17 +1047,24 @@ void ResultsTree::suppressCppcheckID()
{
if (!mSelectionModel)
return;
- ProjectFile *projectFile = ProjectFile::getActiveProject();
+
+ // Extract selected warnings
+ QSet selectedWarnings;
foreach (QModelIndex index, mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
if (!item->parent())
continue;
while (item->parent()->parent())
item = item->parent();
+ selectedWarnings.insert(item);
+ }
+
+ ProjectFile *projectFile = ProjectFile::getActiveProject();
+ for (QStandardItem *item: selectedWarnings) {
+ QStandardItem *fileItem = item->parent();
const QVariantMap data = item->data().toMap();
if (projectFile && data.contains("cppcheckId"))
projectFile->suppressCppcheckId(data["cppcheckId"].toULongLong());
- QStandardItem *fileItem = item->parent();
fileItem->removeRow(item->row());
if (fileItem->rowCount() == 0)
mModel.removeRow(fileItem->row());
From a23d1ca6925ebe07bb30b4d421d69f21b4d430c2 Mon Sep 17 00:00:00 2001
From: Simon Large
Date: Wed, 15 Jul 2020 21:49:25 +0200
Subject: [PATCH 067/116] manual.md: Reformatting lists
---
man/manual.md | 36 ++++++++++++++++++++----------------
1 file changed, 20 insertions(+), 16 deletions(-)
diff --git a/man/manual.md b/man/manual.md
index 63fbe9df0..98a2c126d 100644
--- a/man/manual.md
+++ b/man/manual.md
@@ -175,8 +175,9 @@ As you can see Cppcheck has instantiated `a` until `a<101>` was reached
and then it bails out.
To limit template recursion you can;
- * add template specialisation
- * configure cppcheck (in the GUI project file dialog)
+
+- add template specialisation
+- configure cppcheck (in the GUI project file dialog)
Example code with template specialisation:
@@ -348,14 +349,15 @@ Use `--std` on the command line to specify a C/C++ standard.
Cppcheck assumes that the code is compatible with the latest C/C++ standard but you can override this.
The available options are:
- * c89: C code is C89 compatible
- * c99: C code is C99 compatible
- * c11: C code is C11 compatible (default)
- * c++03: C++ code is C++03 compatible
- * c++11: C++ code is C++11 compatible
- * c++14: C++ code is C++14 compatible
- * c++17: C++ code is C++17 compatible
- * c++20: C++ code is C++20 compatible (default)
+
+- c89: C code is C89 compatible
+- c99: C code is C99 compatible
+- c11: C code is C11 compatible (default)
+- c++03: C++ code is C++03 compatible
+- c++11: C++ code is C++11 compatible
+- c++14: C++ code is C++14 compatible
+- c++17: C++ code is C++17 compatible
+- c++20: C++ code is C++20 compatible (default)
# Suppressions
@@ -873,10 +875,11 @@ This analysis is "soundy"; it should diagnose most bugs reported in CVEs and fro
You have to expect false alarms. However Cppcheck tries to limit false alarms. The purpose of the data flow analysis is to limit false alarms.
Some possible use cases;
- * you are writing new code and want to ensure it is safe.
- * you are reviewing code and want to get hints about possible UB.
- * you need extra help troubleshooting a weird bug.
- * you want to check if a release candidate is safe.
+
+- you are writing new code and want to ensure it is safe.
+- you are reviewing code and want to get hints about possible UB.
+- you need extra help troubleshooting a weird bug.
+- you want to check if a release candidate is safe.
The intention is that this will be used primarily in the GUI.
@@ -923,8 +926,9 @@ Cppcheck will warn:
## Adding a contract in the GUI
There are two ways:
- * Open the "Contracts" tab at the bottom of the screen. Find the function in the listbox and double click on it.
- * Right click on a warning and click on "Edit contract.." in the popup menu. This popup menu item is only available if the warning is not inconclusive.
+
+- Open the "Contracts" tab at the bottom of the screen. Find the function in the listbox and double click on it.
+- Right click on a warning and click on "Edit contract.." in the popup menu. This popup menu item is only available if the warning is not inconclusive.
## Incomplete analysis
From dac72beb9e4bd818ef41b47b37c24a9b97388eeb Mon Sep 17 00:00:00 2001
From: Simon Large
Date: Wed, 15 Jul 2020 21:56:27 +0200
Subject: [PATCH 068/116] manual: add css style sheet
---
man/manual.css | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 86 insertions(+)
create mode 100644 man/manual.css
diff --git a/man/manual.css b/man/manual.css
new file mode 100644
index 000000000..06c29597c
--- /dev/null
+++ b/man/manual.css
@@ -0,0 +1,86 @@
+/* stylelint-disable */
+html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring,button:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}[hidden],template{display:none}
+/* stylelint-enable */
+
+html {
+ -moz-osx-font-smoothing: grayscale;
+ -webkit-font-smoothing: antialiased;
+}
+
+body {
+ background-color: #fff;
+ color: #333;
+ font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
+ font-size: 16px;
+ font-weight: 400;
+ line-height: 1.5;
+ max-width: 1012px;
+ margin: 20px auto;
+ border: 1px solid #eaecef;
+ padding: 20px 100px;
+ overflow-x: hidden;
+}
+
+a {
+ color: #0366d6;
+ text-decoration: none;
+
+}
+
+a:hover, a:focus {
+ text-decoration: underline;
+
+}
+
+h1, h2, h3, h4, h5, h6 {
+ font-weight: 600;
+ line-height: 1.25;
+ margin-top: 24px;
+ margin-bottom: 16px;
+}
+
+h1 {
+ font-size: 2em;
+}
+
+h2 {
+ font-size: 1.5em;
+}
+
+h3 {
+ font-size: 1.25em;
+}
+
+h4, h5, h6 {
+ font-size: 1.1em;
+}
+
+h1, h2 {
+ padding-bottom: 0.3em;
+ border-bottom: 1px solid #eaecef;
+}
+
+pre {
+ padding: 16px;
+ background-color: #f6f8fa;
+ border-radius: 6px;
+ line-height: 1.45;
+ font-size: 85%;
+ margin-top: 0;
+ margin-bottom: 16px;
+ overflow: auto;
+}
+
+code {
+ font-family: SFMono-Regular,Consolas,Liberation Mono,Menlo,monospace;
+ background-color: #f6f8fa;
+ font-size: 100%;
+ word-break: normal;
+ white-space: pre;
+}
+
+ol, ul {
+ padding-left: 2em;
+ margin-top: 0;
+ margin-bottom: 16px;
+}
From c02b39a3baca1cc3da6e7cb54764788223ec318c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Wed, 15 Jul 2020 21:57:49 +0200
Subject: [PATCH 069/116] Use manual.css in manual
---
man/buildman.sh | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/man/buildman.sh b/man/buildman.sh
index d7371c03a..f1ff96f31 100755
--- a/man/buildman.sh
+++ b/man/buildman.sh
@@ -2,8 +2,8 @@
# To install required tools in debian:
# sudo apt-get install pandoc texlive-latex-base texlive-fonts-recommended texlive-latex-extra
-pandoc manual.md -o manual.pdf -s --number-sections --toc
-pandoc manual.md -o manual.html -s --number-sections --toc
+pandoc manual.md -o manual.pdf -s --number-sections --toc --css manual.css
+pandoc manual.md -o manual.html -s --number-sections --toc --css manual.css
pandoc reference-cfg-format.md -o reference-cfg-format.pdf -s --number-sections --toc
pandoc reference-cfg-format.md -o reference-cfg-format.html -s --number-sections --toc
From 118e9eb3e2783b1d9682a91247f9c86d83ad14bf Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 15:27:07 +0200
Subject: [PATCH 070/116] Better handling of CppcheckID suppressions
---
lib/importproject.cpp | 22 +++++++++++++++++-----
lib/suppressions.cpp | 10 +++++++---
2 files changed, 24 insertions(+), 8 deletions(-)
diff --git a/lib/importproject.cpp b/lib/importproject.cpp
index 384ad4682..727c6704f 100644
--- a/lib/importproject.cpp
+++ b/lib/importproject.cpp
@@ -1033,7 +1033,7 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
const std::string &path = mPath;
std::list paths;
- std::list suppressions;
+ std::list suppressions;
Settings temp;
guiProject.analyzeAllVsConfigs.clear();
@@ -1072,8 +1072,20 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
guiProject.excludedPaths = readXmlStringList(node, "", CppcheckXml::IgnorePathName, CppcheckXml::IgnorePathNameAttrib);
else if (strcmp(node->Name(), CppcheckXml::LibrariesElementName) == 0)
guiProject.libraries = readXmlStringList(node, "", CppcheckXml::LibraryElementName, nullptr);
- else if (strcmp(node->Name(), CppcheckXml::SuppressionsElementName) == 0)
- suppressions = readXmlStringList(node, "", CppcheckXml::SuppressionElementName, nullptr);
+ else if (strcmp(node->Name(), CppcheckXml::SuppressionsElementName) == 0) {
+ for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
+ if (strcmp(child->Name(), CppcheckXml::SuppressionsElementName) != 0)
+ continue;
+ auto read = [](const char *s, const char *def) { return s ? s : def; };
+ Suppressions::Suppression s;
+ s.errorId = read(child->GetText(), "");
+ s.fileName = read(child->Attribute("fileName"), "");
+ s.lineNumber = child->IntAttribute("lineNumber", Suppressions::Suppression::NO_LINE);
+ s.symbolName = read(child->Attribute("symbolName"), "");
+ std::istringstream(read(child->Attribute("cppcheck-id"), "0")) >> s.cppcheckId;
+ suppressions.push_back(s);
+ }
+ }
else if (strcmp(node->Name(), CppcheckXml::VSConfigurationElementName) == 0)
guiProject.checkVsConfigs = readXmlStringList(node, "", CppcheckXml::VSConfigurationName, nullptr);
else if (strcmp(node->Name(), CppcheckXml::PlatformElementName) == 0)
@@ -1130,8 +1142,8 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
for (const std::string &p : paths)
guiProject.pathNames.push_back(p);
- for (const std::string &supp : suppressions)
- settings->nomsg.addSuppressionLine(supp);
+ for (const Suppressions::Suppression &supp : suppressions)
+ settings->nomsg.addSuppression(supp);
settings->checkHeaders = temp.checkHeaders;
settings->checkUnusedTemplates = temp.checkUnusedTemplates;
settings->maxCtuDepth = temp.maxCtuDepth;
diff --git a/lib/suppressions.cpp b/lib/suppressions.cpp
index 93bc71531..e436a7413 100644
--- a/lib/suppressions.cpp
+++ b/lib/suppressions.cpp
@@ -98,8 +98,10 @@ std::string Suppressions::parseXmlFile(const char *filename)
s.lineNumber = std::atoi(text);
else if (std::strcmp(e2->Name(), "symbolName") == 0)
s.symbolName = text;
+ else if (*text && std::strcmp(e2->Name(), "cppcheckId") == 0)
+ std::istringstream(text) >> s.cppcheckId;
else
- return "Unknown suppression element <" + std::string(e2->Name()) + ">, expected ///";
+ return "Unknown suppression element <" + std::string(e2->Name()) + ">, expected ////";
}
const std::string err = addSuppression(s);
@@ -317,6 +319,8 @@ std::string Suppressions::Suppression::getText() const
ret += " lineNumber=" + MathLib::toString(lineNumber);
if (!symbolName.empty())
ret += " symbolName=" + symbolName;
+ if (cppcheckId > 0)
+ ret += " cppcheckId=" + MathLib::toString(cppcheckId);
if (ret.compare(0,1," ")==0)
return ret.substr(1);
return ret;
@@ -360,13 +364,13 @@ void Suppressions::dump(std::ostream & out) const
out << " lineNumber=\"" << suppression.lineNumber << '"';
if (!suppression.symbolName.empty())
out << " symbolName=\"" << ErrorLogger::toxml(suppression.symbolName) << '\"';
+ if (suppression.cppcheckId > 0)
+ out << " cppcheckId=\"" << suppression.cppcheckId << '\"';
out << " />" << std::endl;
}
out << " " << std::endl;
}
-#include
-
std::list Suppressions::getUnmatchedLocalSuppressions(const std::string &file, const bool unusedFunctionChecking) const
{
std::list result;
From 9edbec8594c0d841d488552f35b4b80062abefb9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 16:36:11 +0200
Subject: [PATCH 071/116] astyle formatting
---
lib/importproject.cpp | 7 ++++---
1 file changed, 4 insertions(+), 3 deletions(-)
diff --git a/lib/importproject.cpp b/lib/importproject.cpp
index 727c6704f..ad498d21d 100644
--- a/lib/importproject.cpp
+++ b/lib/importproject.cpp
@@ -1076,7 +1076,9 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
if (strcmp(child->Name(), CppcheckXml::SuppressionsElementName) != 0)
continue;
- auto read = [](const char *s, const char *def) { return s ? s : def; };
+ auto read = [](const char *s, const char *def) {
+ return s ? s : def;
+ };
Suppressions::Suppression s;
s.errorId = read(child->GetText(), "");
s.fileName = read(child->Attribute("fileName"), "");
@@ -1085,8 +1087,7 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
std::istringstream(read(child->Attribute("cppcheck-id"), "0")) >> s.cppcheckId;
suppressions.push_back(s);
}
- }
- else if (strcmp(node->Name(), CppcheckXml::VSConfigurationElementName) == 0)
+ } else if (strcmp(node->Name(), CppcheckXml::VSConfigurationElementName) == 0)
guiProject.checkVsConfigs = readXmlStringList(node, "", CppcheckXml::VSConfigurationName, nullptr);
else if (strcmp(node->Name(), CppcheckXml::PlatformElementName) == 0)
guiProject.platform = node->GetText();
From bec78a096004dd5f0f5936dbf46d3621616e5c1b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 16:36:55 +0200
Subject: [PATCH 072/116] GUI: Adding suppression with cppcheckId; include all
relevant fields
---
gui/projectfile.cpp | 15 +++++----------
gui/projectfile.h | 6 +++---
gui/resultstree.cpp | 15 +++++++++++++--
3 files changed, 21 insertions(+), 15 deletions(-)
diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp
index fce386ee8..60872dac3 100644
--- a/gui/projectfile.cpp
+++ b/gui/projectfile.cpp
@@ -719,6 +719,11 @@ void ProjectFile::setSuppressions(const QList &suppre
mSuppressions = suppressions;
}
+void ProjectFile::addSuppression(const Suppressions::Suppression &suppression)
+{
+ mSuppressions.append(suppression);
+}
+
void ProjectFile::setAddons(const QStringList &addons)
{
mAddons = addons;
@@ -1027,13 +1032,3 @@ QString ProjectFile::getAddonFilePath(QString filesDir, const QString &addon)
return QString();
}
-
-void ProjectFile::suppressCppcheckId(std::size_t cppcheckId)
-{
- if (cppcheckId > 0) {
- Suppressions::Suppression s;
- s.cppcheckId = cppcheckId;
- mSuppressions.append(s);
- write();
- }
-}
diff --git a/gui/projectfile.h b/gui/projectfile.h
index fc1effc00..1a92f994e 100644
--- a/gui/projectfile.h
+++ b/gui/projectfile.h
@@ -55,9 +55,6 @@ public:
mActiveProject = this;
}
- /** Suppress warning with Cppcheck-ID */
- void suppressCppcheckId(std::size_t cppcheckId);
-
/**
* @brief Read the project file.
* @param filename Filename (can be also given to constructor).
@@ -312,6 +309,9 @@ public:
*/
void setSuppressions(const QList &suppressions);
+ /** Add suppression */
+ void addSuppression(const Suppressions::Suppression &suppression);
+
/**
* @brief Set list of addons.
* @param addons List of addons.
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index a9202bde0..27274c176 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -1059,16 +1059,27 @@ void ResultsTree::suppressCppcheckID()
selectedWarnings.insert(item);
}
+ bool changed = false;
ProjectFile *projectFile = ProjectFile::getActiveProject();
for (QStandardItem *item: selectedWarnings) {
QStandardItem *fileItem = item->parent();
const QVariantMap data = item->data().toMap();
- if (projectFile && data.contains("cppcheckId"))
- projectFile->suppressCppcheckId(data["cppcheckId"].toULongLong());
+ if (projectFile && data.contains("cppcheckId")) {
+ Suppressions::Suppression suppression;
+ suppression.cppcheckId = data["cppcheckId"].toULongLong();
+ suppression.errorId = data["id"].toString().toStdString();
+ suppression.fileName = data["file"].toString().toStdString();
+ suppression.lineNumber = data["line"].toInt();
+ projectFile->addSuppression(suppression);
+ changed = true;
+ }
fileItem->removeRow(item->row());
if (fileItem->rowCount() == 0)
mModel.removeRow(fileItem->row());
}
+
+ if (changed)
+ projectFile->write();
}
void ResultsTree::openContainingFolder()
From 0632f864491bd1c39ae70479d00c095a84e3375d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 16:38:22 +0200
Subject: [PATCH 073/116] Bug hunting; avoid bailout false positives when
constructor is called
---
lib/bughuntingchecks.cpp | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 46879ec04..454a50bc5 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -248,7 +248,7 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (!var->isLocal() || var->isStatic())
return;
}
- if (var && (Token::Match(var->nameToken(), "%name% [=:]") || Token::Match(var->nameToken(), "%varid% ; %varid% =", var->declarationId())))
+ if (var && (Token::Match(var->nameToken(), "%name% [=:({)]") || Token::Match(var->nameToken(), "%varid% ; %varid% =", var->declarationId())))
return;
if (var && var->nameToken() == tok)
return;
From b249d9be313dec9fcb7fe58f0dfb1413a39fb7c3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 20:19:36 +0200
Subject: [PATCH 074/116] GUI: Refactor tags
---
gui/mainwindow.cpp | 4 ----
gui/resultstree.cpp | 9 +++++----
gui/resultstree.h | 6 ------
gui/resultsview.h | 4 ----
4 files changed, 5 insertions(+), 18 deletions(-)
diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp
index e721b605c..eab66d82f 100644
--- a/gui/mainwindow.cpp
+++ b/gui/mainwindow.cpp
@@ -1524,8 +1524,6 @@ QString MainWindow::getLastResults() const
bool MainWindow::loadLastResults()
{
- if (mProjectFile)
- mUI.mResults->setTags(mProjectFile->getTags());
const QString &lastResults = getLastResults();
if (lastResults.isEmpty())
return false;
@@ -1548,7 +1546,6 @@ void MainWindow::analyzeProject(const ProjectFile *projectFile, const bool check
QDir::setCurrent(inf.absolutePath());
mThread->setAddonsAndTools(projectFile->getAddonsAndTools());
- mUI.mResults->setTags(projectFile->getTags());
// If the root path is not given or is not "current dir", use project
// file's location directory as root path
@@ -1652,7 +1649,6 @@ void MainWindow::closeProjectFile()
delete mProjectFile;
mProjectFile = nullptr;
mUI.mResults->clear(true);
- mUI.mResults->setTags(QStringList());
enableProjectActions(false);
enableProjectOpenActions(true);
formatAndSetTitle();
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index 27274c176..48e481b4f 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -50,8 +50,8 @@
#include "xmlreportv2.h"
// These must match column headers given in ResultsTree::translate()
-static const unsigned int COLUMN_SINCE_DATE = 6;
-static const unsigned int COLUMN_TAGS = 7;
+static const int COLUMN_SINCE_DATE = 6;
+static const int COLUMN_TAGS = 7;
static QString getFunction(QStandardItem *item)
{
@@ -673,7 +673,8 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
connect(suppressCppcheckID, &QAction::triggered, this, &ResultsTree::suppressCppcheckID);
connect(opencontainingfolder, SIGNAL(triggered()), this, SLOT(openContainingFolder()));
- if (!mTags.isEmpty()) {
+ const ProjectFile *currentProject = ProjectFile::getActiveProject();
+ if (currentProject && !currentProject->getTags().isEmpty()) {
menu.addSeparator();
QMenu *tagMenu = menu.addMenu(tr("Tag"));
{
@@ -684,7 +685,7 @@ void ResultsTree::contextMenuEvent(QContextMenuEvent * e)
});
}
- foreach (const QString tagstr, mTags) {
+ foreach (const QString tagstr, currentProject->getTags()) {
QAction *action = new QAction(tagstr, tagMenu);
tagMenu->addAction(action);
connect(action, &QAction::triggered, [=]() {
diff --git a/gui/resultstree.h b/gui/resultstree.h
index 349ea855f..cc7dacd35 100644
--- a/gui/resultstree.h
+++ b/gui/resultstree.h
@@ -52,10 +52,6 @@ public:
virtual ~ResultsTree();
void initialize(QSettings *settings, ApplicationList *list, ThreadHandler *checkThreadHandler);
- void setTags(const QStringList &tags) {
- mTags = tags;
- }
-
/**
* @brief Add a new item to the tree
*
@@ -532,8 +528,6 @@ private:
/** @brief Convert GUI error item into data error item */
void readErrorItem(const QStandardItem *error, ErrorItem *item) const;
- QStringList mTags;
-
QStringList mHiddenMessageId;
QItemSelectionModel *mSelectionModel;
diff --git a/gui/resultsview.h b/gui/resultsview.h
index bd623b836..15f98e9cb 100644
--- a/gui/resultsview.h
+++ b/gui/resultsview.h
@@ -50,10 +50,6 @@ public:
virtual ~ResultsView();
ResultsView &operator=(const ResultsView &) = delete;
- void setTags(const QStringList &tags) {
- mUI.mTree->setTags(tags);
- }
-
void setAddedContracts(const QStringList &addedContracts);
/**
From 9af288e1dde6647ee9fea0a393d54e719007f343 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Thu, 16 Jul 2020 23:03:54 +0200
Subject: [PATCH 075/116] Fixed #9724 (GUI: The tags do not work anymore)
---
gui/mainwindow.cpp | 8 --
gui/mainwindow.h | 3 -
gui/projectfile.cpp | 76 ++++++++++++++++-
gui/projectfile.h | 19 ++++-
gui/resultstree.cpp | 203 ++++++++++++++++++++++++--------------------
gui/resultsview.cpp | 1 -
gui/resultsview.h | 5 --
lib/importproject.h | 4 +
8 files changed, 210 insertions(+), 109 deletions(-)
diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp
index eab66d82f..d98ea4b6e 100644
--- a/gui/mainwindow.cpp
+++ b/gui/mainwindow.cpp
@@ -141,7 +141,6 @@ MainWindow::MainWindow(TranslationHandler* th, QSettings* settings) :
connect(mUI.mResults, &ResultsView::gotResults, this, &MainWindow::resultsAdded);
connect(mUI.mResults, &ResultsView::resultsHidden, mUI.mActionShowHidden, &QAction::setEnabled);
connect(mUI.mResults, &ResultsView::checkSelected, this, &MainWindow::performSelectedFilesCheck);
- connect(mUI.mResults, &ResultsView::tagged, this, &MainWindow::tagged);
connect(mUI.mResults, &ResultsView::suppressIds, this, &MainWindow::suppressIds);
connect(mUI.mResults, &ResultsView::editFunctionContract, this, &MainWindow::editFunctionContract);
connect(mUI.mMenuView, &QMenu::aboutToShow, this, &MainWindow::aboutToShowViewMenu);
@@ -1810,13 +1809,6 @@ void MainWindow::selectPlatform()
}
}
-void MainWindow::tagged()
-{
- const QString &lastResults = getLastResults();
- if (!lastResults.isEmpty())
- mUI.mResults->save(lastResults, Report::XMLV2);
-}
-
void MainWindow::suppressIds(QStringList ids)
{
if (!mProjectFile)
diff --git a/gui/mainwindow.h b/gui/mainwindow.h
index d5ccf2b1c..2ea082d83 100644
--- a/gui/mainwindow.h
+++ b/gui/mainwindow.h
@@ -221,9 +221,6 @@ protected slots:
/** @brief Selects the platform as analyzed platform. */
void selectPlatform();
- /** Some results were tagged */
- void tagged();
-
/** Suppress error ids */
void suppressIds(QStringList ids);
diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp
index 60872dac3..8745cf345 100644
--- a/gui/projectfile.cpp
+++ b/gui/projectfile.cpp
@@ -72,6 +72,8 @@ void ProjectFile::clear()
mCheckUnknownFunctionReturn.clear();
safeChecks.clear();
mVsConfigurations.clear();
+ mTags.clear();
+ mWarningTags.clear();
}
bool ProjectFile::read(const QString &filename)
@@ -188,6 +190,9 @@ bool ProjectFile::read(const QString &filename)
if (xmlReader.name() == CppcheckXml::TagsElementName)
readStringList(mTags, xmlReader, CppcheckXml::TagElementName);
+ if (xmlReader.name() == CppcheckXml::TagWarningsElementName)
+ readTagWarnings(xmlReader, xmlReader.attributes().value(QString(), CppcheckXml::TagAttributeName).toString());
+
if (xmlReader.name() == CppcheckXml::MaxCtuDepthElementName)
mMaxCtuDepth = readInt(xmlReader, mMaxCtuDepth);
@@ -636,6 +641,41 @@ void ProjectFile::readSuppressions(QXmlStreamReader &reader)
}
+void ProjectFile::readTagWarnings(QXmlStreamReader &reader, QString tag)
+{
+ QXmlStreamReader::TokenType type;
+ do {
+ type = reader.readNext();
+ switch (type) {
+ case QXmlStreamReader::StartElement:
+ // Read library-elements
+ if (reader.name().toString() == CppcheckXml::WarningElementName) {
+ std::size_t cppcheckId = reader.attributes().value(QString(), CppcheckXml::CppcheckIdAttributeName).toULongLong();
+ mWarningTags[cppcheckId] = tag;
+ }
+ break;
+
+ case QXmlStreamReader::EndElement:
+ if (reader.name().toString() != CppcheckXml::WarningElementName)
+ return;
+ break;
+
+ // Not handled
+ case QXmlStreamReader::NoToken:
+ case QXmlStreamReader::Invalid:
+ case QXmlStreamReader::StartDocument:
+ case QXmlStreamReader::EndDocument:
+ case QXmlStreamReader::Characters:
+ case QXmlStreamReader::Comment:
+ case QXmlStreamReader::DTD:
+ case QXmlStreamReader::EntityReference:
+ case QXmlStreamReader::ProcessingInstruction:
+ break;
+ }
+ } while (true);
+}
+
+
void ProjectFile::readStringList(QStringList &stringlist, QXmlStreamReader &reader, const char elementname[])
{
QXmlStreamReader::TokenType type;
@@ -734,6 +774,20 @@ void ProjectFile::setVSConfigurations(const QStringList &vsConfigs)
mVsConfigurations = vsConfigs;
}
+void ProjectFile::setWarningTags(std::size_t cppcheckId, QString tag)
+{
+ if (tag.isEmpty())
+ mWarningTags.erase(cppcheckId);
+ else if (cppcheckId > 0)
+ mWarningTags[cppcheckId] = tag;
+}
+
+QString ProjectFile::getWarningTags(std::size_t cppcheckId) const
+{
+ auto it = mWarningTags.find(cppcheckId);
+ return (it != mWarningTags.end()) ? it->second : QString();
+}
+
bool ProjectFile::write(const QString &filename)
{
if (!filename.isEmpty())
@@ -883,7 +937,7 @@ bool ProjectFile::write(const QString &filename)
if (!suppression.symbolName.empty())
xmlWriter.writeAttribute("symbolName", QString::fromStdString(suppression.symbolName));
if (suppression.cppcheckId > 0)
- xmlWriter.writeAttribute("cppcheck-id", QString::number(suppression.cppcheckId));
+ xmlWriter.writeAttribute(CppcheckXml::CppcheckIdAttributeName, QString::number(suppression.cppcheckId));
if (!suppression.errorId.empty())
xmlWriter.writeCharacters(QString::fromStdString(suppression.errorId));
xmlWriter.writeEndElement();
@@ -914,6 +968,26 @@ bool ProjectFile::write(const QString &filename)
CppcheckXml::ToolElementName);
writeStringList(xmlWriter, mTags, CppcheckXml::TagsElementName, CppcheckXml::TagElementName);
+ if (!mWarningTags.empty()) {
+ QStringList tags;
+ for (const auto wt: mWarningTags) {
+ if (!tags.contains(wt.second))
+ tags.append(wt.second);
+ }
+ for (const QString &tag: tags) {
+ xmlWriter.writeStartElement(CppcheckXml::TagWarningsElementName);
+ xmlWriter.writeAttribute(CppcheckXml::TagAttributeName, tag);
+ QStringList warnings;
+ for (const auto wt: mWarningTags) {
+ if (wt.second == tag) {
+ xmlWriter.writeStartElement(CppcheckXml::WarningElementName);
+ xmlWriter.writeAttribute(CppcheckXml::CppcheckIdAttributeName, QString::number(wt.first));
+ xmlWriter.writeEndElement();
+ }
+ }
+ xmlWriter.writeEndElement();
+ }
+ }
xmlWriter.writeEndDocument();
file.close();
diff --git a/gui/projectfile.h b/gui/projectfile.h
index 1a92f994e..1d372ed35 100644
--- a/gui/projectfile.h
+++ b/gui/projectfile.h
@@ -331,6 +331,12 @@ public:
mTags = tags;
}
+ /** Set tags for a warning */
+ void setWarningTags(std::size_t cppcheckId, QString tags);
+
+ /** Get tags for a warning */
+ QString getWarningTags(std::size_t cppcheckId) const;
+
/**
* @brief Write project file (to disk).
* @param filename Filename to use.
@@ -437,6 +443,12 @@ protected:
*/
void readSuppressions(QXmlStreamReader &reader);
+ /**
+ * @brief Read tag warnings, what warnings are tagged with a specific tag
+ * @param reader XML stream reader.
+ */
+ void readTagWarnings(QXmlStreamReader &reader, QString tag);
+
/**
* @brief Read string list
* @param stringlist destination string list
@@ -552,10 +564,15 @@ private:
bool mClangTidy;
/**
- * @brief Warning tags
+ * @brief Tags
*/
QStringList mTags;
+ /**
+ * @brief Warning tags
+ */
+ std::map mWarningTags;
+
/** Max CTU depth */
int mMaxCtuDepth;
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index 48e481b4f..392fc082e 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -49,6 +49,23 @@
#include "path.h"
#include "xmlreportv2.h"
+static const char COLUMN[] = "column";
+static const char CPPCHECKID[] = "cppcheckId";
+static const char CWE[] = "cwe";
+static const char ERRORID[] = "id";
+static const char FILENAME[] = "file";
+static const char FILE0[] = "file0";
+static const char FUNCTION[] = "function";
+static const char HIDE[] = "hide";
+static const char INCOMPLETE[] = "incomplete";
+static const char INCONCLUSIVE[] = "inconclusive";
+static const char LINE[] = "line";
+static const char MESSAGE[] = "message";
+static const char SEVERITY[] = "severity";
+static const char SINCEDATE[] = "sinceDate";
+static const char SUMMARY[] = "summary";
+static const char TAGS[] = "tags";
+
// These must match column headers given in ResultsTree::translate()
static const int COLUMN_SINCE_DATE = 6;
static const int COLUMN_TAGS = 7;
@@ -175,7 +192,9 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
line.message = item.message;
line.severity = item.severity;
line.sinceDate = item.sinceDate;
- line.tags = item.tags;
+ if (const ProjectFile *activeProject = ProjectFile::getActiveProject()) {
+ line.tags = activeProject->getWarningTags(item.cppcheckId);
+ }
//Create the base item for the error and ensure it has a proper
//file item as a parent
QStandardItem* fileItem = ensureFileItem(loc.file, item.file0, hide);
@@ -190,22 +209,22 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
//Add user data to that item
QMap data;
- data["severity"] = ShowTypes::SeverityToShowType(item.severity);
- data["summary"] = item.summary;
- data["message"] = item.message;
- data["file"] = loc.file;
- data["line"] = loc.line;
- data["column"] = loc.column;
- data["id"] = item.errorId;
- data["incomplete"] = item.incomplete;
- data["cwe"] = item.cwe;
- data["cppcheckId"] = item.cppcheckId;
- data["inconclusive"] = item.inconclusive;
- data["file0"] = stripPath(item.file0, true);
- data["function"] = item.function;
- data["sinceDate"] = item.sinceDate;
- data["tags"] = item.tags;
- data["hide"] = hide;
+ data[SEVERITY] = ShowTypes::SeverityToShowType(item.severity);
+ data[SUMMARY] = item.summary;
+ data[MESSAGE] = item.message;
+ data[FILENAME] = loc.file;
+ data[LINE] = loc.line;
+ data[COLUMN] = loc.column;
+ data[ERRORID] = item.errorId;
+ data[INCOMPLETE] = item.incomplete;
+ data[CWE] = item.cwe;
+ data[CPPCHECKID] = item.cppcheckId;
+ data[INCONCLUSIVE] = item.inconclusive;
+ data[FILE0] = stripPath(item.file0, true);
+ data[FUNCTION] = item.function;
+ data[SINCEDATE] = item.sinceDate;
+ data[TAGS] = line.tags;
+ data[HIDE] = hide;
stditem->setData(QVariant(data));
//Add backtrace files as children
@@ -226,17 +245,17 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
// Add user data to that item
QMap child_data;
- child_data["severity"] = ShowTypes::SeverityToShowType(line.severity);
- child_data["summary"] = line.summary;
- child_data["message"] = line.message;
- child_data["file"] = e.file;
- child_data["line"] = e.line;
- child_data["column"] = e.column;
- child_data["id"] = line.errorId;
- child_data["incomplete"] = line.incomplete;
- child_data["cwe"] = line.cwe;
- child_data["cppcheckId"] = line.cppcheckId;
- child_data["inconclusive"] = line.inconclusive;
+ child_data[SEVERITY] = ShowTypes::SeverityToShowType(line.severity);
+ child_data[SUMMARY] = line.summary;
+ child_data[MESSAGE] = line.message;
+ child_data[FILENAME] = e.file;
+ child_data[LINE] = e.line;
+ child_data[COLUMN] = e.column;
+ child_data[ERRORID] = line.errorId;
+ child_data[INCOMPLETE] = line.incomplete;
+ child_data[CWE] = line.cwe;
+ child_data[CPPCHECKID] = line.cppcheckId;
+ child_data[INCONCLUSIVE] = line.inconclusive;
child_item->setData(QVariant(child_data));
}
}
@@ -363,8 +382,8 @@ void ResultsTree::clear(const QString &filename)
continue;
QVariantMap data = fileItem->data().toMap();
- if (stripped == data["file"].toString() ||
- filename == data["file0"].toString()) {
+ if (stripped == data[FILENAME].toString() ||
+ filename == data[FILE0].toString()) {
mModel.removeRow(i);
break;
}
@@ -380,7 +399,7 @@ void ResultsTree::clearRecheckFile(const QString &filename)
QString actualfile((!mCheckPath.isEmpty() && filename.startsWith(mCheckPath)) ? filename.mid(mCheckPath.length() + 1) : filename);
QVariantMap data = fileItem->data().toMap();
- QString storedfile = data["file"].toString();
+ QString storedfile = data[FILENAME].toString();
storedfile = ((!mCheckPath.isEmpty() && storedfile.startsWith(mCheckPath)) ? storedfile.mid(mCheckPath.length() + 1) : storedfile);
if (actualfile == storedfile) {
mModel.removeRow(i);
@@ -450,7 +469,7 @@ void ResultsTree::showHiddenResults()
continue;
QVariantMap data = fileItem->data().toMap();
- data["hide"] = false;
+ data[HIDE] = false;
fileItem->setData(QVariant(data));
int errorcount = fileItem->rowCount();
@@ -458,7 +477,7 @@ void ResultsTree::showHiddenResults()
QStandardItem *child = fileItem->child(j, 0);
if (child) {
data = child->data().toMap();
- data["hide"] = false;
+ data[HIDE] = false;
child->setData(QVariant(data));
}
}
@@ -500,21 +519,21 @@ void ResultsTree::refreshTree()
QVariantMap data = userdata.toMap();
//Check if this error should be hidden
- bool hide = (data["hide"].toBool() || !mShowSeverities.isShown(ShowTypes::VariantToShowType(data["severity"])));
+ bool hide = (data[HIDE].toBool() || !mShowSeverities.isShown(ShowTypes::VariantToShowType(data[SEVERITY])));
//If specified, filter on summary, message, filename, and id
if (!hide && !mFilter.isEmpty()) {
- if (!data["summary"].toString().contains(mFilter, Qt::CaseInsensitive) &&
- !data["message"].toString().contains(mFilter, Qt::CaseInsensitive) &&
- !data["file"].toString().contains(mFilter, Qt::CaseInsensitive) &&
- !data["id"].toString().contains(mFilter, Qt::CaseInsensitive)) {
+ if (!data[SUMMARY].toString().contains(mFilter, Qt::CaseInsensitive) &&
+ !data[MESSAGE].toString().contains(mFilter, Qt::CaseInsensitive) &&
+ !data[FILENAME].toString().contains(mFilter, Qt::CaseInsensitive) &&
+ !data[ERRORID].toString().contains(mFilter, Qt::CaseInsensitive)) {
hide = true;
}
}
// Tool filter
if (!hide) {
- if (data["id"].toString().startsWith("clang"))
+ if (data[ERRORID].toString().startsWith("clang"))
hide = !mShowClang;
else
hide = !mShowCppcheck;
@@ -561,8 +580,8 @@ QStandardItem *ResultsTree::ensureFileItem(const QString &fullpath, const QStrin
//Add user data to that item
QMap data;
- data["file"] = fullpath;
- data["file0"] = file0;
+ data[FILENAME] = fullpath;
+ data[FILE0] = file0;
item->setData(QVariant(data));
mModel.appendRow(item);
@@ -753,7 +772,7 @@ void ResultsTree::startApplication(QStandardItem *target, int application)
QVariantMap data = target->data().toMap();
//Replace (file) with filename
- QString file = data["file"].toString();
+ QString file = data[FILENAME].toString();
file = QDir::toNativeSeparators(file);
#ifdef Q_OS_WIN
file.replace(QString("\\"), QString("\\\\"));
@@ -789,11 +808,11 @@ void ResultsTree::startApplication(QStandardItem *target, int application)
QString params = app.getParameters();
params.replace("(file)", file, Qt::CaseInsensitive);
- QVariant line = data["line"];
+ QVariant line = data[LINE];
params.replace("(line)", QString("%1").arg(line.toInt()), Qt::CaseInsensitive);
- params.replace("(message)", data["message"].toString(), Qt::CaseInsensitive);
- params.replace("(severity)", data["severity"].toString(), Qt::CaseInsensitive);
+ params.replace("(message)", data[MESSAGE].toString(), Qt::CaseInsensitive);
+ params.replace("(severity)", data[SEVERITY].toString(), Qt::CaseInsensitive);
QString program = app.getPath();
@@ -889,14 +908,14 @@ void ResultsTree::copy()
QVariantMap data = item->data().toMap();
if (!data.contains("id"))
continue;
- QString inconclusive = data["inconclusive"].toBool() ? ",inconclusive" : "";
- text += '[' + data["file"].toString() + ':' + QString::number(data["line"].toInt())
+ QString inconclusive = data[INCONCLUSIVE].toBool() ? ",inconclusive" : "";
+ text += '[' + data[FILENAME].toString() + ':' + QString::number(data[LINE].toInt())
+ "] ("
- + QString::fromStdString(Severity::toString(ShowTypes::ShowTypeToSeverity((ShowTypes::ShowType)data["severity"].toInt()))) + inconclusive
+ + QString::fromStdString(Severity::toString(ShowTypes::ShowTypeToSeverity((ShowTypes::ShowType)data[SEVERITY].toInt()))) + inconclusive
+ ") "
- + data["message"].toString()
+ + data[MESSAGE].toString()
+ " ["
- + data["id"].toString()
+ + data[ERRORID].toString()
+ "]\n";
}
@@ -914,7 +933,7 @@ void ResultsTree::hideResult()
QStandardItem *item = mModel.itemFromIndex(index);
//Set the "hide" flag for this item
QVariantMap data = item->data().toMap();
- data["hide"] = true;
+ data[HIDE] = true;
item->setData(QVariant(data));
refreshTree();
@@ -934,7 +953,7 @@ void ResultsTree::recheckSelectedFiles()
while (item->parent())
item = item->parent();
QVariantMap data = item->data().toMap();
- QString currentFile = data["file"].toString();
+ QString currentFile = data[FILENAME].toString();
if (!currentFile.isEmpty()) {
QString fileNameWithCheckPath;
QFileInfo curfileInfo(currentFile);
@@ -948,8 +967,8 @@ void ResultsTree::recheckSelectedFiles()
return;
}
if (Path::isHeader(currentFile.toStdString())) {
- if (!data["file0"].toString().isEmpty() && !selectedItems.contains(data["file0"].toString())) {
- selectedItems<<((!mCheckPath.isEmpty() && (data["file0"].toString().indexOf(mCheckPath) != 0)) ? (mCheckPath + "/" + data["file0"].toString()) : data["file0"].toString());
+ if (!data[FILE0].toString().isEmpty() && !selectedItems.contains(data[FILE0].toString())) {
+ selectedItems<<((!mCheckPath.isEmpty() && (data[FILE0].toString().indexOf(mCheckPath) != 0)) ? (mCheckPath + "/" + data[FILE0].toString()) : data[FILE0].toString());
if (!selectedItems.contains(fileNameWithCheckPath))
selectedItems<parent()->child(mContextItem->row(), 0);
QVariantMap data = mContextItem->data().toMap();
- QString messageId = data["id"].toString();
+ QString messageId = data[ERRORID].toString();
mHiddenMessageId.append(messageId);
@@ -994,8 +1013,8 @@ void ResultsTree::hideAllIdResult()
}
QVariantMap userdata = child->data().toMap();
- if (userdata["id"].toString() == messageId) {
- userdata["hide"] = true;
+ if (userdata[ERRORID].toString() == messageId) {
+ userdata[HIDE] = true;
child->setData(QVariant(userdata));
}
}
@@ -1021,7 +1040,7 @@ void ResultsTree::suppressSelectedIds()
QVariantMap data = item->data().toMap();
if (!data.contains("id"))
continue;
- selectedIds << data["id"].toString();
+ selectedIds << data[ERRORID].toString();
}
// delete all errors with selected message Ids
@@ -1030,7 +1049,7 @@ void ResultsTree::suppressSelectedIds()
for (int j = 0; j < file->rowCount();) {
QStandardItem *errorItem = file->child(j, 0);
QVariantMap userdata = errorItem->data().toMap();
- if (selectedIds.contains(userdata["id"].toString())) {
+ if (selectedIds.contains(userdata[ERRORID].toString())) {
file->removeRow(j);
} else {
j++;
@@ -1067,10 +1086,10 @@ void ResultsTree::suppressCppcheckID()
const QVariantMap data = item->data().toMap();
if (projectFile && data.contains("cppcheckId")) {
Suppressions::Suppression suppression;
- suppression.cppcheckId = data["cppcheckId"].toULongLong();
- suppression.errorId = data["id"].toString().toStdString();
- suppression.fileName = data["file"].toString().toStdString();
- suppression.lineNumber = data["line"].toInt();
+ suppression.cppcheckId = data[CPPCHECKID].toULongLong();
+ suppression.errorId = data[ERRORID].toString().toStdString();
+ suppression.fileName = data[FILENAME].toString().toStdString();
+ suppression.lineNumber = data[LINE].toInt();
projectFile->addSuppression(suppression);
changed = true;
}
@@ -1102,18 +1121,22 @@ void ResultsTree::tagSelectedItems(const QString &tag)
if (!mSelectionModel)
return;
bool isTagged = false;
+ ProjectFile *currentProject = ProjectFile::getActiveProject();
foreach (QModelIndex index, mSelectionModel->selectedRows()) {
QStandardItem *item = mModel.itemFromIndex(index);
QVariantMap data = item->data().toMap();
if (data.contains("tags")) {
- data["tags"] = tag;
+ data[TAGS] = tag;
item->setData(QVariant(data));
item->parent()->child(index.row(), COLUMN_TAGS)->setText(tag);
- isTagged = true;
+ if (currentProject && data.contains(CPPCHECKID)) {
+ isTagged = true;
+ currentProject->setWarningTags(data[CPPCHECKID].toULongLong(), tag);
+ }
}
}
if (isTagged)
- emit tagged();
+ currentProject->write();
}
void ResultsTree::context(int application)
@@ -1137,7 +1160,7 @@ QString ResultsTree::getFilePath(QStandardItem *target, bool fullPath)
QString pathStr;
//Replace (file) with filename
- QString file = data["file"].toString();
+ QString file = data[FILENAME].toString();
pathStr = QDir::toNativeSeparators(file);
if (!fullPath) {
QFileInfo fi(pathStr);
@@ -1237,12 +1260,12 @@ void ResultsTree::updateFromOldReport(const QString &filename)
// New error .. set the "sinceDate" property
if (oldErrorIndex >= 0 && !oldErrors[oldErrorIndex].sinceDate.isEmpty()) {
- data["sinceDate"] = oldErrors[oldErrorIndex].sinceDate;
+ data[SINCEDATE] = oldErrors[oldErrorIndex].sinceDate;
error->setData(data);
fileItem->child(j, COLUMN_SINCE_DATE)->setText(oldErrors[oldErrorIndex].sinceDate);
- } else if (oldErrorIndex < 0 || data["sinceDate"].toString().isEmpty()) {
+ } else if (oldErrorIndex < 0 || data[SINCEDATE].toString().isEmpty()) {
const QString sinceDate = QDate::currentDate().toString(Qt::SystemLocaleShortDate);
- data["sinceDate"] = sinceDate;
+ data[SINCEDATE] = sinceDate;
error->setData(data);
fileItem->child(j, COLUMN_SINCE_DATE)->setText(sinceDate);
if (oldErrorIndex < 0)
@@ -1253,7 +1276,7 @@ void ResultsTree::updateFromOldReport(const QString &filename)
continue;
const ErrorItem &oldErrorItem = oldErrors[oldErrorIndex];
- data["tags"] = oldErrorItem.tags;
+ data[TAGS] = oldErrorItem.tags;
error->setData(data);
}
}
@@ -1264,23 +1287,23 @@ void ResultsTree::readErrorItem(const QStandardItem *error, ErrorItem *item) con
// Get error's user data
QVariantMap data = error->data().toMap();
- item->severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(data["severity"]));
- item->summary = data["summary"].toString();
- item->message = data["message"].toString();
- item->errorId = data["id"].toString();
- item->incomplete = data["incomplete"].toBool();
- item->cwe = data["cwe"].toInt();
- item->cppcheckId = data["cppcheckId"].toULongLong();
- item->inconclusive = data["inconclusive"].toBool();
- item->file0 = data["file0"].toString();
- item->sinceDate = data["sinceDate"].toString();
- item->tags = data["tags"].toString();
+ item->severity = ShowTypes::ShowTypeToSeverity(ShowTypes::VariantToShowType(data[SEVERITY]));
+ item->summary = data[SUMMARY].toString();
+ item->message = data[MESSAGE].toString();
+ item->errorId = data[ERRORID].toString();
+ item->incomplete = data[INCOMPLETE].toBool();
+ item->cwe = data[CWE].toInt();
+ item->cppcheckId = data[CPPCHECKID].toULongLong();
+ item->inconclusive = data[INCONCLUSIVE].toBool();
+ item->file0 = data[FILE0].toString();
+ item->sinceDate = data[SINCEDATE].toString();
+ item->tags = data[TAGS].toString();
if (error->rowCount() == 0) {
QErrorPathItem e;
- e.file = stripPath(data["file"].toString(), true);
- e.line = data["line"].toUInt();
- e.info = data["message"].toString();
+ e.file = stripPath(data[FILENAME].toString(), true);
+ e.line = data[LINE].toInt();
+ e.info = data[MESSAGE].toString();
item->errorPath << e;
}
@@ -1292,9 +1315,9 @@ void ResultsTree::readErrorItem(const QStandardItem *error, ErrorItem *item) con
QVariantMap child_data = child_userdata.toMap();
QErrorPathItem e;
- e.file = stripPath(child_data["file"].toString(), true);
- e.line = child_data["line"].toUInt();
- e.info = child_data["message"].toString();
+ e.file = stripPath(child_data[FILENAME].toString(), true);
+ e.line = child_data[LINE].toUInt();
+ e.info = child_data[MESSAGE].toString();
item->errorPath << e;
}
}
@@ -1362,7 +1385,7 @@ void ResultsTree::refreshFilePaths(QStandardItem *item)
QVariantMap data = userdata.toMap();
//Get list of files
- QString file = data["file"].toString();
+ QString file = data[FILENAME].toString();
//Update this error's text
error->setText(stripPath(file, false));
@@ -1382,7 +1405,7 @@ void ResultsTree::refreshFilePaths(QStandardItem *item)
QVariantMap child_data = child_userdata.toMap();
//Get list of files
- QString child_files = child_data["file"].toString();
+ QString child_files = child_data[FILENAME].toString();
//Update file's path
child->setText(stripPath(child_files, false));
}
diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp
index fcc88d73b..e5cd359fa 100644
--- a/gui/resultsview.cpp
+++ b/gui/resultsview.cpp
@@ -53,7 +53,6 @@ ResultsView::ResultsView(QWidget * parent) :
connect(mUI.mTree, &ResultsTree::resultsHidden, this, &ResultsView::resultsHidden);
connect(mUI.mTree, &ResultsTree::checkSelected, this, &ResultsView::checkSelected);
connect(mUI.mTree, &ResultsTree::treeSelectionChanged, this, &ResultsView::updateDetails);
- connect(mUI.mTree, &ResultsTree::tagged, this, &ResultsView::tagged);
connect(mUI.mTree, &ResultsTree::suppressIds, this, &ResultsView::suppressIds);
connect(mUI.mTree, &ResultsTree::editFunctionContract, this, &ResultsView::editFunctionContract);
connect(this, &ResultsView::showResults, mUI.mTree, &ResultsTree::showResults);
diff --git a/gui/resultsview.h b/gui/resultsview.h
index 15f98e9cb..2332b429f 100644
--- a/gui/resultsview.h
+++ b/gui/resultsview.h
@@ -218,11 +218,6 @@ signals:
*/
void checkSelected(QStringList selectedFilesList);
- /**
- * Some results have been tagged
- */
- void tagged();
-
/** Suppress Ids */
void suppressIds(QStringList ids);
diff --git a/lib/importproject.h b/lib/importproject.h
index 3676c3b8c..3f4e73ef4 100644
--- a/lib/importproject.h
+++ b/lib/importproject.h
@@ -161,6 +161,10 @@ namespace CppcheckXml {
const char ToolsElementName[] = "tools";
const char TagsElementName[] = "tags";
const char TagElementName[] = "tag";
+ const char TagWarningsElementName[] = "tag-warnings";
+ const char TagAttributeName[] = "tag";
+ const char WarningElementName[] = "warning";
+ const char CppcheckIdAttributeName[] = "cppcheck-id";
const char CheckHeadersElementName[] = "check-headers";
const char CheckUnusedTemplatesElementName[] = "check-unused-templates";
const char MaxCtuDepthElementName[] = "max-ctu-depth";
From 592637af612eb7f7985e7eb35b95d42c2fa71ac6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 17 Jul 2020 09:05:38 +0200
Subject: [PATCH 076/116] Bug hunting; Avoid uninit false positives with simple
analysis
---
lib/bughuntingchecks.cpp | 44 ++++++++++++++++++++++++++++++++--------
1 file changed, 36 insertions(+), 8 deletions(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 454a50bc5..cb93bb5c0 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -157,6 +157,39 @@ static void integerOverflow(const Token *tok, const ExprEngine::Value &value, Ex
}
#endif
+/** check if variable is unconditionally assigned */
+static bool isVariableAssigned(const Variable *var, const Token *tok, const Token *scopeStart=nullptr)
+{
+ const Token * const start = scopeStart && precedes(var->nameToken(), scopeStart) ? scopeStart : var->nameToken();
+
+ for (const Token *prev = tok->previous(); prev; prev = prev->previous()) {
+ if (!precedes(start, prev))
+ break;
+
+ if (prev->str() == "}") {
+ if (Token::simpleMatch(prev->link()->tokAt(-2), "} else {")) {
+ const Token *elseEnd = prev;
+ const Token *elseStart = prev->link();
+ const Token *ifEnd = elseStart->tokAt(-2);
+ const Token *ifStart = ifEnd->link();
+ if (isVariableAssigned(var, ifEnd, ifStart) && isVariableAssigned(var, elseEnd, elseStart)) {
+ return true;
+ }
+ }
+ prev = prev->link();
+ }
+ if (scopeStart && Token::Match(prev, "return|throw|continue|break"))
+ return true;
+ if (Token::Match(prev, "%varid% =", var->declarationId()))
+ return true;
+
+ // bailout; if variable is used previously that is checked first
+ if (!scopeStart && prev->varId() == var->declarationId())
+ return true;
+ }
+ return false;
+}
+
static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine::DataBase *dataBase)
{
if (!tok->astParent())
@@ -256,16 +289,11 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
// Are there unconditional assignment?
if (var && Token::Match(var->nameToken(), "%varid% ;| %varid%| =", tok->varId()))
return;
- for (const Token *prev = tok->previous(); prev; prev = prev->previous()) {
- if (!precedes(var->nameToken(), prev))
- break;
- if (prev->str() == "}")
- prev = prev->link();
- if (Token::Match(prev, "%varid% =", tok->varId()))
- return;
- }
}
+ if (tok->variable() && isVariableAssigned(tok->variable(), tok))
+ return;
+
// Uninitialized function argument
bool inconclusive = false;
if (Token::Match(tok->astParent(), "[,(]")) {
From f2bd603bd308effc5dfa0f4d4dd28d7b00f4dfd1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 17 Jul 2020 11:02:46 +0200
Subject: [PATCH 077/116] Bug hunting; Fix TestBughuntingChecks
---
lib/bughuntingchecks.cpp | 18 ++++++++++++------
1 file changed, 12 insertions(+), 6 deletions(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index cb93bb5c0..2162a8d05 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -180,12 +180,18 @@ static bool isVariableAssigned(const Variable *var, const Token *tok, const Toke
}
if (scopeStart && Token::Match(prev, "return|throw|continue|break"))
return true;
- if (Token::Match(prev, "%varid% =", var->declarationId()))
- return true;
-
- // bailout; if variable is used previously that is checked first
- if (!scopeStart && prev->varId() == var->declarationId())
- return true;
+ if (Token::Match(prev, "%varid% =", var->declarationId())) {
+ bool usedInRhs = false;
+ visitAstNodes(prev->next()->astOperand2(), [&usedInRhs, var](const Token *tok) {
+ if (tok->varId() == var->declarationId()) {
+ usedInRhs = true;
+ return ChildrenToVisit::done;
+ }
+ return ChildrenToVisit::op1_and_op2;
+ });
+ if (!usedInRhs)
+ return true;
+ }
}
return false;
}
From 7a4e6daecde8ea2dbc783e85d6b9266675705464 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 17 Jul 2020 11:26:03 +0200
Subject: [PATCH 078/116] Fix import GUI project problem
---
lib/importproject.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/lib/importproject.cpp b/lib/importproject.cpp
index ad498d21d..62ff618ca 100644
--- a/lib/importproject.cpp
+++ b/lib/importproject.cpp
@@ -1074,7 +1074,7 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
guiProject.libraries = readXmlStringList(node, "", CppcheckXml::LibraryElementName, nullptr);
else if (strcmp(node->Name(), CppcheckXml::SuppressionsElementName) == 0) {
for (const tinyxml2::XMLElement *child = node->FirstChildElement(); child; child = child->NextSiblingElement()) {
- if (strcmp(child->Name(), CppcheckXml::SuppressionsElementName) != 0)
+ if (strcmp(child->Name(), CppcheckXml::SuppressionElementName) != 0)
continue;
auto read = [](const char *s, const char *def) {
return s ? s : def;
@@ -1082,6 +1082,8 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
Suppressions::Suppression s;
s.errorId = read(child->GetText(), "");
s.fileName = read(child->Attribute("fileName"), "");
+ if (!s.fileName.empty())
+ s.fileName = joinRelativePath(path, s.fileName);
s.lineNumber = child->IntAttribute("lineNumber", Suppressions::Suppression::NO_LINE);
s.symbolName = read(child->Attribute("symbolName"), "");
std::istringstream(read(child->Attribute("cppcheck-id"), "0")) >> s.cppcheckId;
From 2713474f56a11bbd59e01e7f271ce0901e87856d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 17 Jul 2020 12:25:06 +0200
Subject: [PATCH 079/116] Fixed Cppcheck warning
---
gui/projectfile.cpp | 2 +-
gui/projectfile.h | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/gui/projectfile.cpp b/gui/projectfile.cpp
index 8745cf345..45035aec1 100644
--- a/gui/projectfile.cpp
+++ b/gui/projectfile.cpp
@@ -641,7 +641,7 @@ void ProjectFile::readSuppressions(QXmlStreamReader &reader)
}
-void ProjectFile::readTagWarnings(QXmlStreamReader &reader, QString tag)
+void ProjectFile::readTagWarnings(QXmlStreamReader &reader, const QString &tag)
{
QXmlStreamReader::TokenType type;
do {
diff --git a/gui/projectfile.h b/gui/projectfile.h
index 1d372ed35..388c03379 100644
--- a/gui/projectfile.h
+++ b/gui/projectfile.h
@@ -447,7 +447,7 @@ protected:
* @brief Read tag warnings, what warnings are tagged with a specific tag
* @param reader XML stream reader.
*/
- void readTagWarnings(QXmlStreamReader &reader, QString tag);
+ void readTagWarnings(QXmlStreamReader &reader, const QString &tag);
/**
* @brief Read string list
From 58638d775769acfb50778b87dfc69c9e6a3d8bed Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Fri, 17 Jul 2020 13:20:31 +0200
Subject: [PATCH 080/116] Bug hunting; Fix itc.py test
---
lib/bughuntingchecks.cpp | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 2162a8d05..3ba3643a6 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -295,10 +295,10 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
// Are there unconditional assignment?
if (var && Token::Match(var->nameToken(), "%varid% ;| %varid%| =", tok->varId()))
return;
- }
- if (tok->variable() && isVariableAssigned(tok->variable(), tok))
- return;
+ if (tok->variable() && isVariableAssigned(tok->variable(), tok))
+ return;
+ }
// Uninitialized function argument
bool inconclusive = false;
From 382f21a5c926368dadb4be769c4dd238b83421cb Mon Sep 17 00:00:00 2001
From: Georgy Komarov
Date: Sat, 18 Jul 2020 07:02:12 +0300
Subject: [PATCH 081/116] Fixed crash on garbage code: comparisson with an
empty second operand
This will fix #9774.
---
lib/tokenize.cpp | 17 ++++++++++++-----
test/testgarbage.cpp | 2 +-
test/testtokenize.cpp | 5 ++++-
3 files changed, 17 insertions(+), 7 deletions(-)
diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp
index a9fa35bea..196653206 100644
--- a/lib/tokenize.cpp
+++ b/lib/tokenize.cpp
@@ -9624,11 +9624,18 @@ void Tokenizer::findGarbageCode() const
if (match1 && match2)
syntaxError(tok);
}
- if (Token::Match(tok, "%or%|%oror%|~|^|!|%comp%|+|-|/|% )|]|}")) {
- if (isC())
- syntaxError(tok, tok->str() + tok->next()->str());
- if (tok->str() != ">" && !Token::simpleMatch(tok->previous(), "operator"))
- syntaxError(tok, tok->str() + " " + tok->next()->str());
+ if (Token::Match(tok, "%or%|%oror%|~|^|!|%comp%|+|-|/|%")) {
+ std::string code = "";
+ if (Token::Match(tok->next(), ")|]|}"))
+ code = tok->str() + tok->next()->str();
+ if (Token::simpleMatch(tok->next(), "( )"))
+ code = tok->str() + "()";
+ if (!code.empty()) {
+ if (isC())
+ syntaxError(tok, code);
+ if (tok->str() != ">" && !Token::simpleMatch(tok->previous(), "operator"))
+ syntaxError(tok, code);
+ }
}
if (Token::Match(tok, "%num%|%bool%|%char%|%str% %num%|%bool%|%char%|%str%") && !Token::Match(tok, "%str% %str%"))
syntaxError(tok);
diff --git a/test/testgarbage.cpp b/test/testgarbage.cpp
index 48c1df944..814d2ac21 100644
--- a/test/testgarbage.cpp
+++ b/test/testgarbage.cpp
@@ -1402,7 +1402,7 @@ private:
void garbageCode164() {
//7234
- checkCode("class d{k p;}(){d::d():B<()}");
+ ASSERT_THROW(checkCode("class d{k p;}(){d::d():B<()}"), InternalError);
}
void garbageCode165() {
diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp
index 361c396a8..4d2705d9e 100644
--- a/test/testtokenize.cpp
+++ b/test/testtokenize.cpp
@@ -8087,7 +8087,7 @@ private:
ASSERT_THROW(tokenizeAndStringify("void foo() { for_chain( if (!done) done = 1); }"), InternalError);
ASSERT_THROW(tokenizeAndStringify("void foo() { for_chain( a, b, if (!done) done = 1); }"), InternalError);
- ASSERT_THROW_EQUALS(tokenizeAndStringify("void f() { if (retval==){} }"), InternalError, "syntax error: == )");
+ ASSERT_THROW_EQUALS(tokenizeAndStringify("void f() { if (retval==){} }"), InternalError, "syntax error: ==)");
// after (expr)
ASSERT_NO_THROW(tokenizeAndStringify("void f() { switch (a) int b; }"));
@@ -8108,6 +8108,9 @@ private:
// Ticket #9664
ASSERT_NO_THROW(tokenizeAndStringify("S s = { .x { 2 }, .y[0] { 3 } };"));
+
+ ASSERT_THROW_EQUALS(tokenizeAndStringify("void f() { assert(a==()); }"), InternalError, "syntax error: ==()");
+ ASSERT_THROW_EQUALS(tokenizeAndStringify("void f() { assert(a+()); }"), InternalError, "syntax error: +()");
}
From 6bc13080eec83491e31f6cdc1f7f4d66733830fc Mon Sep 17 00:00:00 2001
From: Georgy Komarov
Date: Sat, 18 Jul 2020 07:07:20 +0300
Subject: [PATCH 082/116] Simplify condition
---
lib/tokenize.cpp | 4 +---
1 file changed, 1 insertion(+), 3 deletions(-)
diff --git a/lib/tokenize.cpp b/lib/tokenize.cpp
index 196653206..06884c75a 100644
--- a/lib/tokenize.cpp
+++ b/lib/tokenize.cpp
@@ -9631,9 +9631,7 @@ void Tokenizer::findGarbageCode() const
if (Token::simpleMatch(tok->next(), "( )"))
code = tok->str() + "()";
if (!code.empty()) {
- if (isC())
- syntaxError(tok, code);
- if (tok->str() != ">" && !Token::simpleMatch(tok->previous(), "operator"))
+ if (isC() || (tok->str() != ">" && !Token::simpleMatch(tok->previous(), "operator")))
syntaxError(tok, code);
}
}
From 744b3631861d510abde174dee88c83359b178dc0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 08:23:04 +0200
Subject: [PATCH 083/116] GUI; Tweaks. Add tooltips, change texts.
---
gui/projectfiledialog.cpp | 5 +--
gui/projectfiledialog.ui | 39 ++++++++++++++++++----
gui/resultsview.ui | 69 +++++++++++++++------------------------
3 files changed, 62 insertions(+), 51 deletions(-)
diff --git a/gui/projectfiledialog.cpp b/gui/projectfiledialog.cpp
index 4eb1c403d..52ce8c61e 100644
--- a/gui/projectfiledialog.cpp
+++ b/gui/projectfiledialog.cpp
@@ -208,6 +208,7 @@ ProjectFileDialog::ProjectFileDialog(ProjectFile *projectFile, QWidget *parent)
connect(mUI.mListSuppressions, &QListWidget::doubleClicked, this, &ProjectFileDialog::editSuppression);
connect(mUI.mBtnBrowseMisraFile, &QPushButton::clicked, this, &ProjectFileDialog::browseMisraFile);
connect(mUI.mChkAllVsConfigs, &QCheckBox::clicked, this, &ProjectFileDialog::checkAllVSConfigs);
+ connect(mUI.mBtnNormalAnalysis, &QCheckBox::toggled, mUI.mBtnSafeClasses, &QCheckBox::setEnabled);
loadFromProjectFile(projectFile);
}
@@ -266,7 +267,7 @@ void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
else
mUI.mBtnCppcheckParser->setChecked(true);
mUI.mBtnSafeClasses->setChecked(projectFile->safeChecks.classes);
- mUI.mBugHunting->setChecked(projectFile->bugHunting);
+ mUI.mBtnBugHunting->setChecked(projectFile->bugHunting);
setExcludedPaths(projectFile->getExcludedPaths());
setLibraries(projectFile->getLibraries());
const QString platform = projectFile->getPlatform();
@@ -371,7 +372,7 @@ void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
projectFile->setLibraries(getLibraries());
projectFile->clangParser = mUI.mBtnClangParser->isChecked();
projectFile->safeChecks.classes = mUI.mBtnSafeClasses->isChecked();
- projectFile->bugHunting = mUI.mBugHunting->isChecked();
+ projectFile->bugHunting = mUI.mBtnBugHunting->isChecked();
if (mUI.mComboBoxPlatform->currentText().endsWith(".xml"))
projectFile->setPlatform(mUI.mComboBoxPlatform->currentText());
else {
diff --git a/gui/projectfiledialog.ui b/gui/projectfiledialog.ui
index 1cf6d5d15..d809dd894 100644
--- a/gui/projectfiledialog.ui
+++ b/gui/projectfiledialog.ui
@@ -420,7 +420,11 @@
-
-
+
+
+ This is a workfolder that Cppcheck will use for various purposes.
+
+
-
@@ -461,18 +465,31 @@
-
- Check that code is safe
+ Analysis
-
-
+
- Bug hunting -- Detect all bugs. Generates mostly noise.
+ Normal analysis -- Avoid false positives.
+
+
+ true
+
+
+
+ -
+
+
+ Bug hunting -- Generates mostly noise. The goal is to be "soundy" and detect most bugs.
-
+
+ If you want to design your classes to be as flexible and robust as possible then the public interface must be very robust. Cppcheck will asumme that arguments can take *any* value.
+
Check that each class has a safe public interface
@@ -605,7 +622,11 @@
-
-
+
+
+ Filepaths in warnings will be relative to this path
+
+
@@ -617,7 +638,11 @@
-
-
+
+
+ If tags are added, you will be able to right click on warnings and set one of these tags. You can manually categorize warnings.
+
+
@@ -625,7 +650,7 @@
-
- Exclude source files in paths
+ Exclude source files
-
diff --git a/gui/resultsview.ui b/gui/resultsview.ui
index 584c8a9ea..cfe8b57d5 100644
--- a/gui/resultsview.ui
+++ b/gui/resultsview.ui
@@ -159,49 +159,34 @@
-
-
-
- Qt::Vertical
+
+
+ Configured contracts:
+
+
+
+ -
+
+
+ QAbstractItemView::NoEditTriggers
+
+
+
+ -
+
+
+ Missing contracts:
+
+
+
+ -
+
+
+ QAbstractItemView::NoEditTriggers
+
+
+ true
-
-
-
-
-
-
- Configured contracts:
-
-
-
- -
-
-
- QAbstractItemView::NoEditTriggers
-
-
-
-
-
-
-
- -
-
-
- Missing contracts:
-
-
-
- -
-
-
- QAbstractItemView::NoEditTriggers
-
-
- true
-
-
-
-
-
From 23008e7bc0cae23b93269f782a4c7a15772e3c50 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 08:56:31 +0200
Subject: [PATCH 084/116] GUI: Add button in ProjectFileDialog to exclude a
file
---
gui/projectfiledialog.cpp | 20 ++++++++++++++++----
gui/projectfiledialog.h | 7 ++++++-
gui/projectfiledialog.ui | 9 ++++++++-
3 files changed, 30 insertions(+), 6 deletions(-)
diff --git a/gui/projectfiledialog.cpp b/gui/projectfiledialog.cpp
index 52ce8c61e..70452845a 100644
--- a/gui/projectfiledialog.cpp
+++ b/gui/projectfiledialog.cpp
@@ -199,6 +199,7 @@ ProjectFileDialog::ProjectFileDialog(ProjectFile *projectFile, QWidget *parent)
connect(mUI.mBtnEditInclude, &QPushButton::clicked, this, &ProjectFileDialog::editIncludeDir);
connect(mUI.mBtnRemoveInclude, &QPushButton::clicked, this, &ProjectFileDialog::removeIncludeDir);
connect(mUI.mBtnAddIgnorePath, SIGNAL(clicked()), this, SLOT(addExcludePath()));
+ connect(mUI.mBtnAddIgnoreFile, SIGNAL(clicked()), this, SLOT(addExcludeFile()));
connect(mUI.mBtnEditIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::editExcludePath);
connect(mUI.mBtnRemoveIgnorePath, &QPushButton::clicked, this, &ProjectFileDialog::removeExcludePath);
connect(mUI.mBtnIncludeUp, &QPushButton::clicked, this, &ProjectFileDialog::moveIncludePathUp);
@@ -718,9 +719,17 @@ void ProjectFileDialog::editIncludeDir()
void ProjectFileDialog::addExcludePath()
{
- QString dir = getExistingDirectory(tr("Select directory to ignore"), true);
- if (!dir.isEmpty())
- addExcludePath(dir);
+ addExcludePath(getExistingDirectory(tr("Select directory to ignore"), true));
+}
+
+void ProjectFileDialog::addExcludeFile()
+{
+ const QFileInfo inf(mProjectFile->getFilename());
+ const QDir &dir = inf.absoluteDir();
+ QMap filters;
+ filters[tr("Source files")] = "*.c *.cpp";
+ filters[tr("All files")] = "*.*";
+ addExcludePath(QFileDialog::getOpenFileName(this, tr("Exclude file"), dir.canonicalPath(), toFilterString(filters)));
}
void ProjectFileDialog::editExcludePath()
@@ -803,7 +812,10 @@ int ProjectFileDialog::getSuppressionIndex(const QString &shortText) const
void ProjectFileDialog::browseMisraFile()
{
- const QString fileName = QFileDialog::getOpenFileName(this, tr("Select MISRA rule texts file"), QDir::homePath(), tr("Misra rule texts file (%1)").arg("*.txt"));
+ const QString fileName = QFileDialog::getOpenFileName(this,
+ tr("Select MISRA rule texts file"),
+ QDir::homePath(),
+ tr("Misra rule texts file (%1)").arg("*.txt"));
if (!fileName.isEmpty()) {
QSettings settings;
mUI.mEditMisraFile->setText(fileName);
diff --git a/gui/projectfiledialog.h b/gui/projectfiledialog.h
index 30237a370..fef320a4f 100644
--- a/gui/projectfiledialog.h
+++ b/gui/projectfiledialog.h
@@ -215,10 +215,15 @@ protected slots:
void editIncludeDir();
/**
- * @brief Add new path to exclude.
+ * @brief Add new path to exclude list.
*/
void addExcludePath();
+ /**
+ * @brief Add new file to exclude list.
+ */
+ void addExcludeFile();
+
/**
* @brief Edit excluded path in the list.
*/
diff --git a/gui/projectfiledialog.ui b/gui/projectfiledialog.ui
index d809dd894..4ba8af1aa 100644
--- a/gui/projectfiledialog.ui
+++ b/gui/projectfiledialog.ui
@@ -661,7 +661,14 @@
-
- Add...
+ Add folder...
+
+
+
+ -
+
+
+ Add file...
From 9ec5ae2929dcded279c3c9d73330c201fc90d031 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 15:27:25 +0200
Subject: [PATCH 085/116] GUI: Started writing a manual
---
man/gui-manual.md | 183 ++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 183 insertions(+)
create mode 100644 man/gui-manual.md
diff --git a/man/gui-manual.md b/man/gui-manual.md
new file mode 100644
index 000000000..d4ccee5ac
--- /dev/null
+++ b/man/gui-manual.md
@@ -0,0 +1,183 @@
+---
+title: Cppcheck GUI manual
+subtitle: Version 2.1.99
+author: Cppcheck team
+lang: en
+documentclass: report
+---
+
+
+# Standalone analysis
+
+It is possible to quickly analyze files. Open the `Analyze` menu and click on either `Files...` or `Directory...`.
+
+It is recommended that you create a project for analysis. A properly configured project will give you better analysis.
+
+# Project
+
+## Creating project
+
+Open the `File` menu and click on `New project...`.
+
+## Project options
+
+The `Project file` dialog contains 4 tabs:
+ - Paths and defines; paths to check and basic preprocessor settings.
+ - Types and Functions; configuration of platform and 3rd party libraries
+ - Analysis; analysis options
+ - Warning options; formatting warnings, suppressing warnings, etc
+ - Addons; extra analysis with addons
+
+### Paths and defines
+
+It is recommended to import a project file.
+
+#### Import project
+
+Project to import. Cppcheck will get:
+ * what files to check
+ * preprocessor defines
+ * preprocessor include paths
+ * language standard if set
+
+#### Paths (If you do not import project)
+
+What paths to check.
+
+#### Defines (If you do not import project)
+
+Cppcheck automatically checks the code with different preprocessor configurations.
+
+ #ifdef A
+ code1
+ #endif
+ #ifdef B
+ code2
+ #endif
+
+Cppcheck will automatically perform analysis both when A is defined and B is defined. So any bugs in both code1 and code2 will be detected.
+
+If you want to configure that A will always be defined in Cppcheck analysis you can do that here.
+
+Defines are separated by semicolon. So you can for instance write:
+
+ A;B=3;C
+
+#### Undefines (If you do not import project)
+
+
+Cppcheck automatically checks the code with different preprocessor configurations.
+
+ #ifdef A
+ code1
+ #endif
+ #ifdef B
+ code2
+ #endif
+
+Cppcheck will automatically perform analysis both when A is defined and B is defined. So any bugs in both code1 and code2 will be detected.
+
+If you want to configure that A is never defined in Cppcheck analysis you can do that here.
+
+Undefines are separated by semicolon. So you can for instance write:
+
+ A;C
+
+#### Include paths (If you do not import project)
+
+Specify include paths.
+
+### Types and Functions
+
+Cppcheck uses `Platform` setting to determine size of short/int/long/pointer/etc.
+
+Check the libraries that you use in the `Libraries` listbox.
+
+### Analysis
+
+#### Cppcheck build dir
+
+This is a work-folder that Cppcheck uses. Each Cppcheck project should have a separate build dir. It is used for:
+ * whole program analysis
+ * debug output
+ * faster analysis (if a source file has changed check it, if source file is not changed then reuse old results)
+ * statistics
+
+#### Parser
+
+It is in general recommended to use Cppcheck parser. However you can choose to use Clang parser; Clang will be executed with a command line flag that tells it to dump its AST and Cppcheck will read that AST and convert it into a corresponding Cppcheck AST and use that.
+
+#### Analysis
+
+Configure what kind of analysis you want.
+
+The `Normal analysis` is recommended for most use cases. Especially if you use Cppcheck in CI.
+
+The `Bug hunting` can be used if you really want to find a bug in your code and can invest time looking at bad results and providing extra configuration.
+
+#### Limit analysis
+
+You can turn off checking of headers. That could be interesting if Cppcheck is very slow. But normally, you should check the code in headers.
+
+It is possible to check the code in unused templates. However the Cppcheck AST will be incomplete/wrong. The recommendation is that you do not check unused templates to avoid wrong warnings. The templates will be checked properly when you do use them.
+
+Max CTU depth: How deep should the whole program analysis be. The risk with a "too high" value is that Cppcheck will be slow.
+
+Max recursion in template instantiation: Max recursion when Cppcheck instantiates templates. The risk with a "too high" value is that Cppcheck will be slow and can require much memory.
+
+
+### Warning options
+
+#### Root path
+
+The root path for warnings. Cppcheck will strip away this part of the path from warnings. For instance if there is a warning in `../myproject/foo/bar/file.cpp` and the root path is `../myproject/foo` then the path for the warning will be `bar/file.cpp`.
+
+#### Warning Tags
+
+Tags allow you to manually categorize warnings.
+
+#### Exclude source files
+
+Excluded source files will not be analyzed by Cppcheck
+
+#### Suppressions
+
+List of suppressions. These warnings will not be shown.
+
+### Addons
+
+Y2038 - 32-bit timers that count number of seconds since 1970 will overflow in year 2038. Check that the code does not use such timers.
+
+Thread safety - Check that the code is thread safe
+
+Cert - Ensure that the Cert coding standard is followed
+
+Misra - Ensure that the Misra coding standard is followed. Please note you need to have a textfile with the misra rule texts to get proper warning messages. Cppcheck is not legally allowed to distribute the misra rule texts.
+
+Clang-tidy - Run Clang-tidy
+
+
+# Preferences
+
+TODO
+
+
+# Looking at results
+
+When you have run the analysis it is time to look at the results.
+
+If you click on a warning then the corresponding code will be shown in the "Warning details" at the bottom.
+
+You can right click warnings to get options. The difference of "hiding" a warning and "suppressing" a warning is that the suppression is permanent and hiding the warning is only temporary.
+
+
+# Tagging warnings
+
+You can manually categorize warnings.
+
+You choose the names of the categories yourself in the project file dialog.
+
+If tag names are configured then when you look at results you can right click on a warning and tag it.
+
+
+
From 2b0505930722af59c0070d093f59cec3d3245f22 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 17:10:39 +0200
Subject: [PATCH 086/116] GUI; Tweaked button texts
---
gui/projectfiledialog.ui | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/gui/projectfiledialog.ui b/gui/projectfiledialog.ui
index 4ba8af1aa..31884ce91 100644
--- a/gui/projectfiledialog.ui
+++ b/gui/projectfiledialog.ui
@@ -661,14 +661,14 @@
-
- Add folder...
+ Exclude folder...
-
- Add file...
+ Exclude file...
From 46d997cd71db27754e4079266ea0cfa13d2023b4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 17:20:45 +0200
Subject: [PATCH 087/116] GUI; Remove unused signal ResultTree::tagged
---
gui/resultstree.h | 5 -----
1 file changed, 5 deletions(-)
diff --git a/gui/resultstree.h b/gui/resultstree.h
index cc7dacd35..5f2557826 100644
--- a/gui/resultstree.h
+++ b/gui/resultstree.h
@@ -202,11 +202,6 @@ signals:
*/
void treeSelectionChanged(const QModelIndex ¤t);
- /**
- * Selected item(s) has been tagged
- */
- void tagged();
-
/** Suppress Ids */
void suppressIds(QStringList ids);
From 7cb65b7f674ee9d04a03e6e6a56d0b33eae23f0a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 18:14:55 +0200
Subject: [PATCH 088/116] GUI: Speedup code editor when selecting another
warning in the same file
---
gui/codeeditor.cpp | 13 +++++++++++++
gui/codeeditor.h | 24 ++++++++++++++++++++++++
gui/resultstree.cpp | 3 +++
gui/resultsview.cpp | 32 +++++++++++++++++++-------------
gui/resultsview.h | 3 +++
lib/bughuntingchecks.cpp | 7 +++++--
6 files changed, 67 insertions(+), 15 deletions(-)
diff --git a/gui/codeeditor.cpp b/gui/codeeditor.cpp
index a44e351c1..e7d6c6f07 100644
--- a/gui/codeeditor.cpp
+++ b/gui/codeeditor.cpp
@@ -257,6 +257,19 @@ void CodeEditor::setError(const QString &code, int errorLine, const QStringList
highlightErrorLine();
}
+void CodeEditor::setError(int errorLine, const QStringList &symbols)
+{
+ mHighlighter->setSymbols(symbols);
+
+ mErrorPosition = getPos(toPlainText(), errorLine);
+ QTextCursor tc = textCursor();
+ tc.setPosition(mErrorPosition);
+ setTextCursor(tc);
+ centerCursor();
+
+ highlightErrorLine();
+}
+
int CodeEditor::lineNumberAreaWidth()
{
int digits = 1;
diff --git a/gui/codeeditor.h b/gui/codeeditor.h
index 09fe523d0..3ed01d6b0 100644
--- a/gui/codeeditor.h
+++ b/gui/codeeditor.h
@@ -77,6 +77,29 @@ public:
*/
void setError(const QString &code, int errorLine, const QStringList &symbols);
+ /**
+ * Goto another error in existing source file
+ * \param errorLine line number
+ * \param symbols the related symbols, these are marked
+ */
+ void setError(int errorLine, const QStringList &symbols);
+
+ void setFileName(const QString &fileName)
+ {
+ mFileName = fileName;
+ }
+
+ QString getFileName() const
+ {
+ return mFileName;
+ }
+
+ void clear()
+ {
+ mFileName.clear();
+ setPlainText(QString());
+ }
+
protected:
void resizeEvent(QResizeEvent *event) override;
@@ -93,6 +116,7 @@ private:
Highlighter *mHighlighter;
CodeEditorStyle *mWidgetStyle;
int mErrorPosition;
+ QString mFileName;
};
diff --git a/gui/resultstree.cpp b/gui/resultstree.cpp
index 392fc082e..191735c39 100644
--- a/gui/resultstree.cpp
+++ b/gui/resultstree.cpp
@@ -63,6 +63,7 @@ static const char LINE[] = "line";
static const char MESSAGE[] = "message";
static const char SEVERITY[] = "severity";
static const char SINCEDATE[] = "sinceDate";
+static const char SYMBOLNAMES[] = "symbolNames";
static const char SUMMARY[] = "summary";
static const char TAGS[] = "tags";
@@ -223,6 +224,7 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
data[FILE0] = stripPath(item.file0, true);
data[FUNCTION] = item.function;
data[SINCEDATE] = item.sinceDate;
+ data[SYMBOLNAMES] = item.symbolNames;
data[TAGS] = line.tags;
data[HIDE] = hide;
stditem->setData(QVariant(data));
@@ -256,6 +258,7 @@ bool ResultsTree::addErrorItem(const ErrorItem &item)
child_data[CWE] = line.cwe;
child_data[CPPCHECKID] = line.cppcheckId;
child_data[INCONCLUSIVE] = line.inconclusive;
+ child_data[SYMBOLNAMES] = item.symbolNames;
child_item->setData(QVariant(child_data));
}
}
diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp
index e5cd359fa..35a5b5d96 100644
--- a/gui/resultsview.cpp
+++ b/gui/resultsview.cpp
@@ -385,9 +385,8 @@ void ResultsView::updateDetails(const QModelIndex &index)
QStandardItemModel *model = qobject_cast(mUI.mTree->model());
QStandardItem *item = model->itemFromIndex(index);
- mUI.mCode->setPlainText(QString());
-
if (!item) {
+ mUI.mCode->clear();
mUI.mDetails->setText(QString());
return;
}
@@ -400,6 +399,7 @@ void ResultsView::updateDetails(const QModelIndex &index)
// If there is no severity data then it is a parent item without summary and message
if (!data.contains("severity")) {
+ mUI.mCode->clear();
mUI.mDetails->setText(QString());
return;
}
@@ -425,19 +425,25 @@ void ResultsView::updateDetails(const QModelIndex &index)
if (!QFileInfo(filepath).exists() && QFileInfo(mUI.mTree->getCheckDirectory() + '/' + filepath).exists())
filepath = mUI.mTree->getCheckDirectory() + '/' + filepath;
- QFile file(filepath);
- if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
- QStringList symbols;
- QRegularExpression re(".*: ([A-Za-z_][A-Za-z0-9_]*)$");
- const QString errorMessage = data["message"].toString();
- QRegularExpressionMatch match = re.match(errorMessage);
- if (match.hasMatch()) {
- symbols << match.captured(1);
- }
+ QStringList symbols;
+ if (data.contains("symbolNames"))
+ symbols = data["symbolNames"].toString().split("\n");
- QTextStream in(&file);
- mUI.mCode->setError(in.readAll(), lineNumber, symbols);
+ if (filepath == mUI.mCode->getFileName())
+ {
+ mUI.mCode->setError(lineNumber, symbols);
+ return;
}
+
+ QFile file(filepath);
+ if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ mUI.mCode->clear();
+ return;
+ }
+
+ QTextStream in(&file);
+ mUI.mCode->setError(in.readAll(), lineNumber, symbols);
+ mUI.mCode->setFileName(filepath);
}
void ResultsView::log(const QString &str)
diff --git a/gui/resultsview.h b/gui/resultsview.h
index 2332b429f..44871a266 100644
--- a/gui/resultsview.h
+++ b/gui/resultsview.h
@@ -359,6 +359,9 @@ private slots:
void on_mListLog_customContextMenuRequested(const QPoint &pos);
private:
QSet mContracts;
+
+ /** Current file shown in the code editor */
+ QString mCurrentFileName;
};
/// @}
#endif // RESULTSVIEW_H
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 3ba3643a6..82c7bdde9 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -352,10 +352,11 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
const std::string inconclusiveMessage(inconclusive ? ". It is inconclusive if there would be a problem in the function call." : "");
if (!uninitStructMember.empty()) {
+ const std::string symbol = tok->expressionString() + "." + uninitStructMember;
dataBase->reportError(tok,
Severity::SeverityType::error,
"bughuntingUninitStructMember",
- "Cannot determine that '" + tok->expressionString() + "." + uninitStructMember + "' is initialized" + inconclusiveMessage,
+ "$symbol:" + symbol + "\nCannot determine that '$symbol' is initialized" + inconclusiveMessage,
CWE_USE_OF_UNINITIALIZED_VARIABLE,
inconclusive,
value.type == ExprEngine::ValueType::BailoutValue);
@@ -366,10 +367,12 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (uninitData)
uninitexpr += "[0]";
+ const std::string symbol = (tok->varId() > 0) ? ("$symbol:" + tok->str() + "\n") : std::string();
+
dataBase->reportError(tok,
Severity::SeverityType::error,
"bughuntingUninit",
- "Cannot determine that '" + uninitexpr + "' is initialized" + inconclusiveMessage,
+ symbol + "Cannot determine that '" + uninitexpr + "' is initialized" + inconclusiveMessage,
CWE_USE_OF_UNINITIALIZED_VARIABLE,
inconclusive,
value.type == ExprEngine::ValueType::BailoutValue);
From e9281babc498e7fd3bcd19a9f418637a9a399634 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sat, 18 Jul 2020 18:54:21 +0200
Subject: [PATCH 089/116] Bug hunting; avoid false positives for
structs/classes with constructors
---
lib/exprengine.cpp | 11 +++++++++--
test/testbughuntingchecks.cpp | 12 ++++++++++++
2 files changed, 21 insertions(+), 2 deletions(-)
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index 388f4149c..f0ad91118 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -2567,8 +2567,15 @@ static ExprEngine::ValuePtr createVariableValue(const Variable &var, Data &data)
data.addConstraints(value, var.nameToken());
return value;
}
- if (valueType->type == ValueType::Type::RECORD)
- return createStructVal(valueType->typeScope, var.isLocal() && !var.isStatic(), data);
+ if (valueType->type == ValueType::Type::RECORD) {
+ bool init = true;
+ if (var.isLocal() && !var.isStatic()) {
+ init = valueType->typeScope &&
+ valueType->typeScope->definedType &&
+ valueType->typeScope->definedType->needInitialization != Type::NeedInitialization::False;
+ }
+ return createStructVal(valueType->typeScope, init, data);
+ }
if (valueType->smartPointerType) {
auto structValue = createStructVal(valueType->smartPointerType->classScope, var.isLocal() && !var.isStatic(), data);
auto size = std::make_shared(data.getNewSymbolName(), 1, ~0UL);
diff --git a/test/testbughuntingchecks.cpp b/test/testbughuntingchecks.cpp
index bfb62e985..392991b31 100644
--- a/test/testbughuntingchecks.cpp
+++ b/test/testbughuntingchecks.cpp
@@ -39,6 +39,7 @@ private:
TEST_CASE(uninit_array);
TEST_CASE(uninit_function_par);
TEST_CASE(uninit_malloc);
+ TEST_CASE(uninit_struct);
TEST_CASE(ctu);
#endif
}
@@ -98,6 +99,17 @@ private:
ASSERT_EQUALS("[test.cpp:1]: (error) Cannot determine that '*p' is initialized\n", errout.str());
}
+ void uninit_struct() {
+ // Assume that constructors initialize all members
+ // TODO whole program analysis
+ check("struct Data { Data(); int x; }\n"
+ "void foo() {\n"
+ " Data data;\n"
+ " x = data.x;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+ }
+
void ctu() {
check("void init(int &x) {\n"
" x = 1;\n"
From 3723c708fc051c74269a56b2d338087f5db9db97 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 08:07:10 +0200
Subject: [PATCH 090/116] ImportProject; Do not fail loading a GUI project that
has warning tags
---
lib/importproject.cpp | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/lib/importproject.cpp b/lib/importproject.cpp
index 62ff618ca..3f81338d6 100644
--- a/lib/importproject.cpp
+++ b/lib/importproject.cpp
@@ -1130,7 +1130,9 @@ bool ImportProject::importCppcheckGuiProject(std::istream &istr, Settings *setti
else
return false;
}
- } else
+ } else if (strcmp(node->Name(), CppcheckXml::TagWarningsElementName) == 0)
+ ; // TODO
+ else
return false;
}
settings->basePaths = temp.basePaths;
From 011c5e97f98e9d2a5db36297fd85f3a5591b1b0e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 08:56:14 +0200
Subject: [PATCH 091/116] gui-manual: Preferences
---
man/gui-manual.md | 133 ++++++++++++++++++++++++++++++++++++++--------
1 file changed, 110 insertions(+), 23 deletions(-)
diff --git a/man/gui-manual.md b/man/gui-manual.md
index d4ccee5ac..a94b0c664 100644
--- a/man/gui-manual.md
+++ b/man/gui-manual.md
@@ -9,9 +9,11 @@ documentclass: report
# Standalone analysis
-It is possible to quickly analyze files. Open the `Analyze` menu and click on either `Files...` or `Directory...`.
+It is possible to quickly analyze files. Open the `Analyze` menu and click on
+either `Files...` or `Directory...`.
-It is recommended that you create a project for analysis. A properly configured project will give you better analysis.
+It is recommended that you create a project for analysis. A properly configured
+project will give you better analysis.
# Project
@@ -55,9 +57,11 @@ Cppcheck automatically checks the code with different preprocessor configuration
code2
#endif
-Cppcheck will automatically perform analysis both when A is defined and B is defined. So any bugs in both code1 and code2 will be detected.
+Cppcheck will automatically perform analysis both when A is defined and B is
+defined. So any bugs in both code1 and code2 will be detected.
-If you want to configure that A will always be defined in Cppcheck analysis you can do that here.
+If you want to configure that A will always be defined in Cppcheck analysis you
+can do that here.
Defines are separated by semicolon. So you can for instance write:
@@ -75,9 +79,11 @@ Cppcheck automatically checks the code with different preprocessor configuration
code2
#endif
-Cppcheck will automatically perform analysis both when A is defined and B is defined. So any bugs in both code1 and code2 will be detected.
+Cppcheck will automatically perform analysis both when A is defined and B is
+defined. So any bugs in both code1 and code2 will be detected.
-If you want to configure that A is never defined in Cppcheck analysis you can do that here.
+If you want to configure that A is never defined in Cppcheck analysis you can
+do that here.
Undefines are separated by semicolon. So you can for instance write:
@@ -97,40 +103,57 @@ Check the libraries that you use in the `Libraries` listbox.
#### Cppcheck build dir
-This is a work-folder that Cppcheck uses. Each Cppcheck project should have a separate build dir. It is used for:
+This is a work-folder that Cppcheck uses. Each Cppcheck project should have a
+separate build dir. It is used for:
* whole program analysis
* debug output
- * faster analysis (if a source file has changed check it, if source file is not changed then reuse old results)
+ * faster analysis (if a source file has changed check it, if source file is
+ not changed then reuse old results)
* statistics
#### Parser
-It is in general recommended to use Cppcheck parser. However you can choose to use Clang parser; Clang will be executed with a command line flag that tells it to dump its AST and Cppcheck will read that AST and convert it into a corresponding Cppcheck AST and use that.
+It is in general recommended to use Cppcheck parser. However you can choose to
+use Clang parser; Clang will be executed with a command line flag that tells it
+to dump its AST and Cppcheck will read that AST and convert it into a
+corresponding Cppcheck AST and use that.
#### Analysis
Configure what kind of analysis you want.
-The `Normal analysis` is recommended for most use cases. Especially if you use Cppcheck in CI.
+The `Normal analysis` is recommended for most use cases. Especially if you use
+Cppcheck in CI.
-The `Bug hunting` can be used if you really want to find a bug in your code and can invest time looking at bad results and providing extra configuration.
+The `Bug hunting` can be used if you really want to find a bug in your code
+and can invest time looking at bad results and providing extra configuration.
#### Limit analysis
-You can turn off checking of headers. That could be interesting if Cppcheck is very slow. But normally, you should check the code in headers.
+You can turn off checking of headers. That could be interesting if Cppcheck is
+very slow. But normally, you should check the code in headers.
-It is possible to check the code in unused templates. However the Cppcheck AST will be incomplete/wrong. The recommendation is that you do not check unused templates to avoid wrong warnings. The templates will be checked properly when you do use them.
+It is possible to check the code in unused templates. However the Cppcheck AST
+will be incomplete/wrong. The recommendation is that you do not check unused
+templates to avoid wrong warnings. The templates will be checked properly when
+you do use them.
-Max CTU depth: How deep should the whole program analysis be. The risk with a "too high" value is that Cppcheck will be slow.
+Max CTU depth: How deep should the whole program analysis be. The risk with a
+"too high" value is that Cppcheck will be slow.
-Max recursion in template instantiation: Max recursion when Cppcheck instantiates templates. The risk with a "too high" value is that Cppcheck will be slow and can require much memory.
+Max recursion in template instantiation: Max recursion when Cppcheck
+instantiates templates. The risk with a "too high" value is that Cppcheck will
+be slow and can require much memory.
### Warning options
#### Root path
-The root path for warnings. Cppcheck will strip away this part of the path from warnings. For instance if there is a warning in `../myproject/foo/bar/file.cpp` and the root path is `../myproject/foo` then the path for the warning will be `bar/file.cpp`.
+The root path for warnings. Cppcheck will strip away this part of the path
+from warnings. For instance if there is a warning in
+`../myproject/foo/bar/file.cpp` and the root path is `../myproject/foo` then
+the path for the warning will be `bar/file.cpp`.
#### Warning Tags
@@ -146,38 +169,102 @@ List of suppressions. These warnings will not be shown.
### Addons
-Y2038 - 32-bit timers that count number of seconds since 1970 will overflow in year 2038. Check that the code does not use such timers.
+Y2038 - 32-bit timers that count number of seconds since 1970 will overflow in
+year 2038. Check that the code does not use such timers.
Thread safety - Check that the code is thread safe
Cert - Ensure that the Cert coding standard is followed
-Misra - Ensure that the Misra coding standard is followed. Please note you need to have a textfile with the misra rule texts to get proper warning messages. Cppcheck is not legally allowed to distribute the misra rule texts.
+Misra - Ensure that the Misra coding standard is followed. Please note you
+need to have a textfile with the misra rule texts to get proper warning
+messages. Cppcheck is not legally allowed to distribute the misra rule texts.
Clang-tidy - Run Clang-tidy
# Preferences
-TODO
+`Number of threads`: Number of threads to use in analysis. Each thread checks
+its own source file.
+
+`Force checking of all #ifdef configurations`: Cppcheck try to check all code
+and will therefore guess different preprocessor configurations. The maximum
+number of configurations that is checked is 14 by default.
+
+`Show full path of files`: Show the full paths in the results.
+
+`Show "No errors found" message when no errors found`: If you want to get a
+message box about this.
+
+`Display error id column "Id"`: Show error id in results
+
+`Enable inline suppressions`: You can suppress warnings with comments. See the
+Cppcheck manual (http://cppcheck.sf.net/manual.pdf) for more information about
+those.
+
+`Check for inconclusive errors also`: When full analysis of the code can not
+determine if there should be a warning or not, it is inconclusive. Normally
+Cppcheck does not warn then.
+
+`Show statistics on check completion`: Show statistics in a window when
+analysis finish.
+
+`Show internal warnings in log`: Internal warnings (for debugging) is shown
+in the `Analysis log`.
+
+`Applications`: Configure external editor to open from context menu when you
+right click on a warning.
+
+`Save all errors when creating report`: If hidden warnings should be saved or
+not.
+
+`Save full path to files in report`: If you use `Root path` the warnings on the
+screen will not have the full path.
+
+`Language`: Configure language to use for GUI.
+
+`Python binary`: To be able to execute addons, Cppcheck needs to know where
+python is. Unless you configure something, Cppcheck will try to execute python
+in your PATH.
+
+`Misra rule texts`: Only needed if you want to use the Misra addon. Cppcheck is
+not legally allowed to distribute the Misra rule texts and these must be
+provided by users. The Misra rule texts are proprietary. An example rule text
+file can be found here: https://github.com/danmar/cppcheck/blob/main/addons/test/misra/misra2012_rules_dummy_ascii.txt
+
+`Clang path`: The path to `clang` binary. If no path is provided then system
+PATH is used.
+
+`Visual studio headers`: If you want to use the Visual Studio headers in the
+analysis you can provide the path(s) here. Hint: Open a visual studio command
+prompt and type `SET INCLUDE`. Then copy/paste the paths.
+
+`Code editor style`: The visual theme to use for the code editor that is used
+when you investigate results.
+
# Looking at results
When you have run the analysis it is time to look at the results.
-If you click on a warning then the corresponding code will be shown in the "Warning details" at the bottom.
+If you click on a warning then the corresponding code will be shown in the
+"Warning details" at the bottom.
-You can right click warnings to get options. The difference of "hiding" a warning and "suppressing" a warning is that the suppression is permanent and hiding the warning is only temporary.
+You can right click warnings to get options. The difference of "hiding" a
+warning and "suppressing" a warning is that the suppression is permanent and
+hiding the warning is only temporary.
# Tagging warnings
You can manually categorize warnings.
-You choose the names of the categories yourself in the project file dialog.
+You choose the names of the categories yourself in the project file dialog.
-If tag names are configured then when you look at results you can right click on a warning and tag it.
+If tag names are configured then when you look at results you can right click
+on a warning and tag it.
From 7e65b561f0e47d03b856cbd7c65a57d72c6a337e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 11:10:38 +0200
Subject: [PATCH 092/116] AST: Fix ast for 'for ((..initexpr..);;)'
---
lib/tokenlist.cpp | 12 ++++++++++++
test/testtokenize.cpp | 2 ++
2 files changed, 14 insertions(+)
diff --git a/lib/tokenlist.cpp b/lib/tokenlist.cpp
index d923ca7b3..e12983f8e 100644
--- a/lib/tokenlist.cpp
+++ b/lib/tokenlist.cpp
@@ -1387,6 +1387,18 @@ static Token * createAstAtToken(Token *tok, bool cpp)
init1 = tok2;
AST_state state1(cpp);
compileExpression(tok2, state1);
+ if (init1->str() == "(") {
+ for (Token *tok3 = init1; tok3 != tok3->link(); tok3 = tok3->next()) {
+ if (tok3->astParent()) {
+ while (tok3->astParent())
+ tok3 = tok3->astParent();
+ init1 = tok3;
+ break;
+ }
+ if (!Token::Match(tok3, "%op%|(|["))
+ init1 = tok3;
+ }
+ }
} else {
while (tok2 && tok2 != endPar && tok2->str() != ";") {
if (tok2->str() == "<" && tok2->link()) {
diff --git a/test/testtokenize.cpp b/test/testtokenize.cpp
index 4d2705d9e..63438b58e 100644
--- a/test/testtokenize.cpp
+++ b/test/testtokenize.cpp
@@ -7677,6 +7677,8 @@ private:
ASSERT_EQUALS("pf.pf.12,(&&", testAst("((p.f) && (p.f)(1,2))"));
+ ASSERT_EQUALS("forresdirGetFirst.file&_T(,(=;;(", testAst("for ((res = dir.GetFirst(&file, _T("")));;) {}"));
+
// problems with: if (x[y]==z)
ASSERT_EQUALS("ifa(0[1==(", testAst("if(a()[0]==1){}"));
ASSERT_EQUALS("ifbuff0[&(*1==(", testAst("if (*((DWORD*)&buff[0])==1){}"));
From 5df9cd90a61b8adaf33e9ee1ce73c2ed85dcf059 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 11:10:53 +0200
Subject: [PATCH 093/116] astyle formatting
[ci skip]
---
gui/codeeditor.h | 9 +++------
gui/resultsview.cpp | 3 +--
2 files changed, 4 insertions(+), 8 deletions(-)
diff --git a/gui/codeeditor.h b/gui/codeeditor.h
index 3ed01d6b0..479125c0a 100644
--- a/gui/codeeditor.h
+++ b/gui/codeeditor.h
@@ -84,18 +84,15 @@ public:
*/
void setError(int errorLine, const QStringList &symbols);
- void setFileName(const QString &fileName)
- {
+ void setFileName(const QString &fileName) {
mFileName = fileName;
}
- QString getFileName() const
- {
+ QString getFileName() const {
return mFileName;
}
- void clear()
- {
+ void clear() {
mFileName.clear();
setPlainText(QString());
}
diff --git a/gui/resultsview.cpp b/gui/resultsview.cpp
index 35a5b5d96..b3beb24b7 100644
--- a/gui/resultsview.cpp
+++ b/gui/resultsview.cpp
@@ -429,8 +429,7 @@ void ResultsView::updateDetails(const QModelIndex &index)
if (data.contains("symbolNames"))
symbols = data["symbolNames"].toString().split("\n");
- if (filepath == mUI.mCode->getFileName())
- {
+ if (filepath == mUI.mCode->getFileName()) {
mUI.mCode->setError(lineNumber, symbols);
return;
}
From 41a846d8a714b50410dbca5e03d690e5540cc274 Mon Sep 17 00:00:00 2001
From: "Richard A. Smith"
Date: Thu, 16 Jul 2020 16:29:17 -0300
Subject: [PATCH 094/116] misra.py: Squelch duplicate violation messages
When checking multiple files if the same violation is encountered from
an included file then the violation is both displayed and counted in the
error summary.
Track each violation by location and error number and if the violation
has been previously encountered then do not report it again.
---
addons/misra.py | 16 ++++++++++++----
1 file changed, 12 insertions(+), 4 deletions(-)
diff --git a/addons/misra.py b/addons/misra.py
index 5763ce668..6e8b1602f 100755
--- a/addons/misra.py
+++ b/addons/misra.py
@@ -1059,6 +1059,8 @@ class MisraChecker:
self.severity = None
+ self.existing_violations = set()
+
def __repr__(self):
attrs = ["settings", "verify_expected", "verify_actual", "violations",
"ruleTexts", "suppressedRules", "dumpfileSuppressions",
@@ -2726,11 +2728,17 @@ class MisraChecker:
if self.severity:
cppcheck_severity = self.severity
- cppcheckdata.reportError(location, cppcheck_severity, errmsg, 'misra', errorId, misra_severity)
+ this_violation = '{}-{}-{}-{}'.format(location.file, location.linenr, location.column, ruleNum)
- if misra_severity not in self.violations:
- self.violations[misra_severity] = []
- self.violations[misra_severity].append('misra-' + errorId)
+ # If this is new violation then record it and show it. If not then
+ # skip it since it has already been displayed.
+ if not this_violation in self.existing_violations:
+ self.existing_violations.add(this_violation)
+ cppcheckdata.reportError(location, cppcheck_severity, errmsg, 'misra', errorId, misra_severity)
+
+ if misra_severity not in self.violations:
+ self.violations[misra_severity] = []
+ self.violations[misra_severity].append('misra-' + errorId)
def loadRuleTexts(self, filename):
num1 = 0
From fe0081496c95526ec9491bb043ed7a81e8f6953e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 16:27:56 +0200
Subject: [PATCH 095/116] Bug hunting; Avoid bailout uninit FP, arrays
---
lib/bughuntingchecks.cpp | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index 82c7bdde9..eb38858e1 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -296,6 +296,10 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (var && Token::Match(var->nameToken(), "%varid% ;| %varid%| =", tok->varId()))
return;
+ // Arrays are allocated on the stack
+ if (var && Token::Match(tok, "%var% [") && var->isArray())
+ return;
+
if (tok->variable() && isVariableAssigned(tok->variable(), tok))
return;
}
From 4a76dbb632320c1c387c7327a7e06613622eedf3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 16:54:44 +0200
Subject: [PATCH 096/116] Bug hunting; Avoid bailout uninit FP, stream object
---
lib/bughuntingchecks.cpp | 4 ++++
lib/exprengine.cpp | 4 ++++
test/testbughuntingchecks.cpp | 17 +++++++++++++++++
3 files changed, 25 insertions(+)
diff --git a/lib/bughuntingchecks.cpp b/lib/bughuntingchecks.cpp
index eb38858e1..afb55c5f7 100644
--- a/lib/bughuntingchecks.cpp
+++ b/lib/bughuntingchecks.cpp
@@ -269,6 +269,10 @@ static void uninit(const Token *tok, const ExprEngine::Value &value, ExprEngine:
if (Token::Match(tok, "%var% .") && tok->next()->originalName() != "->")
return;
+ // Assume that stream object is initialized
+ if (Token::Match(tok->previous(), "[;{}] %var% <<|>>") && !tok->next()->astParent())
+ return;
+
// Containers are not uninitialized
std::vector tokens{tok, tok->astOperand1(), tok->astOperand2()};
if (Token::Match(tok->previous(), ". %name%"))
diff --git a/lib/exprengine.cpp b/lib/exprengine.cpp
index f0ad91118..59fc71ffa 100644
--- a/lib/exprengine.cpp
+++ b/lib/exprengine.cpp
@@ -2241,6 +2241,10 @@ static std::string execute(const Token *start, const Token *end, Data &data)
if (Token::Match(tok, "[;{}]"))
data.trackProgramState(tok);
+ if (Token::simpleMatch(tok, "__CPPCHECK_BAILOUT__ ;"))
+ // This is intended for testing
+ throw ExprEngineException(tok, "__CPPCHECK_BAILOUT__");
+
if (Token::simpleMatch(tok, "while (") && (tok->linkAt(1), ") ;") && tok->next()->astOperand1()->hasKnownIntValue() && tok->next()->astOperand1()->getKnownIntValue() == 0) {
tok = tok->tokAt(4);
continue;
diff --git a/test/testbughuntingchecks.cpp b/test/testbughuntingchecks.cpp
index 392991b31..0e2d7ccc1 100644
--- a/test/testbughuntingchecks.cpp
+++ b/test/testbughuntingchecks.cpp
@@ -40,6 +40,7 @@ private:
TEST_CASE(uninit_function_par);
TEST_CASE(uninit_malloc);
TEST_CASE(uninit_struct);
+ TEST_CASE(uninit_bailout);
TEST_CASE(ctu);
#endif
}
@@ -110,6 +111,22 @@ private:
ASSERT_EQUALS("", errout.str());
}
+ void uninit_bailout() {
+ check("void foo() {\n"
+ " __CPPCHECK_BAILOUT__;\n"
+ " int values[5];\n"
+ " values[i] = 123;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+
+ check("void foo() {\n"
+ " __CPPCHECK_BAILOUT__;\n"
+ " std::ostringstream comm;\n"
+ " comm << 123;\n"
+ "}");
+ ASSERT_EQUALS("", errout.str());
+ }
+
void ctu() {
check("void init(int &x) {\n"
" x = 1;\n"
From 0a84a1fad7186e5a850ee9509ea93bc6261737ef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Sun, 19 Jul 2020 21:40:17 +0200
Subject: [PATCH 097/116] GUI: Add help files that replace the gui-manual.md
---
gui/help/investigating-warnings.html | 22 +++
gui/help/preferences.html | 74 ++++++++
gui/help/projectfiledialog.html | 181 ++++++++++++++++++
gui/help/standalone-analysis.html | 17 ++
gui/help/tagging.html | 22 +++
man/gui-manual.md | 270 ---------------------------
6 files changed, 316 insertions(+), 270 deletions(-)
create mode 100644 gui/help/investigating-warnings.html
create mode 100644 gui/help/preferences.html
create mode 100644 gui/help/projectfiledialog.html
create mode 100644 gui/help/standalone-analysis.html
create mode 100644 gui/help/tagging.html
delete mode 100644 man/gui-manual.md
diff --git a/gui/help/investigating-warnings.html b/gui/help/investigating-warnings.html
new file mode 100644
index 000000000..5eec66bd0
--- /dev/null
+++ b/gui/help/investigating-warnings.html
@@ -0,0 +1,22 @@
+
+
+Investigating warnings
+
+
+
+Investigating warnings
+
+When you have run the analysis it is time to look at the results.
+
+If you click on a warning then the corresponding code will be shown in the
+"Warning details" at the bottom.
+
+You can right click warnings to get options. The difference of
+"hiding" a warning and "suppressing" a warning is that
+the suppression is permanent and hiding the warning is only temporary. When
+suppressing warning(s), that is saved in the project file.
+
+
+
+
+
diff --git a/gui/help/preferences.html b/gui/help/preferences.html
new file mode 100644
index 000000000..31cce6593
--- /dev/null
+++ b/gui/help/preferences.html
@@ -0,0 +1,74 @@
+
+
+Preferences
+
+
+
+Preferences
+
+Number of threads
Number of threads to use in analysis. Each
+thread checks its own source file.
+
+Force checking of all #ifdef configurations
Cppcheck try to check
+all code and will therefore guess different preprocessor configurations. The
+maximum number of configurations that is checked is 14 by default.
+
+Show full path of files
Show the full paths in the results.
+
+Show "No errors found" message when no errors found
+If you want to get a message box about this.
+
+Display error id column "Id"
Show error id in results
+
+Enable inline suppressions
You can suppress warnings with comments.
+See the Cppcheck manual (http://cppcheck.sf.net/manual.pdf) for more information
+about inline suppressions.
+
+Check for inconclusive errors also
When full analysis of the code
+can not determine if there should be a warning or not, it is inconclusive.
+Normally Cppcheck does not warn then.
+
+Show statistics on check completion
Show statistics in a window
+when analysis finish.
+
+Show internal warnings in log
Internal warnings (for debugging) is
+shown in the Analysis log.
+
+Applications
Configure external editor to open from context menu
+when you right click on a warning.
+
+Save all errors when creating report
If hidden warnings should be
+saved or not.
+
+Save full path to files in report
If you use Root path the
+warnings on the screen will not have the full path.
+
+Language
Configure language to use for GUI.
+
+Python binary
To be able to execute addons, Cppcheck needs to know
+where python is. Unless you configure something, Cppcheck will try to execute
+python in your PATH.
+
+Misra rule texts
Only needed if you want to use the Misra addon.
+Cppcheck is not legally allowed to distribute the Misra rule texts and these
+must be provided by users. The Misra rule texts are proprietary. An example
+rule text file:
+
Appendix A Summary of guidelines
+Rule 1.1
+Text of rule 1.1
+Rule 1.2
+Text of rule 1.2
+
+
+Clang path
The path to clang binary. If no path is provided
+then system PATH is used.
+
+Visual studio headers
If you want to use the Visual Studio headers
+in the analysis you can provide the path(s) here. Hint: Open a visual studio
+command prompt and type SET INCLUDE. Then copy/paste the paths.
+
+Code editor style
The visual theme to use for the code editor that
+is used when you investigate results.
+
+
+
diff --git a/gui/help/projectfiledialog.html b/gui/help/projectfiledialog.html
new file mode 100644
index 000000000..5e4ef7bc5
--- /dev/null
+++ b/gui/help/projectfiledialog.html
@@ -0,0 +1,181 @@
+
+
+Project File Dialog
+
+
+
+Project File Dialog
+
+The Project file dialog contains 4 tabs:
+
+- Paths and defines; paths to check and basic preprocessor settings.
+
- Types and Functions; configuration of platform and 3rd party libraries
+
- Analysis; analysis options
+
- Warning options; formatting warnings, suppressing warnings, etc
+
- Addons; extra analysis with addons
+
+
+Paths and defines
+
+It is recommended to import a project file.
+
+ Import project
+
+Project to import. Cppcheck will get:
+
+- What files to check
+
- Preprocessor defines
+
- Preprocessor include paths
+
- Language standard if set
+
+
+Paths (If you do not import project)
+
+What paths to check.
+
+Defines (If you do not import project)
+
+Cppcheck automatically checks the code with different preprocessor
+configurations.
+
+#ifdef A
+code1
+#endif
+#ifdef B
+code2
+#endif
+
+Cppcheck will automatically perform analysis both when A is defined and B is
+defined. So any bugs in both code1 and code2 will be detected.
+
+If you want to configure that A will always be defined in Cppcheck analysis
+you can do that here.
+
+Defines are separated by semicolon. So you can for instance write:
+
+A;B=3;C
+
+Undefines (If you do not import project)
+
+Cppcheck automatically checks the code with different preprocessor
+configurations.
+
+#ifdef A
+code1
+#endif
+#ifdef B
+code2
+#endif
+
+Cppcheck will automatically perform analysis both when A is defined and B is
+defined. So any bugs in both code1 and code2 will be detected.
+
+If you want to configure that A is never defined in Cppcheck analysis you
+can do that here.
+
+Undefines are separated by semicolon. So you can for instance write:
+
+A;C
+
+Include paths (If you do not import project)
+
+Specify include paths.
+
+Types and Functions
+
+Cppcheck uses the Platform setting to determine size of
+short/int/long/pointer/etc.
+
+Check the libraries that you use in the Libraries listbox.
+
+Analysis
+
+Cppcheck build dir
+
+This is a work-folder that Cppcheck uses. Each Cppcheck project should have
+a separate build dir. It is used for:
+
+- whole program analysis
+
- debug output
+
- faster analysis (if a source file has changed check it, if source file is
+ not changed then reuse old results)
+
- statistics
+
+
+Parser
+
+It is in general recommended to use Cppcheck parser. However you can choose
+to use Clang parser; Clang will be executed with a command line flag that tells
+it to dump its AST and Cppcheck will read that AST and convert it into a
+corresponding Cppcheck AST and use that.
+
+Analysis
+
+Configure what kind of analysis you want.
+
+The Normal analysis is recommended for most use cases. Especially if
+you use Cppcheck in CI.
+
+The Bug hunting can be used if you really want to find a bug in your
+code and can invest time looking at bad results and providing extra
+configuration.
+
+Limit analysis
+
+You can turn off checking of headers. That could be interesting if Cppcheck
+is very slow. But normally, you should check the code in headers.
+
+It is possible to check the code in unused templates. However the Cppcheck
+AST will be incomplete/wrong. The recommendation is that you do not check
+unused templates to avoid wrong warnings. The templates will be checked
+properly when you do use them.
+
+Max CTU depth: How deep should the whole program analysis be. The risk with
+a "too high" value is that Cppcheck will be slow.
+
+Max recursion in template instantiation: Max recursion when Cppcheck
+instantiates templates. The risk with a "too high" value is that
+Cppcheck will be slow and can require much memory.
+
+
+Warning options
+
+Root path
+
+The root path for warnings. Cppcheck will strip away this part of the path
+from warnings. For instance if there is a warning in
+
../myproject/foo/bar/file.cpp
and the root path is
+../myproject/foo
then the path for the warning will be
+bar/file.cpp
.
+
+Warning Tags
+
+Tags allow you to manually categorize warnings.
+
+Exclude source files
+
+Excluded source files will not be analyzed by Cppcheck.
+
+Suppressions
+
+List of suppressions. These warnings will not be shown.
+
+Addons
+
+Y2038
32-bit timers that count number of seconds since 1970 will
+overflow in year 2038. Check that the code does not use such timers.
+
+Thread safety
Check that the code is thread safe
+
+Cert
Ensure that the Cert coding standard is followed
+
+Misra
Ensure that the Misra coding standard is followed. Please
+note you need to have a textfile with the misra rule texts to get proper
+warning messages. Cppcheck is not legally allowed to distribute the misra
+rule texts.
+
+Clang-tidy
Run Clang-tidy
+
+
+
+
diff --git a/gui/help/standalone-analysis.html b/gui/help/standalone-analysis.html
new file mode 100644
index 000000000..ad7fae5fe
--- /dev/null
+++ b/gui/help/standalone-analysis.html
@@ -0,0 +1,17 @@
+
+
+
+Standalone analysis
+
+
+
+Standalone analysis
+
+It is possible to quickly analyze files. Open the Analyze menu and click on
+either Files... or Directory....
+
+It is recommended that you create a project for analysis. A properly configured
+project will give you better analysis.
+
+
+
diff --git a/gui/help/tagging.html b/gui/help/tagging.html
new file mode 100644
index 000000000..7ac4e7ee8
--- /dev/null
+++ b/gui/help/tagging.html
@@ -0,0 +1,22 @@
+
+
+Tagging warnings
+
+
+
+Tagging warnings
+
+You can manually categorize warnings.
+
+You choose the names of the categories yourself in the project file
+dialog.
+
+If tag names are configured, then you can tag the warnings by
+right-clicking on them and selecting the proper tag in the
+context menu.
+
+Tags are saved in the project file and will be permanent.
+
+
+
+
diff --git a/man/gui-manual.md b/man/gui-manual.md
deleted file mode 100644
index a94b0c664..000000000
--- a/man/gui-manual.md
+++ /dev/null
@@ -1,270 +0,0 @@
----
-title: Cppcheck GUI manual
-subtitle: Version 2.1.99
-author: Cppcheck team
-lang: en
-documentclass: report
----
-
-
-# Standalone analysis
-
-It is possible to quickly analyze files. Open the `Analyze` menu and click on
-either `Files...` or `Directory...`.
-
-It is recommended that you create a project for analysis. A properly configured
-project will give you better analysis.
-
-# Project
-
-## Creating project
-
-Open the `File` menu and click on `New project...`.
-
-## Project options
-
-The `Project file` dialog contains 4 tabs:
- - Paths and defines; paths to check and basic preprocessor settings.
- - Types and Functions; configuration of platform and 3rd party libraries
- - Analysis; analysis options
- - Warning options; formatting warnings, suppressing warnings, etc
- - Addons; extra analysis with addons
-
-### Paths and defines
-
-It is recommended to import a project file.
-
-#### Import project
-
-Project to import. Cppcheck will get:
- * what files to check
- * preprocessor defines
- * preprocessor include paths
- * language standard if set
-
-#### Paths (If you do not import project)
-
-What paths to check.
-
-#### Defines (If you do not import project)
-
-Cppcheck automatically checks the code with different preprocessor configurations.
-
- #ifdef A
- code1
- #endif
- #ifdef B
- code2
- #endif
-
-Cppcheck will automatically perform analysis both when A is defined and B is
-defined. So any bugs in both code1 and code2 will be detected.
-
-If you want to configure that A will always be defined in Cppcheck analysis you
-can do that here.
-
-Defines are separated by semicolon. So you can for instance write:
-
- A;B=3;C
-
-#### Undefines (If you do not import project)
-
-
-Cppcheck automatically checks the code with different preprocessor configurations.
-
- #ifdef A
- code1
- #endif
- #ifdef B
- code2
- #endif
-
-Cppcheck will automatically perform analysis both when A is defined and B is
-defined. So any bugs in both code1 and code2 will be detected.
-
-If you want to configure that A is never defined in Cppcheck analysis you can
-do that here.
-
-Undefines are separated by semicolon. So you can for instance write:
-
- A;C
-
-#### Include paths (If you do not import project)
-
-Specify include paths.
-
-### Types and Functions
-
-Cppcheck uses `Platform` setting to determine size of short/int/long/pointer/etc.
-
-Check the libraries that you use in the `Libraries` listbox.
-
-### Analysis
-
-#### Cppcheck build dir
-
-This is a work-folder that Cppcheck uses. Each Cppcheck project should have a
-separate build dir. It is used for:
- * whole program analysis
- * debug output
- * faster analysis (if a source file has changed check it, if source file is
- not changed then reuse old results)
- * statistics
-
-#### Parser
-
-It is in general recommended to use Cppcheck parser. However you can choose to
-use Clang parser; Clang will be executed with a command line flag that tells it
-to dump its AST and Cppcheck will read that AST and convert it into a
-corresponding Cppcheck AST and use that.
-
-#### Analysis
-
-Configure what kind of analysis you want.
-
-The `Normal analysis` is recommended for most use cases. Especially if you use
-Cppcheck in CI.
-
-The `Bug hunting` can be used if you really want to find a bug in your code
-and can invest time looking at bad results and providing extra configuration.
-
-#### Limit analysis
-
-You can turn off checking of headers. That could be interesting if Cppcheck is
-very slow. But normally, you should check the code in headers.
-
-It is possible to check the code in unused templates. However the Cppcheck AST
-will be incomplete/wrong. The recommendation is that you do not check unused
-templates to avoid wrong warnings. The templates will be checked properly when
-you do use them.
-
-Max CTU depth: How deep should the whole program analysis be. The risk with a
-"too high" value is that Cppcheck will be slow.
-
-Max recursion in template instantiation: Max recursion when Cppcheck
-instantiates templates. The risk with a "too high" value is that Cppcheck will
-be slow and can require much memory.
-
-
-### Warning options
-
-#### Root path
-
-The root path for warnings. Cppcheck will strip away this part of the path
-from warnings. For instance if there is a warning in
-`../myproject/foo/bar/file.cpp` and the root path is `../myproject/foo` then
-the path for the warning will be `bar/file.cpp`.
-
-#### Warning Tags
-
-Tags allow you to manually categorize warnings.
-
-#### Exclude source files
-
-Excluded source files will not be analyzed by Cppcheck
-
-#### Suppressions
-
-List of suppressions. These warnings will not be shown.
-
-### Addons
-
-Y2038 - 32-bit timers that count number of seconds since 1970 will overflow in
-year 2038. Check that the code does not use such timers.
-
-Thread safety - Check that the code is thread safe
-
-Cert - Ensure that the Cert coding standard is followed
-
-Misra - Ensure that the Misra coding standard is followed. Please note you
-need to have a textfile with the misra rule texts to get proper warning
-messages. Cppcheck is not legally allowed to distribute the misra rule texts.
-
-Clang-tidy - Run Clang-tidy
-
-
-# Preferences
-
-`Number of threads`: Number of threads to use in analysis. Each thread checks
-its own source file.
-
-`Force checking of all #ifdef configurations`: Cppcheck try to check all code
-and will therefore guess different preprocessor configurations. The maximum
-number of configurations that is checked is 14 by default.
-
-`Show full path of files`: Show the full paths in the results.
-
-`Show "No errors found" message when no errors found`: If you want to get a
-message box about this.
-
-`Display error id column "Id"`: Show error id in results
-
-`Enable inline suppressions`: You can suppress warnings with comments. See the
-Cppcheck manual (http://cppcheck.sf.net/manual.pdf) for more information about
-those.
-
-`Check for inconclusive errors also`: When full analysis of the code can not
-determine if there should be a warning or not, it is inconclusive. Normally
-Cppcheck does not warn then.
-
-`Show statistics on check completion`: Show statistics in a window when
-analysis finish.
-
-`Show internal warnings in log`: Internal warnings (for debugging) is shown
-in the `Analysis log`.
-
-`Applications`: Configure external editor to open from context menu when you
-right click on a warning.
-
-`Save all errors when creating report`: If hidden warnings should be saved or
-not.
-
-`Save full path to files in report`: If you use `Root path` the warnings on the
-screen will not have the full path.
-
-`Language`: Configure language to use for GUI.
-
-`Python binary`: To be able to execute addons, Cppcheck needs to know where
-python is. Unless you configure something, Cppcheck will try to execute python
-in your PATH.
-
-`Misra rule texts`: Only needed if you want to use the Misra addon. Cppcheck is
-not legally allowed to distribute the Misra rule texts and these must be
-provided by users. The Misra rule texts are proprietary. An example rule text
-file can be found here: https://github.com/danmar/cppcheck/blob/main/addons/test/misra/misra2012_rules_dummy_ascii.txt
-
-`Clang path`: The path to `clang` binary. If no path is provided then system
-PATH is used.
-
-`Visual studio headers`: If you want to use the Visual Studio headers in the
-analysis you can provide the path(s) here. Hint: Open a visual studio command
-prompt and type `SET INCLUDE`. Then copy/paste the paths.
-
-`Code editor style`: The visual theme to use for the code editor that is used
-when you investigate results.
-
-
-
-# Looking at results
-
-When you have run the analysis it is time to look at the results.
-
-If you click on a warning then the corresponding code will be shown in the
-"Warning details" at the bottom.
-
-You can right click warnings to get options. The difference of "hiding" a
-warning and "suppressing" a warning is that the suppression is permanent and
-hiding the warning is only temporary.
-
-
-# Tagging warnings
-
-You can manually categorize warnings.
-
-You choose the names of the categories yourself in the project file dialog.
-
-If tag names are configured then when you look at results you can right click
-on a warning and tag it.
-
-
-
From 2ace2b006a533e1ad75b4e491296101e27d7c2ce Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Thu, 9 Jul 2020 22:40:52 +0200
Subject: [PATCH 098/116] Refactor: Use visitAstNodes in checkleakautovar
---
lib/checkleakautovar.cpp | 23 +++++++++--------------
1 file changed, 9 insertions(+), 14 deletions(-)
diff --git a/lib/checkleakautovar.cpp b/lib/checkleakautovar.cpp
index 0991bfdf0..a6c681814 100644
--- a/lib/checkleakautovar.cpp
+++ b/lib/checkleakautovar.cpp
@@ -463,27 +463,21 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
VarInfo varInfo1(*varInfo); // VarInfo for if code
VarInfo varInfo2(*varInfo); // VarInfo for else code
- // Recursively scan variable comparisons in condition
- std::stack tokens;
// Skip expressions before commas
const Token * astOperand2AfterCommas = tok->next()->astOperand2();
while (Token::simpleMatch(astOperand2AfterCommas, ","))
astOperand2AfterCommas = astOperand2AfterCommas->astOperand2();
- tokens.push(astOperand2AfterCommas);
- while (!tokens.empty()) {
- const Token *tok3 = tokens.top();
- tokens.pop();
+
+ // Recursively scan variable comparisons in condition
+ visitAstNodes(astOperand2AfterCommas, [&](const Token *tok3) {
if (!tok3)
- continue;
+ return ChildrenToVisit::none;
if (tok3->str() == "&&" || tok3->str() == "||") {
// FIXME: handle && ! || better
- tokens.push(tok3->astOperand1());
- tokens.push(tok3->astOperand2());
- continue;
+ return ChildrenToVisit::op1_and_op2;
}
if (tok3->str() == "(" && Token::Match(tok3->astOperand1(), "UNLIKELY|LIKELY")) {
- tokens.push(tok3->astOperand2());
- continue;
+ return ChildrenToVisit::op2;
} else if (tok3->str() == "(" && Token::Match(tok3->previous(), "%name%")) {
const std::vector params = getArguments(tok3->previous());
for (const Token *par : params) {
@@ -500,7 +494,7 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
varInfo2.erase(vartok->varId());
}
}
- continue;
+ return ChildrenToVisit::none;
}
const Token *vartok = nullptr;
@@ -517,7 +511,8 @@ void CheckLeakAutoVar::checkScope(const Token * const startToken,
} else if (astIsVariableComparison(tok3, "==", "-1", &vartok)) {
varInfo1.erase(vartok->varId());
}
- }
+ return ChildrenToVisit::none;
+ });
checkScope(closingParenthesis->next(), &varInfo1, notzero, recursiveCount);
closingParenthesis = closingParenthesis->linkAt(1);
From 82fe6193fa6a36e5411208550b42cd9d278f7a25 Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Thu, 9 Jul 2020 23:08:04 +0200
Subject: [PATCH 099/116] Refactor: Use visitAstNodes in checkstring
---
lib/checkstring.cpp | 19 +++++++------------
1 file changed, 7 insertions(+), 12 deletions(-)
diff --git a/lib/checkstring.cpp b/lib/checkstring.cpp
index a87d5cd0c..576be7a1b 100644
--- a/lib/checkstring.cpp
+++ b/lib/checkstring.cpp
@@ -355,37 +355,32 @@ void CheckString::overlappingStrcmp()
continue;
std::list equals0;
std::list notEquals0;
- std::stack tokens;
- tokens.push(tok);
- while (!tokens.empty()) {
- const Token * const t = tokens.top();
- tokens.pop();
+ visitAstNodes(tok, [&](const Token * t) {
if (!t)
- continue;
+ return ChildrenToVisit::none;
if (t->str() == "||") {
- tokens.push(t->astOperand1());
- tokens.push(t->astOperand2());
- continue;
+ return ChildrenToVisit::op1_and_op2;
}
if (t->str() == "==") {
if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0"))
equals0.push_back(t->astOperand1());
else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0"))
equals0.push_back(t->astOperand2());
- continue;
+ return ChildrenToVisit::none;
}
if (t->str() == "!=") {
if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0"))
notEquals0.push_back(t->astOperand1());
else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0"))
notEquals0.push_back(t->astOperand2());
- continue;
+ return ChildrenToVisit::none;
}
if (t->str() == "!" && Token::simpleMatch(t->astOperand1(), "("))
equals0.push_back(t->astOperand1());
else if (t->str() == "(")
notEquals0.push_back(t);
- }
+ return ChildrenToVisit::none;
+ });
for (const Token *eq0 : equals0) {
for (const Token * ne0 : notEquals0) {
From 9ced26a7a112bf1d50adb6fcd41db5a7ec77640c Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Fri, 10 Jul 2020 00:50:57 +0200
Subject: [PATCH 100/116] Refactor: Use visitAstNodes in checkcondition
---
lib/checkcondition.cpp | 46 ++++++++++++++++--------------------------
1 file changed, 17 insertions(+), 29 deletions(-)
diff --git a/lib/checkcondition.cpp b/lib/checkcondition.cpp
index 22f166646..97dad288e 100644
--- a/lib/checkcondition.cpp
+++ b/lib/checkcondition.cpp
@@ -688,16 +688,11 @@ void CheckCondition::multiCondition2()
ErrorPath errorPath;
if (type == MULTICONDITIONTYPE::INNER) {
- std::stack tokens1;
- tokens1.push(cond1);
- while (!tokens1.empty()) {
- const Token *firstCondition = tokens1.top();
- tokens1.pop();
+ visitAstNodes(cond1, [&](const Token* firstCondition) {
if (!firstCondition)
- continue;
+ return ChildrenToVisit::none;
if (firstCondition->str() == "&&") {
- tokens1.push(firstCondition->astOperand1());
- tokens1.push(firstCondition->astOperand2());
+ return ChildrenToVisit::op1_and_op2;
} else if (!firstCondition->hasKnownIntValue()) {
if (!isReturnVar && isOppositeCond(false, mTokenizer->isCPP(), firstCondition, cond2, mSettings->library, true, true, &errorPath)) {
if (!isAliased(vars))
@@ -706,7 +701,8 @@ void CheckCondition::multiCondition2()
identicalInnerConditionError(firstCondition, cond2, errorPath);
}
}
- }
+ return ChildrenToVisit::none;
+ });
} else {
visitAstNodes(cond2, [&](const Token *secondCondition) {
if (secondCondition->str() == "||" || secondCondition->str() == "&&")
@@ -1436,20 +1432,15 @@ void CheckCondition::alwaysTrueFalse()
// Don't warn when there are expanded macros..
bool isExpandedMacro = false;
- std::stack tokens;
- tokens.push(tok);
- while (!tokens.empty()) {
- const Token *tok2 = tokens.top();
- tokens.pop();
+ visitAstNodes(tok, [&](const Token * tok2) {
if (!tok2)
- continue;
- tokens.push(tok2->astOperand1());
- tokens.push(tok2->astOperand2());
+ return ChildrenToVisit::none;
if (tok2->isExpandedMacro()) {
isExpandedMacro = true;
- break;
+ return ChildrenToVisit::done;
}
- }
+ return ChildrenToVisit::op1_and_op2;
+ });
if (isExpandedMacro)
continue;
for (const Token *parent = tok; parent; parent = parent->astParent()) {
@@ -1464,24 +1455,21 @@ void CheckCondition::alwaysTrueFalse()
// don't warn when condition checks sizeof result
bool hasSizeof = false;
bool hasNonNumber = false;
- tokens.push(tok);
- while (!tokens.empty()) {
- const Token *tok2 = tokens.top();
- tokens.pop();
+ visitAstNodes(tok, [&](const Token * tok2) {
if (!tok2)
- continue;
+ return ChildrenToVisit::none;
if (tok2->isNumber())
- continue;
+ return ChildrenToVisit::none;
if (Token::simpleMatch(tok2->previous(), "sizeof (")) {
hasSizeof = true;
- continue;
+ return ChildrenToVisit::none;
}
if (tok2->isComparisonOp() || tok2->isArithmeticalOp()) {
- tokens.push(tok2->astOperand1());
- tokens.push(tok2->astOperand2());
+ return ChildrenToVisit::op1_and_op2;
} else
hasNonNumber = true;
- }
+ return ChildrenToVisit::none;
+ });
if (!hasNonNumber && hasSizeof)
continue;
From ed36856451b0a77ea0d5c0a66f4f5ab3377238db Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Sat, 11 Jul 2020 00:02:28 +0200
Subject: [PATCH 101/116] Refactor: Use visitAstNodes in checkuninitvar
---
lib/checkuninitvar.cpp | 17 ++++++-----------
1 file changed, 6 insertions(+), 11 deletions(-)
diff --git a/lib/checkuninitvar.cpp b/lib/checkuninitvar.cpp
index e46f94304..c1b9d6454 100644
--- a/lib/checkuninitvar.cpp
+++ b/lib/checkuninitvar.cpp
@@ -881,22 +881,17 @@ bool CheckUninitVar::checkLoopBody(const Token *tok, const Variable& var, const
usetok = tok;
else if (tok->strAt(1) == "=") {
bool varIsUsedInRhs = false;
- std::stack tokens;
- tokens.push(tok->next()->astOperand2());
- while (!tokens.empty()) {
- const Token *t = tokens.top();
- tokens.pop();
+ visitAstNodes(tok->next()->astOperand2(), [&](const Token * t) {
if (!t)
- continue;
+ return ChildrenToVisit::none;
if (t->varId() == var.declarationId()) {
varIsUsedInRhs = true;
- break;
+ return ChildrenToVisit::done;
}
if (Token::simpleMatch(t->previous(),"sizeof ("))
- continue;
- tokens.push(t->astOperand1());
- tokens.push(t->astOperand2());
- }
+ return ChildrenToVisit::none;
+ return ChildrenToVisit::op1_and_op2;
+ });
if (!varIsUsedInRhs)
return true;
} else {
From 7973fd843c46c3b2a7e1ff7fb4955facb727e46d Mon Sep 17 00:00:00 2001
From: Rikard Falkeborn
Date: Mon, 20 Jul 2020 11:15:18 +0200
Subject: [PATCH 102/116] Refactor: Simplify checkSignConversion
The loop only checks astoperand1 and astoperand2. Simplify the condition
to loop over these instead of using a stack. Also, add a testcase for
when astoperand2 is negative.
---
lib/checktype.cpp | 8 ++------
test/testtype.cpp | 3 +++
2 files changed, 5 insertions(+), 6 deletions(-)
diff --git a/lib/checktype.cpp b/lib/checktype.cpp
index 6ac2709b6..e46a8142d 100644
--- a/lib/checktype.cpp
+++ b/lib/checktype.cpp
@@ -239,12 +239,8 @@ void CheckType::checkSignConversion()
continue;
// Check if an operand can be negative..
- std::stack tokens;
- tokens.push(tok->astOperand1());
- tokens.push(tok->astOperand2());
- while (!tokens.empty()) {
- const Token *tok1 = tokens.top();
- tokens.pop();
+ const Token * astOperands[] = { tok->astOperand1(), tok->astOperand2() };
+ for (const Token * tok1 : astOperands) {
if (!tok1)
continue;
const ValueFlow::Value *negativeValue = tok1->getValueLE(-1,mSettings);
diff --git a/test/testtype.cpp b/test/testtype.cpp
index e5ea6f2bd..4a121a09a 100644
--- a/test/testtype.cpp
+++ b/test/testtype.cpp
@@ -252,6 +252,9 @@ private:
check("x = -4 * (unsigned)y;");
ASSERT_EQUALS("[test.cpp:1]: (warning) Expression '-4' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout.str());
+ check("x = (unsigned)y * -4;");
+ ASSERT_EQUALS("[test.cpp:1]: (warning) Expression '-4' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.\n", errout.str());
+
check("unsigned int dostuff(int x) {\n" // x is signed
" if (x==0) {}\n"
" return (x-1)*sizeof(int);\n"
From 09241030c38e435d046e69e04ae0cd1878cc1db5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 11:59:28 +0200
Subject: [PATCH 103/116] GUI: Add online help
---
gui/gui.pro | 4 ++
gui/help/index.html | 52 ++++++++++++++++++
gui/help/online-help.qhp | 22 ++++++--
gui/helpdialog.cpp | 52 ++++++++++++++++++
gui/helpdialog.h | 36 +++++++++++++
gui/helpdialog.ui | 110 +++++++++++++++++++++++++++++++++++++++
gui/mainwindow.cpp | 12 +++--
7 files changed, 279 insertions(+), 9 deletions(-)
create mode 100644 gui/help/index.html
create mode 100644 gui/helpdialog.cpp
create mode 100644 gui/helpdialog.h
create mode 100644 gui/helpdialog.ui
diff --git a/gui/gui.pro b/gui/gui.pro
index 7052e4b90..b8d53034d 100644
--- a/gui/gui.pro
+++ b/gui/gui.pro
@@ -10,6 +10,7 @@ INCLUDEPATH += . \
../externals/z3/include
QT += widgets
QT += printsupport
+QT += help
contains(LINKCORE, [yY][eE][sS]) {
LIBS += -l../bin/cppcheck-core
@@ -61,6 +62,7 @@ FORMS = about.ui \
application.ui \
file.ui \
functioncontractdialog.ui \
+ helpdialog.ui \
mainwindow.ui \
projectfiledialog.ui \
resultsview.ui \
@@ -110,6 +112,7 @@ HEADERS += aboutdialog.h \
filelist.h \
fileviewdialog.h \
functioncontractdialog.h \
+ helpdialog.h \
mainwindow.h \
platforms.h \
printablereport.h \
@@ -150,6 +153,7 @@ SOURCES += aboutdialog.cpp \
filelist.cpp \
fileviewdialog.cpp \
functioncontractdialog.cpp \
+ helpdialog.cpp \
main.cpp \
mainwindow.cpp\
platforms.cpp \
diff --git a/gui/help/index.html b/gui/help/index.html
new file mode 100644
index 000000000..b466002dc
--- /dev/null
+++ b/gui/help/index.html
@@ -0,0 +1,52 @@
+
+
+Cppcheck GUI
+
+
+
+Cppcheck GUI
+
+With the Cppcheck GUI you can analyze your code.
+
+Quick walk through
+
+Step 1: Create a project.
+
+Create a new project.
+
+In the Paths and Defines tab, it is recommended that you import your project file at the top.
+
+In the Types and Functions tab, try to activate all 3rd party libraries you use (windows, posix, ...).
+
+In the Analysis tab, leave the default settings to start with.
+
+In the Warnings options tab, leave the default settings to start with.
+
+In the Addons tab, leave the default settings to start with.
+
+
+Step 2: Analyze code.
+
+When the project file has been created, the analysis will start automatically.
+
+While analysis is performed in the background, you can investigate the warnings.
+
+
+Step 3: Investigate warnings.
+
+In the toolbar you choose what types of warnings you want to see (error/warning/style/performance/portability/information).
+
+All warnings are shown in a list. If you select a warning in the list, then details about that warning is shown below the list.
+
+If you right click on warning(s) then you get a context menu.
+
+
+Step 4: Configuration.
+
+It is possible to improve configuration to get better analysis. The automatic assumptions are conservative and through configuration those automatic assumptions can be avoided.
+
+TODO: library, contracts
+
+
+
+
diff --git a/gui/help/online-help.qhp b/gui/help/online-help.qhp
index 16ab79981..4bbe8074d 100644
--- a/gui/help/online-help.qhp
+++ b/gui/help/online-help.qhp
@@ -4,11 +4,25 @@
doc
-
+
-
+
+
+
+
- manual.html
+ index.html
+ investigating-warnings.html
+ preferences.html
+ projectfiledialog.html
+ standalone-analysis.html
+ tagging.html
-
+
diff --git a/gui/helpdialog.cpp b/gui/helpdialog.cpp
new file mode 100644
index 000000000..920671834
--- /dev/null
+++ b/gui/helpdialog.cpp
@@ -0,0 +1,52 @@
+#include "helpdialog.h"
+#include "ui_helpdialog.h"
+
+#include
+#include
+#include
+
+void HelpBrowser::setHelpEngine(QHelpEngine *helpEngine)
+{
+ mHelpEngine = helpEngine;
+}
+
+QVariant HelpBrowser::loadResource(int type, const QUrl &name){
+ if (name.scheme() == "qthelp") {
+ QString url(name.toString());
+ while (url.indexOf("/./") > 0)
+ url.remove(url.indexOf("/./"), 2);
+ return QVariant(mHelpEngine->fileData(QUrl(url)));
+ }
+ return QTextBrowser::loadResource(type, name);
+}
+
+HelpDialog::HelpDialog(QWidget *parent) :
+ QDialog(parent),
+ mUi(new Ui::HelpDialog)
+{
+ mUi->setupUi(this);
+
+ mHelpEngine = new QHelpEngine(QApplication::applicationDirPath() + "/online-help.qhc");
+ mHelpEngine->setupData();
+
+ mUi->contents->addWidget(mHelpEngine->contentWidget());
+ mUi->index->addWidget(mHelpEngine->indexWidget());
+
+ mUi->textBrowser->setHelpEngine(mHelpEngine);
+
+ mUi->textBrowser->setSource(QUrl("qthelp://cppcheck.sourceforge.net/doc/index.html"));
+ connect(mHelpEngine->contentWidget(),
+ SIGNAL(linkActivated(QUrl)),
+ mUi->textBrowser,
+ SLOT(setSource(QUrl)));
+
+ connect(mHelpEngine->indexWidget(),
+ SIGNAL(linkActivated(QUrl, QString)),
+ mUi->textBrowser,
+ SLOT(setSource(QUrl)));
+}
+
+HelpDialog::~HelpDialog()
+{
+ delete mUi;
+}
diff --git a/gui/helpdialog.h b/gui/helpdialog.h
new file mode 100644
index 000000000..36e1e7954
--- /dev/null
+++ b/gui/helpdialog.h
@@ -0,0 +1,36 @@
+#ifndef HELPDIALOG_H
+#define HELPDIALOG_H
+
+#include
+#include
+
+namespace Ui {
+class HelpDialog;
+}
+
+class QHelpEngine;
+
+class HelpBrowser : public QTextBrowser
+{
+public:
+ HelpBrowser(QWidget* parent = 0) : QTextBrowser(parent), mHelpEngine(nullptr) {}
+ void setHelpEngine(QHelpEngine *helpEngine);
+ QVariant loadResource (int type, const QUrl& name);
+private:
+ QHelpEngine* mHelpEngine;
+};
+
+class HelpDialog : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit HelpDialog(QWidget *parent = nullptr);
+ ~HelpDialog();
+
+private:
+ Ui::HelpDialog *mUi;
+ QHelpEngine* mHelpEngine;
+};
+
+#endif // HELPDIALOG_H
diff --git a/gui/helpdialog.ui b/gui/helpdialog.ui
new file mode 100644
index 000000000..bc5ccc706
--- /dev/null
+++ b/gui/helpdialog.ui
@@ -0,0 +1,110 @@
+
+
+ HelpDialog
+
+
+
+ 0
+ 0
+ 635
+ 446
+
+
+
+ Cppcheck GUI help
+
+
+ -
+
+
+ Qt::Horizontal
+
+
+
+
+ 200
+ 16777215
+
+
+
+ 0
+
+
+
+ Contents
+
+
+
-
+
+
+
+
+
+
+ Index
+
+
+ -
+
+
+
+
+
+
+
+
+ -
+
+
+ Qt::Horizontal
+
+
+ QDialogButtonBox::Close
+
+
+
+
+
+
+
+ HelpBrowser
+ QTextBrowser
+
+
+
+
+
+
+ buttonBox
+ accepted()
+ HelpDialog
+ accept()
+
+
+ 248
+ 254
+
+
+ 157
+ 274
+
+
+
+
+ buttonBox
+ rejected()
+ HelpDialog
+ reject()
+
+
+ 316
+ 260
+
+
+ 286
+ 274
+
+
+
+
+
diff --git a/gui/mainwindow.cpp b/gui/mainwindow.cpp
index d98ea4b6e..5a1e8189f 100644
--- a/gui/mainwindow.cpp
+++ b/gui/mainwindow.cpp
@@ -34,20 +34,21 @@
#include "applicationlist.h"
#include "aboutdialog.h"
#include "common.h"
-#include "threadhandler.h"
+#include "filelist.h"
#include "fileviewdialog.h"
#include "functioncontractdialog.h"
+#include "helpdialog.h"
+#include "librarydialog.h"
#include "projectfile.h"
#include "projectfiledialog.h"
#include "report.h"
#include "scratchpad.h"
+#include "showtypes.h"
#include "statsdialog.h"
#include "settingsdialog.h"
+#include "threadhandler.h"
#include "threadresult.h"
#include "translationhandler.h"
-#include "filelist.h"
-#include "showtypes.h"
-#include "librarydialog.h"
static const QString OnlineHelpURL("http://cppcheck.net/manual.html");
static const QString compile_commands_json("compile_commands.json");
@@ -1465,7 +1466,8 @@ void MainWindow::openHelpContents()
void MainWindow::openOnlineHelp()
{
- QDesktopServices::openUrl(QUrl(OnlineHelpURL));
+ HelpDialog *helpDialog = new HelpDialog;
+ helpDialog->showMaximized();
}
void MainWindow::openProjectFile()
From 89ba12d9b38dece6396b92e94cc905672027010d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 12:04:51 +0200
Subject: [PATCH 104/116] Remove old build.bat file
---
build.bat | 72 -------------------------------------------------------
1 file changed, 72 deletions(-)
delete mode 100644 build.bat
diff --git a/build.bat b/build.bat
deleted file mode 100644
index 9c075594e..000000000
--- a/build.bat
+++ /dev/null
@@ -1,72 +0,0 @@
-@echo off
-REM A simple script to build different cppcheck targets from project root
-REM folder. This script can be run from VS prompt or Qt prompt.
-REM
-REM Usage: build [release|debug]
-REM where is any of cppcheck/gui/tests/all
-REM release or debug is the configuration
-REM all-target builds both cppcheck and gui.
-REM
-REM Run the command before build.bat to enable rules using pcre:
-REM set HAVE_RULES=yes
-REM
-REM TODO:
-REM - run tests too
-
-pushd %~dp0
-
-if "%1" == "" goto help
-
-REM Qt prompt sets QMAKESPEC
-if "%QMAKESPEC%" == "" (
-REM parse qmakespec to see if it's some msvc
- if "%QMAKESPEC:~6,4%" == "msvc" (
- set MAKE=nmake
- ) else (
- set MAKE=mingw32-make
- )
-) else (
- set MAKE=nmake
-)
-
-if "%2" == "" set TARGET=release
-if "%2" == "debug" set TARGET=debug
-if "%2" == "release" set TARGET=release
-
-if "%1" == "all" goto cppcheck
-if "%1" == "cppcheck" goto cppcheck
-if "%1" == "gui" goto gui
-if "%1" == "tests" goto tests
-goto help
-
-:cppcheck
-pushd cli
-qmake -config %TARGET% HAVE_RULES=%HAVE_RULES%
-%MAKE%
-popd
-if "%1" == "all" goto gui
-goto end
-
-:gui
-pushd gui
-qmake -config %TARGET% HAVE_RULES=%HAVE_RULES%
-%MAKE%
-lupdate -no-obsolete gui.pro
-lrelease gui.pro
-popd
-goto end
-
-:tests
-pushd test
-qmake -config %TARGET% HAVE_RULES=%HAVE_RULES%
-%MAKE%
-popd
-goto end
-
-:help
-echo Syntax: build ^ [debug^|release]
-echo where ^ is any of cppcheck/gui/tests/all
-echo debug or release define used configuration
-echo all- target builds both cppcheck and gui.
-
-:end
From 65742b9779135e7ddcf94040368ae7418df60fef Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 12:43:08 +0200
Subject: [PATCH 105/116] gui.pro: build help
---
gui/gui.pro | 7 +++++++
1 file changed, 7 insertions(+)
diff --git a/gui/gui.pro b/gui/gui.pro
index b8d53034d..6fe367f7e 100644
--- a/gui/gui.pro
+++ b/gui/gui.pro
@@ -12,6 +12,13 @@ QT += widgets
QT += printsupport
QT += help
+# Build online help
+onlinehelp.target = online-help.qhc
+#onlinehelp.depends = $$PWD/help/online-help.qhp
+onlinehelp.commands = qhelpgenerator $$PWD/help/online-help.qhp -o online-help.qch ; qhelpgenerator $$PWD/help/online-help.qhcp -o online-help.qhc
+QMAKE_EXTRA_TARGETS += onlinehelp
+PRE_TARGETDEPS += online-help.qhc
+
contains(LINKCORE, [yY][eE][sS]) {
LIBS += -l../bin/cppcheck-core
DEFINES += CPPCHECKLIB_IMPORT
From bdb7db0fd5a69e2c6636792ea429fc54ea1749b1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 19:04:47 +0200
Subject: [PATCH 106/116] Travis: Try to install qt help
---
.travis.yml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/.travis.yml b/.travis.yml
index 1552c56a5..b901ba75d 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -20,7 +20,7 @@ env:
before_install:
# install needed deps
- travis_retry sudo apt-get update -qq
- - travis_retry sudo apt-get install -qq python3-pip qt5-default qt5-qmake qtbase5-dev qtcreator libxml2-utils libpcre3 gdb unzip wx-common xmlstarlet python3-dev liblua5.3-dev libcurl3 libcairo2-dev libsigc++-2.0-dev tidy libopencv-dev libz3-dev
+ - travis_retry sudo apt-get install -qq python3-pip qt5-default qt5-qmake qtbase5-dev qtcreator qttools5-dev qttools5-dev-tools libxml2-utils libpcre3 gdb unzip wx-common xmlstarlet python3-dev liblua5.3-dev libcurl3 libcairo2-dev libsigc++-2.0-dev tidy libopencv-dev libz3-dev
# Python 2 modules
- travis_retry python2 -m pip install --user pytest==4.6.4
- travis_retry python2 -m pip install --user pylint
From 1c39bed5b0ec5b761d4d5d72812bd7cf2bd065ff Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 19:18:06 +0200
Subject: [PATCH 107/116] buildhelp.bat: remove old script
---
gui/help/buildhelp.bat | 10 ----------
1 file changed, 10 deletions(-)
delete mode 100644 gui/help/buildhelp.bat
diff --git a/gui/help/buildhelp.bat b/gui/help/buildhelp.bat
deleted file mode 100644
index b0cfbcc0d..000000000
--- a/gui/help/buildhelp.bat
+++ /dev/null
@@ -1,10 +0,0 @@
-@echo off
-
-pushd %~dp0
-
-if exist online-help.qhc del online-help.qhc
-if exist online-help.qch del online-help.qch
-
-qcollectiongenerator online-help.qhcp -o online-help.qhc
-
-popd
From d7f9dc25cd1cf3b5470bb014f2d07f8262a76153 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 19:19:37 +0200
Subject: [PATCH 108/116] Quick fix for Travis problems. Skip building gui
online-help.
---
gui/gui.pro | 9 ++++-----
1 file changed, 4 insertions(+), 5 deletions(-)
diff --git a/gui/gui.pro b/gui/gui.pro
index 6fe367f7e..3fd8663fb 100644
--- a/gui/gui.pro
+++ b/gui/gui.pro
@@ -13,11 +13,10 @@ QT += printsupport
QT += help
# Build online help
-onlinehelp.target = online-help.qhc
-#onlinehelp.depends = $$PWD/help/online-help.qhp
-onlinehelp.commands = qhelpgenerator $$PWD/help/online-help.qhp -o online-help.qch ; qhelpgenerator $$PWD/help/online-help.qhcp -o online-help.qhc
-QMAKE_EXTRA_TARGETS += onlinehelp
-PRE_TARGETDEPS += online-help.qhc
+#onlinehelp.target = online-help.qhc
+#onlinehelp.commands = qhelpgenerator $$PWD/help/online-help.qhp -o online-help.qch ; qhelpgenerator $$PWD/help/online-help.qhcp -o online-help.qhc
+#QMAKE_EXTRA_TARGETS += onlinehelp
+#PRE_TARGETDEPS += online-help.qhc
contains(LINKCORE, [yY][eE][sS]) {
LIBS += -l../bin/cppcheck-core
From 5fca5830c53da2d68d9a5ed10eb15d26345c8565 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 21:41:46 +0200
Subject: [PATCH 109/116] astyle formatting
[ci skip]
---
gui/helpdialog.cpp | 3 ++-
gui/helpdialog.h | 10 ++++------
2 files changed, 6 insertions(+), 7 deletions(-)
diff --git a/gui/helpdialog.cpp b/gui/helpdialog.cpp
index 920671834..68b306509 100644
--- a/gui/helpdialog.cpp
+++ b/gui/helpdialog.cpp
@@ -10,7 +10,8 @@ void HelpBrowser::setHelpEngine(QHelpEngine *helpEngine)
mHelpEngine = helpEngine;
}
-QVariant HelpBrowser::loadResource(int type, const QUrl &name){
+QVariant HelpBrowser::loadResource(int type, const QUrl &name)
+{
if (name.scheme() == "qthelp") {
QString url(name.toString());
while (url.indexOf("/./") > 0)
diff --git a/gui/helpdialog.h b/gui/helpdialog.h
index 36e1e7954..e37784437 100644
--- a/gui/helpdialog.h
+++ b/gui/helpdialog.h
@@ -5,23 +5,21 @@
#include
namespace Ui {
-class HelpDialog;
+ class HelpDialog;
}
class QHelpEngine;
-class HelpBrowser : public QTextBrowser
-{
+class HelpBrowser : public QTextBrowser {
public:
HelpBrowser(QWidget* parent = 0) : QTextBrowser(parent), mHelpEngine(nullptr) {}
void setHelpEngine(QHelpEngine *helpEngine);
- QVariant loadResource (int type, const QUrl& name);
+ QVariant loadResource(int type, const QUrl& name);
private:
QHelpEngine* mHelpEngine;
};
-class HelpDialog : public QDialog
-{
+class HelpDialog : public QDialog {
Q_OBJECT
public:
From a68d9e75ef4024c03a4673524033afc6d8529795 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Mon, 20 Jul 2020 22:06:07 +0200
Subject: [PATCH 110/116] GUI: In ProjectFileDialog; updated choice of vs
configurations
---
gui/projectfiledialog.cpp | 64 ++++++++++++++++++++++++---------------
gui/projectfiledialog.h | 4 +--
gui/projectfiledialog.ui | 12 +-------
3 files changed, 42 insertions(+), 38 deletions(-)
diff --git a/gui/projectfiledialog.cpp b/gui/projectfiledialog.cpp
index 70452845a..c084ac658 100644
--- a/gui/projectfiledialog.cpp
+++ b/gui/projectfiledialog.cpp
@@ -62,6 +62,8 @@ static const int numberOfBuiltinPlatforms = sizeof(builtinPlatforms) / sizeof(bu
QStringList ProjectFileDialog::getProjectConfigs(const QString &fileName)
{
+ if (!fileName.endsWith(".sln") && !fileName.endsWith(".vcxproj"))
+ return QStringList();
QStringList ret;
ImportProject importer;
Settings projSettings;
@@ -244,8 +246,12 @@ static void updateAddonCheckBox(QCheckBox *cb, const ProjectFile *projectFile, c
void ProjectFileDialog::checkAllVSConfigs()
{
- if (mUI.mChkAllVsConfigs->isChecked())
- mUI.mListVsConfigs->selectAll();
+ if (mUI.mChkAllVsConfigs->isChecked()) {
+ for (int row = 0; row < mUI.mListVsConfigs->count(); ++row) {
+ QListWidgetItem *item = mUI.mListVsConfigs->item(row);
+ item->setCheckState(Qt::Checked);
+ }
+ }
mUI.mListVsConfigs->setEnabled(!mUI.mChkAllVsConfigs->isChecked());
}
@@ -259,6 +265,14 @@ void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
setCheckPaths(projectFile->getCheckPaths());
setImportProject(projectFile->getImportProject());
mUI.mChkAllVsConfigs->setChecked(projectFile->getAnalyzeAllVsConfigs());
+ setProjectConfigurations(getProjectConfigs(mUI.mEditImportProject->text()));
+ for (int row = 0; row < mUI.mListVsConfigs->count(); ++row) {
+ QListWidgetItem *item = mUI.mListVsConfigs->item(row);
+ if (projectFile->getAnalyzeAllVsConfigs() || projectFile->getVsConfigurations().contains(item->text()))
+ item->setCheckState(Qt::Checked);
+ else
+ item->setCheckState(Qt::Unchecked);
+ }
mUI.mCheckHeaders->setChecked(projectFile->getCheckHeaders());
mUI.mCheckUnusedTemplates->setChecked(projectFile->getCheckUnusedTemplates());
mUI.mMaxCtuDepth->setValue(projectFile->getMaxCtuDepth());
@@ -342,17 +356,6 @@ void ProjectFileDialog::loadFromProjectFile(const ProjectFile *projectFile)
}
mUI.mEditTags->setText(projectFile->getTags().join(';'));
updatePathsAndDefines();
- if (mUI.mEditImportProject->text().endsWith(".sln") || mUI.mEditImportProject->text().endsWith(".vcxproj")) {
- setVsConfigurations(getProjectConfigs(mUI.mEditImportProject->text()));
- foreach (const QString &cfg, projectFile->getVsConfigurations()) {
- QList items = mUI.mListVsConfigs->findItems(cfg, Qt::MatchFlag::MatchExactly);
- items[0]->setSelected(true);
- }
- } else {
- mUI.mListVsConfigs->clear();
- mUI.mListVsConfigs->setEnabled(false);
- }
-
}
void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
@@ -361,6 +364,7 @@ void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
projectFile->setBuildDir(getBuildDir());
projectFile->setImportProject(getImportProject());
projectFile->setAnalyzeAllVsConfigs(mUI.mChkAllVsConfigs->isChecked());
+ projectFile->setVSConfigurations(getProjectConfigurations());
projectFile->setCheckHeaders(mUI.mCheckHeaders->isChecked());
projectFile->setCheckUnusedTemplates(mUI.mCheckUnusedTemplates->isChecked());
projectFile->setMaxCtuDepth(mUI.mMaxCtuDepth->value());
@@ -414,7 +418,6 @@ void ProjectFileDialog::saveToProjectFile(ProjectFile *projectFile) const
projectFile->setClangAnalyzer(mUI.mToolClangAnalyzer->isChecked());
projectFile->setClangTidy(mUI.mToolClangTidy->isChecked());
projectFile->setTags(mUI.mEditTags->text().split(";", QString::SkipEmptyParts));
- projectFile->setVSConfigurations(getVsConfigurations());
}
void ProjectFileDialog::ok()
@@ -460,6 +463,7 @@ void ProjectFileDialog::updatePathsAndDefines()
{
const QString &fileName = mUI.mEditImportProject->text();
bool importProject = !fileName.isEmpty();
+ bool hasConfigs = fileName.endsWith(".sln") || fileName.endsWith(".vcxproj");
mUI.mBtnClearImportProject->setEnabled(importProject);
mUI.mListCheckPaths->setEnabled(!importProject);
mUI.mListIncludeDirs->setEnabled(!importProject);
@@ -473,9 +477,9 @@ void ProjectFileDialog::updatePathsAndDefines()
mUI.mBtnRemoveInclude->setEnabled(!importProject);
mUI.mBtnIncludeUp->setEnabled(!importProject);
mUI.mBtnIncludeDown->setEnabled(!importProject);
- mUI.mChkAllVsConfigs->setEnabled(fileName.endsWith(".sln") || fileName.endsWith(".vcxproj"));
- mUI.mListVsConfigs->setEnabled(fileName.endsWith(".sln") || fileName.endsWith(".vcxproj"));
- if (!mUI.mListVsConfigs->isEnabled())
+ mUI.mChkAllVsConfigs->setEnabled(hasConfigs);
+ mUI.mListVsConfigs->setEnabled(hasConfigs && !mUI.mChkAllVsConfigs->isChecked());
+ if (!hasConfigs)
mUI.mListVsConfigs->clear();
}
@@ -499,24 +503,34 @@ void ProjectFileDialog::browseImportProject()
if (!fileName.isEmpty()) {
mUI.mEditImportProject->setText(dir.relativeFilePath(fileName));
updatePathsAndDefines();
- setVsConfigurations(getProjectConfigs(fileName));
- mUI.mListVsConfigs->selectAll();
+ setProjectConfigurations(getProjectConfigs(fileName));
+ for (int row = 0; row < mUI.mListVsConfigs->count(); ++row) {
+ QListWidgetItem *item = mUI.mListVsConfigs->item(row);
+ item->setCheckState(Qt::Checked);
+ }
}
}
-QStringList ProjectFileDialog::getVsConfigurations() const
+QStringList ProjectFileDialog::getProjectConfigurations() const
{
QStringList configs;
- foreach (QListWidgetItem *item, mUI.mListVsConfigs->selectedItems())
- configs << item->text();
-
+ for (int row = 0; row < mUI.mListVsConfigs->count(); ++row) {
+ QListWidgetItem *item = mUI.mListVsConfigs->item(row);
+ if (item->checkState() == Qt::Checked)
+ configs << item->text();
+ }
return configs;
}
-void ProjectFileDialog::setVsConfigurations(const QStringList &configs)
+void ProjectFileDialog::setProjectConfigurations(const QStringList &configs)
{
mUI.mListVsConfigs->clear();
- mUI.mListVsConfigs->addItems(configs);
+ mUI.mListVsConfigs->setEnabled(!configs.isEmpty() && !mUI.mChkAllVsConfigs->isChecked());
+ foreach (const QString &cfg, configs) {
+ QListWidgetItem* item = new QListWidgetItem(cfg, mUI.mListVsConfigs);
+ item->setFlags(item->flags() | Qt::ItemIsUserCheckable); // set checkable flag
+ item->setCheckState(Qt::Unchecked);
+ }
}
QString ProjectFileDialog::getImportProject() const
diff --git a/gui/projectfiledialog.h b/gui/projectfiledialog.h
index fef320a4f..d7ad84d24 100644
--- a/gui/projectfiledialog.h
+++ b/gui/projectfiledialog.h
@@ -58,8 +58,8 @@ private:
*/
QString getRootPath() const;
- QStringList getVsConfigurations() const;
- void setVsConfigurations(const QStringList &configs);
+ QStringList getProjectConfigurations() const;
+ void setProjectConfigurations(const QStringList &configs);
QString getImportProject() const;
diff --git a/gui/projectfiledialog.ui b/gui/projectfiledialog.ui
index 31884ce91..879ca9261 100644
--- a/gui/projectfiledialog.ui
+++ b/gui/projectfiledialog.ui
@@ -130,17 +130,7 @@
-
-
-
-
- 16777215
- 100
-
-
-
- QAbstractItemView::MultiSelection
-
-
+
From ae0ad171520fcfc63df2108d5bf94fdfa3cc4260 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?=
Date: Tue, 21 Jul 2020 10:30:50 +0200
Subject: [PATCH 111/116] GUI: quick walk through in online-help
---
gui/help/images/walkthrough-analysis.png | Bin 0 -> 142639 bytes
.../images/walkthrough-import-project.png | Bin 0 -> 12437 bytes
gui/help/images/walkthrough-library.png | Bin 0 -> 4743 bytes
gui/help/images/walkthrough-new-project.png | Bin 0 -> 10712 bytes
.../images/walkthrough-toolbar-severities.png | Bin 0 -> 6693 bytes
gui/help/images/walkthrough-warning-menu.png | Bin 0 -> 10339 bytes
gui/help/index.html | 39 ----------
gui/help/online-help.qhp | 8 ++
gui/help/walkthrough.html | 69 ++++++++++++++++++
gui/helpdialog.ui | 45 +-----------
10 files changed, 78 insertions(+), 83 deletions(-)
create mode 100644 gui/help/images/walkthrough-analysis.png
create mode 100644 gui/help/images/walkthrough-import-project.png
create mode 100644 gui/help/images/walkthrough-library.png
create mode 100644 gui/help/images/walkthrough-new-project.png
create mode 100644 gui/help/images/walkthrough-toolbar-severities.png
create mode 100644 gui/help/images/walkthrough-warning-menu.png
create mode 100644 gui/help/walkthrough.html
diff --git a/gui/help/images/walkthrough-analysis.png b/gui/help/images/walkthrough-analysis.png
new file mode 100644
index 0000000000000000000000000000000000000000..94efb2890d80f5d4a1ea5e1c0d127b81b5228b76
GIT binary patch
literal 142639
zcmb5V1yCJZvo=h~POuPM0)gP}?h@SH-GX~?cZc8*+}+(Bf(Lg9t{Zp#C$HW2-kkGQ
z{Z&H&n_;HcYJ2+WULms5BJi+Sun-Us@M5BZ@(>Vjgdrdx`=H+fpCELzCj;MLY(&-U
zAt2z8e}BE2T=9H_fWU(g6XaKP);>ymld7aN*FVR^*h}}-NgNLHt#2k7rY_}M#|}q~
z`Ou6v^(Q6znMp~7{z8N+(4tO~jNEIk*Eao(LD;*iO^lLUOKT1^H%B#_9XAU%>AR(M
zj;hkq((QE75HR2V?&2dRK-3PoA1aUeyE}l-z47_<;!u1*qTYXVWlkbx(y8wUrs9yi
zLdN@>E0b=Boez@e?=IPWXj#m%uL5K5WB*g)f<
zE8-&|0w%;+w~pxkUV9J$a$|q9+rM|oM_k0a+awR$&N1n46!&|Vy2*C`e#5`<uD}!7c1SleT5qG
zBO-tzH$cmcy_^Bkk4sa=CZ$hFSJn?YyKcr%fy?rg99|td@e-4q);6QT{-&X9@yK*8rWP=_{hT(29kSO{?zkFQ^-|+
zIi2i6t<$gV4H~}pHLzEPwg=#kusI^G`IVl)DtlP?UogM`f(h6vb!DR;pkrBYLI{(1w-G~pk9%0e|WpvOMcE278^#^CG(hXU3t
zR2ME{FM46Hat^BS@X50Nuvq42DYNwm<-2P(^JM)T1V6q(=Z92O#@QRj!^%Q
zmM<8_Ih6JQRirH>%TYphc}W93XI5u9WrT@5Wg3P%BWjbSYWAiJ
z)p@=B{aCischyuP;Mx4^n*_FlT6N|O1@Kj
z8t!JNSQ4r4Ke{fN21kB;TV94Vmm~SZJ%1;$bAAZOFM|H+5z0jbRklh-hqGnXHWT{$
zlX+oPxPZYd8bsYMj;8YjUqjMLxX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