www.luxoft.com
C++ static code analysis
Last update 2 Jul 2016
www.luxoft.com
What is static code analysis?
 Static program analysis is the analysis of computer software that is performed without actually
executing programs (Wikipedia)
www.luxoft.com
Why do we need static code analysis
Save money
Improve relations in the team
Boost developers self-concept
www.luxoft.com
Project to analyse
 Open source
 C++ code base
 About 20 developers team
 Cross platform (Linux, QNX, Windows, Qt)
 SmartDeviceLink https://github.com/smartdevicelink/sdl_core/
SmartDeviceLink (SDL) is a standard set of protocols and messages that connect applications on a
smartphone to a vehicle head unit.
www.luxoft.com
CppCheck
Cppcheck is a static analysis tool for C/C++ code. Unlike C/C++ compilers and many other analysis
tools it does not detect syntax errors in the code. Cppcheck primarily detects the types of bugs that
the compilers normally do not detect. The goal is to detect only real errors in the code (i.e. have zero
false positives).
Cppcheck is a static analysis tool for C/C++ code.
 Free, open source
 Easy to use
 Perform analysis on local workstation
 Console plain text output
 A lot of plugins for most of IDE
www.luxoft.com
Cppcheck simple output
$ cppcheck -q --template='{id} {file}:{line} {message}' ./src/components
memleak mobile_message_handler.cc:161 Memory leak: outgoing_message
resourceLeak ini_file.cc:199 Resource leak: rd_fp
resourceLeak ini_file.cc:205 Resource leak: rd_fp
syntaxError sql_pt_representation.cc:76 Invalid number of character '(' when these macros are
defined: '__QNX__'.
memleak bluetooth_device_scanner_posix.cc:100 Memory leak: buffer
mismatchAllocDealloc file_system_win.cc:357 Mismatching allocation and deallocation:
security_descriptor
www.luxoft.com
Check compilence
SQLPTRepresentation::SQLPTRepresentation()
#if defined(__QNX__)
: db_(new utils::dbms::SQLDatabase(kDatabaseName)
#else
: db_(new utils::dbms::SQLDatabase(
file_system::ConcatPath(app_storage_folder, kDatabaseName),
"PolicyDatabase"))
#endif
{}
www.luxoft.com
Dummy errors
uint8_t* security_descriptor = new uint8_t[length];
…
delete security_descriptor;
www.luxoft.com
Cpp check analyse statistic
cppcheck -q --force --enable=all --template='{id} {file}:{line} {message}' ./src/components 2>&1 | grep -v test | tee ../cpp_check_output
cat cpp_check_output | awk '{print $1}' | sort | uniq -c | sort
1 knownConditionTrueFalse
1 mismatchAllocDealloc
1 missingInclude
1 noConstructor
1 syntaxError
1 unsignedLessThanZero
2 asctimeCalled
2 clarifyCondition
2 memleak
2 resourceLeak
2 sizeofDivisionMemfunc
2 unreachableCode
3 oppositeInnerCondition
3 passedByValue
4 duplicateBreak
4 uninitMemberVar
7 postfixOperator
8 unreadVariable
13 redundantAssignment
14 noExplicitConstructor
19 variableScope
26 unusedFunction
www.luxoft.com
unsignedLessThanZero

 const uint32_t packet_size = GetPacketSize(header_);
 if (packet_size <= 0) {
www.luxoft.com
False positive oppositeInnerCondition
if (!db_->Open()) {
...
for (int i = 0; i < attempts; ++i) {
usleep(sleep_interval_mcsec);
if (db_->Open()) {
...
}
}
www.luxoft.com
passedByValue
class FromMicToFileRecorderThread::Impl {
public:
Impl(const std::string oKey_,
const std::string tKey_,
const std::string outputFileName,
int32_t duration);
...
};
www.luxoft.com
Dummy errors
if (some_condition) {
return true;
break;
}
bool SQLDatabase::IsReadWrite() {
return sqlite3_db(conn_);
return true;
}
DWORD addressSize = sizeof(addressAsString);
addressSize = sizeof(addressAsString);
www.luxoft.com
variableScope
bool SpeakRequest::IsWhiteSpaceExist() {
const char* str = NULL;
if ((*message_)[strings::msg_params].keyExists(strings::tts_chunks)) {
...
for (; it_tc != it_tc_end; ++it_tc) {
str = (*it_tc)[strings::text].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
SDL_ERROR("Invalid tts_chunks syntax check failed");
return true;
}
...
}
}
return false;
}
www.luxoft.com
Coverity
 Free for open source projects
 Perform analyse on cloud
 Privode delailed interctive online report
 Provides limitted analyses per week.
Coverity Scan is a free cloud-based static analysis product for the open source
community.
www.luxoft.com
Clang static code analisys
 Free open source
 Privode delailed interctive html report
 Require clan build
 Perform analyzing within compiling
 Support incremental analyse
The Clang Static Analyzer is a source code analysis tool that finds bugs in C, C++, and
Objective-C programs.
www.luxoft.com
Static code analyse is only one step
Code formating
Code review
Unit tests
Automated tests
Continious integration
Compile your code with different compilers
www.luxoft.com
THANK YOU

Александр Куцан: "Static Code Analysis in C++"

  • 1.
    www.luxoft.com C++ static codeanalysis Last update 2 Jul 2016
  • 2.
    www.luxoft.com What is staticcode analysis?  Static program analysis is the analysis of computer software that is performed without actually executing programs (Wikipedia)
  • 3.
    www.luxoft.com Why do weneed static code analysis Save money Improve relations in the team Boost developers self-concept
  • 4.
    www.luxoft.com Project to analyse Open source  C++ code base  About 20 developers team  Cross platform (Linux, QNX, Windows, Qt)  SmartDeviceLink https://github.com/smartdevicelink/sdl_core/ SmartDeviceLink (SDL) is a standard set of protocols and messages that connect applications on a smartphone to a vehicle head unit.
  • 5.
    www.luxoft.com CppCheck Cppcheck is astatic analysis tool for C/C++ code. Unlike C/C++ compilers and many other analysis tools it does not detect syntax errors in the code. Cppcheck primarily detects the types of bugs that the compilers normally do not detect. The goal is to detect only real errors in the code (i.e. have zero false positives). Cppcheck is a static analysis tool for C/C++ code.  Free, open source  Easy to use  Perform analysis on local workstation  Console plain text output  A lot of plugins for most of IDE
  • 6.
    www.luxoft.com Cppcheck simple output $cppcheck -q --template='{id} {file}:{line} {message}' ./src/components memleak mobile_message_handler.cc:161 Memory leak: outgoing_message resourceLeak ini_file.cc:199 Resource leak: rd_fp resourceLeak ini_file.cc:205 Resource leak: rd_fp syntaxError sql_pt_representation.cc:76 Invalid number of character '(' when these macros are defined: '__QNX__'. memleak bluetooth_device_scanner_posix.cc:100 Memory leak: buffer mismatchAllocDealloc file_system_win.cc:357 Mismatching allocation and deallocation: security_descriptor
  • 7.
    www.luxoft.com Check compilence SQLPTRepresentation::SQLPTRepresentation() #if defined(__QNX__) :db_(new utils::dbms::SQLDatabase(kDatabaseName) #else : db_(new utils::dbms::SQLDatabase( file_system::ConcatPath(app_storage_folder, kDatabaseName), "PolicyDatabase")) #endif {}
  • 8.
    www.luxoft.com Dummy errors uint8_t* security_descriptor= new uint8_t[length]; … delete security_descriptor;
  • 9.
    www.luxoft.com Cpp check analysestatistic cppcheck -q --force --enable=all --template='{id} {file}:{line} {message}' ./src/components 2>&1 | grep -v test | tee ../cpp_check_output cat cpp_check_output | awk '{print $1}' | sort | uniq -c | sort 1 knownConditionTrueFalse 1 mismatchAllocDealloc 1 missingInclude 1 noConstructor 1 syntaxError 1 unsignedLessThanZero 2 asctimeCalled 2 clarifyCondition 2 memleak 2 resourceLeak 2 sizeofDivisionMemfunc 2 unreachableCode 3 oppositeInnerCondition 3 passedByValue 4 duplicateBreak 4 uninitMemberVar 7 postfixOperator 8 unreadVariable 13 redundantAssignment 14 noExplicitConstructor 19 variableScope 26 unusedFunction
  • 10.
    www.luxoft.com unsignedLessThanZero   const uint32_tpacket_size = GetPacketSize(header_);  if (packet_size <= 0) {
  • 11.
    www.luxoft.com False positive oppositeInnerCondition if(!db_->Open()) { ... for (int i = 0; i < attempts; ++i) { usleep(sleep_interval_mcsec); if (db_->Open()) { ... } }
  • 12.
    www.luxoft.com passedByValue class FromMicToFileRecorderThread::Impl { public: Impl(conststd::string oKey_, const std::string tKey_, const std::string outputFileName, int32_t duration); ... };
  • 13.
    www.luxoft.com Dummy errors if (some_condition){ return true; break; } bool SQLDatabase::IsReadWrite() { return sqlite3_db(conn_); return true; } DWORD addressSize = sizeof(addressAsString); addressSize = sizeof(addressAsString);
  • 14.
    www.luxoft.com variableScope bool SpeakRequest::IsWhiteSpaceExist() { constchar* str = NULL; if ((*message_)[strings::msg_params].keyExists(strings::tts_chunks)) { ... for (; it_tc != it_tc_end; ++it_tc) { str = (*it_tc)[strings::text].asCharArray(); if (strlen(str) && !CheckSyntax(str)) { SDL_ERROR("Invalid tts_chunks syntax check failed"); return true; } ... } } return false; }
  • 15.
    www.luxoft.com Coverity  Free foropen source projects  Perform analyse on cloud  Privode delailed interctive online report  Provides limitted analyses per week. Coverity Scan is a free cloud-based static analysis product for the open source community.
  • 16.
    www.luxoft.com Clang static codeanalisys  Free open source  Privode delailed interctive html report  Require clan build  Perform analyzing within compiling  Support incremental analyse The Clang Static Analyzer is a source code analysis tool that finds bugs in C, C++, and Objective-C programs.
  • 17.
    www.luxoft.com Static code analyseis only one step Code formating Code review Unit tests Automated tests Continious integration Compile your code with different compilers
  • 18.