Skip to content

Commit 38f6275

Browse files
committed
Merge branch 'main' of https://github.com/cppcheck-opensource/cppcheck into fix-15295
# Conflicts: # .github/workflows/scriptcheck.yml
2 parents c7d9c0f + 6a4fedd commit 38f6275

29 files changed

Lines changed: 3429 additions & 59 deletions

‎.github/workflows/scriptcheck.yml‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,8 @@ jobs:
9797
python -m pip install requests
9898
python -m pip install psutil
9999
python -m pip install setuptools
100+
python -m pip install -r tools/donate-cpu-server-requirements.txt
101+
python -m pip install httpx
100102
101103
- name: run Shellcheck
102104
if: matrix.python-latest
@@ -191,6 +193,12 @@ jobs:
191193
env:
192194
PYTHONPATH: ./tools
193195

196+
- name: test donate_cpu_server_rest
197+
run: |
198+
python -m pytest -Werror --strict-markers -vv test/tools/donate_cpu_server_rest_test.py
199+
env:
200+
PYTHONPATH: ./tools
201+
194202
# uses the node that is installed on the runner
195203
- name: test explorer report javascript
196204
run: |

‎AUTHORS‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,7 @@ Tam Do Thanh
422422
Teddy Didé
423423
Temuri Doghonadze
424424
Thomas Arnhold
425+
Tom Sobczynski
425426
Tomasz Edward Posluszny
426427
Thomas Jarosch
427428
Thomas Niederberger

‎addons/cppcheckdata.py‎

Lines changed: 130 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1626,37 +1626,6 @@ def simpleMatch(token, pattern):
16261626
'<*>': lambda tok: tok.link if tok.str == '<' and tok.link else None,
16271627
}
16281628

1629-
def match_atom(token, p):
1630-
if not token:
1631-
return None
1632-
if not p:
1633-
return None
1634-
if token.str == p:
1635-
return token
1636-
if p in ['!', '|', '||', '%', '!=', '*']:
1637-
return None
1638-
if p in patterns:
1639-
return patterns[p](token)
1640-
if '|' in p:
1641-
for x in p.split('|'):
1642-
t = match_atom(token, x)
1643-
if t:
1644-
return t
1645-
elif p.startswith('!!'):
1646-
t = match_atom(token, p[2:])
1647-
if not t:
1648-
return token
1649-
elif p.startswith('**'):
1650-
a = p[2:]
1651-
t = token
1652-
while t:
1653-
if match_atom(t, a):
1654-
return t
1655-
if t.link and t.str in ['(', '[', '<', '{']:
1656-
t = t.link
1657-
t = t.next
1658-
return None
1659-
16601629
class MatchResult:
16611630
def __init__(self, matches, bindings=None, keys=None):
16621631
self.__dict__.update(bindings or {})
@@ -1680,22 +1649,139 @@ def bind_split(s):
16801649
return (p[0], p[2])
16811650
return (s, None)
16821651

1652+
class CompiledPattern:
1653+
"""
1654+
A match() pattern compiled once so it can be matched against many tokens.
1655+
1656+
Each word of the pattern is compiled into a matcher: a function that takes
1657+
a token (never None) and returns the last token the word matched, or None.
1658+
1659+
Attributes:
1660+
pattern The pattern string
1661+
atoms List of (matcher, binding name) for each word in the pattern
1662+
failed The MatchResult returned when the pattern does not match
1663+
"""
1664+
1665+
_literal_atoms = frozenset(['!', '|', '||', '|=', '%', '!=', '*'])
1666+
_link_open = frozenset(['(', '[', '<', '{'])
1667+
1668+
def __init__(self, pattern):
1669+
self.pattern = pattern
1670+
words = [bind_split(word) for word in pattern.split()]
1671+
self.atoms = [(self.compile_atom(p), b) for p, b in words]
1672+
keys = [b for p, b in words] + ['end'] if words else []
1673+
self.failed = MatchResult(False, keys=keys)
1674+
1675+
def __repr__(self):
1676+
return "CompiledPattern(pattern={})".format(repr(self.pattern))
1677+
1678+
def match(self, token):
1679+
if not self.atoms:
1680+
# empty pattern (or only whitespace) never matches
1681+
return self.failed
1682+
end = None
1683+
bindings = {}
1684+
for m, b in self.atoms:
1685+
if token is None:
1686+
return self.failed
1687+
t = m(token)
1688+
if b:
1689+
bindings[b] = token
1690+
if t is None:
1691+
return self.failed
1692+
end = t
1693+
token = t.next
1694+
bindings['end'] = end
1695+
return MatchResult(True, bindings=bindings)
1696+
1697+
@classmethod
1698+
def compile_atom(cls, p):
1699+
"""Compile one pattern word into a matcher."""
1700+
if not p:
1701+
return cls._match_none
1702+
if p in cls._literal_atoms:
1703+
return cls._match_literal(p)
1704+
if p in patterns:
1705+
return patterns[p]
1706+
prefix, word = p[:2], p[2:]
1707+
if prefix == '!!':
1708+
# as in the C++ Token::Match, '!!' is checked before alternation
1709+
# and the rest is compared as a whole: '!!a|b' is "not the token a|b"
1710+
inner = cls._match_literal(word) if '|' in word else cls.compile_atom(word)
1711+
return cls._match_negation(inner)
1712+
if prefix == '**':
1713+
# '**a|b' searches ahead for a or b
1714+
return cls._match_forward(cls.compile_atom(word))
1715+
if '|' in p:
1716+
return cls._match_alternatives([cls.compile_atom(x) for x in p.split('|')])
1717+
return cls._match_literal(p)
1718+
1719+
@staticmethod
1720+
def _match_none(tok):
1721+
return None
1722+
1723+
@staticmethod
1724+
def _match_literal(p):
1725+
def m(tok):
1726+
return tok if tok.str == p else None
1727+
return m
1728+
1729+
@staticmethod
1730+
def _match_alternatives(alternatives):
1731+
def m(tok):
1732+
for a in alternatives:
1733+
t = a(tok)
1734+
if t:
1735+
return t
1736+
return None
1737+
return m
1738+
1739+
@staticmethod
1740+
def _match_negation(inner):
1741+
def m(tok):
1742+
return None if inner(tok) else tok
1743+
return m
1744+
1745+
@classmethod
1746+
def _match_forward(cls, inner):
1747+
link_open = cls._link_open
1748+
def m(tok):
1749+
t = tok
1750+
while t:
1751+
if inner(t):
1752+
return t
1753+
if t.link and t.str in link_open:
1754+
t = t.link
1755+
t = t.next
1756+
return None
1757+
return m
1758+
1759+
@functools.lru_cache(maxsize=1024)
1760+
def compile_pattern(pattern):
1761+
"""
1762+
Return the CompiledPattern for a pattern string.
1763+
1764+
The most recently used patterns are kept, so compiling the same pattern
1765+
string again is cheap.
1766+
"""
1767+
return CompiledPattern(pattern)
1768+
16831769
def match(token, pattern):
1770+
"""
1771+
Match the tokens starting at token against pattern.
1772+
1773+
Returns a MatchResult, which is true when the pattern matches.
1774+
1775+
Use constant pattern strings. A pattern is compiled the first time it is
1776+
used and only a limited number of compiled patterns are kept, so a pattern
1777+
string built at run time, such as name + ' (', is compiled again for every
1778+
new string. Compare the varying part separately instead:
1779+
1780+
match(tok, '%name% (') and tok.str == name
1781+
"""
16841782
if not pattern:
16851783
return MatchResult(False)
1686-
end = None
1687-
bindings = {}
1688-
words = [bind_split(word) for word in pattern.split()]
1689-
for p, b in words:
1690-
t = match_atom(token, p)
1691-
if b:
1692-
bindings[b] = token
1693-
if not t:
1694-
return MatchResult(False, keys=[xx for pp, xx in words]+['end'])
1695-
end = t
1696-
token = t.next
1697-
bindings['end'] = end
1698-
return MatchResult(True, bindings=bindings)
1784+
return compile_pattern(pattern).match(token)
16991785

17001786
def get_function_call_name_args(token):
17011787
"""Get function name and arguments for function call

‎cli/cmdlineparser.cpp‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2228,6 +2228,8 @@ bool CmdLineParser::loadAddons(Settings& settings)
22282228
result = false;
22292229
continue;
22302230
}
2231+
if (!settings.buildDir.empty())
2232+
addonInfo.initContentHash();
22312233
settings.addonInfos.emplace_back(std::move(addonInfo));
22322234
}
22332235
return result;

‎gui/mainwindow.cpp‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1259,8 +1259,11 @@ bool MainWindow::getCppcheckSettings(Settings& settings, Suppressions& supprs)
12591259
settings.severity.enable(Severity::portability);
12601260
settings.severity.enable(Severity::information);
12611261
settings.checks.enable(Checks::missingInclude);
1262-
if (!settings.buildDir.empty())
1262+
if (!settings.buildDir.empty()) {
12631263
settings.checks.enable(Checks::unusedFunction);
1264+
for (AddonInfo& addonInfo : settings.addonInfos)
1265+
addonInfo.initContentHash();
1266+
}
12641267
settings.debugwarnings = mSettings->value(SETTINGS_SHOW_DEBUG_WARNINGS, false).toBool();
12651268
settings.quiet = false;
12661269
settings.verbose = true;

‎lib/addoninfo.cpp‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include <iostream>
2626
#include <string>
2727
#include <utility>
28+
#include <vector>
2829

2930
#include "json.h"
3031

@@ -209,6 +210,7 @@ std::string AddonInfo::getAddonInfo(const std::string &fileName, const std::stri
209210
std::ifstream fin(fileName);
210211
if (!fin.is_open())
211212
return "Failed to open " + fileName;
213+
jsonFile = Path::fromNativeSeparators(fileName);
212214
if (name.empty()) {
213215
name = Path::fromNativeSeparators(fileName);
214216
if (name.find('/') != std::string::npos)
@@ -218,3 +220,45 @@ std::string AddonInfo::getAddonInfo(const std::string &fileName, const std::stri
218220
fin >> json;
219221
return parseAddonInfo(*this, json, fileName, exename);
220222
}
223+
224+
// split the args like the shell running the addon, quotes only (no escapes or variables)
225+
static std::vector<std::string> splitArgs(const std::string &args) {
226+
#ifdef _WIN32
227+
const std::string quotes = "\"";
228+
#else
229+
// popen() runs /bin/sh, which also removes single quotes
230+
const std::string quotes = "\"\'";
231+
#endif
232+
std::vector<std::string> ret(1);
233+
char quote = '\0';
234+
for (const char c : args) {
235+
if (quote == '\0' && quotes.find(c) != std::string::npos)
236+
quote = c;
237+
else if (c == quote)
238+
quote = '\0';
239+
else if (c == ' ' && quote == '\0')
240+
ret.emplace_back();
241+
else
242+
ret.back() += c;
243+
}
244+
return ret;
245+
}
246+
247+
void AddonInfo::initContentHash() {
248+
contentHash.clear();
249+
if (!jsonFile.empty())
250+
contentHash += hashFileContent(jsonFile);
251+
if (!scriptFile.empty())
252+
contentHash += hashFileContent(scriptFile);
253+
if (!executable.empty())
254+
contentHash += hashFileContent(executable);
255+
// files referenced as OPTION=FILE in args, e.g. --rule-texts=FILE
256+
for (const std::string &arg : splitArgs(args)) {
257+
const std::string::size_type pos = arg.find('=');
258+
if (pos == std::string::npos)
259+
continue;
260+
const std::string path = arg.substr(pos + 1);
261+
if (Path::isFile(path))
262+
contentHash += hashFileContent(path);
263+
}
264+
}

‎lib/addoninfo.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
struct CPPCHECKLIB AddonInfo {
2828
std::string name;
29+
std::string jsonFile; // addon json file
2930
std::string scriptFile; // addon script
3031
std::string executable; // addon executable
3132
std::string args; // special extra arguments
@@ -34,7 +35,10 @@ struct CPPCHECKLIB AddonInfo {
3435
std::string runScript;
3536
std::map<std::string, std::string> checkers; // checker name and its requirement
3637

38+
std::string contentHash; // hash of the addon files
39+
3740
std::string getAddonInfo(const std::string &fileName, const std::string &exename, bool debug = false);
41+
void initContentHash();
3842
};
3943

4044
#endif // addonInfoH

‎lib/cppcheck.cpp‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -906,6 +906,7 @@ std::size_t CppCheck::calculateHash(const Preprocessor& preprocessor, const std:
906906
for (const auto &a : mSettings.addonInfos) {
907907
toolinfo << a.name;
908908
toolinfo << a.args;
909+
toolinfo << a.contentHash;
909910
}
910911
toolinfo << mSettings.premiumArgs;
911912
// TODO: do we need to add more options?

‎lib/programmemory.cpp‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,8 @@ static void programMemoryParseCondition(ProgramMemory& pm,
530530
return;
531531
if (!truevalue.isIntValue())
532532
return;
533-
if (endTok && changed(vartok, tok->next(), endTok))
533+
// The other operand is evaluated with its current value, so it must be unchanged as well
534+
if (endTok && changed(tok, tok->next(), endTok))
534535
return;
535536
const bool impossible = (tok->str() == "==" && !then) || (tok->str() == "!=" && then);
536537
ValueFlow::Value& v = then ? truevalue : falsevalue;

‎lib/tokenize.cpp‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3774,7 +3774,7 @@ void Tokenizer::concatenateNegativeNumberAndAnyPositive()
37743774
if (tok->findOpeningBracket())
37753775
continue;
37763776

3777-
if (!tok->tokAt(2) || (tok->tokAt(2)->isOp() && !Token::Match(tok->tokAt(2), "[+-*]")))
3777+
if (!tok->tokAt(2) || (tok->tokAt(2)->isOp() && !Token::Match(tok->tokAt(2), "+|-|*|!|~|&|--|++")))
37783778
syntaxError(tok);
37793779

37803780
while ((tok->isArithmeticalOp() || tok->isComparisonOp()) && tok->str() != ">" && tok->next() && tok->strAt(1) == "+" &&
@@ -7527,6 +7527,7 @@ void Tokenizer::simplifyVarDecl(const bool only_k_r_fpar)
75277527
simplifyVarDecl(list.front(), nullptr, only_k_r_fpar);
75287528
}
75297529

7530+
// Returns the closing parenthesis of the parameter list if tok ends a trailing return type
75307531
static Token* isTrailingReturnType(Token* tok)
75317532
{
75327533
while (Token::Match(tok, "%name%|::|>")) {
@@ -7535,8 +7536,20 @@ static Token* isTrailingReturnType(Token* tok)
75357536
else
75367537
tok = tok->tokAt(-1);
75377538
}
7538-
if (tok && Token::simpleMatch(tok->tokAt(-1), ") ."))
7539-
return tok->tokAt(-1);
7539+
if (!Token::simpleMatch(tok, "."))
7540+
return nullptr;
7541+
// Skip the specifiers between the parameter list and the trailing return type
7542+
tok = tok->previous();
7543+
while (tok) {
7544+
if (Token::Match(tok, "const|volatile|&|&&|noexcept|mutable|constexpr|consteval|static"))
7545+
tok = tok->previous();
7546+
else if (tok->str() == ")" && Token::Match(tok->link()->previous(), "noexcept|throw"))
7547+
tok = tok->link()->tokAt(-2);
7548+
else
7549+
break;
7550+
}
7551+
if (Token::simpleMatch(tok, ")"))
7552+
return tok;
75407553
return nullptr;
75417554
}
75427555

@@ -7597,7 +7610,8 @@ void Tokenizer::simplifyVarDecl(Token * tokBegin, const Token * const tokEnd, co
75977610
if (only_k_r_fpar && finishedwithkr) {
75987611
if (Token::Match(tok, "(|[|{")) {
75997612
tok = tok->link();
7600-
if (tok->next() && Token::Match(tok, ") !!{"))
7613+
// Don't step onto tokEnd: the loop increment would then step past it
7614+
if (tok->next() && tok->next() != tokEnd && Token::Match(tok, ") !!{"))
76017615
tok = tok->next();
76027616
else
76037617
continue;

0 commit comments

Comments
 (0)