Disable or enable warnings for cppcheck using a configuration file - c++

With clang-tidy static analyzer I can keep a file (.clang-tidy) in the root of the project with the warnings I want to activate or deactivate.
clang-tidy will look for this file (as far I know) and use the options defined there. This saves me from hard coding long command lines in CMake or Makefiles.
Is it possible to do the same with cppcheck static analyzer?
Currently I have this very long command line hardcoded:
cppcheck --max-ctu-depth=3 --enable=all --inline-suppr --suppress=*:*thrust/complex* --suppress=missingInclude --suppress=syntaxError --suppress=unmatchedSuppression --suppress=preprocessorErrorDirective --language=c++ --std=c++14 --error-exitcode=666
This is an example of .clang-tidy configuration file that I keep at the root of a project:
---
Checks: '
*,
-readability-magic-numbers,
-modernize-use-nodiscard,
-altera-struct-pack-align,
-cert-err58-cpp,
-cppcoreguidelines-avoid-non-const-global-variables,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-pro-type-vararg,
-cppcoreguidelines-avoid-magic-numbers,
-fuchsia-default-arguments-calls,
-fuchsia-trailing-return,
-fuchsia-statically-constructed-objects,
-fuchsia-overloaded-operator,
-hicpp-vararg,
-hicpp-no-array-decay,
-llvm-header-guard,
-llvmlibc-restrict-system-libc-headers,
-llvmlibc-implementation-in-namespace,
-llvmlibc-callee-namespace
'
WarningsAsErrors: '*'
HeaderFilterRegex: '.'
AnalyzeTemporaryDtors: false
FormatStyle: file
...

You can store the configuration in a *.cppcheck file and then use the --project command line option to run the check. See the manual - Cppcheck GUI project section.
cppcheck files are normally generated by CppCheckGUI via File -> New project file. The exact syntax is undocumented but it's basically just an XML file and looks to be fairly straightforward if you want to create the file directly without using the GUI.
Sample test.cppcheck file:
<?xml version="1.0" encoding="UTF-8"?>
<project version="1">
<builddir>test2-cppcheck-build-dir</builddir>
<platform>Unspecified</platform>
<analyze-all-vs-configs>false</analyze-all-vs-configs>
<check-headers>true</check-headers>
<check-unused-templates>false</check-unused-templates>
<max-ctu-depth>10</max-ctu-depth>
<exclude>
<path name="WINDOWS/"/>
</exclude>
<suppressions>
<suppression>IOWithoutPositioning</suppression>
</suppressions>
</project>

Related

How to dump CLion's default clang-tidy configuration?

I want to use the default configuration of enabled/disabled checks from CLion (with some small changes) and I want to enforce it when building my application.
Enforcing clang-tidy works perfectly by using the cmake directive for clang-tidy, for example with all checks enabled:
set(CMAKE_CXX_CLANG_TIDY clang-tidy;
-checks=*,
-warnings-as-errors=*;
)
The default list of enabled and disabled checks in CLion can be found on the website but not in a machine readable way.
Is it possible to dump the config that CLion uses, like it is for clang-format, because the clang-tidy executable provides the option -dump-config? If so, how?
yes it is possible to dump the config but very hard to-do. I had to run the code analyzer on a large project and by luck capture the commandline arguments.
C:\Users\peter\AppData\Local\JetBrains\Toolbox\apps\CLion\ch-0\211.7628.27\bin\clang\win\clang-tidy.exe -config='"{\"Checks\":\"-*,bugprone-argument-comment,bugprone-assert-side-effect,bugprone-bad-signal-to-kill-thread,bugprone-branch-clone,bugprone-copy-constructor-init,bugprone-dangling-handle,bugprone-dynamic-static-initializers,bugprone-fold-init-type,bugprone-forward-declaration-namespace,bugprone-forwarding-reference-overload,bugprone-inaccurate-erase,bugprone-incorrect-roundings,bugprone-integer-division,bugprone-lambda-function-name,bugprone-macro-parentheses,bugprone-macro-repeated-side-effects,bugprone-misplaced-operator-in-strlen-in-alloc,bugprone-misplaced-pointer-arithmetic-in-alloc,bugprone-misplaced-widening-cast,bugprone-move-forwarding-reference,bugprone-multiple-statement-macro,bugprone-no-escape,bugprone-not-null-terminated-result,bugprone-parent-virtual-call,bugprone-posix-return,bugprone-reserved-identifier,bugprone-sizeof-container,bugprone-sizeof-expression,bugprone-spuriously-wake-up-functions,bugprone-string-constructor,bugprone-string-integer-assignment,bugprone-string-literal-with-embedded-nul,bugprone-suspicious-enum-usage,bugprone-suspicious-include,bugprone-suspicious-memset-usage,bugprone-suspicious-missing-comma,bugprone-suspicious-semicolon,bugprone-suspicious-string-compare,bugprone-swapped-arguments,bugprone-terminating-continue,bugprone-throw-keyword-missing,bugprone-too-small-loop-variable,bugprone-undefined-memory-manipulation,bugprone-undelegated-constructor,bugprone-unhandled-self-assignment,bugprone-unused-raii,bugprone-unused-return-value,bugprone-use-after-move,bugprone-virtual-near-miss,cert-dcl21-cpp,cert-dcl58-cpp,cert-err34-c,cert-err52-cpp,cert-err58-cpp,cert-err60-cpp,cert-flp30-c,cert-msc50-cpp,cert-msc51-cpp,cert-str34-c,cppcoreguidelines-interfaces-global-init,cppcoreguidelines-narrowing-conversions,cppcoreguidelines-pro-type-member-init,cppcoreguidelines-pro-type-static-cast-downcast,cppcoreguidelines-slicing,google-default-arguments,google-explicit-constructor,google-runtime-operator,hicpp-exception-baseclass,hicpp-multiway-paths-covered,misc-misplaced-const,misc-new-delete-overloads,misc-no-recursion,misc-non-copyable-objects,misc-throw-by-value-catch-by-reference,misc-unconventional-assign-operator,misc-uniqueptr-reset-release,modernize-avoid-bind,modernize-concat-nested-namespaces,modernize-deprecated-headers,modernize-deprecated-ios-base-aliases,modernize-loop-convert,modernize-make-shared,modernize-make-unique,modernize-pass-by-value,modernize-raw-string-literal,modernize-redundant-void-arg,modernize-replace-auto-ptr,modernize-replace-disallow-copy-and-assign-macro,modernize-replace-random-shuffle,modernize-return-braced-init-list,modernize-shrink-to-fit,modernize-unary-static-assert,modernize-use-auto,modernize-use-bool-literals,modernize-use-emplace,modernize-use-equals-default,modernize-use-equals-delete,modernize-use-nodiscard,modernize-use-noexcept,modernize-use-nullptr,modernize-use-override,modernize-use-transparent-functors,modernize-use-uncaught-exceptions,mpi-buffer-deref,mpi-type-mismatch,openmp-use-default-none,performance-faster-string-find,performance-for-range-copy,performance-implicit-conversion-in-loop,performance-inefficient-algorithm,performance-inefficient-string-concatenation,performance-inefficient-vector-operation,performance-move-const-arg,performance-move-constructor-init,performance-no-automatic-move,performance-noexcept-move-constructor,performance-trivially-destructible,performance-type-promotion-in-math-fn,performance-unnecessary-copy-initialization,performance-unnecessary-value-param,portability-simd-intrinsics,readability-avoid-const-params-in-decls,readability-const-return-type,readability-container-size-empty,readability-convert-member-functions-to-static,readability-delete-null-pointer,readability-deleted-default,readability-inconsistent-declaration-parameter-name,readability-make-member-function-const,readability-misleading-indentation,readability-misplaced-array-index,readability-non-const-parameter,readability-redundant-control-flow,readability-redundant-declaration,readability-redundant-function-ptr-dereference,readability-redundant-smartptr-get,readability-redundant-string-cstr,readability-redundant-string-init,readability-simplify-subscript-expr,readability-static-accessed-through-instance,readability-static-definition-in-anonymous-namespace,readability-string-compare,readability-uniqueptr-delete-release,readability-use-anyofallof,-clion-*\",\"CheckOptions\":[]}"' -dump-config > clion.yml
this is the command I used to dump it to yaml format. And the output of the command can be seen here in this gist https://gist.github.com/jfm535/7581ccadbd539303d8bed2f46f973108
gist also contains the full list of supported options by clions clang-tidy
Copy the list of rules from Clion to a file named rules.txt:
Then:
clang-tidy -checks="$(cat rules.txt | tr '\n' ',' | sed 's/,$//')" --dump-config > .clang-tidy
Here is a gist with the result as the day of writing this: https://gist.github.com/ArnaudValensi/0d36639fb84b80ee57d0c3c977deb70e

Set debug/run environment variable in Visual Studio 2017 C++ project?

I'm trying to set automatically run/debug environmental variables for my project in Visual Studio.
I mean, is there any CMake or C++ code line to do this not needing to do it manually?
Here are the instructions how to do it manually (what I want to avoid).
Here there is an still unsolved question about how to do it with Cmake (seems not to be possible).
I also tried with setenv() and putenv() in different ways but it didn't work, because the main function doesn't even run until that line of code, before an error message shows up: "Some.dll was not found" and the program stops.
If your dll is one you are intending to use, this answer details how to quickly ensure it is found at runtime (putting the DLL alongside the executable)
If by 'automatic' you mean in code, you can set environment variables in code using _putenv as described in this answer similar to what you seem to be describing.
ostringstream classSize;
classSize << "classSize=" << howManyInClass;
_putenv(classSize.str().c_str());
The solution I found is base on this answer.
Steps for the solution:
Create a UserTemplate.vcxproj.user file next to the CMakeLists.txt file, with the next content:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<LocalDebuggerEnvironment>PATH=..\Your\Path\to\Binaries;%PATH%".</LocalDebuggerEnvironment>
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
Where ..\Your\Path\to\Binaries is the relative path to your binary
files (the two points at the beginning .. are optional, if you
want to go up in the relative directory path, you may want to use
them).
Add the next lines of code in the CMakeLists.txt file.
# Configure the template file
SET(USER_FILE main.vcxproj.user)
SET(OUTPUT_PATH ${CMAKE_CURRENT_BINARY_DIR}/${USER_FILE})
CONFIGURE_FILE(UserTemplate.vcxproj.user ${USER_FILE} #ONLY)
Where ProjectName is the name of the VS project where you want to define your PATH variable.

Sonarqube ignore test execution data

I'm trying to import generic test execution with sonar.testExecutionReportPaths.
I'm using the xml file format provided in the doc.
I use full path to the file in the path attribute. And files exist.
I don't understand why my files are ignored. Any idea ?
sonar.testExecutionReportPaths = "C:\Program Files (x86)\Jenkins\workspace\CI\Sonarqube.xml"
sonar.test.inclusions = "**\*Test*.cs"
Here is the log from Sonar Runner:
INFO: Sensor Generic Test Executions Report
INFO: Parsing C:\Program Files (x86)\Jenkins\workspace\CI\Sonarqube.xml
WARNING: WARN: Property 'sonar.genericcoverage.unitTestReportPaths' is deprecated. Please use 'sonar.testExecutionReportPaths' instead.
INFO: Imported test execution data for 0 files
INFO: Test execution data ignored for 5 unknown files, including:
C:\Program Files (x86)\Jenkins\workspace\CI\Tests\A-Test.cs
C:\Program Files (x86)\Jenkins\workspace\CI\Tests\B-Tests.cs
C:\Program Files (x86)\Jenkins\workspace\CI\Tests\C-Tests.cs
C:\Program Files (x86)\Jenkins\workspace\CI\Tests\D-Test.cs
C:\Program Files (x86)\Jenkins\workspace\CI\Tests\E-Test.cs
INFO: Sensor Generic Test Executions Report (done) | time=265ms
Here is the a part of the Generic XMl File:
<testExecutions version="1">
<file path="C:\Program Files (x86)\Jenkins\workspace\CI\Tests\A-Test.cs">
<testCase name="My A Test" duration="1210" />
</file>
<file path="C:\Program Files (x86)\Jenkins\workspace\CI\Tests\B-Tests.cs">
<testCase name="My B Test" duration="566" />
</file>
</testExecutions>
Thank you!
What did it for me was adding:
sonar.testExecutionReportPaths=coverage/test-report.xml
sonar.tests=src
sonar.test.inclusions=**/*.spec.ts to my sonar-project.properties file. "sonarqube-scanner-node".
Basically, you need to confirm those parts if you want to make the sonar unit test count show correctly, it must be one of the error
Add config sonar.testExecutionReportPaths=xx/test-report.xml to properties and make sure the path is correct.
Check your test-report.xml file field and path content(file path="C:\Program Files (x86)\Jenkins\workspace\CI\Tests\A-Test.cs"), make sure the path is the same as the file in your local or server, for example, if you run this inside docker, you need to check the A-Test.cs file path in the docker container, whether it's the with the defined path in xml file.
Finally, I solved my problem by doing this check, hopefully, it can help you.
And there are some tips from standard documentation here
* The root node should be named testExecutions.
* Its version attribute should be set to 1.
* Insert a file element for each test file.
* Its path attribute can be either absolute or relative to the root of the module.
BTW, there is a warning in your sonar log:
WARNING: WARN: Property 'sonar.genericcoverage.unitTestReportPaths' is deprecated. Please use 'sonar.testExecutionReportPaths' instead.
But I can see you already use the testExecutionReportPaths, you may need to check whether sonar run the lasted version of settings and the option soanr56x is false in your package.json config.

How to set SAFESEH linker option using MSBuild command line

I am trying to build my C++ project created in VS2008 and upgraded to VS2013 using MSBuild.
I am referencing 3 third party dlls.
In the project settings I'm using /SAFESEH:NO. With this setting when I build my project in Visual Studio, it successfully builds.
An issue arises when I build the same project using MSBuild, error as follows: error LNK2026: module unsafe for SAFESEH image
Build command:
"C:\Program Files (x86)\MSBuild\12.0\bin\MSBuild.exe" TI.sln /t:ReBuild /p:configuration=Release /p:Platform="Win32" /p:ToolVersion="12.0" /p:SAFESEH="NO"
Please suggest me a solution
/SAFESEH:NO shown in the project settings is very different from passing an msbuild property named SAFESEH and set it to "NO": /SAFESEH is a linker command line option and there is no direct relation to msbuild properties. Instead in an msbuild project file the linker options are specified in the ItemDefinitionGroup called Link so if you open the file in a text editor you'll see something like
<ItemDefinitionGroup>
<Link>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
Now if your project doesn't build without SAFESEH truned off, I don't see why you wouldn't permanently configure it that way in the project settings. It also has the benefit it'll build from VS and command line without additional configuration.
If for some reason you cannot do that there are a couple of options. First one is basically the same as my answer to the question on how to set compiler options via the command line: create a file, say c:\nosafeseh.props, containing
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemDefinitionGroup>
<Link>
<ImageHasSafeExceptionHandlers>false</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
</Project>
then put it to use by calling
msbuild TI.sln /p:ForceImportBeforeCppTargets=c:\nosafeseh.props
Another option is to 'translate' a property into the ItemDefinitionGroup entry. Open the project file using a text editor and add these lines, in the same location where VS would put the linker options, ususally right before the line with '':
<ItemDefinitionGroup>
<Link>
<ImageHasSafeExceptionHandlers Conditon="'$(SafeSeh)'!='">$(SafeSeh)</ImageHasSafeExceptionHandlers>
</Link>
</ItemDefinitionGroup>
This sets the value of ImageHasSafeExceptionHandlers to the value of the property named SafeSeh (this is an arbitrary name, you can select whatever you want), and only if that property is defined and has a value. So, to set it to false, you'd call
msbuild TI.sln /p:SafeSeh=False

Checkstyle suppressions: what am I doing wrong?

I'm using checkstyle on the commandline. Not in Maven or ANT.
I've defined a suppressions.xml file and referenced it from my -c CheckstyleConfig.xml.
Checkstyle runs (no parsing errors), but it isn't suppressing anything.
I'm trying to make Checkstyle ignore .class files. Here is the content of my suppression.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://www.puppycrawl.com/dtds/suppressions_1_1.dtd">
<suppressions>
<suppress checks="." files="(.*\.class)"/>
</suppressions>
Any ideas on what I'm doing wrong? Checkstyle is still processing .class files.
Thanks.
Checkstyle does not work on class files, it cannot parse them. Checkstyle works on Java source code, which are files that end with ".java".
So, the problem is your regular expression to suppress errors. The suppression should be:
<suppress checks="." files="(.*\.java)"/>
Checkstyle works on whatever you feed it. A default eclipse-cs installation will only feed it Java files and property files, but since you're running from the command line, you'll have to exclude the .class files from checking or suppress the warnings.
It is better to exclude the .class files from checking (so that Checkstyle never sees them), because it will save you time.
But if you want to suppress the warnings, you can do that, too. The files regex in a suppressions.xml is greedy, so .* already covers the whole file name, and the pattern in your example never matches. Try this syntax (suppressing all .class files):
<suppressions>
<suppress checks=".*" files="\.class$" />
</suppressions>