Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -700,7 +700,7 @@ $(libcppdir)/vfvalue.o: lib/vfvalue.cpp lib/config.h lib/errortypes.h lib/mathli
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
$(CXX) ${INCLUDE_FOR_FE} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ frontend/frontend.cpp

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
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
$(CXX) ${INCLUDE_FOR_CLI} $(CPPFLAGS) $(CXXFLAGS) -c -o $@ cli/cmdlineparser.cpp

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
Expand Down
41 changes: 39 additions & 2 deletions cli/cmdlineparser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "color.h"
#include "config.h"
#include "cppcheck.h"
#include "cppcheckexecutor.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filelister.h"
Expand Down Expand Up @@ -121,9 +122,13 @@ static bool addPathsToSet(const std::string& fileName, std::set<std::string>& se
namespace {
class XMLErrorMessagesLogger : public ErrorLogger
{
public:
explicit XMLErrorMessagesLogger(std::ostream &out) : mOut(out) {}

private:
void reportOut(const std::string & outmsg, Color /*c*/ = Color::Reset) override
{
std::cout << outmsg << std::endl;
mOut << outmsg << std::endl;
}

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

void reportProgress(const std::string & /*filename*/, const char /*stage*/[], const std::size_t /*value*/) override
{}

std::ostream &mOut;
};
}

Expand Down Expand Up @@ -377,9 +384,18 @@ CmdLineParser::Result CmdLineParser::parseFromArgs(int argc, const char* const a
// print all possible error messages..
if (std::strcmp(argv[i], "--errorlist") == 0) {
{
XMLErrorMessagesLogger xmlLogger;
// get the premium messages first so there is no partial output if that fails
std::ostringstream premiumErrors;
if (mSettings.premium) {
XMLErrorMessagesLogger premiumLogger(premiumErrors);
if (!getPremiumErrorMessages(premiumLogger))
return Result::Fail;
}

XMLErrorMessagesLogger xmlLogger(std::cout);
std::cout << ErrorMessage::getXMLHeader(mSettings.cppcheckCfgProductName, 2);
CppCheck::getErrorMessages(xmlLogger);
std::cout << premiumErrors.str();
std::cout << ErrorMessage::getXMLFooter(2) << std::endl;
}
return Result::Exit;
Expand Down Expand Up @@ -2233,6 +2249,27 @@ bool CmdLineParser::loadAddons(Settings& settings)
return result;
}

bool CmdLineParser::getPremiumErrorMessages(ErrorLogger &errorLogger)
{
for (const std::string &addon: mSettings.addons) {
AddonInfo addonInfo;
const std::string failedToGetAddonInfo = addonInfo.getAddonInfo(addon, mSettings.exename, mSettings.debuglookup || mSettings.debuglookupAddon);
if (!failedToGetAddonInfo.empty()) {
mLogger.printError(failedToGetAddonInfo);
return false;
}
if (addonInfo.name != "premiumaddon.json" || addonInfo.executable.empty())
continue;
try {
CppCheck::getAddonErrorMessages(addonInfo, errorLogger, CppCheckExecutor::executeCommand);
} catch (const InternalError &e) {
mLogger.printError(e.errorMessage + (e.details.empty() ? "" : "\n" + e.details));
return false;
}
}
return true;
}

bool CmdLineParser::loadCppcheckCfg()
{
if (!mSettings.settingsFiles.empty())
Expand Down
7 changes: 7 additions & 0 deletions cli/cmdlineparser.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
class Settings;
struct Suppressions;
class Library;
class ErrorLogger;

/// @addtogroup CLI
/// @{
Expand Down Expand Up @@ -152,6 +153,12 @@ class CmdLineParser {

bool loadCppcheckCfg();

/**
* @brief Get the error messages of the Cppcheck Premium addon
* @return Returns true if successful
*/
bool getPremiumErrorMessages(ErrorLogger &errorLogger);

void outputFormatOptionMixingError() const;

CmdLineLogger& mLogger;
Expand Down
4 changes: 2 additions & 2 deletions cli/cppcheckexecutor.h
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,13 @@ class CppCheckExecutor {
*/
int check(int argc, const char* const argv[]);

protected:

/**
* Execute a shell command and read the output from it. Returns exitcode of the executed command,.
*/
static int executeCommand(std::string exe, std::vector<std::string> args, std::string redirect, std::string &output_);

protected:

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

private:
Expand Down
120 changes: 75 additions & 45 deletions lib/cppcheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -453,46 +453,15 @@ static std::string detectPython(const CppCheck::ExecuteCmdFn &executeCommand)
/**
* @throws InternalError thrown when execution fails
*/
static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
const std::string &defaultPythonExe,
const std::string &file,
const std::string &premiumArgs,
const CppCheck::ExecuteCmdFn &executeCommand)
static std::vector<picojson::value> runAddonCommand(const std::string &addonName,
const std::string &exe,
const std::string &args,
const CppCheck::ExecuteCmdFn &executeCommand)
{
if (!executeCommand)
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");

std::string pythonExe;

if (!addonInfo.executable.empty())
pythonExe = addonInfo.executable;
else if (!addonInfo.python.empty())
pythonExe = cmdFileName(addonInfo.python);
else if (!defaultPythonExe.empty())
pythonExe = cmdFileName(defaultPythonExe);
else {
// store in static variable so we only look this up once - TODO: do not cache globally
static const std::string detectedPythonExe = detectPython(executeCommand);
if (detectedPythonExe.empty())
throw InternalError(nullptr, "Failed to auto detect python");
pythonExe = detectedPythonExe;
}

std::string args;
if (addonInfo.executable.empty())
args = cmdFileName(addonInfo.runScript) + " " + cmdFileName(addonInfo.scriptFile);
args += std::string(args.empty() ? "" : " ") + "--cli" + addonInfo.args;
if (!premiumArgs.empty() && !addonInfo.executable.empty())
args += " " + premiumArgs;

const bool is_file_list = (file.find(FILELIST) != std::string::npos);
const std::string fileArg = (is_file_list ? " --file-list " : " ") + cmdFileName(file);
args += fileArg;

std::string result;
if (const int exitcode = executeCommand(pythonExe, split(args), "2>&1", result)) {
std::string message("Failed to execute addon '" + addonInfo.name + "' - exitcode is " + std::to_string(exitcode));
std::string details = pythonExe + " " + args;
if (const int exitcode = executeCommand(exe, split(args), "2>&1", result)) {
std::string message("Failed to execute addon '" + addonName + "' - exitcode is " + std::to_string(exitcode));
std::string details = exe + " " + args;
if (result.size() > 2) {
details += "\nOutput:\n";
details += result;
Expand All @@ -511,34 +480,34 @@ static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
while (std::getline(istr, line)) {
// TODO: also bail out?
if (line.empty()) {
//std::cout << "addon '" << addonInfo.name << "' result contains empty line" << std::endl;
//std::cout << "addon '" << addonName << "' result contains empty line" << std::endl;
continue;
}

// TODO: get rid of this
if (startsWith(line,"Checking ")) {
//std::cout << "addon '" << addonInfo.name << "' result contains 'Checking ' line" << std::endl;
//std::cout << "addon '" << addonName << "' result contains 'Checking ' line" << std::endl;
continue;
}

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

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

//std::cout << "addon '" << addonInfo.name << "' result is " << line << std::endl;
//std::cout << "addon '" << addonName << "' result is " << line << std::endl;

// TODO: make these failures?
picojson::value res;
const std::string err = picojson::parse(res, line);
if (!err.empty()) {
//std::cout << "addon '" << addonInfo.name << "' result is not a valid JSON (" << err << ")" << std::endl;
//std::cout << "addon '" << addonName << "' result is not a valid JSON (" << err << ")" << std::endl;
continue;
}
if (!res.is<picojson::object>()) {
//std::cout << "addon '" << addonInfo.name << "' result is not a JSON object" << std::endl;
//std::cout << "addon '" << addonName << "' result is not a JSON object" << std::endl;
continue;
}
addonResult.emplace_back(std::move(res));
Expand All @@ -548,6 +517,48 @@ static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
return addonResult;
}

/**
* @throws InternalError thrown when execution fails
*/
static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo,
const std::string &defaultPythonExe,
const std::string &file,
const std::string &premiumArgs,
const CppCheck::ExecuteCmdFn &executeCommand)
{
if (!executeCommand)
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");

std::string pythonExe;

if (!addonInfo.executable.empty())
pythonExe = addonInfo.executable;
else if (!addonInfo.python.empty())
pythonExe = cmdFileName(addonInfo.python);
else if (!defaultPythonExe.empty())
pythonExe = cmdFileName(defaultPythonExe);
else {
// store in static variable so we only look this up once - TODO: do not cache globally
static const std::string detectedPythonExe = detectPython(executeCommand);
if (detectedPythonExe.empty())
throw InternalError(nullptr, "Failed to auto detect python");
pythonExe = detectedPythonExe;
}

std::string args;
if (addonInfo.executable.empty())
args = cmdFileName(addonInfo.runScript) + " " + cmdFileName(addonInfo.scriptFile);
args += std::string(args.empty() ? "" : " ") + "--cli" + addonInfo.args;
if (!premiumArgs.empty() && !addonInfo.executable.empty())
args += " " + premiumArgs;

const bool is_file_list = (file.find(FILELIST) != std::string::npos);
const std::string fileArg = (is_file_list ? " --file-list " : " ") + cmdFileName(file);
args += fileArg;

return runAddonCommand(addonInfo.name, pythonExe, args, executeCommand);
}

static std::string getDefinesFlags(const std::string &semicolonSeparatedString)
{
std::string flags;
Expand Down Expand Up @@ -1805,6 +1816,25 @@ void CppCheck::getErrorMessages(ErrorLogger &errorlogger)
SymbolDatabase::getErrorMessages(errorlogger);
}

void CppCheck::getAddonErrorMessages(const AddonInfo &addonInfo, ErrorLogger &errorlogger, const ExecuteCmdFn &executeCommand)
{
if (!executeCommand)
throw InternalError(nullptr, "Failed to execute addon - no command callback provided");

const std::vector<picojson::value> results = runAddonCommand(addonInfo.name, addonInfo.executable, "--cli --errorlist", executeCommand);

for (const picojson::value& res : results) {
// this is a copy so we can access missing fields and get a default value
picojson::object obj = res.get<picojson::object>();

ErrorMessage errmsg;
errmsg.id = obj["addon"].get<std::string>() + "-" + obj["errorId"].get<std::string>();
errmsg.setmsg(obj["message"].get<std::string>());
errmsg.severity = severityFromString(obj["severity"].get<std::string>());
errorlogger.reportErr(errmsg);
}
}

void CppCheck::analyseClangTidy(const FileSettings &fileSettings)
{
std::string allIncludes;
Expand Down
7 changes: 7 additions & 0 deletions lib/cppcheck.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class FileWithDetails;
class AnalyzerInformation;
class ErrorLogger;
class Settings;
struct AddonInfo;
struct Suppressions;
class Preprocessor;
class TimerResults;
Expand Down Expand Up @@ -132,6 +133,12 @@ class CPPCHECKLIB CppCheck {
*/
static void getErrorMessages(ErrorLogger &errorlogger);

/**
* @brief Get all error messages that an addon executable can report, by running it with --errorlist.
* @throws InternalError thrown when execution fails
*/
static void getAddonErrorMessages(const AddonInfo &addonInfo, ErrorLogger &errorlogger, const ExecuteCmdFn &executeCommand);

void tooManyConfigsError(const std::string &file, int numberOfConfigurations);

/** Analyse whole program, run this after all TUs has been scanned.
Expand Down
53 changes: 53 additions & 0 deletions test/cli/premium_test.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@

# python -m pytest premium_test.py

import json
import os
import re
import shutil
import sys
import time
from xml.etree import ElementTree

import pytest

from testutils import cppcheck, __lookup_cppcheck_exe

Expand Down Expand Up @@ -199,3 +203,52 @@ def test_hash(tmpdir):

_, _, stderr = cppcheck(args)
assert '<error id="a-id" severity="error" msg="bug" verbose="bug" hash="123" ' in stderr


def __add_premiumaddon(exe, tmpdir, script):
addon_exe = os.path.join(tmpdir, 'premiumaddon.sh')
with open(addon_exe, 'wt') as f:
f.write('#!/bin/sh\n' + script)
os.chmod(addon_exe, 0o755)

with open(os.path.join(tmpdir, 'premiumaddon.json'), 'wt') as f:
f.write(json.dumps({'executable': addon_exe}))

cfg_file = os.path.join(os.path.dirname(exe), 'cppcheck.cfg')
with open(cfg_file, 'rt') as f:
cfg = json.load(f)
cfg['addons'] = [os.path.join(tmpdir, 'premiumaddon.json')]
with open(cfg_file, 'wt') as f:
f.write(json.dumps(cfg))


@pytest.mark.skipif(sys.platform == 'win32', reason='uses a shell script as addon executable')
def test_errorlist(tmpdir):
exe = __copy_cppcheck_premium(tmpdir)
__add_premiumaddon(exe, tmpdir,
'[ "$*" = "--cli --errorlist" ] || exit 1\n'
'echo \'{"addon":"premium","column":1,"errorId":"misra-c-2012-1.1","extra":"","file":"file.cpp",'
'"flags":["--premium=misra-c-2012"],"linenr":1,"message":"Some message","severity":"style"}\'\n')

exitcode, stdout, stderr = cppcheck(['--errorlist'], cppcheck_exe=exe)
assert exitcode == 0, stdout
assert stderr == ''
errors = ElementTree.fromstring(stdout).findall('errors/error')
ids = [e.get('id') for e in errors]
assert 'nullPointer' in ids
premium = [e for e in errors if e.get('id') == 'premium-misra-c-2012-1.1']
assert len(premium) == 1
assert premium[0].get('severity') == 'style'
assert premium[0].get('msg') == 'Some message'


@pytest.mark.skipif(sys.platform == 'win32', reason='uses a shell script as addon executable')
def test_errorlist_failure(tmpdir):
exe = __copy_cppcheck_premium(tmpdir)
__add_premiumaddon(exe, tmpdir, 'echo "something went wrong"\nexit 1\n')

exitcode, stdout, _ = cppcheck(['--errorlist'], cppcheck_exe=exe)
assert exitcode == 1, stdout
assert "Failed to execute addon 'premiumaddon.json' - exitcode is 1" in stdout
assert 'something went wrong' in stdout
assert '<results' not in stdout
Loading