Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix #11797 crash on missing/renamed files #5921

Closed
wants to merge 13 commits into from
Closed
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
49 changes: 23 additions & 26 deletions lib/cppcheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -551,6 +551,14 @@ unsigned int CppCheck::checkClang(const FileWithDetails &file)
return mExitCode;
}

static ErrorMessage makeError(const std::string &filename, int line, unsigned int column, const std::string &msg, const std::string &id)
{
const ErrorMessage::FileLocation loc1(filename, line, column);
const std::list<ErrorMessage::FileLocation> callstack(1, loc1);

return ErrorMessage(callstack, emptyString, Severity::error, msg, id, Certainty::normal);
}

unsigned int CppCheck::check(const FileWithDetails &file)
{
if (mSettings.clang)
Expand All @@ -570,7 +578,6 @@ unsigned int CppCheck::check(const FileSettings &fs)
// TODO: move to constructor when CppCheck no longer owns the settings
if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck)
mUnusedFunctionsCheck.reset(new CheckUnusedFunctions());

CppCheck temp(mErrorLogger, mUseGlobalSuppressions, mExecuteCommand);
temp.mSettings = mSettings;
if (!temp.mSettings.userDefines.empty())
Expand Down Expand Up @@ -622,8 +629,6 @@ unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string
if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck)
mUnusedFunctionsCheck.reset(new CheckUnusedFunctions());

mExitCode = 0;
danmar marked this conversation as resolved.
Show resolved Hide resolved

if (Settings::terminated())
return mExitCode;

Expand Down Expand Up @@ -688,16 +693,20 @@ unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string
std::string locfile = Path::fromNativeSeparators(output.location.file());
if (mSettings.relativePaths)
locfile = Path::getRelativePath(locfile, mSettings.basePaths);

ErrorMessage::FileLocation loc1(locfile, output.location.line, output.location.col);

ErrorMessage errmsg({std::move(loc1)},
"", // TODO: is this correct?
Severity::error,
output.msg,
"syntaxError",
Certainty::normal);
reportErr(errmsg);
if (output.type == simplecpp::Output::Type::FILE_NOT_FOUND) {
const std::string fixedpath = Path::toNativeSeparators(file.path());
danmar marked this conversation as resolved.
Show resolved Hide resolved
const std::string errorMsg("File " + fixedpath + " does not exist. Skipping file.");

reportErr(ErrorMessage(std::list<ErrorMessage::FileLocation> (),
emptyString,
Severity::error,
errorMsg,
"fileNotFound",
Certainty::normal));
}
else {
reportErr(makeError(file.path(), output.location.line, output.location.col, output.msg, "syntaxError"));
danmar marked this conversation as resolved.
Show resolved Hide resolved
}
return mExitCode;
}

Expand Down Expand Up @@ -757,7 +766,6 @@ unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string
return mExitCode; // known results => no need to reanalyze file
}
}

FilesDeleter filesDeleter;

// write dump file xml prolog
Expand Down Expand Up @@ -1027,18 +1035,7 @@ unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string
// TODO: replace with ErrorMessage::fromInternalError()
void CppCheck::internalError(const std::string &filename, const std::string &msg)
{
const std::string fullmsg("Bailing out from analysis: " + msg);

ErrorMessage::FileLocation loc1(filename, 0, 0);

ErrorMessage errmsg({std::move(loc1)},
emptyString,
Severity::error,
fullmsg,
"internalError",
Certainty::normal);

mErrorLogger.reportErr(errmsg);
mErrorLogger.reportErr(makeError(filename, 0, 0U, "Bailing out from analysis:" + msg, "internalError"));
}

//---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions lib/errorlogger.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
const std::set<std::string> ErrorLogger::mCriticalErrorIds{
"cppcheckError",
"cppcheckLimit",
"fileNotFound",
"internalAstError",
"instantiationError",
"internalError",
Expand Down
133 changes: 133 additions & 0 deletions test/cli/more-projects_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,3 +864,136 @@ def test_shared_items_project(tmpdir = ""):
# Assume no errors, and that shared items code files have been checked as well
assert any('2/2 files checked 100% done' in x for x in lines)
assert stderr == ''


def test_project_missing_files(tmpdir):
filename = os.path.join(tmpdir, 'main.c')
project_file = os.path.join(tmpdir, 'helloworld.vcxproj')
with open(project_file, 'wt') as f:
f.write(
"""<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>15.0</VCProjectVersion>
<ProjectGuid>{7319858B-261C-4F0D-B022-92BB896242DD}</ProjectGuid>
<RootNamespace>invalidProjet</RootNamespace>
<WindowsTargetPlatformVersion>10.0.16299.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v141</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>MultiByte</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.c" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>""")
ret, _, stderr = cppcheck(['--template=cppcheck1', '--project=' + os.path.join(tmpdir, 'helloworld.vcxproj')])
assert ret == 0
assert stderr == ': (error) File {} does not exists. Skipping file.\n'.format(filename)
12 changes: 12 additions & 0 deletions test/testcppcheck.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class TestCppcheck : public TestFixture {
void run() override {
TEST_CASE(getErrorMessages);
TEST_CASE(checkWithFile);
TEST_CASE(checkWithoutFile);
TEST_CASE(checkWithFS);
TEST_CASE(suppress_error_library);
TEST_CASE(unique_errors);
Expand Down Expand Up @@ -112,6 +113,17 @@ class TestCppcheck : public TestFixture {
ASSERT_EQUALS("nullPointer", *errorLogger.ids.cbegin());
}

void checkWithoutFile() const
{
ErrorLogger2 errorLogger;
CppCheck cppcheck(errorLogger, false, {});
ASSERT_EQUALS(1, cppcheck.check(FileWithDetails("NotAFile")));

ASSERT_EQUALS(1, errorLogger.ids.size());
ASSERT_EQUALS("fileNotFound", *errorLogger.ids.cbegin());
ASSERT_EQUALS("File NotAFile does not exists. Skipping file.", errorLogger.errmsgs.cbegin()->shortMessage());
}

void checkWithFS() const
{
ScopedFile file("test.cpp",
Expand Down
26 changes: 14 additions & 12 deletions test/testsuppressions.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1190,8 +1190,9 @@ class TestSuppressions : public TestFixture {
ASSERT_EQUALS("", settings.supprs.nomsg.addSuppressionLine("uninitvar"));
settings.exitCode = 1;

const char code[] = "int f() { int a; return a; }";
ASSERT_EQUALS(0, cppCheck.check(FileWithDetails("test.c"), code)); // <- no unsuppressed error is seen
ScopedFile file("test.c", "int f() { int a; return a; }");
FileSettings fs{file.path()};
ASSERT_EQUALS(0, cppCheck.check(fs)); // <- no unsuppressed error is seen
ASSERT_EQUALS("[test.c:1]: (error) Uninitialized variable: a\n", errout_str()); // <- report error so ThreadExecutor can suppress it and make sure the global suppression is matched.
}

Expand Down Expand Up @@ -1223,16 +1224,17 @@ class TestSuppressions : public TestFixture {
settings.inlineSuppressions = true;
settings.relativePaths = true;
settings.basePaths.emplace_back("/somewhere");
const char code[] =
"struct Point\n"
"{\n"
" // cppcheck-suppress unusedStructMember\n"
" int x;\n"
" // cppcheck-suppress unusedStructMember\n"
" int y;\n"
"};";
ASSERT_EQUALS(0, cppCheck.check(FileWithDetails("/somewhere/test.cpp"), code));
ASSERT_EQUALS("",errout_str());
ScopedFile file("test.cpp",
"struct Point\n"
"{\n"
" // cppcheck-suppress unusedStructMember\n"
" int x;\n"
" // cppcheck-suppress unusedStructMember\n"
" int y;\n"
"};");
FileSettings fs{file.path()};
ASSERT_EQUALS(0, cppCheck.check(fs));
ASSERT_EQUALS("", errout_str());
}

void suppressingSyntaxErrorsInternal(unsigned int (TestSuppressions::*check)(const char[], const std::string &)) { // syntaxErrors should be suppressible (#7076)
Expand Down
Loading