Skip to content

Commit bd73631

Browse files
committed
1
1 parent 35e76b5 commit bd73631

7 files changed

Lines changed: 184 additions & 50 deletions

File tree

‎Makefile‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -700,7 +700,7 @@ $(libcppdir)/vfvalue.o: lib/vfvalue.cpp lib/config.h lib/errortypes.h lib/mathli
700700
frontend/frontend.o: frontend/frontend.cpp frontend/frontend.h lib/checkers.h lib/config.h lib/filesettings.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/settings.h lib/standards.h lib/utils.h
701701
$(CXX) ${INCLUDE_FOR_FE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ frontend/frontend.cpp
702702

703-
cli/cmdlineparser.o: cli/cmdlineparser.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/filelister.h externals/tinyxml2/tinyxml2.h lib/addoninfo.h lib/check.h lib/checkers.h lib/checks.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/importproject.h lib/library.h lib/mathlib.h lib/path.h lib/pathmatch.h lib/platform.h lib/refthunk.h lib/regex.h lib/rule.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h lib/xml.h
703+
cli/cmdlineparser.o: cli/cmdlineparser.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/cppcheckexecutor.h cli/filelister.h externals/tinyxml2/tinyxml2.h lib/addoninfo.h lib/check.h lib/checkers.h lib/checks.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/importproject.h lib/library.h lib/mathlib.h lib/path.h lib/pathmatch.h lib/platform.h lib/refthunk.h lib/regex.h lib/rule.h lib/settings.h lib/standards.h lib/suppressions.h lib/utils.h lib/xml.h
704704
$(CXX) ${INCLUDE_FOR_CLI} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ cli/cmdlineparser.cpp
705705

706706
cli/cppcheckexecutor.o: cli/cppcheckexecutor.cpp cli/cmdlinelogger.h cli/cmdlineparser.h cli/cppcheckexecutor.h cli/executor.h cli/processexecutor.h cli/sehwrapper.h cli/signalhandler.h cli/singleexecutor.h cli/threadexecutor.h externals/picojson/picojson.h lib/analyzerinfo.h lib/check.h lib/checkers.h lib/checkersreport.h lib/color.h lib/config.h lib/cppcheck.h lib/errorlogger.h lib/errortypes.h lib/filesettings.h lib/json.h lib/library.h lib/mathlib.h lib/path.h lib/platform.h lib/refthunk.h lib/sarifreport.h lib/settings.h lib/standards.h lib/suppressions.h lib/timer.h lib/utils.h

‎cli/cmdlineparser.cpp‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include "color.h"
2626
#include "config.h"
2727
#include "cppcheck.h"
28+
#include "cppcheckexecutor.h"
2829
#include "errorlogger.h"
2930
#include "errortypes.h"
3031
#include "filelister.h"
@@ -121,9 +122,13 @@ static bool addPathsToSet(const std::string& fileName, std::set<std::string>& se
121122
namespace {
122123
class XMLErrorMessagesLogger : public ErrorLogger
123124
{
125+
public:
126+
explicit XMLErrorMessagesLogger(std::ostream &out) : mOut(out) {}
127+
128+
private:
124129
void reportOut(const std::string & outmsg, Color /*c*/ = Color::Reset) override
125130
{
126-
std::cout << outmsg << std::endl;
131+
mOut << outmsg << std::endl;
127132
}
128133

129134
void reportErr(const ErrorMessage &msg) override
@@ -139,6 +144,8 @@ namespace {
139144

140145
void reportProgress(const std::string & /*filename*/, const char /*stage*/[], const std::size_t /*value*/) override
141146
{}
147+
148+
std::ostream &mOut;
142149
};
143150
}
144151

@@ -377,9 +384,18 @@ CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const a
377384
// print all possible error messages..
378385
if (std::strcmp(argv[i], "--errorlist") == 0) {
379386
{
380-
XMLErrorMessagesLogger xmlLogger;
387+
// get the premium messages first so there is no partial output if that fails
388+
std::ostringstream premiumErrors;
389+
if (mSettings.premium) {
390+
XMLErrorMessagesLogger premiumLogger(premiumErrors);
391+
if (!getPremiumErrorMessages(premiumLogger))
392+
return Result::Fail;
393+
}
394+
395+
XMLErrorMessagesLogger xmlLogger(std::cout);
381396
std::cout << ErrorMessage::getXMLHeader(mSettings.cppcheckCfgProductName, 2);
382397
CppCheck::getErrorMessages(xmlLogger);
398+
std::cout << premiumErrors.str();
383399
std::cout << ErrorMessage::getXMLFooter(2) << std::endl;
384400
}
385401
return Result::Exit;
@@ -2233,6 +2249,27 @@ bool CmdLineParser::loadAddons(Settings& settings)
22332249
return result;
22342250
}
22352251

2252+
bool CmdLineParser::getPremiumErrorMessages(ErrorLogger &errorLogger)
2253+
{
2254+
for (const std::string &addon: mSettings.addons) {
2255+
AddonInfo addonInfo;
2256+
const std::string failedToGetAddonInfo = addonInfo.getAddonInfo(addon, mSettings.exename, mSettings.debuglookup || mSettings.debuglookupAddon);
2257+
if (!failedToGetAddonInfo.empty()) {
2258+
mLogger.printError(failedToGetAddonInfo);
2259+
return false;
2260+
}
2261+
if (addonInfo.name != "premiumaddon.json" || addonInfo.executable.empty())
2262+
continue;
2263+
try {
2264+
CppCheck::getAddonErrorMessages(addonInfo, errorLogger, CppCheckExecutor::executeCommand);
2265+
} catch (const InternalError &e) {
2266+
mLogger.printError(e.errorMessage + (e.details.empty() ? "" : "\n" + e.details));
2267+
return false;
2268+
}
2269+
}
2270+
return true;
2271+
}
2272+
22362273
bool CmdLineParser::loadCppcheckCfg()
22372274
{
22382275
if (!mSettings.settingsFiles.empty())

‎cli/cmdlineparser.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
class Settings;
3434
struct Suppressions;
3535
class Library;
36+
class ErrorLogger;
3637

3738
/// @addtogroup CLI
3839
/// @{
@@ -152,6 +153,12 @@ class CmdLineParser {
152153

153154
bool loadCppcheckCfg();
154155

156+
/**
157+
* @brief Get the error messages of the Cppcheck Premium addon
158+
* @return Returns true if successful
159+
*/
160+
bool getPremiumErrorMessages(ErrorLogger &errorLogger);
161+
155162
void outputFormatOptionMixingError() const;
156163

157164
CmdLineLogger& mLogger;

‎cli/cppcheckexecutor.h‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,13 +59,13 @@ class CppCheckExecutor {
5959
*/
6060
int check(int argc, const char* const argv[]);
6161

62-
protected:
63-
6462
/**
6563
* Execute a shell command and read the output from it. Returns exitcode of the executed command,.
6664
*/
6765
static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output_);
6866

67+
protected:
68+
6969
static bool reportUnmatchedSuppressions(const Settings &settings, const SuppressionList& suppressions, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, ErrorLogger& errorLogger);
7070

7171
private:

‎lib/cppcheck.cpp‎

Lines changed: 75 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -453,46 +453,15 @@ static std::string detectPython(const CppCheck::ExecuteCmdFn &executeCommand)
453453
/**
454454
* @throws InternalError thrown when execution fails
455455
*/
456-
static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
457-
const std::string &defaultPythonExe,
458-
const std::string &file,
459-
const std::string &premiumArgs,
460-
const CppCheck::ExecuteCmdFn &executeCommand)
456+
static std::vector<picojson::value> runAddonCommand(const std::string &addonName,
457+
const std::string &exe,
458+
const std::string &args,
459+
const CppCheck::ExecuteCmdFn &executeCommand)
461460
{
462-
if (!executeCommand)
463-
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");
464-
465-
std::string pythonExe;
466-
467-
if (!addonInfo.executable.empty())
468-
pythonExe = addonInfo.executable;
469-
else if (!addonInfo.python.empty())
470-
pythonExe = cmdFileName(addonInfo.python);
471-
else if (!defaultPythonExe.empty())
472-
pythonExe = cmdFileName(defaultPythonExe);
473-
else {
474-
// store in static variable so we only look this up once - TODO: do not cache globally
475-
static const std::string detectedPythonExe = detectPython(executeCommand);
476-
if (detectedPythonExe.empty())
477-
throw InternalError(nullptr, "Failed to auto detect python");
478-
pythonExe = detectedPythonExe;
479-
}
480-
481-
std::string args;
482-
if (addonInfo.executable.empty())
483-
args = cmdFileName(addonInfo.runScript) + " " + cmdFileName(addonInfo.scriptFile);
484-
args += std::string(args.empty() ? "" : " ") + "--cli" + addonInfo.args;
485-
if (!premiumArgs.empty() && !addonInfo.executable.empty())
486-
args += " " + premiumArgs;
487-
488-
const bool is_file_list = (file.find(FILELIST) != std::string::npos);
489-
const std::string fileArg = (is_file_list ? " --file-list " : " ") + cmdFileName(file);
490-
args += fileArg;
491-
492461
std::string result;
493-
if (const int exitcode = executeCommand(pythonExe, split(args), "2>&1", result)) {
494-
std::string message("Failed to execute addon '" + addonInfo.name + "' - exitcode is " + std::to_string(exitcode));
495-
std::string details = pythonExe + " " + args;
462+
if (const int exitcode = executeCommand(exe, split(args), "2>&1", result)) {
463+
std::string message("Failed to execute addon '" + addonName + "' - exitcode is " + std::to_string(exitcode));
464+
std::string details = exe + " " + args;
496465
if (result.size() > 2) {
497466
details += "\nOutput:\n";
498467
details += result;
@@ -511,34 +480,34 @@ static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
511480
while (std::getline(istr, line)) {
512481
// TODO: also bail out?
513482
if (line.empty()) {
514-
//std::cout << "addon '" << addonInfo.name << "' result contains empty line" << std::endl;
483+
//std::cout << "addon '" << addonName << "' result contains empty line" << std::endl;
515484
continue;
516485
}
517486

518487
// TODO: get rid of this
519488
if (startsWith(line,"Checking ")) {
520-
//std::cout << "addon '" << addonInfo.name << "' result contains 'Checking ' line" << std::endl;
489+
//std::cout << "addon '" << addonName << "' result contains 'Checking ' line" << std::endl;
521490
continue;
522491
}
523492

524493
if (line[0] != '{') {
525-
//std::cout << "addon '" << addonInfo.name << "' result is not a JSON" << std::endl;
494+
//std::cout << "addon '" << addonName << "' result is not a JSON" << std::endl;
526495

527496
result.erase(result.find_last_not_of('\n') + 1, std::string::npos); // Remove trailing newlines
528-
throw InternalError(nullptr, "Failed to execute '" + pythonExe + " " + args + "'. " + result);
497+
throw InternalError(nullptr, "Failed to execute '" + exe + " " + args + "'. " + result);
529498
}
530499

531-
//std::cout << "addon '" << addonInfo.name << "' result is " << line << std::endl;
500+
//std::cout << "addon '" << addonName << "' result is " << line << std::endl;
532501

533502
// TODO: make these failures?
534503
picojson::value res;
535504
const std::string err = picojson::parse(res, line);
536505
if (!err.empty()) {
537-
//std::cout << "addon '" << addonInfo.name << "' result is not a valid JSON (" << err << ")" << std::endl;
506+
//std::cout << "addon '" << addonName << "' result is not a valid JSON (" << err << ")" << std::endl;
538507
continue;
539508
}
540509
if (!res.is<picojson::object>()) {
541-
//std::cout << "addon '" << addonInfo.name << "' result is not a JSON object" << std::endl;
510+
//std::cout << "addon '" << addonName << "' result is not a JSON object" << std::endl;
542511
continue;
543512
}
544513
addonResult.emplace_back(std::move(res));
@@ -548,6 +517,48 @@ static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
548517
return addonResult;
549518
}
550519

520+
/**
521+
* @throws InternalError thrown when execution fails
522+
*/
523+
static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
524+
const std::string &defaultPythonExe,
525+
const std::string &file,
526+
const std::string &premiumArgs,
527+
const CppCheck::ExecuteCmdFn &executeCommand)
528+
{
529+
if (!executeCommand)
530+
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");
531+
532+
std::string pythonExe;
533+
534+
if (!addonInfo.executable.empty())
535+
pythonExe = addonInfo.executable;
536+
else if (!addonInfo.python.empty())
537+
pythonExe = cmdFileName(addonInfo.python);
538+
else if (!defaultPythonExe.empty())
539+
pythonExe = cmdFileName(defaultPythonExe);
540+
else {
541+
// store in static variable so we only look this up once - TODO: do not cache globally
542+
static const std::string detectedPythonExe = detectPython(executeCommand);
543+
if (detectedPythonExe.empty())
544+
throw InternalError(nullptr, "Failed to auto detect python");
545+
pythonExe = detectedPythonExe;
546+
}
547+
548+
std::string args;
549+
if (addonInfo.executable.empty())
550+
args = cmdFileName(addonInfo.runScript) + " " + cmdFileName(addonInfo.scriptFile);
551+
args += std::string(args.empty() ? "" : " ") + "--cli" + addonInfo.args;
552+
if (!premiumArgs.empty() && !addonInfo.executable.empty())
553+
args += " " + premiumArgs;
554+
555+
const bool is_file_list = (file.find(FILELIST) != std::string::npos);
556+
const std::string fileArg = (is_file_list ? " --file-list " : " ") + cmdFileName(file);
557+
args += fileArg;
558+
559+
return runAddonCommand(addonInfo.name, pythonExe, args, executeCommand);
560+
}
561+
551562
static std::string getDefinesFlags(const std::string &semicolonSeparatedString)
552563
{
553564
std::string flags;
@@ -1805,6 +1816,25 @@ void CppCheck::getErrorMessages(ErrorLogger &errorlogger)
18051816
SymbolDatabase::getErrorMessages(errorlogger);
18061817
}
18071818

1819+
void CppCheck::getAddonErrorMessages(const AddonInfo &addonInfo, ErrorLogger &errorlogger, const ExecuteCmdFn &executeCommand)
1820+
{
1821+
if (!executeCommand)
1822+
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");
1823+
1824+
const std::vector<picojson::value> results = runAddonCommand(addonInfo.name, addonInfo.executable, "--cli --errorlist", executeCommand);
1825+
1826+
for (const picojson::value& res : results) {
1827+
// this is a copy so we can access missing fields and get a default value
1828+
picojson::object obj = res.get<picojson::object>();
1829+
1830+
ErrorMessage errmsg;
1831+
errmsg.id = obj["addon"].get<std::string>() + "-" + obj["errorId"].get<std::string>();
1832+
errmsg.setmsg(obj["message"].get<std::string>());
1833+
errmsg.severity = severityFromString(obj["severity"].get<std::string>());
1834+
errorlogger.reportErr(errmsg);
1835+
}
1836+
}
1837+
18081838
void CppCheck::analyseClangTidy(const FileSettings &fileSettings)
18091839
{
18101840
std::string allIncludes;

‎lib/cppcheck.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ class FileWithDetails;
4141
class AnalyzerInformation;
4242
class ErrorLogger;
4343
class Settings;
44+
struct AddonInfo;
4445
struct Suppressions;
4546
class Preprocessor;
4647
class TimerResults;
@@ -132,6 +133,12 @@ class CPPCHECKLIB CppCheck {
132133
*/
133134
static void getErrorMessages(ErrorLogger &errorlogger);
134135

136+
/**
137+
* @brief Get all error messages that an addon executable can report, by running it with --errorlist.
138+
* @throws InternalError thrown when execution fails
139+
*/
140+
static void getAddonErrorMessages(const AddonInfo &addonInfo, ErrorLogger &errorlogger, const ExecuteCmdFn &executeCommand);
141+
135142
void tooManyConfigsError(const std::string &file, int numberOfConfigurations);
136143

137144
/** Analyse whole program, run this after all TUs has been scanned.

‎test/cli/premium_test.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11

22
# python -m pytest premium_test.py
33

4+
import json
45
import os
56
import re
67
import shutil
78
import sys
89
import time
10+
from xml.etree import ElementTree
11+
12+
import pytest
913

1014
from testutils import cppcheck, __lookup_cppcheck_exe
1115

@@ -199,3 +203,52 @@ def test_hash(tmpdir):
199203

200204
_, _, stderr = cppcheck(args)
201205
assert '<error id="a-id" severity="error" msg="bug" verbose="bug" hash="123" ' in stderr
206+
207+
208+
def __add_premiumaddon(exe, tmpdir, script):
209+
addon_exe = os.path.join(tmpdir, 'premiumaddon.sh')
210+
with open(addon_exe, 'wt') as f:
211+
f.write('#!/bin/sh\n' + script)
212+
os.chmod(addon_exe, 0o755)
213+
214+
with open(os.path.join(tmpdir, 'premiumaddon.json'), 'wt') as f:
215+
f.write(json.dumps({'executable': addon_exe}))
216+
217+
cfg_file = os.path.join(os.path.dirname(exe), 'cppcheck.cfg')
218+
with open(cfg_file, 'rt') as f:
219+
cfg = json.load(f)
220+
cfg['addons'] = [os.path.join(tmpdir, 'premiumaddon.json')]
221+
with open(cfg_file, 'wt') as f:
222+
f.write(json.dumps(cfg))
223+
224+
225+
@pytest.mark.skipif(sys.platform == 'win32', reason='uses a shell script as addon executable')
226+
def test_errorlist(tmpdir):
227+
exe = __copy_cppcheck_premium(tmpdir)
228+
__add_premiumaddon(exe, tmpdir,
229+
'[ "$*" = "--cli --errorlist" ] || exit 1\n'
230+
'echo \'{"addon":"premium","column":1,"errorId":"misra-c-2012-1.1","extra":"","file":"file.cpp",'
231+
'"flags":["--premium=misra-c-2012"],"linenr":1,"message":"Some message","severity":"style"}\'\n')
232+
233+
exitcode, stdout, stderr = cppcheck(['--errorlist'], cppcheck_exe=exe)
234+
assert exitcode == 0, stdout
235+
assert stderr == ''
236+
errors = ElementTree.fromstring(stdout).findall('errors/error')
237+
ids = [e.get('id') for e in errors]
238+
assert 'nullPointer' in ids
239+
premium = [e for e in errors if e.get('id') == 'premium-misra-c-2012-1.1']
240+
assert len(premium) == 1
241+
assert premium[0].get('severity') == 'style'
242+
assert premium[0].get('msg') == 'Some message'
243+
244+
245+
@pytest.mark.skipif(sys.platform == 'win32', reason='uses a shell script as addon executable')
246+
def test_errorlist_failure(tmpdir):
247+
exe = __copy_cppcheck_premium(tmpdir)
248+
__add_premiumaddon(exe, tmpdir, 'echo "something went wrong"\nexit 1\n')
249+
250+
exitcode, stdout, _ = cppcheck(['--errorlist'], cppcheck_exe=exe)
251+
assert exitcode == 1, stdout
252+
assert "Failed to execute addon 'premiumaddon.json' - exitcode is 1" in stdout
253+
assert 'something went wrong' in stdout
254+
assert '<results' not in stdout

0 commit comments

Comments
 (0)