Skip to content

Commit 59d717f

Browse files
authored
Partial fix for #8328 (build dir: hash the addon files) (#9029)
1 parent 16f7cd7 commit 59d717f

9 files changed

Lines changed: 208 additions & 1 deletion

File tree

‎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/utils.cpp‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,10 @@
2020

2121
#include <algorithm>
2222
#include <cctype>
23+
#include <fstream>
24+
#include <functional>
25+
#include <ios>
26+
#include <sstream>
2327
#include <stack>
2428
#include <utility>
2529

@@ -198,3 +202,13 @@ std::vector<std::string> splitString(const std::string& str, char sep)
198202
}
199203
return l;
200204
}
205+
206+
std::string hashFileContent(const std::string& path)
207+
{
208+
std::ifstream fin(path, std::ios::binary);
209+
if (!fin.is_open())
210+
return "";
211+
std::ostringstream ostr;
212+
ostr << fin.rdbuf();
213+
return std::to_string(std::hash<std::string> {}(ostr.str()));
214+
}

‎lib/utils.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,13 @@ static inline T* empty_if_null(T* p)
431431
*/
432432
CPPCHECKLIB std::vector<std::string> splitString(const std::string& str, char sep);
433433

434+
/**
435+
* Hash the content of a file.
436+
* @param path The file to read
437+
* @return The hash, empty if the file cannot be opened.
438+
*/
439+
CPPCHECKLIB std::string hashFileContent(const std::string& path);
440+
434441
namespace utils {
435442
/**
436443
* Drop-in replacement for C++17's std::as_const

‎test/cli/other_test.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2416,6 +2416,59 @@ def test_builddir_hash_check_level(tmp_path): # #13376
24162416
assert hash_1 != hash_2
24172417

24182418

2419+
def test_builddir_hash_addon(tmp_path):
2420+
test_file = tmp_path / 'test.c'
2421+
with open(test_file, 'wt') as f:
2422+
f.write('void f() {}\n')
2423+
2424+
addon_script = tmp_path / 'addon1.py'
2425+
with open(addon_script, 'wt') as f:
2426+
f.write('# addon1.py\n')
2427+
2428+
rule_texts = tmp_path / 'rule texts.txt'
2429+
with open(rule_texts, 'wt') as f:
2430+
f.write('# rule texts.txt\n')
2431+
2432+
extra_file = tmp_path / 'extra file.txt'
2433+
with open(extra_file, 'wt') as f:
2434+
f.write('# extra file.txt\n')
2435+
2436+
addon_file = tmp_path / 'addon1.json'
2437+
with open(addon_file, 'wt') as f:
2438+
f.write(json.dumps({
2439+
'script': str(addon_script),
2440+
'args': ['"--rule-texts={}"'.format(rule_texts), '--extra="{}"'.format(extra_file)]
2441+
}))
2442+
2443+
build_dir = tmp_path / 'b1'
2444+
os.mkdir(build_dir)
2445+
2446+
args = [
2447+
'--addon={}'.format(addon_file),
2448+
'--cppcheck-build-dir={}'.format(build_dir),
2449+
str(test_file)
2450+
]
2451+
2452+
cache_file = build_dir / 'test.a1'
2453+
2454+
def get_hash():
2455+
exitcode, stdout, stderr = cppcheck(args)
2456+
assert exitcode == 0, stdout
2457+
assert stderr == ''
2458+
root = ElementTree.fromstring(cache_file.read_text())
2459+
return root.findtext('hash')
2460+
2461+
hash_1 = get_hash()
2462+
assert get_hash() == hash_1
2463+
2464+
for changed_file in (addon_script, rule_texts, extra_file, addon_file):
2465+
with open(changed_file, 'a') as f:
2466+
f.write('\n')
2467+
hash_2 = get_hash()
2468+
assert hash_2 != hash_1
2469+
hash_1 = hash_2
2470+
2471+
24192472
def test_def_undef(tmp_path):
24202473
test_file = tmp_path / 'test.c'
24212474
with open(test_file, 'wt') as f:

‎test/testcppcheck.cpp‎

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@
3535
#include <algorithm>
3636
#include <cstdio>
3737
#include <cstdlib>
38+
#include <fstream>
3839
#include <list>
3940
#include <string>
4041
#include <unordered_set>
@@ -100,6 +101,13 @@ class TestCppcheck : public TestFixture {
100101
TEST_CASE(getDumpFileContentsLibrary);
101102
TEST_CASE(checkPlistOutput);
102103
TEST_CASE(premiumResultsCache);
104+
TEST_CASE(addonScriptHash);
105+
TEST_CASE(addonJsonHash);
106+
TEST_CASE(addonArgsHash);
107+
TEST_CASE(addonQuotedArgsHash);
108+
#ifndef _WIN32
109+
TEST_CASE(addonSingleQuotedArgsHash);
110+
#endif
103111
TEST_CASE(purgedConfiguration);
104112
TEST_CASE(recheckInclude);
105113
}
@@ -612,6 +620,77 @@ class TestCppcheck : public TestFixture {
612620
ASSERT(hash1 != hash2);
613621
}
614622

623+
void addonHashInternal(AddonInfo addon, const ScopedFile& file) const
624+
{
625+
Settings settings;
626+
Suppressions supprs;
627+
ErrorLogger2 errorLogger;
628+
629+
std::vector<std::string> files;
630+
631+
const char code[] = "void f();\nint x;\n";
632+
simplecpp::TokenList tokens(code, files, "m1.c");
633+
634+
Preprocessor preprocessor(tokens, settings, errorLogger, Standards::Language::C);
635+
ASSERT(preprocessor.loadAllIncludes(files));
636+
637+
addon.name = "testaddon";
638+
settings.addons.insert(addon.name);
639+
settings.addonInfos.push_back(std::move(addon));
640+
settings.addonInfos.back().initContentHash();
641+
642+
CppCheck check(settings, supprs, errorLogger, nullptr, false, {});
643+
const size_t hash1 = check.calculateHash(preprocessor);
644+
645+
settings.addonInfos.back().initContentHash();
646+
ASSERT_EQUALS(hash1, check.calculateHash(preprocessor));
647+
648+
{
649+
std::ofstream of(file.path());
650+
of << "changed content\n";
651+
}
652+
settings.addonInfos.back().initContentHash();
653+
// cppcheck-suppress knownConditionTrueFalse
654+
ASSERT(hash1 != check.calculateHash(preprocessor));
655+
}
656+
657+
void addonScriptHash() const {
658+
ScopedFile addon_script("testaddon.py", "# addon v1\n");
659+
AddonInfo addon;
660+
addon.scriptFile = addon_script.path();
661+
addonHashInternal(addon, addon_script);
662+
}
663+
664+
void addonJsonHash() const {
665+
ScopedFile addon_config("testaddon.json", "{ \"script\": \"x.py\" }\n");
666+
AddonInfo addon;
667+
addon.jsonFile = addon_config.path();
668+
addonHashInternal(addon, addon_config);
669+
}
670+
671+
void addonArgsHash() const {
672+
ScopedFile rule_texts("testrules.txt", "rule v1\n");
673+
AddonInfo addon;
674+
addon.args = "--rule-texts=" + rule_texts.path();
675+
addonHashInternal(addon, rule_texts);
676+
}
677+
678+
void addonQuotedArgsHash() const {
679+
ScopedFile rule_texts("test rules.txt", "rule v1\n");
680+
AddonInfo addon;
681+
addon.args = "--rule-texts=\"" + rule_texts.path() + "\"";
682+
addonHashInternal(addon, rule_texts);
683+
}
684+
685+
#ifndef _WIN32
686+
void addonSingleQuotedArgsHash() const {
687+
ScopedFile rule_texts("test rules.txt", "rule v1\n");
688+
AddonInfo addon;
689+
addon.args = "--rule-texts='" + rule_texts.path() + "'";
690+
addonHashInternal(addon, rule_texts);
691+
}
692+
#endif
693+
615694
void purgedConfiguration() const
616695
{
617696
ScopedFile test_file("test.cpp",

0 commit comments

Comments
 (0)