ID
int64 1
1.09k
| Language
stringclasses 1
value | Repository Name
stringclasses 8
values | File Name
stringlengths 3
35
| File Path in Repository
stringlengths 9
82
| File Path for Unit Test
stringclasses 5
values | Code
stringlengths 17
1.91M
| Unit Test - (Ground Truth)
stringclasses 5
values |
---|---|---|---|---|---|---|---|
801 | cpp | cppcheck | utils.h | lib/utils.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef utilsH
#define utilsH
//---------------------------------------------------------------------------
#include "config.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <initializer_list>
#include <limits>
#include <list>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <vector>
struct SelectMapKeys {
template<class Pair>
// NOLINTNEXTLINE(readability-const-return-type) - false positive
typename Pair::first_type operator()(const Pair& p) const {
return p.first;
}
};
struct SelectMapValues {
template<class Pair>
typename Pair::second_type operator()(const Pair& p) const {
return p.second;
}
};
struct OnExit {
std::function<void()> f;
~OnExit() {
f();
}
};
template<class Range, class T>
bool contains(const Range& r, const T& x)
{
return std::find(r.cbegin(), r.cend(), x) != r.cend();
}
template<class T>
bool contains(const std::initializer_list<T>& r, const T& x)
{
return std::find(r.begin(), r.end(), x) != r.end();
}
template<class T, class U>
bool contains(const std::initializer_list<T>& r, const U& x)
{
return std::find(r.begin(), r.end(), x) != r.end();
}
template<class T, class ... Ts>
inline std::array<T, sizeof...(Ts) + 1> makeArray(T x, Ts... xs)
{
return {std::move(x), std::move(xs)...};
}
// Enum hash for C++11. This is not needed in C++14
struct EnumClassHash {
template<typename T>
std::size_t operator()(T t) const
{
return static_cast<std::size_t>(t);
}
};
inline bool startsWith(const std::string& str, const char start[], std::size_t startlen)
{
return str.compare(0, startlen, start) == 0;
}
template<std::size_t N>
bool startsWith(const std::string& str, const char (&start)[N])
{
return startsWith(str, start, N - 1);
}
inline bool startsWith(const std::string& str, const std::string& start)
{
return startsWith(str, start.c_str(), start.length());
}
inline bool endsWith(const std::string &str, char c)
{
return !str.empty() && str.back() == c;
}
inline bool endsWith(const std::string &str, const char end[], std::size_t endlen)
{
return (str.size() >= endlen) && (str.compare(str.size()-endlen, endlen, end)==0);
}
template<std::size_t N>
bool endsWith(const std::string& str, const char (&end)[N])
{
return endsWith(str, end, N - 1);
}
inline static bool isPrefixStringCharLiteral(const std::string &str, char q, const std::string& p)
{
// str must be at least the prefix plus the start and end quote
if (str.length() < p.length() + 2)
return false;
// check for end quote
if (!endsWith(str, q))
return false;
// check for start quote
if (str[p.size()] != q)
return false;
// check for prefix
if (str.compare(0, p.size(), p) != 0)
return false;
return true;
}
inline static bool isStringCharLiteral(const std::string &str, char q)
{
// early out to avoid the loop
if (!endsWith(str, q))
return false;
static const std::array<std::string, 5> suffixes{"", "u8", "u", "U", "L"};
return std::any_of(suffixes.cbegin(), suffixes.cend(), [&](const std::string& p) {
return isPrefixStringCharLiteral(str, q, p);
});
}
inline static bool isStringLiteral(const std::string &str)
{
return isStringCharLiteral(str, '"');
}
inline static bool isCharLiteral(const std::string &str)
{
return isStringCharLiteral(str, '\'');
}
inline static std::string getStringCharLiteral(const std::string &str, char q)
{
const std::size_t quotePos = str.find(q);
return str.substr(quotePos + 1U, str.size() - quotePos - 2U);
}
inline static std::string getStringLiteral(const std::string &str)
{
if (isStringLiteral(str))
return getStringCharLiteral(str, '"');
return "";
}
inline static std::string getCharLiteral(const std::string &str)
{
if (isCharLiteral(str))
return getStringCharLiteral(str, '\'');
return "";
}
inline static const char *getOrdinalText(int i)
{
if (i == 1)
return "st";
if (i == 2)
return "nd";
if (i == 3)
return "rd";
return "th";
}
CPPCHECKLIB int caseInsensitiveStringCompare(const std::string& lhs, const std::string& rhs);
CPPCHECKLIB bool isValidGlobPattern(const std::string& pattern);
CPPCHECKLIB bool matchglob(const std::string& pattern, const std::string& name);
CPPCHECKLIB bool matchglobs(const std::vector<std::string> &patterns, const std::string &name);
CPPCHECKLIB void strTolower(std::string& str);
template<typename T, typename std::enable_if<std::is_signed<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
long long tmp;
try {
std::size_t idx = 0;
tmp = std::stoll(str, &idx);
if (idx != str.size()) {
if (err)
*err = "not an integer";
return false;
}
} catch (const std::out_of_range&) {
if (err)
*err = "out of range (stoll)";
return false;
} catch (const std::invalid_argument &) {
if (err)
*err = "not an integer";
return false;
}
if (str.front() == '-' && std::numeric_limits<T>::min() == 0) {
if (err)
*err = "needs to be positive";
return false;
}
if (tmp < std::numeric_limits<T>::min() || tmp > std::numeric_limits<T>::max()) {
if (err)
*err = "out of range (limits)";
return false;
}
num = static_cast<T>(tmp);
return true;
}
template<typename T, typename std::enable_if<std::is_unsigned<T>::value, bool>::type=true>
bool strToInt(const std::string& str, T &num, std::string* err = nullptr)
{
unsigned long long tmp;
try {
std::size_t idx = 0;
tmp = std::stoull(str, &idx);
if (idx != str.size()) {
if (err)
*err = "not an integer";
return false;
}
} catch (const std::out_of_range&) {
if (err)
*err = "out of range (stoull)";
return false;
} catch (const std::invalid_argument &) {
if (err)
*err = "not an integer";
return false;
}
if (str.front() == '-') {
if (err)
*err = "needs to be positive";
return false;
}
if (tmp > std::numeric_limits<T>::max()) {
if (err)
*err = "out of range (limits)";
return false;
}
num = tmp;
return true;
}
template<typename T>
T strToInt(const std::string& str)
{
T tmp = 0;
std::string err;
if (!strToInt(str, tmp, &err))
throw std::runtime_error("converting '" + str + "' to integer failed - " + err);
return tmp;
}
/**
* Simple helper function:
* \return size of array
* */
template<typename T, int size>
// cppcheck-suppress unusedFunction - only used in conditional code
std::size_t getArrayLength(const T (& /*unused*/)[size])
{
return size;
}
/**
* @brief get id string. i.e. for dump files
* it will be a hexadecimal output.
*/
static inline std::string id_string_i(std::uintptr_t l)
{
if (!l)
return "0";
static constexpr int ptr_size = sizeof(void*);
// two characters of each byte / contains terminating \0
static constexpr int buf_size = (ptr_size * 2) + 1;
char buf[buf_size];
// needs to be signed so we don't underflow in padding loop
int idx = buf_size - 1;
buf[idx] = '\0';
while (l != 0)
{
char c;
const std::uintptr_t temp = l % 16; // get the remainder
if (temp < 10) {
// 0-9
c = '0' + temp;
}
else {
// a-f
c = 'a' + (temp - 10);
}
buf[--idx] = c; // store in reverse order
l = l / 16;
}
return &buf[idx];
}
static inline std::string id_string(const void* p)
{
return id_string_i(reinterpret_cast<std::uintptr_t>(p));
}
static inline const char* bool_to_string(bool b)
{
return b ? "true" : "false";
}
/**
* Remove heading and trailing whitespaces from the input parameter.
* If string is all spaces/tabs, return empty string.
* @param s The string to trim.
* @param t The characters to trim.
*/
CPPCHECKLIB std::string trim(const std::string& s, const std::string& t = " \t");
/**
* Replace all occurrences of searchFor with replaceWith in the
* given source.
* @param source The string to modify
* @param searchFor What should be searched for
* @param replaceWith What will replace the found item
*/
CPPCHECKLIB void findAndReplace(std::string &source, const std::string &searchFor, const std::string &replaceWith);
/**
* Replace all escape sequences in the given string.
* @param source The string that contains escape sequences
*/
CPPCHECKLIB std::string replaceEscapeSequences(const std::string &source);
namespace cppcheck
{
NORETURN inline void unreachable()
{
#if defined(__GNUC__)
__builtin_unreachable();
#elif defined(_MSC_VER)
__assume(false);
#else
#error "no unreachable implementation"
#endif
}
}
template<typename T>
static inline T* default_if_null(T* p, T* def)
{
return p ? p : def;
}
template<typename T>
static inline T* empty_if_null(T* p)
{
return default_if_null(p, "");
}
/**
* Split string by given sperator.
* @param str The string to split
* @param sep The seperator
* @return The list of seperate strings (including empty ones). The whole input string if no seperator found.
*/
CPPCHECKLIB std::list<std::string> splitString(const std::string& str, char sep);
namespace utils {
template<class T>
constexpr typename std::add_const<T>::type & as_const(T& t) noexcept
{
return t;
}
}
#endif
| null |
802 | cpp | cppcheck | calculate.h | lib/calculate.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef calculateH
#define calculateH
#include "mathlib.h"
#include "errortypes.h"
#include <limits>
#include <string>
template<class T>
bool isEqual(T x, T y)
{
return x == y;
}
inline bool isEqual(double x, double y)
{
const double diff = (x > y) ? x - y : y - x;
return !((diff / 2) < diff);
}
inline bool isEqual(float x, float y)
{
return isEqual(double(x), double(y));
}
template<class T>
bool isZero(T x)
{
return isEqual(x, T(0));
}
template<class R, class T>
R calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
{
auto wrap = [](T z) {
return R{z};
};
constexpr MathLib::bigint maxBitsShift = sizeof(MathLib::bigint) * 8;
// For portability we cannot shift signed integers by 63 bits
constexpr MathLib::bigint maxBitsSignedShift = maxBitsShift - 1;
switch (MathLib::encodeMultiChar(s)) {
case '+':
return wrap(x + y);
case '-':
return wrap(x - y);
case '*':
return wrap(x * y);
case '/':
if (isZero(y) || (std::is_integral<T>{} && std::is_signed<T>{} && isEqual(y, T(-1)) && isEqual(x, std::numeric_limits<T>::min()))) {
if (error)
*error = true;
return R{};
}
return wrap(x / y);
case '%':
if (isZero(MathLib::bigint(y)) || (std::is_integral<T>{} && std::is_signed<T>{} && isEqual(y, T(-1)) && isEqual(x, std::numeric_limits<T>::min()))) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) % MathLib::bigint(y));
case '&':
return wrap(MathLib::bigint(x) & MathLib::bigint(y));
case '|':
return wrap(MathLib::bigint(x) | MathLib::bigint(y));
case '^':
return wrap(MathLib::bigint(x) ^ MathLib::bigint(y));
case '>':
return wrap(x > y);
case '<':
return wrap(x < y);
case '<<':
if (y >= maxBitsSignedShift || y < 0 || x < 0) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) << MathLib::bigint(y));
case '>>':
if (y >= maxBitsSignedShift || y < 0 || x < 0) {
if (error)
*error = true;
return R{};
}
return wrap(MathLib::bigint(x) >> MathLib::bigint(y));
case '&&':
return wrap(!isZero(x) && !isZero(y));
case '||':
return wrap(!isZero(x) || !isZero(y));
case '==':
return wrap(isEqual(x, y));
case '!=':
return wrap(!isEqual(x, y));
case '>=':
return wrap(x >= y);
case '<=':
return wrap(x <= y);
case '<=>':
return wrap(x - y);
}
throw InternalError(nullptr, "Unknown operator: " + s);
}
template<class T>
T calculate(const std::string& s, const T& x, const T& y, bool* error = nullptr)
{
return calculate<T, T>(s, x, y, error);
}
#endif
| null |
803 | cpp | cppcheck | checkexceptionsafety.cpp | lib/checkexceptionsafety.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkexceptionsafety.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "astutils.h"
#include <list>
#include <set>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register CheckExceptionSafety..
namespace {
CheckExceptionSafety instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE703(703U); // Improper Check or Handling of Exceptional Conditions
static const CWE CWE480(480U); // Use of Incorrect Operator
//---------------------------------------------------------------------------
void CheckExceptionSafety::destructors()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckExceptionSafety::destructors"); // warning
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Perform check..
for (const Scope * scope : symbolDatabase->functionScopes) {
const Function * function = scope->function;
if (!function)
continue;
// only looking for destructors
if (function->type == Function::eDestructor) {
// Inspect this destructor.
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// Skip try blocks
if (Token::simpleMatch(tok, "try {")) {
tok = tok->linkAt(1);
}
// Skip uncaught exceptions
else if (Token::simpleMatch(tok, "if ( ! std :: uncaught_exception ( ) ) {")) {
tok = tok->linkAt(1); // end of if ( ... )
tok = tok->linkAt(1); // end of { ... }
}
// throw found within a destructor
else if (tok->str() == "throw" && function->isNoExcept()) {
destructorsError(tok, scope->className);
break;
}
}
}
}
}
void CheckExceptionSafety::destructorsError(const Token * const tok, const std::string &className)
{
reportError(tok, Severity::warning, "exceptThrowInDestructor",
"Class " + className + " is not safe, destructor throws exception\n"
"The class " + className + " is not safe because its destructor "
"throws an exception. If " + className + " is used and an exception "
"is thrown that is caught in an outer scope the program will terminate.", CWE398, Certainty::normal);
}
void CheckExceptionSafety::deallocThrow()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckExceptionSafety::deallocThrow"); // warning
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Deallocate a global/member pointer and then throw exception
// the pointer will be a dead pointer
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// only looking for delete now
if (tok->str() != "delete")
continue;
// Check if this is something similar with: "delete p;"
tok = tok->next();
if (Token::simpleMatch(tok, "[ ]"))
tok = tok->tokAt(2);
if (!tok || tok == scope->bodyEnd)
break;
if (!Token::Match(tok, "%var% ;"))
continue;
// we only look for global variables
const Variable *var = tok->variable();
if (!var || !(var->isGlobal() || var->isStatic()))
continue;
const unsigned int varid(tok->varId());
// Token where throw occurs
const Token *throwToken = nullptr;
// is there a throw after the deallocation?
const Token* const end2 = tok->scope()->bodyEnd;
for (const Token *tok2 = tok; tok2 != end2; tok2 = tok2->next()) {
// Throw after delete -> Dead pointer
if (tok2->str() == "throw") {
if (printInconclusive) { // For inconclusive checking, throw directly.
deallocThrowError(tok2, tok->str());
break;
}
throwToken = tok2;
}
// Variable is assigned -> Bail out
else if (Token::Match(tok2, "%varid% =", varid)) {
if (throwToken) // For non-inconclusive checking, wait until we find an assignment to it. Otherwise we assume it is safe to leave a dead pointer.
deallocThrowError(throwToken, tok2->str());
break;
}
// Variable passed to function. Assume it becomes assigned -> Bail out
else if (Token::Match(tok2, "[,(] &| %varid% [,)]", varid)) // TODO: No bailout if passed by value or as const reference
break;
}
}
}
}
void CheckExceptionSafety::deallocThrowError(const Token * const tok, const std::string &varname)
{
reportError(tok, Severity::warning, "exceptDeallocThrow", "Exception thrown in invalid state, '" +
varname + "' points at deallocated memory.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// catch(const exception & err)
// {
// throw err; // <- should be just "throw;"
// }
//---------------------------------------------------------------------------
void CheckExceptionSafety::checkRethrowCopy()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("exceptRethrowCopy"))
return;
logChecker("CheckExceptionSafety::checkRethrowCopy"); // style
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eCatch)
continue;
const unsigned int varid = scope.bodyStart->tokAt(-2)->varId();
if (varid) {
for (const Token* tok = scope.bodyStart->next(); tok && tok != scope.bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "catch (") && tok->linkAt(1) && tok->linkAt(1)->next()) { // Don't check inner catch - it is handled in another iteration of outer loop.
tok = tok->linkAt(1)->linkAt(1);
if (!tok)
break;
} else if (Token::Match(tok, "%varid% .", varid)) {
const Token *parent = tok->astParent();
while (Token::simpleMatch(parent->astParent(), "."))
parent = parent->astParent();
if (Token::Match(parent->astParent(), "%assign%|++|--|(") && parent == parent->astParent()->astOperand1())
break;
} else if (Token::Match(tok, "throw %varid% ;", varid))
rethrowCopyError(tok, tok->strAt(1));
}
}
}
}
void CheckExceptionSafety::rethrowCopyError(const Token * const tok, const std::string &varname)
{
reportError(tok, Severity::style, "exceptRethrowCopy",
"Throwing a copy of the caught exception instead of rethrowing the original exception.\n"
"Rethrowing an exception with 'throw " + varname + ";' creates an unnecessary copy of '" + varname + "'. "
"To rethrow the caught exception without unnecessary copying or slicing, use a bare 'throw;'.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// try {} catch (std::exception err) {} <- Should be "std::exception& err"
//---------------------------------------------------------------------------
void CheckExceptionSafety::checkCatchExceptionByValue()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("catchExceptionByValue"))
return;
logChecker("CheckExceptionSafety::checkCatchExceptionByValue"); // style
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eCatch)
continue;
// Find a pass-by-value declaration in the catch(), excluding basic types
// e.g. catch (std::exception err)
const Variable *var = scope.bodyStart->tokAt(-2)->variable();
if (var && var->isClass() && !var->isPointer() && !var->isReference())
catchExceptionByValueError(scope.classDef);
}
}
void CheckExceptionSafety::catchExceptionByValueError(const Token *tok)
{
reportError(tok, Severity::style,
"catchExceptionByValue", "Exception should be caught by reference.\n"
"The exception is caught by value. It could be caught "
"as a (const) reference which is usually recommended in C++.", CWE398, Certainty::normal);
}
static const Token * functionThrowsRecursive(const Function * function, std::set<const Function *> & recursive)
{
// check for recursion and bail if found
if (!recursive.insert(function).second)
return nullptr;
if (!function->functionScope)
return nullptr;
for (const Token *tok = function->functionScope->bodyStart->next();
tok != function->functionScope->bodyEnd; tok = tok->next()) {
tok = skipUnreachableBranch(tok);
if (Token::simpleMatch(tok, "try {"))
tok = tok->linkAt(1); // skip till start of catch clauses
if (tok->str() == "throw")
return tok;
if (tok->function()) {
const Function * called = tok->function();
// check if called function has an exception specification
if (called->isThrow() && called->throwArg)
return tok;
if (called->isNoExcept() && called->noexceptArg &&
called->noexceptArg->str() != "true")
return tok;
if (functionThrowsRecursive(called, recursive))
return tok;
}
}
return nullptr;
}
static const Token * functionThrows(const Function * function)
{
std::set<const Function *> recursive;
return functionThrowsRecursive(function, recursive);
}
//--------------------------------------------------------------------------
// void func() noexcept { throw x; }
// void func() throw() { throw x; }
// void func() __attribute__((nothrow)); void func() { throw x; }
//--------------------------------------------------------------------------
void CheckExceptionSafety::nothrowThrows()
{
logChecker("CheckExceptionSafety::nothrowThrows");
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Function* function = scope->function;
if (!function)
continue;
// check noexcept and noexcept(true) functions
if (function->isNoExcept()) {
const Token *throws = functionThrows(function);
if (throws)
noexceptThrowError(throws);
}
// check throw() functions
else if (function->isThrow() && !function->throwArg) {
const Token *throws = functionThrows(function);
if (throws)
noexceptThrowError(throws);
}
// check __attribute__((nothrow)) or __declspec(nothrow) functions
else if (function->isAttributeNothrow()) {
const Token *throws = functionThrows(function);
if (throws)
noexceptThrowError(throws);
}
}
}
void CheckExceptionSafety::noexceptThrowError(const Token * const tok)
{
reportError(tok, Severity::error, "throwInNoexceptFunction", "Exception thrown in function declared not to throw exceptions.", CWE398, Certainty::normal);
}
//--------------------------------------------------------------------------
// void func() { functionWithExceptionSpecification(); }
//--------------------------------------------------------------------------
void CheckExceptionSafety::unhandledExceptionSpecification()
{
if ((!mSettings->severity.isEnabled(Severity::style) || !mSettings->certainty.isEnabled(Certainty::inconclusive)) &&
!mSettings->isPremiumEnabled("unhandledExceptionSpecification"))
return;
logChecker("CheckExceptionSafety::unhandledExceptionSpecification"); // style,inconclusive
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
// only check functions without exception specification
if (scope->function && !scope->function->isThrow() && !mSettings->library.isentrypoint(scope->className)) {
for (const Token *tok = scope->function->functionScope->bodyStart->next();
tok != scope->function->functionScope->bodyEnd; tok = tok->next()) {
if (tok->str() == "try")
break;
if (tok->function()) {
const Function * called = tok->function();
// check if called function has an exception specification
if (called->isThrow() && called->throwArg) {
unhandledExceptionSpecificationError(tok, called->tokenDef, scope->function->name());
break;
}
}
}
}
}
}
void CheckExceptionSafety::unhandledExceptionSpecificationError(const Token * const tok1, const Token * const tok2, const std::string & funcname)
{
const std::string str1(tok1 ? tok1->str() : "foo");
const std::list<const Token*> locationList = { tok1, tok2 };
reportError(locationList, Severity::style, "unhandledExceptionSpecification",
"Unhandled exception specification when calling function " + str1 + "().\n"
"Unhandled exception specification when calling function " + str1 + "(). "
"Either use a try/catch around the function call, or add a exception specification for " + funcname + "() also.", CWE703, Certainty::inconclusive);
}
//--------------------------------------------------------------------------
// 7.6.18.4 If no exception is presently being handled, evaluating a throw-expression with no operand calls std::terminate().
//--------------------------------------------------------------------------
void CheckExceptionSafety::rethrowNoCurrentException()
{
logChecker("CheckExceptionSafety::rethrowNoCurrentException");
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Function* function = scope->function;
if (!function)
continue;
// Rethrow can be used in 'exception dispatcher' idiom which is FP in such case
// https://isocpp.org/wiki/faq/exceptions#throw-without-an-object
// We check the beginning of the function with idiom pattern
if (Token::simpleMatch(function->functionScope->bodyStart->next(), "try { throw ; } catch ("))
continue;
for (const Token *tok = function->functionScope->bodyStart->next();
tok != function->functionScope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "catch (")) {
tok = tok->linkAt(1); // skip catch argument
if (Token::simpleMatch(tok, ") {"))
tok = tok->linkAt(1); // skip catch scope
else
break;
}
if (Token::simpleMatch(tok, "throw ;")) {
rethrowNoCurrentExceptionError(tok);
}
}
}
}
void CheckExceptionSafety::rethrowNoCurrentExceptionError(const Token *tok)
{
reportError(tok, Severity::error, "rethrowNoCurrentException",
"Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow."
" If there is no current exception this calls std::terminate()."
" More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object",
CWE480, Certainty::normal);
}
| null |
804 | cpp | cppcheck | matchcompiler.h | lib/matchcompiler.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef matchcompilerH
#define matchcompilerH
#include <string>
namespace MatchCompiler {
template<unsigned int n>
class ConstString {
public:
using StringRef = const char (&)[n];
explicit ConstString(StringRef s)
: _s(s) {}
operator StringRef() const {
return _s;
}
private:
StringRef _s;
};
template<unsigned int n>
inline bool equalN(const char s1[], const char s2[])
{
return (*s1 == *s2) && equalN<n-1>(s1+1, s2+1);
}
template<>
inline bool equalN<0>(const char /*s1*/[], const char /*s2*/[])
{
return true;
}
template<unsigned int n>
inline bool operator==(const std::string & s1, ConstString<n> const & s2)
{
return equalN<n>(s1.c_str(), s2);
}
template<unsigned int n>
inline bool operator!=(const std::string & s1, ConstString<n> const & s2)
{
return !operator==(s1,s2);
}
template<unsigned int n>
inline ConstString<n> makeConstString(const char (&s)[n])
{
return ConstString<n>(s);
}
}
#endif // matchcompilerH
| null |
805 | cpp | cppcheck | infer.h | lib/infer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef inferH
#define inferH
#include "config.h"
#include "mathlib.h"
#include "vfvalue.h"
#include <list>
#include <string>
#include <vector>
template<class T> class ValuePtr;
struct InferModel {
virtual bool match(const ValueFlow::Value& value) const = 0;
virtual ValueFlow::Value yield(MathLib::bigint value) const = 0;
virtual ~InferModel() = default;
InferModel(const InferModel&) = default;
protected:
InferModel() = default;
};
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
std::list<ValueFlow::Value> lhsValues,
std::list<ValueFlow::Value> rhsValues);
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
MathLib::bigint lhs,
std::list<ValueFlow::Value> rhsValues);
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
std::list<ValueFlow::Value> lhsValues,
MathLib::bigint rhs);
CPPCHECKLIB std::vector<MathLib::bigint> getMinValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values);
std::vector<MathLib::bigint> getMaxValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values);
ValuePtr<InferModel> makeIntegralInferModel();
ValueFlow::Value inferCondition(const std::string& op, const Token* varTok, MathLib::bigint val);
#endif
| null |
806 | cpp | cppcheck | checkboost.h | lib/checkboost.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkboostH
#define checkboostH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief %Check Boost usage */
class CPPCHECKLIB CheckBoost : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckBoost() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckBoost(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.isCPP())
return;
CheckBoost checkBoost(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkBoost.checkBoostForeachModification();
}
/** @brief %Check for container modification while using the BOOST_FOREACH macro */
void checkBoostForeachModification();
void boostForeachError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckBoost c(nullptr, settings, errorLogger);
c.boostForeachError(nullptr);
}
static std::string myName() {
return "Boost usage";
}
std::string classInfo() const override {
return "Check for invalid usage of Boost:\n"
"- container modification during BOOST_FOREACH\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkboostH
| null |
807 | cpp | cppcheck | checksizeof.cpp | lib/checksizeof.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checksizeof.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <algorithm>
#include <iterator>
#include <map>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckSizeof instance;
}
// CWE IDs used:
static const CWE CWE467(467U); // Use of sizeof() on a Pointer Type
static const CWE CWE682(682U); // Incorrect Calculation
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void CheckSizeof::checkSizeofForNumericParameter()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckSizeof::checkSizeofForNumericParameter"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "sizeof ( %num% )") ||
Token::Match(tok, "sizeof %num%")) {
sizeofForNumericParameterError(tok);
}
}
}
}
void CheckSizeof::sizeofForNumericParameterError(const Token *tok)
{
reportError(tok, Severity::warning,
"sizeofwithnumericparameter", "Suspicious usage of 'sizeof' with a numeric constant as parameter.\n"
"It is unusual to use a constant value with sizeof. For example, 'sizeof(10)'"
" returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 10. 'sizeof('A')'"
" and 'sizeof(char)' can return different results.", CWE682, Certainty::normal);
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
void CheckSizeof::checkSizeofForArrayParameter()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckSizeof::checkSizeofForArrayParameter"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "sizeof ( %var% )") ||
Token::Match(tok, "sizeof %var% !![")) {
const Token* varTok = tok->next();
if (varTok->str() == "(") {
varTok = varTok->next();
}
const Variable *var = varTok->variable();
if (var && var->isArray() && var->isArgument() && !var->isReference())
sizeofForArrayParameterError(tok);
}
}
}
}
void CheckSizeof::sizeofForArrayParameterError(const Token *tok)
{
reportError(tok, Severity::warning,
"sizeofwithsilentarraypointer", "Using 'sizeof' on array given as function argument "
"returns size of a pointer.\n"
"Using 'sizeof' for array given as function argument returns the size of a pointer. "
"It does not return the size of the whole array in bytes as might be "
"expected. For example, this code:\n"
" int f(char a[100]) {\n"
" return sizeof(a);\n"
" }\n"
"returns 4 (in 32-bit systems) or 8 (in 64-bit systems) instead of 100 (the "
"size of the array in bytes).", CWE467, Certainty::normal
);
}
void CheckSizeof::checkSizeofForPointerSize()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckSizeof::checkSizeofForPointerSize"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
const Token* tokSize;
const Token* tokFunc;
const Token *variable = nullptr;
const Token *variable2 = nullptr;
// Find any function that may use sizeof on a pointer
// Once leaving those tests, it is mandatory to have:
// - variable matching the used pointer
// - tokVar pointing on the argument where sizeof may be used
if (Token::Match(tok->tokAt(2), "%name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2))) {
if (Token::Match(tok, "%var% ="))
variable = tok;
else if (tok->strAt(1) == ")" && Token::Match(tok->linkAt(1)->tokAt(-2), "%var% ="))
variable = tok->linkAt(1)->tokAt(-2);
else if (tok->link() && Token::Match(tok, "> ( %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)) && Token::Match(tok->link()->tokAt(-3), "%var% ="))
variable = tok->link()->tokAt(-3);
tokSize = tok->tokAt(4);
tokFunc = tok->tokAt(2);
} else if (Token::simpleMatch(tok, "memset (") && tok->strAt(-1) != ".") {
variable = tok->tokAt(2);
tokSize = variable->nextArgument();
if (tokSize)
tokSize = tokSize->nextArgument();
tokFunc = tok;
} else if (Token::Match(tok, "memcpy|memcmp|memmove|strncpy|strncmp|strncat (") && tok->strAt(-1) != ".") {
variable = tok->tokAt(2);
variable2 = variable->nextArgument();
if (!variable2)
continue;
tokSize = variable2->nextArgument();
tokFunc = tok;
} else {
continue;
}
if (tokSize && tokFunc->str() == "calloc")
tokSize = tokSize->nextArgument();
if (tokSize) {
const Token * const paramsListEndTok = tokFunc->linkAt(1);
for (const Token* tok2 = tokSize; tok2 != paramsListEndTok; tok2 = tok2->next()) {
if (Token::simpleMatch(tok2, "/ sizeof")) {
// Allow division with sizeof(char)
if (Token::simpleMatch(tok2->next(), "sizeof (")) {
const Token *sztok = tok2->tokAt(2)->astOperand2();
const ValueType *vt = ((sztok != nullptr) ? sztok->valueType() : nullptr);
if (vt && vt->type == ValueType::CHAR && vt->pointer == 0)
continue;
}
auto hasMultiplication = [](const Token* parTok) -> bool {
while (parTok) { // Allow division if followed by multiplication
if (parTok->isArithmeticalOp() && parTok->str() == "*") {
const Token* szToks[] = { parTok->astOperand1(), parTok->astOperand2() };
if (std::any_of(std::begin(szToks), std::end(szToks), [](const Token* szTok) {
return Token::simpleMatch(szTok, "(") && Token::simpleMatch(szTok->previous(), "sizeof");
}))
return true;
}
parTok = parTok->astParent();
}
return false;
};
if (hasMultiplication(tok2->astParent()))
continue;
divideBySizeofError(tok2, tokFunc->str());
}
}
}
if (!variable || !tokSize)
continue;
while (Token::Match(variable, "%var% ::|."))
variable = variable->tokAt(2);
while (Token::Match(variable2, "%var% ::|."))
variable2 = variable2->tokAt(2);
if (!variable)
continue;
// Ensure the variables are in the symbol database
// Also ensure the variables are pointers
// Only keep variables which are pointers
const Variable *var = variable->variable();
if (!var || !var->isPointer() || var->isArray()) {
variable = nullptr;
}
if (variable2) {
var = variable2->variable();
if (!var || !var->isPointer() || var->isArray()) {
variable2 = nullptr;
}
}
// If there are no pointer variable at this point, there is
// no need to continue
if (variable == nullptr && variable2 == nullptr) {
continue;
}
// Jump to the next sizeof token in the function and in the parameter
// This is to allow generic operations with sizeof
for (; tokSize && tokSize->str() != ")" && tokSize->str() != "," && tokSize->str() != "sizeof"; tokSize = tokSize->next()) {}
if (tokSize->str() != "sizeof")
continue;
// Now check for the sizeof usage: Does the level of pointer indirection match?
const Token * const tokLink = tokSize->linkAt(1);
if (tokLink && tokLink->strAt(-1) == "*") {
if (variable && variable->valueType() && variable->valueType()->pointer == 1 && variable->valueType()->type != ValueType::VOID)
sizeofForPointerError(variable, variable->str());
else if (variable2 && variable2->valueType() && variable2->valueType()->pointer == 1 && variable2->valueType()->type != ValueType::VOID)
sizeofForPointerError(variable2, variable2->str());
}
if (Token::simpleMatch(tokSize, "sizeof ( &"))
tokSize = tokSize->tokAt(3);
else if (Token::Match(tokSize, "sizeof (|&"))
tokSize = tokSize->tokAt(2);
else
tokSize = tokSize->next();
while (Token::Match(tokSize, "%var% ::|."))
tokSize = tokSize->tokAt(2);
if (Token::Match(tokSize, "%var% [|("))
continue;
// Now check for the sizeof usage again. Once here, everything using sizeof(varid) or sizeof(&varid)
// looks suspicious
if (variable && tokSize->varId() == variable->varId())
sizeofForPointerError(variable, variable->str());
if (variable2 && tokSize->varId() == variable2->varId())
sizeofForPointerError(variable2, variable2->str());
}
}
}
void CheckSizeof::sizeofForPointerError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::warning, "pointerSize",
"Size of pointer '" + varname + "' used instead of size of its data.\n"
"Size of pointer '" + varname + "' used instead of size of its data. "
"This is likely to lead to a buffer overflow. You probably intend to "
"write 'sizeof(*" + varname + ")'.", CWE467, Certainty::normal);
}
void CheckSizeof::divideBySizeofError(const Token *tok, const std::string &memfunc)
{
reportError(tok, Severity::warning, "sizeofDivisionMemfunc",
"Division by result of sizeof(). " + memfunc + "() expects a size in bytes, did you intend to multiply instead?", CWE682, Certainty::normal);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CheckSizeof::sizeofsizeof()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckSizeof::sizeofsizeof"); // warning
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof (| sizeof")) {
sizeofsizeofError(tok);
tok = tok->next();
}
}
}
void CheckSizeof::sizeofsizeofError(const Token *tok)
{
reportError(tok, Severity::warning,
"sizeofsizeof", "Calling 'sizeof' on 'sizeof'.\n"
"Calling sizeof for 'sizeof looks like a suspicious code and "
"most likely there should be just one 'sizeof'. The current "
"code is equivalent to 'sizeof(size_t)'", CWE682, Certainty::normal);
}
//-----------------------------------------------------------------------------
void CheckSizeof::sizeofCalculation()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckSizeof::sizeofCalculation"); // warning
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "sizeof ("))
continue;
// ignore if the `sizeof` result is cast to void inside a macro, i.e. the calculation is
// expected to be parsed but skipped, such as in a disabled custom ASSERT() macro
if (tok->isExpandedMacro() && tok->previous()) {
const Token *cast_end = (tok->strAt(-1) == "(") ? tok->previous() : tok;
if (Token::simpleMatch(cast_end->tokAt(-3), "( void )") ||
Token::simpleMatch(cast_end->tokAt(-4), "static_cast < void >")) {
continue;
}
}
const Token *argument = tok->next()->astOperand2();
if (!argument || !argument->isCalculation())
continue;
bool inconclusive = false;
if (argument->isExpandedMacro())
inconclusive = true;
else if (tok->next()->isExpandedMacro())
inconclusive = true;
if (!inconclusive || printInconclusive)
sizeofCalculationError(argument, inconclusive);
}
}
void CheckSizeof::sizeofCalculationError(const Token *tok, bool inconclusive)
{
reportError(tok, Severity::warning,
"sizeofCalculation", "Found calculation inside sizeof().", CWE682, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
//-----------------------------------------------------------------------------
void CheckSizeof::sizeofFunction()
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("sizeofFunctionCall"))
return;
logChecker("CheckSizeof::sizeofFunction"); // warning
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
// ignore if the `sizeof` result is cast to void inside a macro, i.e. the calculation is
// expected to be parsed but skipped, such as in a disabled custom ASSERT() macro
if (tok->isExpandedMacro() && tok->previous()) {
const Token *cast_end = (tok->strAt(-1) == "(") ? tok->previous() : tok;
if (Token::simpleMatch(cast_end->tokAt(-3), "( void )") ||
Token::simpleMatch(cast_end->tokAt(-4), "static_cast < void >")) {
continue;
}
}
if (const Token *argument = tok->next()->astOperand2()) {
const Token *checkToken = argument->previous();
if (checkToken->tokType() == Token::eName)
break;
const Function * fun = checkToken->function();
// Don't report error if the function is overloaded
if (fun && fun->nestedIn->functionMap.count(checkToken->str()) == 1) {
sizeofFunctionError(tok);
}
}
}
}
}
void CheckSizeof::sizeofFunctionError(const Token *tok)
{
reportError(tok, Severity::warning,
"sizeofFunctionCall", "Found function call inside sizeof().", CWE682, Certainty::normal);
}
//-----------------------------------------------------------------------------
// Check for code like sizeof()*sizeof() or sizeof(ptr)/value
//-----------------------------------------------------------------------------
void CheckSizeof::suspiciousSizeofCalculation()
{
if (!mSettings->severity.isEnabled(Severity::warning) || !mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckSizeof::suspiciousSizeofCalculation"); // warning,inconclusive
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
const Token* lPar = tok->astParent();
if (lPar && lPar->str() == "(") {
const Token* const rPar = lPar->link();
const Token* varTok = lPar->astOperand2();
int derefCount = 0;
while (Token::Match(varTok, "[|*")) {
++derefCount;
varTok = varTok->astOperand1();
}
if (lPar->astParent() && lPar->astParent()->str() == "/") {
const Variable* var = varTok ? varTok->variable() : nullptr;
if (var && var->isPointer() && !var->isArray() && !(var->valueType() && var->valueType()->pointer <= derefCount))
divideSizeofError(tok);
}
else if (Token::simpleMatch(rPar, ") * sizeof") && rPar->next()->astOperand1() == tok->next())
multiplySizeofError(tok);
}
}
}
}
void CheckSizeof::multiplySizeofError(const Token *tok)
{
reportError(tok, Severity::warning,
"multiplySizeof", "Multiplying sizeof() with sizeof() indicates a logic error.", CWE682, Certainty::inconclusive);
}
void CheckSizeof::divideSizeofError(const Token *tok)
{
reportError(tok, Severity::warning,
"divideSizeof", "Division of result of sizeof() on pointer type.\n"
"Division of result of sizeof() on pointer type. sizeof() returns the size of the pointer, "
"not the size of the memory area it points to.", CWE682, Certainty::inconclusive);
}
void CheckSizeof::sizeofVoid()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("CheckSizeof::sizeofVoid"); // portability
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof ( void )")) {
sizeofVoidError(tok);
} else if (Token::simpleMatch(tok, "sizeof (") && tok->next()->astOperand2()) {
const ValueType *vt = tok->next()->astOperand2()->valueType();
if (vt && vt->type == ValueType::Type::VOID && vt->pointer == 0U)
sizeofDereferencedVoidPointerError(tok, tok->strAt(3));
} else if (tok->str() == "-") {
// only warn for: 'void *' - 'integral'
const ValueType *vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType *vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr;
const bool op1IsvoidPointer = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U);
const bool op2IsIntegral = (vt2 && vt2->isIntegral() && vt2->pointer == 0U);
if (op1IsvoidPointer && op2IsIntegral)
arithOperationsOnVoidPointerError(tok, tok->astOperand1()->expressionString(), vt1->str());
} else if (Token::Match(tok, "+|++|--|+=|-=")) { // Arithmetic operations on variable of type "void*"
const ValueType *vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType *vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr;
const bool voidpointer1 = (vt1 && vt1->type == ValueType::Type::VOID && vt1->pointer == 1U);
const bool voidpointer2 = (vt2 && vt2->type == ValueType::Type::VOID && vt2->pointer == 1U);
if (voidpointer1)
arithOperationsOnVoidPointerError(tok, tok->astOperand1()->expressionString(), vt1->str());
if (!tok->isAssignmentOp() && voidpointer2)
arithOperationsOnVoidPointerError(tok, tok->astOperand2()->expressionString(), vt2->str());
}
}
}
void CheckSizeof::sizeofVoidError(const Token *tok)
{
const std::string message = "Behaviour of 'sizeof(void)' is not covered by the ISO C standard.";
const std::string verbose = message + " A value for 'sizeof(void)' is defined only as part of a GNU C extension, which defines 'sizeof(void)' to be 1.";
reportError(tok, Severity::portability, "sizeofVoid", message + "\n" + verbose, CWE682, Certainty::normal);
}
void CheckSizeof::sizeofDereferencedVoidPointerError(const Token *tok, const std::string &varname)
{
const std::string message = "'*" + varname + "' is of type 'void', the behaviour of 'sizeof(void)' is not covered by the ISO C standard.";
const std::string verbose = message + " A value for 'sizeof(void)' is defined only as part of a GNU C extension, which defines 'sizeof(void)' to be 1.";
reportError(tok, Severity::portability, "sizeofDereferencedVoidPointer", message + "\n" + verbose, CWE682, Certainty::normal);
}
void CheckSizeof::arithOperationsOnVoidPointerError(const Token* tok, const std::string &varname, const std::string &vartype)
{
const std::string message = "'$symbol' is of type '" + vartype + "'. When using void pointers in calculations, the behaviour is undefined.";
const std::string verbose = message + " Arithmetic operations on 'void *' is a GNU C extension, which defines the 'sizeof(void)' to be 1.";
reportError(tok, Severity::portability, "arithOperationsOnVoidPointer", "$symbol:" + varname + '\n' + message + '\n' + verbose, CWE467, Certainty::normal);
}
| null |
808 | cpp | cppcheck | checkuninitvar.h | lib/checkuninitvar.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkuninitvarH
#define checkuninitvarH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "mathlib.h"
#include "errortypes.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <cstdint>
#include <map>
#include <set>
#include <string>
class Scope;
class Token;
class Variable;
class ErrorLogger;
class Settings;
class Library;
struct VariableValue {
explicit VariableValue(MathLib::bigint val = 0) : value(val) {}
MathLib::bigint value;
bool notEqual{};
};
/// @addtogroup Checks
/// @{
/** @brief Checking for uninitialized variables */
class CPPCHECKLIB CheckUninitVar : public Check {
friend class TestUninitVar;
public:
/** @brief This constructor is used when registering the CheckUninitVar */
CheckUninitVar() : Check(myName()) {}
enum Alloc : std::uint8_t { NO_ALLOC, NO_CTOR_CALL, CTOR_CALL, ARRAY };
static const Token *isVariableUsage(const Token *vartok, const Library &library, bool pointer, Alloc alloc, int indirect = 0);
const Token *isVariableUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect = 0) const;
private:
/** @brief This constructor is used when running checks. */
CheckUninitVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckUninitVar checkUninitVar(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkUninitVar.valueFlowUninit();
checkUninitVar.check();
}
bool diag(const Token* tok);
/** Check for uninitialized variables */
void check();
void checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs);
void checkStruct(const Token *tok, const Variable &structvar);
bool checkScopeForVariable(const Token *tok, const Variable& var, bool* possibleInit, bool* noreturn, Alloc* alloc, const std::string &membervar, std::map<nonneg int, VariableValue>& variableValue);
const Token* checkExpr(const Token* tok, const Variable& var, Alloc alloc, bool known, bool* bailout = nullptr) const;
bool checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar);
bool checkLoopBody(const Token *tok, const Variable& var, Alloc alloc, const std::string &membervar, bool suppressErrors);
const Token* checkLoopBodyRecursive(const Token *start, const Variable& var, Alloc alloc, const std::string &membervar, bool &bailout, bool &alwaysReturns) const;
void checkRhs(const Token *tok, const Variable &var, Alloc alloc, nonneg int number_of_if, const std::string &membervar);
static int isFunctionParUsage(const Token *vartok, const Library &library, bool pointer, Alloc alloc, int indirect = 0);
int isFunctionParUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect = 0) const;
bool isMemberVariableAssignment(const Token *tok, const std::string &membervar) const;
bool isMemberVariableUsage(const Token *tok, bool isPointer, Alloc alloc, const std::string &membervar) const;
/** ValueFlow-based checking for uninitialized variables */
void valueFlowUninit();
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
void uninitvarError(const Token* tok, const ValueFlow::Value& v);
void uninitdataError(const Token *tok, const std::string &varname);
void uninitvarError(const Token *tok, const std::string &varname, ErrorPath errorPath);
void uninitvarError(const Token *tok, const std::string &varname) {
uninitvarError(tok, varname, ErrorPath{});
}
void uninitvarError(const Token *tok, const std::string &varname, Alloc alloc) {
if (alloc == NO_CTOR_CALL || alloc == CTOR_CALL)
uninitdataError(tok, varname);
else
uninitvarError(tok, varname);
}
void uninitStructMemberError(const Token *tok, const std::string &membername);
std::set<const Token*> mUninitDiags;
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const override
{
CheckUninitVar c(nullptr, settings, errorLogger);
ValueFlow::Value v{};
c.uninitvarError(nullptr, v);
c.uninitdataError(nullptr, "varname");
c.uninitStructMemberError(nullptr, "a.b");
}
static std::string myName() {
return "Uninitialized variables";
}
std::string classInfo() const override {
return "Uninitialized variables\n"
"- using uninitialized local variables\n"
"- using allocated data before it has been initialized\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkuninitvarH
| null |
809 | cpp | cppcheck | token.cpp | lib/token.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "token.h"
#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "simplecpp.h"
#include "symboldatabase.h"
#include "tokenlist.h"
#include "utils.h"
#include "tokenrange.h"
#include "valueflow.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <climits>
#include <cstdio>
#include <cstring>
#include <functional>
#include <iostream>
#include <iterator>
#include <map>
#include <set>
#include <sstream>
#include <stack>
#include <type_traits>
#include <unordered_set>
#include <utility>
namespace {
struct less {
template<class T, class U>
bool operator()(const T &x, const U &y) const {
return x < y;
}
};
}
const std::list<ValueFlow::Value> TokenImpl::mEmptyValueList;
Token::Token(TokensFrontBack &tokensFrontBack)
: mTokensFrontBack(tokensFrontBack)
, mIsC(mTokensFrontBack.list.isC())
, mIsCpp(mTokensFrontBack.list.isCPP())
{
mImpl = new TokenImpl();
}
Token::Token(const Token* tok)
: Token(const_cast<Token*>(tok)->mTokensFrontBack)
{
fileIndex(tok->fileIndex());
linenr(tok->linenr());
}
Token::~Token()
{
delete mImpl;
}
/*
* Get a TokenRange which starts at this token and contains every token following it in order up to but not including 't'
* e.g. for the sequence of tokens A B C D E, C.until(E) would yield the Range C D
* note t can be nullptr to iterate all the way to the end.
*/
// cppcheck-suppress unusedFunction // only used in testtokenrange.cpp
ConstTokenRange Token::until(const Token* t) const
{
return ConstTokenRange(this, t);
}
static const std::unordered_set<std::string> controlFlowKeywords = {
"goto",
"do",
"if",
"else",
"for",
"while",
"switch",
"case",
"break",
"continue",
"return"
};
void Token::update_property_info()
{
setFlag(fIsControlFlowKeyword, controlFlowKeywords.find(mStr) != controlFlowKeywords.end());
isStandardType(false);
if (!mStr.empty()) {
if (mStr == "true" || mStr == "false")
tokType(eBoolean);
else if (isStringLiteral(mStr)) {
tokType(eString);
isLong(isPrefixStringCharLiteral(mStr, '"', "L"));
}
else if (isCharLiteral(mStr)) {
tokType(eChar);
isLong(isPrefixStringCharLiteral(mStr, '\'', "L"));
}
else if (std::isalpha((unsigned char)mStr[0]) || mStr[0] == '_' || mStr[0] == '$') { // Name
if (mImpl->mVarId)
tokType(eVariable);
else if (mTokensFrontBack.list.isKeyword(mStr) || mStr == "asm") // TODO: not a keyword
tokType(eKeyword);
else if (mTokType != eVariable && mTokType != eFunction && mTokType != eType && mTokType != eKeyword)
tokType(eName);
} else if (simplecpp::Token::isNumberLike(mStr)) {
if (MathLib::isInt(mStr) || MathLib::isFloat(mStr))
tokType(eNumber);
else
tokType(eName); // assume it is a user defined literal
} else if (mStr == "=" || mStr == "<<=" || mStr == ">>=" ||
(mStr.size() == 2U && mStr[1] == '=' && std::strchr("+-*/%&^|", mStr[0])))
tokType(eAssignmentOp);
else if (mStr.size() == 1 && mStr.find_first_of(",[]()?:") != std::string::npos)
tokType(eExtendedOp);
else if (mStr=="<<" || mStr==">>" || (mStr.size()==1 && mStr.find_first_of("+-*/%") != std::string::npos))
tokType(eArithmeticalOp);
else if (mStr.size() == 1 && mStr.find_first_of("&|^~") != std::string::npos)
tokType(eBitOp);
else if (mStr.size() <= 2 &&
(mStr == "&&" ||
mStr == "||" ||
mStr == "!"))
tokType(eLogicalOp);
else if (mStr.size() <= 2 && !mLink &&
(mStr == "==" ||
mStr == "!=" ||
mStr == "<" ||
mStr == "<=" ||
mStr == ">" ||
mStr == ">="))
tokType(eComparisonOp);
else if (mStr == "<=>")
tokType(eComparisonOp);
else if (mStr.size() == 2 &&
(mStr == "++" ||
mStr == "--"))
tokType(eIncDecOp);
else if (mStr.size() == 1 && (mStr.find_first_of("{}") != std::string::npos || (mLink && mStr.find_first_of("<>") != std::string::npos)))
tokType(eBracket);
else if (mStr == "...")
tokType(eEllipsis);
else
tokType(eOther);
update_property_isStandardType();
} else {
tokType(eNone);
}
}
static const std::unordered_set<std::string> stdTypes = { "bool"
, "_Bool"
, "char"
, "double"
, "float"
, "int"
, "long"
, "short"
, "size_t"
, "void"
, "wchar_t"
, "signed"
, "unsigned"
};
bool Token::isStandardType(const std::string& str)
{
return stdTypes.find(str) != stdTypes.end();
}
void Token::update_property_isStandardType()
{
if (mStr.size() < 3 || mStr.size() > 7)
return;
if (isStandardType(mStr)) {
isStandardType(true);
tokType(eType);
}
}
bool Token::isUpperCaseName() const
{
if (!isName())
return false;
return std::none_of(mStr.begin(), mStr.end(), [](char c) {
return std::islower(c);
});
}
void Token::concatStr(std::string const& b)
{
mStr.pop_back();
mStr.append(getStringLiteral(b) + "\"");
if (isCChar() && isStringLiteral(b) && b[0] != '"') {
mStr.insert(0, b.substr(0, b.find('"')));
}
update_property_info();
}
std::string Token::strValue() const
{
assert(mTokType == eString);
std::string ret(getStringLiteral(mStr));
std::string::size_type pos = 0U;
while ((pos = ret.find('\\', pos)) != std::string::npos) {
ret.erase(pos,1U);
if (ret[pos] >= 'a') {
if (ret[pos] == 'n')
ret[pos] = '\n';
else if (ret[pos] == 'r')
ret[pos] = '\r';
else if (ret[pos] == 't')
ret[pos] = '\t';
}
if (ret[pos] == '0')
return ret.substr(0,pos);
pos++;
}
return ret;
}
void Token::deleteNext(nonneg int count)
{
while (mNext && count > 0) {
Token *n = mNext;
// #8154 we are about to be unknown -> destroy the link to us
if (n->mLink && n->mLink->mLink == n)
n->mLink->link(nullptr);
mNext = n->next();
delete n;
--count;
}
if (mNext)
mNext->previous(this);
else
mTokensFrontBack.back = this;
}
void Token::deletePrevious(nonneg int count)
{
while (mPrevious && count > 0) {
Token *p = mPrevious;
// #8154 we are about to be unknown -> destroy the link to us
if (p->mLink && p->mLink->mLink == p)
p->mLink->link(nullptr);
mPrevious = p->previous();
delete p;
--count;
}
if (mPrevious)
mPrevious->next(this);
else
mTokensFrontBack.front = this;
}
void Token::swapWithNext()
{
if (mNext) {
std::swap(mStr, mNext->mStr);
std::swap(mTokType, mNext->mTokType);
std::swap(mFlags, mNext->mFlags);
std::swap(mImpl, mNext->mImpl);
if (mImpl->mTemplateSimplifierPointers)
// cppcheck-suppress shadowFunction - TODO: fix this
for (auto *templateSimplifierPointer : *mImpl->mTemplateSimplifierPointers) {
templateSimplifierPointer->token(this);
}
if (mNext->mImpl->mTemplateSimplifierPointers)
// cppcheck-suppress shadowFunction - TODO: fix this
for (auto *templateSimplifierPointer : *mNext->mImpl->mTemplateSimplifierPointers) {
templateSimplifierPointer->token(mNext);
}
if (mNext->mLink)
mNext->mLink->mLink = this;
if (this->mLink)
this->mLink->mLink = mNext;
std::swap(mLink, mNext->mLink);
}
}
void Token::takeData(Token *fromToken)
{
mStr = fromToken->mStr;
tokType(fromToken->mTokType);
mFlags = fromToken->mFlags;
delete mImpl;
mImpl = fromToken->mImpl;
fromToken->mImpl = nullptr;
if (mImpl->mTemplateSimplifierPointers)
// cppcheck-suppress shadowFunction - TODO: fix this
for (auto *templateSimplifierPointer : *mImpl->mTemplateSimplifierPointers) {
templateSimplifierPointer->token(this);
}
mLink = fromToken->mLink;
if (mLink)
mLink->link(this);
}
void Token::deleteThis()
{
if (mNext) { // Copy next to this and delete next
takeData(mNext);
mNext->link(nullptr); // mark as unlinked
deleteNext();
} else if (mPrevious) { // Copy previous to this and delete previous
takeData(mPrevious);
mPrevious->link(nullptr);
deletePrevious();
} else {
// We are the last token in the list, we can't delete
// ourselves, so just make us empty
str(";");
}
}
void Token::replace(Token *replaceThis, Token *start, Token *end)
{
// Fix the whole in the old location of start and end
if (start->previous())
start->previous()->next(end->next());
if (end->next())
end->next()->previous(start->previous());
// Move start and end to their new location
if (replaceThis->previous())
replaceThis->previous()->next(start);
if (replaceThis->next())
replaceThis->next()->previous(end);
start->previous(replaceThis->previous());
end->next(replaceThis->next());
if (end->mTokensFrontBack.back == end) {
while (end->next())
end = end->next();
end->mTokensFrontBack.back = end;
}
// Update mProgressValue, fileIndex and linenr
for (Token *tok = start; tok != end->next(); tok = tok->next())
tok->mImpl->mProgressValue = replaceThis->mImpl->mProgressValue;
// Delete old token, which is replaced
delete replaceThis;
}
static
#if defined(__GNUC__)
// GCC does not inline this by itself
// need to use the old syntax since the C++11 [[xxx:always_inline]] cannot be used here
inline __attribute__((always_inline))
#endif
int multiComparePercent(const Token *tok, const char*& haystack, nonneg int varid)
{
++haystack;
// Compare only the first character of the string for optimization reasons
switch (haystack[0]) {
case 'v':
if (haystack[3] == '%') { // %var%
haystack += 4;
if (tok->varId() != 0)
return 1;
} else { // %varid%
if (varid == 0) {
throw InternalError(tok, "Internal error. Token::Match called with varid 0. Please report this to Cppcheck developers");
}
haystack += 6;
if (tok->varId() == varid)
return 1;
}
break;
case 't':
// Type (%type%)
{
haystack += 5;
if (tok->isName() && tok->varId() == 0)
return 1;
}
break;
case 'a':
// Accept any token (%any%) or assign (%assign%)
{
if (haystack[3] == '%') { // %any%
haystack += 4;
return 1;
}
// %assign%
haystack += 7;
if (tok->isAssignmentOp())
return 1;
}
break;
case 'n':
// Number (%num%) or name (%name%)
{
if (haystack[4] == '%') { // %name%
haystack += 5;
if (tok->isName())
return 1;
} else {
haystack += 4;
if (tok->isNumber())
return 1;
}
}
break;
case 'c': {
haystack += 1;
// Character (%char%)
if (haystack[0] == 'h') {
haystack += 4;
if (tok->tokType() == Token::eChar)
return 1;
}
// Const operator (%cop%)
else if (haystack[1] == 'p') {
haystack += 3;
if (tok->isConstOp())
return 1;
}
// Comparison operator (%comp%)
else {
haystack += 4;
if (tok->isComparisonOp())
return 1;
}
}
break;
case 's':
// String (%str%)
{
haystack += 4;
if (tok->tokType() == Token::eString)
return 1;
}
break;
case 'b':
// Bool (%bool%)
{
haystack += 5;
if (tok->isBoolean())
return 1;
}
break;
case 'o': {
++haystack;
if (haystack[1] == '%') {
// Op (%op%)
if (haystack[0] == 'p') {
haystack += 2;
if (tok->isOp())
return 1;
}
// Or (%or%)
else {
haystack += 2;
if (tok->tokType() == Token::eBitOp && tok->str() == "|")
return 1;
}
}
// Oror (%oror%)
else {
haystack += 4;
if (tok->tokType() == Token::eLogicalOp && tok->str() == "||")
return 1;
}
}
break;
default:
//unknown %cmd%, abort
throw InternalError(tok, "Unexpected command");
}
if (*haystack == '|')
haystack += 1;
else
return -1;
return 0xFFFF;
}
static
#if defined(__GNUC__)
// need to use the old syntax since the C++11 [[xxx:always_inline]] cannot be used here
inline __attribute__((always_inline))
#endif
int multiCompareImpl(const Token *tok, const char *haystack, nonneg int varid)
{
const char *needle = tok->str().c_str();
const char *needlePointer = needle;
for (;;) {
if (needlePointer == needle && haystack[0] == '%' && haystack[1] != '|' && haystack[1] != '\0' && haystack[1] != ' ') {
const int ret = multiComparePercent(tok, haystack, varid);
if (ret < 2)
return ret;
} else if (*haystack == '|') {
if (*needlePointer == 0) {
// If needle is at the end, we have a match.
return 1;
}
needlePointer = needle;
++haystack;
} else if (*needlePointer == *haystack) {
if (*needlePointer == '\0')
return 1;
++needlePointer;
++haystack;
} else if (*haystack == ' ' || *haystack == '\0') {
if (needlePointer == needle)
return 0;
break;
}
// If haystack and needle don't share the same character,
// find next '|' character.
else {
needlePointer = needle;
do {
++haystack;
if (*haystack == ' ' || *haystack == '\0') {
return -1;
}
if (*haystack == '|') {
break;
}
} while (true);
++haystack;
}
}
if (*needlePointer == '\0')
return 1;
return -1;
}
// cppcheck-suppress unusedFunction - used in tests only
int Token::multiCompare(const Token *tok, const char *haystack, nonneg int varid)
{
return multiCompareImpl(tok, haystack, varid);
}
bool Token::simpleMatch(const Token *tok, const char pattern[], size_t pattern_len)
{
if (!tok)
return false; // shortcut
const char *current = pattern;
const char *end = pattern + pattern_len;
// cppcheck-suppress shadowFunction - TODO: fix this
const char *next = static_cast<const char*>(std::memchr(pattern, ' ', pattern_len));
if (!next)
next = end;
while (*current) {
const std::size_t length = next - current;
if (!tok || length != tok->mStr.length() || std::strncmp(current, tok->mStr.c_str(), length) != 0)
return false;
current = next;
if (*next) {
next = std::strchr(++current, ' ');
if (!next)
next = end;
}
tok = tok->next();
}
return true;
}
bool Token::firstWordEquals(const char *str, const char *word)
{
for (;;) {
if (*str != *word)
return (*str == ' ' && *word == 0);
if (*str == 0)
break;
++str;
++word;
}
return true;
}
const char *Token::chrInFirstWord(const char *str, char c)
{
for (;;) {
if (*str == ' ' || *str == 0)
return nullptr;
if (*str == c)
return str;
++str;
}
}
bool Token::Match(const Token *tok, const char pattern[], nonneg int varid)
{
if (!(*pattern))
return true;
const char *p = pattern;
while (true) {
// Skip spaces in pattern..
while (*p == ' ')
++p;
// No token => Success!
if (*p == '\0')
break;
if (!tok) {
// If we have no tokens, pattern "!!else" should return true
if (p[0] == '!' && p[1] == '!' && p[2] != '\0') {
while (*p && *p != ' ')
++p;
continue;
}
return false;
}
// [.. => search for a one-character token..
if (p[0] == '[' && chrInFirstWord(p, ']')) {
if (tok->str().length() != 1)
return false;
const char *temp = p+1;
bool chrFound = false;
int count = 0;
while (*temp && *temp != ' ') {
if (*temp == ']') {
++count;
}
else if (*temp == tok->str()[0]) {
chrFound = true;
break;
}
++temp;
}
if (count > 1 && tok->str()[0] == ']')
chrFound = true;
if (!chrFound)
return false;
p = temp;
}
// Parse "not" options. Token can be anything except the given one
else if (p[0] == '!' && p[1] == '!' && p[2] != '\0') {
p += 2;
if (firstWordEquals(p, tok->str().c_str()))
return false;
}
// Parse multi options, such as void|int|char (accept token which is one of these 3)
else {
const int res = multiCompareImpl(tok, p, varid);
if (res == 0) {
// Empty alternative matches, use the same token on next round
while (*p && *p != ' ')
++p;
continue;
}
if (res == -1) {
// No match
return false;
}
}
// using strchr() for the other instances leads to a performance decrease
if (!(p = strchr(p, ' ')))
break;
tok = tok->next();
}
// The end of the pattern has been reached and nothing wrong has been found
return true;
}
nonneg int Token::getStrLength(const Token *tok)
{
assert(tok != nullptr);
assert(tok->mTokType == eString);
const std::string s(replaceEscapeSequences(getStringLiteral(tok->str())));
const auto pos = s.find('\0');
return pos < s.size() ? pos : s.size();
}
nonneg int Token::getStrArraySize(const Token *tok)
{
assert(tok != nullptr);
assert(tok->tokType() == eString);
// cppcheck-suppress shadowFunction - TODO: fix this
const std::string str(getStringLiteral(tok->str()));
int sizeofstring = 1;
for (int i = 0; i < (int)str.size(); i++) {
if (str[i] == '\\')
++i;
++sizeofstring;
}
return sizeofstring;
}
nonneg int Token::getStrSize(const Token *tok, const Settings &settings)
{
assert(tok != nullptr && tok->tokType() == eString);
nonneg int sizeofType = 1;
if (tok->valueType()) {
ValueType vt(*tok->valueType());
vt.pointer = 0;
sizeofType = ValueFlow::getSizeOf(vt, settings);
}
return getStrArraySize(tok) * sizeofType;
}
void Token::move(Token *srcStart, Token *srcEnd, Token *newLocation)
{
/**[newLocation] -> b -> c -> [srcStart] -> [srcEnd] -> f */
// Fix the gap, which tokens to be moved will leave
srcStart->previous()->next(srcEnd->next());
srcEnd->next()->previous(srcStart->previous());
// Fix the tokens to be moved
srcEnd->next(newLocation->next());
srcStart->previous(newLocation);
// Fix the tokens at newLocation
newLocation->next()->previous(srcEnd);
newLocation->next(srcStart);
// Update _progressValue
for (Token *tok = srcStart; tok != srcEnd->next(); tok = tok->next())
tok->mImpl->mProgressValue = newLocation->mImpl->mProgressValue;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T* nextArgumentImpl(T *thisTok)
{
for (T* tok = thisTok; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
if (tok->link() && Token::Match(tok, "(|{|[|<"))
tok = tok->link();
else if (Token::Match(tok, ")|;"))
return nullptr;
}
return nullptr;
}
const Token* Token::nextArgument() const
{
return nextArgumentImpl(this);
}
Token *Token::nextArgument()
{
return nextArgumentImpl(this);
}
const Token* Token::nextArgumentBeforeCreateLinks2() const
{
for (const Token* tok = this; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
if (tok->link() && Token::Match(tok, "(|{|["))
tok = tok->link();
else if (tok->str() == "<") {
const Token* temp = tok->findClosingBracket();
if (temp)
tok = temp;
} else if (Token::Match(tok, ")|;"))
return nullptr;
}
return nullptr;
}
const Token* Token::nextTemplateArgument() const
{
for (const Token* tok = this; tok; tok = tok->next()) {
if (tok->str() == ",")
return tok->next();
if (tok->link() && Token::Match(tok, "(|{|[|<"))
tok = tok->link();
else if (Token::Match(tok, ">|;"))
return nullptr;
}
return nullptr;
}
static bool isOperator(const Token *tok)
{
if (tok->link())
tok = tok->link();
// TODO handle multi token operators
return tok->strAt(-1) == "operator";
}
const Token * Token::findClosingBracket() const
{
if (mStr != "<")
return nullptr;
if (!mPrevious)
return nullptr;
if (!(mPrevious->isName() || Token::simpleMatch(mPrevious, "]") ||
Token::Match(mPrevious->previous(), "operator %op% <") ||
Token::Match(mPrevious->tokAt(-2), "operator [([] [)]] <")))
return nullptr;
const Token *closing = nullptr;
const bool templateParameter(strAt(-1) == "template");
std::set<std::string> templateParameters;
bool isDecl = true;
for (const Token *prev = previous(); prev; prev = prev->previous()) {
if (prev->str() == "=")
isDecl = false;
if (Token::simpleMatch(prev, "template <"))
isDecl = true;
if (Token::Match(prev, "[;{}]"))
break;
}
unsigned int depth = 0;
for (closing = this; closing != nullptr; closing = closing->next()) {
if (Token::Match(closing, "{|[|(")) {
closing = closing->link();
if (!closing)
return nullptr; // #6803
} else if (Token::Match(closing, "}|]|)|;"))
return nullptr;
// we can make some guesses for template parameters
else if (closing->str() == "<" && closing->previous() &&
(closing->previous()->isName() || Token::simpleMatch(closing->previous(), "]") || isOperator(closing->previous())) &&
(templateParameter ? templateParameters.find(closing->strAt(-1)) == templateParameters.end() : true))
++depth;
else if (closing->str() == ">") {
if (--depth == 0)
return closing;
} else if (closing->str() == ">>" || closing->str() == ">>=") {
if (!isDecl && depth == 1)
continue;
if (depth <= 2)
return closing;
depth -= 2;
}
// save named template parameter
else if (templateParameter && depth == 1 && Token::Match(closing, "[,=]") &&
closing->previous()->isName() && !Token::Match(closing->previous(), "class|typename|.") && !Token::Match(closing->tokAt(-2), "=|::"))
templateParameters.insert(closing->strAt(-1));
}
return closing;
}
Token * Token::findClosingBracket()
{
// return value of const function
return const_cast<Token*>(static_cast<const Token*>(this)->findClosingBracket());
}
const Token * Token::findOpeningBracket() const
{
if (mStr != ">")
return nullptr;
const Token *opening = nullptr;
unsigned int depth = 0;
for (opening = this; opening != nullptr; opening = opening->previous()) {
if (Token::Match(opening, "}|]|)")) {
opening = opening->link();
if (!opening)
return nullptr;
} else if (Token::Match(opening, "{|{|(|;"))
return nullptr;
else if (opening->str() == ">")
++depth;
else if (opening->str() == "<") {
if (--depth == 0)
return opening;
}
}
return opening;
}
Token * Token::findOpeningBracket()
{
// return value of const function
return const_cast<Token*>(static_cast<const Token*>(this)->findOpeningBracket());
}
//---------------------------------------------------------------------------
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *findsimplematchImpl(T * const startTok, const char pattern[], size_t pattern_len)
{
for (T* tok = startTok; tok; tok = tok->next()) {
if (Token::simpleMatch(tok, pattern, pattern_len))
return tok;
}
return nullptr;
}
const Token *Token::findsimplematch(const Token * const startTok, const char pattern[], size_t pattern_len)
{
return findsimplematchImpl(startTok, pattern, pattern_len);
}
Token *Token::findsimplematch(Token * const startTok, const char pattern[], size_t pattern_len)
{
return findsimplematchImpl(startTok, pattern, pattern_len);
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *findsimplematchImpl(T * const startTok, const char pattern[], size_t pattern_len, const Token * const end)
{
for (T* tok = startTok; tok && tok != end; tok = tok->next()) {
if (Token::simpleMatch(tok, pattern, pattern_len))
return tok;
}
return nullptr;
}
const Token *Token::findsimplematch(const Token * const startTok, const char pattern[], size_t pattern_len, const Token * const end)
{
return findsimplematchImpl(startTok, pattern, pattern_len, end);
}
Token *Token::findsimplematch(Token * const startTok, const char pattern[], size_t pattern_len, const Token * const end) {
return findsimplematchImpl(startTok, pattern, pattern_len, end);
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *findmatchImpl(T * const startTok, const char pattern[], const nonneg int varId)
{
for (T* tok = startTok; tok; tok = tok->next()) {
if (Token::Match(tok, pattern, varId))
return tok;
}
return nullptr;
}
const Token *Token::findmatch(const Token * const startTok, const char pattern[], const nonneg int varId)
{
return findmatchImpl(startTok, pattern, varId);
}
Token *Token::findmatch(Token * const startTok, const char pattern[], const nonneg int varId) {
return findmatchImpl(startTok, pattern, varId);
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *findmatchImpl(T * const startTok, const char pattern[], const Token * const end, const nonneg int varId)
{
for (T* tok = startTok; tok && tok != end; tok = tok->next()) {
if (Token::Match(tok, pattern, varId))
return tok;
}
return nullptr;
}
const Token *Token::findmatch(const Token * const startTok, const char pattern[], const Token * const end, const nonneg int varId)
{
return findmatchImpl(startTok, pattern, end, varId);
}
Token *Token::findmatch(Token * const startTok, const char pattern[], const Token * const end, const nonneg int varId) {
return findmatchImpl(startTok, pattern, end, varId);
}
void Token::function(const Function *f)
{
mImpl->mFunction = f;
if (f) {
if (f->isLambda())
tokType(eLambda);
else
tokType(eFunction);
} else if (mTokType == eFunction)
tokType(eName);
}
Token* Token::insertToken(const std::string& tokenStr, const std::string& originalNameStr, const std::string& macroNameStr, bool prepend)
{
Token *newToken;
if (mStr.empty())
newToken = this;
else
newToken = new Token(mTokensFrontBack);
newToken->str(tokenStr);
newToken->originalName(originalNameStr);
newToken->setMacroName(macroNameStr);
if (newToken != this) {
newToken->mImpl->mLineNumber = mImpl->mLineNumber;
newToken->mImpl->mFileIndex = mImpl->mFileIndex;
newToken->mImpl->mProgressValue = mImpl->mProgressValue;
if (prepend) {
if (this->previous()) {
newToken->previous(this->previous());
newToken->previous()->next(newToken);
} else {
mTokensFrontBack.front = newToken;
}
this->previous(newToken);
newToken->next(this);
} else {
if (this->next()) {
newToken->next(this->next());
newToken->next()->previous(newToken);
} else {
mTokensFrontBack.back = newToken;
}
this->next(newToken);
newToken->previous(this);
}
if (mImpl->mScopeInfo) {
// If the brace is immediately closed there is no point opening a new scope for it
if (newToken->str() == "{") {
std::string nextScopeNameAddition;
// This might be the opening of a member function
Token *tok1 = newToken;
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->previous() && tok1->strAt(-1) == ")") {
tok1 = tok1->linkAt(-1);
if (Token::Match(tok1->previous(), "throw|noexcept")) {
tok1 = tok1->previous();
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->strAt(-1) != ")")
return newToken;
} else if (Token::Match(newToken->tokAt(-2), ":|, %name%")) {
tok1 = tok1->tokAt(-2);
if (tok1->strAt(-1) != ")")
return newToken;
}
if (tok1->strAt(-1) == ">")
tok1 = tok1->previous()->findOpeningBracket();
if (tok1 && Token::Match(tok1->tokAt(-3), "%name% :: %name%")) {
tok1 = tok1->tokAt(-2);
// cppcheck-suppress shadowFunction - TODO: fix this
std::string scope = tok1->strAt(-1);
while (Token::Match(tok1->tokAt(-2), ":: %name%")) {
scope = tok1->strAt(-3) + " :: " + scope;
tok1 = tok1->tokAt(-2);
}
nextScopeNameAddition += scope;
}
}
// Or it might be a namespace/class/struct
if (Token::Match(newToken->previous(), "%name%|>")) {
Token* nameTok = newToken->previous();
while (nameTok && !Token::Match(nameTok, "namespace|class|struct|union %name% {|::|:|<")) {
nameTok = nameTok->previous();
}
if (nameTok) {
for (nameTok = nameTok->next(); nameTok && !Token::Match(nameTok, "{|:|<"); nameTok = nameTok->next()) {
nextScopeNameAddition.append(nameTok->str());
nextScopeNameAddition.append(" ");
}
if (!nextScopeNameAddition.empty())
nextScopeNameAddition.pop_back();
}
}
// New scope is opening, record it here
std::shared_ptr<ScopeInfo2> newScopeInfo = std::make_shared<ScopeInfo2>(mImpl->mScopeInfo->name, nullptr, mImpl->mScopeInfo->usingNamespaces);
if (!newScopeInfo->name.empty() && !nextScopeNameAddition.empty()) newScopeInfo->name.append(" :: ");
newScopeInfo->name.append(nextScopeNameAddition);
nextScopeNameAddition = "";
newToken->scopeInfo(std::move(newScopeInfo));
} else if (newToken->str() == "}") {
Token* matchingTok = newToken->previous();
int depth = 0;
while (matchingTok && (depth != 0 || !Token::simpleMatch(matchingTok, "{"))) {
if (Token::simpleMatch(matchingTok, "}")) depth++;
if (Token::simpleMatch(matchingTok, "{")) depth--;
matchingTok = matchingTok->previous();
}
if (matchingTok && matchingTok->previous()) {
newToken->mImpl->mScopeInfo = matchingTok->previous()->scopeInfo();
}
} else {
if (prepend && newToken->previous()) {
newToken->mImpl->mScopeInfo = newToken->previous()->scopeInfo();
} else {
newToken->mImpl->mScopeInfo = mImpl->mScopeInfo;
}
if (newToken->str() == ";") {
const Token* statementStart = newToken;
while (statementStart->previous() && !Token::Match(statementStart->previous(), ";|{")) {
statementStart = statementStart->previous();
}
if (Token::Match(statementStart, "using namespace %name% ::|;")) {
const Token * tok1 = statementStart->tokAt(2);
std::string nameSpace;
while (tok1 && tok1->str() != ";") {
if (!nameSpace.empty())
nameSpace += " ";
nameSpace += tok1->str();
tok1 = tok1->next();
}
mImpl->mScopeInfo->usingNamespaces.insert(nameSpace);
}
}
}
}
}
return newToken;
}
void Token::eraseTokens(Token *begin, const Token *end)
{
if (!begin || begin == end)
return;
while (begin->next() && begin->next() != end) {
begin->deleteNext();
}
}
void Token::createMutualLinks(Token *begin, Token *end)
{
assert(begin != nullptr);
assert(end != nullptr);
assert(begin != end);
begin->link(end);
end->link(begin);
}
void Token::printOut() const
{
printOut(std::cout, "");
}
void Token::printOut(std::ostream& out, const char *title) const
{
if (title && title[0])
out << "\n### " << title << " ###\n";
out << stringifyList(stringifyOptions::forPrintOut(), nullptr, nullptr) << std::endl;
}
void Token::printOut(std::ostream& out, const char *title, const std::vector<std::string> &fileNames) const
{
if (title && title[0])
out << "\n### " << title << " ###\n";
out << stringifyList(stringifyOptions::forPrintOut(), &fileNames, nullptr) << std::endl;
}
// cppcheck-suppress unusedFunction - used for debugging
void Token::printLines(std::ostream& out, int lines) const
{
const Token *end = this;
while (end && end->linenr() < lines + linenr())
end = end->next();
out << stringifyList(stringifyOptions::forDebugExprId(), nullptr, end) << std::endl;
}
std::string Token::stringify(const stringifyOptions& options) const
{
std::string ret;
if (options.attributes) {
if (isUnsigned())
ret += "unsigned ";
else if (isSigned())
ret += "signed ";
if (isComplex())
ret += "_Complex ";
if (isLong()) {
if (!(mTokType == eString || mTokType == eChar))
ret += "long ";
}
}
if (options.macro && isExpandedMacro())
ret += '$';
if (isName() && mStr.find(' ') != std::string::npos) {
for (const char i : mStr) {
if (i != ' ')
ret += i;
}
} else if (mStr[0] != '\"' || mStr.find('\0') == std::string::npos)
ret += mStr;
else {
for (const char i : mStr) {
if (i == '\0')
ret += "\\0";
else
ret += i;
}
}
if (options.varid && mImpl->mVarId != 0) {
ret += '@';
ret += (options.idtype ? "var" : "");
ret += std::to_string(mImpl->mVarId);
} else if (options.exprid && mImpl->mExprId != 0) {
ret += '@';
ret += (options.idtype ? "expr" : "");
if ((mImpl->mExprId & (1U << efIsUnique)) != 0)
ret += "UNIQUE";
else
ret += std::to_string(mImpl->mExprId);
}
return ret;
}
std::string Token::stringify(bool varid, bool attributes, bool macro) const
{
stringifyOptions options;
options.varid = varid;
options.attributes = attributes;
options.macro = macro;
return stringify(options);
}
std::string Token::stringifyList(const stringifyOptions& options, const std::vector<std::string>* fileNames, const Token* end) const
{
if (this == end)
return "";
std::string ret;
unsigned int lineNumber = mImpl->mLineNumber - (options.linenumbers ? 1U : 0U);
// cppcheck-suppress shadowFunction - TODO: fix this
unsigned int fileIndex = options.files ? ~0U : mImpl->mFileIndex;
std::map<int, unsigned int> lineNumbers;
for (const Token *tok = this; tok != end; tok = tok->next()) {
assert(tok && "end precedes token");
if (!tok)
return ret;
bool fileChange = false;
if (tok->mImpl->mFileIndex != fileIndex) {
if (fileIndex != ~0U) {
lineNumbers[fileIndex] = tok->mImpl->mFileIndex;
}
fileIndex = tok->mImpl->mFileIndex;
if (options.files) {
ret += "\n\n##file ";
if (fileNames && fileNames->size() > tok->mImpl->mFileIndex)
ret += fileNames->at(tok->mImpl->mFileIndex);
else
ret += std::to_string(fileIndex);
ret += '\n';
}
lineNumber = lineNumbers[fileIndex];
fileChange = true;
}
if (options.linebreaks && (lineNumber != tok->linenr() || fileChange)) {
if (lineNumber+4 < tok->linenr() && fileIndex == tok->mImpl->mFileIndex) {
ret += '\n';
ret += std::to_string(lineNumber+1);
ret += ":\n|\n";
ret += std::to_string(tok->linenr()-1);
ret += ":\n";
ret += std::to_string(tok->linenr());
ret += ": ";
} else if (this == tok && options.linenumbers) {
ret += std::to_string(tok->linenr());
ret += ": ";
} else if (lineNumber > tok->linenr()) {
lineNumber = tok->linenr();
ret += '\n';
if (options.linenumbers) {
ret += std::to_string(lineNumber);
ret += ':';
ret += ' ';
}
} else {
while (lineNumber < tok->linenr()) {
++lineNumber;
ret += '\n';
if (options.linenumbers) {
ret += std::to_string(lineNumber);
ret += ':';
if (lineNumber == tok->linenr())
ret += ' ';
}
}
}
lineNumber = tok->linenr();
}
ret += tok->stringify(options); // print token
if (tok->next() != end && (!options.linebreaks || (tok->next()->linenr() == tok->linenr() && tok->next()->fileIndex() == tok->fileIndex())))
ret += ' ';
}
if (options.linebreaks && (options.files || options.linenumbers))
ret += '\n';
return ret;
}
std::string Token::stringifyList(bool varid, bool attributes, bool linenumbers, bool linebreaks, bool files, const std::vector<std::string>* fileNames, const Token* end) const
{
stringifyOptions options;
options.varid = varid;
options.attributes = attributes;
options.macro = attributes;
options.linenumbers = linenumbers;
options.linebreaks = linebreaks;
options.files = files;
return stringifyList(options, fileNames, end);
}
std::string Token::stringifyList(const Token* end, bool attributes) const
{
return stringifyList(false, attributes, false, false, false, nullptr, end);
}
std::string Token::stringifyList(bool varid) const
{
return stringifyList(varid, false, true, true, true, nullptr, nullptr);
}
void Token::astParent(Token* tok)
{
const Token* tok2 = tok;
while (tok2) {
if (this == tok2)
throw InternalError(this, "Internal error. AST cyclic dependency.");
tok2 = tok2->astParent();
}
// Clear children to avoid nodes referenced twice
if (this->astParent()) {
Token* parent = this->astParent();
if (parent->astOperand1() == this)
parent->mImpl->mAstOperand1 = nullptr;
if (parent->astOperand2() == this)
parent->mImpl->mAstOperand2 = nullptr;
}
mImpl->mAstParent = tok;
}
void Token::astOperand1(Token *tok)
{
if (mImpl->mAstOperand1)
mImpl->mAstOperand1->astParent(nullptr);
// goto parent operator
if (tok) {
tok = tok->astTop();
tok->astParent(this);
}
mImpl->mAstOperand1 = tok;
}
void Token::astOperand2(Token *tok)
{
if (mImpl->mAstOperand2)
mImpl->mAstOperand2->astParent(nullptr);
// goto parent operator
if (tok) {
tok = tok->astTop();
tok->astParent(this);
}
mImpl->mAstOperand2 = tok;
}
static const Token* goToLeftParenthesis(const Token* start, const Token* end)
{
// move start to lpar in such expression: '(*it).x'
int par = 0;
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
if (tok->str() == "(")
++par;
else if (tok->str() == ")") {
if (par == 0)
start = tok->link();
else
--par;
}
}
return start;
}
static const Token* goToRightParenthesis(const Token* start, const Token* end)
{
// move end to rpar in such expression: '2>(x+1)'
int par = 0;
for (const Token *tok = end; tok && tok != start; tok = tok->previous()) {
if (tok->str() == ")")
++par;
else if (tok->str() == "(") {
if (par == 0)
end = tok->link();
else
--par;
}
}
return end;
}
std::pair<const Token *, const Token *> Token::findExpressionStartEndTokens() const
{
const Token * const top = this;
// find start node in AST tree
const Token *start = top;
while (start->astOperand1() && precedes(start->astOperand1(), start))
start = start->astOperand1();
// find end node in AST tree
const Token *end = top;
while (end->astOperand1() && (end->astOperand2() || end->isUnaryPreOp())) {
// lambda..
if (end->str() == "[") {
const Token *lambdaEnd = findLambdaEndToken(end);
if (lambdaEnd) {
end = lambdaEnd;
break;
}
}
if (Token::Match(end,"(|[|{") &&
!(Token::Match(end, "( ::| %type%") && !end->astOperand2())) {
end = end->link();
break;
}
end = end->astOperand2() ? end->astOperand2() : end->astOperand1();
}
// skip parentheses
start = goToLeftParenthesis(start, end);
end = goToRightParenthesis(start, end);
if (Token::simpleMatch(end, "{"))
end = end->link();
if (precedes(top, start))
throw InternalError(start, "Cannot find start of expression");
if (succeeds(top, end))
throw InternalError(end, "Cannot find end of expression");
return std::pair<const Token *, const Token *>(start,end);
}
bool Token::isCalculation() const
{
if (!Token::Match(this, "%cop%|++|--"))
return false;
if (Token::Match(this, "*|&")) {
// dereference or address-of?
if (!this->astOperand2())
return false;
if (this->astOperand2()->str() == "[")
return false;
// type specification?
std::stack<const Token *> operands;
operands.push(this);
while (!operands.empty()) {
const Token *op = operands.top();
operands.pop();
if (op->isNumber() || op->varId() > 0)
return true;
if (op->astOperand1())
operands.push(op->astOperand1());
if (op->astOperand2())
operands.push(op->astOperand2());
else if (Token::Match(op, "*|&"))
return false;
}
// type specification => return false
return false;
}
return true;
}
bool Token::isUnaryPreOp() const
{
if (!astOperand1() || astOperand2())
return false;
if (this->tokType() != Token::eIncDecOp)
return true;
const Token *tokbefore = mPrevious;
const Token *tokafter = mNext;
for (int distance = 1; distance < 10 && tokbefore; distance++) {
if (tokbefore == mImpl->mAstOperand1)
return false;
if (tokafter == mImpl->mAstOperand1)
return true;
tokbefore = tokbefore->mPrevious;
tokafter = tokafter->mPrevious;
}
return false; // <- guess
}
static std::string stringFromTokenRange(const Token* start, const Token* end)
{
std::string ret;
if (end)
end = end->next();
for (const Token *tok = start; tok && tok != end; tok = tok->next()) {
if (tok->isUnsigned())
ret += "unsigned ";
if (tok->isLong() && !tok->isLiteral())
ret += "long ";
if (tok->tokType() == Token::eString) {
for (const unsigned char c: tok->str()) {
if (c == '\n')
ret += "\\n";
else if (c == '\r')
ret += "\\r";
else if (c == '\t')
ret += "\\t";
else if (c >= ' ' && c <= 126)
ret += c;
else {
char str[10];
sprintf(str, "\\x%02x", c);
ret += str;
}
}
} else if (tok->originalName().empty() || tok->isUnsigned() || tok->isLong()) {
ret += tok->str();
} else
ret += tok->originalName();
if (Token::Match(tok, "%name%|%num% %name%|%num%"))
ret += ' ';
}
return ret;
}
std::string Token::expressionString() const
{
const auto tokens = findExpressionStartEndTokens();
return stringFromTokenRange(tokens.first, tokens.second);
}
static void astStringXml(const Token *tok, nonneg int indent, std::ostream &out)
{
const std::string strindent(indent, ' ');
out << strindent << "<token str=\"" << tok->str() << '\"';
if (tok->varId())
out << " varId=\"" << tok->varId() << '\"';
if (tok->variable())
out << " variable=\"" << tok->variable() << '\"';
if (tok->function())
out << " function=\"" << tok->function() << '\"';
if (!tok->values().empty())
out << " values=\"" << &tok->values() << '\"';
if (!tok->astOperand1() && !tok->astOperand2()) {
out << "/>" << std::endl;
}
else {
out << '>' << std::endl;
if (tok->astOperand1())
astStringXml(tok->astOperand1(), indent+2U, out);
if (tok->astOperand2())
astStringXml(tok->astOperand2(), indent+2U, out);
out << strindent << "</token>" << std::endl;
}
}
void Token::printAst(bool verbose, bool xml, const std::vector<std::string> &fileNames, std::ostream &out) const
{
if (!xml)
out << "\n\n##AST" << std::endl;
std::set<const Token *> printed;
for (const Token *tok = this; tok; tok = tok->next()) {
if (!tok->mImpl->mAstParent && tok->mImpl->mAstOperand1) {
if (printed.find(tok) != printed.end())
continue;
printed.insert(tok);
if (xml) {
out << "<ast scope=\"" << tok->scope() << "\" fileIndex=\"" << tok->fileIndex() << "\" linenr=\"" << tok->linenr()
<< "\" column=\"" << tok->column() << "\">" << std::endl;
astStringXml(tok, 2U, out);
out << "</ast>" << std::endl;
} else if (verbose)
out << "[" << fileNames[tok->fileIndex()] << ":" << tok->linenr() << "]" << std::endl << tok->astStringVerbose() << std::endl;
else
out << tok->astString(" ") << std::endl;
if (tok->str() == "(")
tok = tok->link();
}
}
}
static void indent(std::string &str, const nonneg int indent1, const nonneg int indent2)
{
for (int i = 0; i < indent1; ++i)
str += ' ';
for (int i = indent1; i < indent2; i += 2)
str += "| ";
}
void Token::astStringVerboseRecursive(std::string& ret, const nonneg int indent1, const nonneg int indent2) const
{
if (isExpandedMacro())
ret += '$';
ret += mStr;
if (mImpl->mValueType)
ret += " \'" + mImpl->mValueType->str() + '\'';
if (function()) {
std::ostringstream ostr;
ostr << std::hex << function();
ret += " f:" + ostr.str();
}
ret += '\n';
if (mImpl->mAstOperand1) {
int i1 = indent1, i2 = indent2 + 2;
if (indent1 == indent2 && !mImpl->mAstOperand2)
i1 += 2;
indent(ret, indent1, indent2);
ret += mImpl->mAstOperand2 ? "|-" : "`-";
mImpl->mAstOperand1->astStringVerboseRecursive(ret, i1, i2);
}
if (mImpl->mAstOperand2) {
int i1 = indent1, i2 = indent2 + 2;
if (indent1 == indent2)
i1 += 2;
indent(ret, indent1, indent2);
ret += "`-";
mImpl->mAstOperand2->astStringVerboseRecursive(ret, i1, i2);
}
}
std::string Token::astStringVerbose() const
{
std::string ret;
astStringVerboseRecursive(ret);
return ret;
}
// cppcheck-suppress unusedFunction // used in test
std::string Token::astStringZ3() const
{
if (!astOperand1())
return str();
if (!astOperand2())
return "(" + str() + " " + astOperand1()->astStringZ3() + ")";
return "(" + str() + " " + astOperand1()->astStringZ3() + " " + astOperand2()->astStringZ3() + ")";
}
void Token::printValueFlow(bool xml, std::ostream &out) const
{
std::string outs;
// cppcheck-suppress shadowFunction
int fileIndex = -1;
int line = 0;
if (xml)
outs += " <valueflow>\n";
else
outs += "\n\n##Value flow\n";
for (const Token *tok = this; tok; tok = tok->next()) {
// cppcheck-suppress shadowFunction - TODO: fix this
const auto* const values = tok->mImpl->mValues;
if (!values)
continue;
if (values->empty()) // Values might be removed by removeContradictions
continue;
if (xml) {
outs += " <values id=\"";
outs += id_string(values);
outs += "\">";
outs += '\n';
}
else {
if (fileIndex != tok->fileIndex()) {
outs += "File ";
outs += tok->mTokensFrontBack.list.getFiles()[tok->fileIndex()];
outs += '\n';
line = 0;
}
if (line != tok->linenr()) {
outs += "Line ";
outs += std::to_string(tok->linenr());
outs += '\n';
}
}
fileIndex = tok->fileIndex();
line = tok->linenr();
if (!xml) {
ValueFlow::Value::ValueKind valueKind = values->front().valueKind;
const bool same = std::all_of(values->begin(), values->end(), [&](const ValueFlow::Value& value) {
return value.valueKind == valueKind;
});
outs += " ";
outs += tok->str();
outs += " ";
if (same) {
switch (valueKind) {
case ValueFlow::Value::ValueKind::Impossible:
case ValueFlow::Value::ValueKind::Known:
outs += "always ";
break;
case ValueFlow::Value::ValueKind::Inconclusive:
outs += "inconclusive ";
break;
case ValueFlow::Value::ValueKind::Possible:
outs += "possible ";
break;
}
}
if (values->size() > 1U)
outs += '{';
}
for (const ValueFlow::Value& value : *values) {
if (xml) {
outs += " <value ";
switch (value.valueType) {
case ValueFlow::Value::ValueType::INT:
if (tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED) {
outs += "intvalue=\"";
outs += std::to_string(static_cast<MathLib::biguint>(value.intvalue));
outs += '\"';
}
else {
outs += "intvalue=\"";
outs += std::to_string(value.intvalue);
outs += '\"';
}
break;
case ValueFlow::Value::ValueType::TOK:
outs += "tokvalue=\"";
outs += id_string(value.tokvalue);
outs += '\"';
break;
case ValueFlow::Value::ValueType::FLOAT:
outs += "floatvalue=\"";
outs += std::to_string(value.floatValue); // TODO: should this be MathLib::toString()?
outs += '\"';
break;
case ValueFlow::Value::ValueType::MOVED:
outs += "movedvalue=\"";
outs += ValueFlow::Value::toString(value.moveKind);
outs += '\"';
break;
case ValueFlow::Value::ValueType::UNINIT:
outs += "uninit=\"1\"";
break;
case ValueFlow::Value::ValueType::BUFFER_SIZE:
outs += "buffer-size=\"";
outs += std::to_string(value.intvalue);
outs += "\"";
break;
case ValueFlow::Value::ValueType::CONTAINER_SIZE:
outs += "container-size=\"";
outs += std::to_string(value.intvalue);
outs += '\"';
break;
case ValueFlow::Value::ValueType::ITERATOR_START:
outs += "iterator-start=\"";
outs += std::to_string(value.intvalue);
outs += '\"';
break;
case ValueFlow::Value::ValueType::ITERATOR_END:
outs += "iterator-end=\"";
outs += std::to_string(value.intvalue);
outs += '\"';
break;
case ValueFlow::Value::ValueType::LIFETIME:
outs += "lifetime=\"";
outs += id_string(value.tokvalue);
outs += '\"';
outs += " lifetime-scope=\"";
outs += ValueFlow::Value::toString(value.lifetimeScope);
outs += "\"";
outs += " lifetime-kind=\"";
outs += ValueFlow::Value::toString(value.lifetimeKind);
outs += "\"";
break;
case ValueFlow::Value::ValueType::SYMBOLIC:
outs += "symbolic=\"";
outs += id_string(value.tokvalue);
outs += '\"';
outs += " symbolic-delta=\"";
outs += std::to_string(value.intvalue);
outs += '\"';
break;
}
outs += " bound=\"";
outs += ValueFlow::Value::toString(value.bound);
outs += "\"";
if (value.condition) {
outs += " condition-line=\"";
outs += std::to_string(value.condition->linenr());
outs += '\"';
}
if (value.isKnown())
outs += " known=\"true\"";
else if (value.isPossible())
outs += " possible=\"true\"";
else if (value.isImpossible())
outs += " impossible=\"true\"";
else if (value.isInconclusive())
outs += " inconclusive=\"true\"";
outs += " path=\"";
outs += std::to_string(value.path);
outs += "\"";
outs += "/>\n";
}
else {
if (&value != &values->front())
outs += ",";
outs += value.toString();
}
}
if (xml)
outs += " </values>\n";
else if (values->size() > 1U)
outs += "}\n";
else
outs += '\n';
}
if (xml)
outs += " </valueflow>\n";
out << outs;
}
const ValueFlow::Value * Token::getValueLE(const MathLib::bigint val, const Settings &settings) const
{
if (!mImpl->mValues)
return nullptr;
return ValueFlow::findValue(*mImpl->mValues, settings, [&](const ValueFlow::Value& v) {
return !v.isImpossible() && v.isIntValue() && v.intvalue <= val;
});
}
const ValueFlow::Value * Token::getValueGE(const MathLib::bigint val, const Settings &settings) const
{
if (!mImpl->mValues)
return nullptr;
return ValueFlow::findValue(*mImpl->mValues, settings, [&](const ValueFlow::Value& v) {
return !v.isImpossible() && v.isIntValue() && v.intvalue >= val;
});
}
const ValueFlow::Value * Token::getValueNE(MathLib::bigint val) const
{
if (!mImpl->mValues)
return nullptr;
const auto it = std::find_if(mImpl->mValues->cbegin(), mImpl->mValues->cend(), [=](const ValueFlow::Value& value) {
return value.isIntValue() && !value.isImpossible() && value.intvalue != val;
});
return it == mImpl->mValues->end() ? nullptr : &*it;
}
const ValueFlow::Value * Token::getInvalidValue(const Token *ftok, nonneg int argnr, const Settings &settings) const
{
if (!mImpl->mValues)
return nullptr;
const ValueFlow::Value *ret = nullptr;
for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) {
if (it->isImpossible())
continue;
if ((it->isIntValue() && !settings.library.isIntArgValid(ftok, argnr, it->intvalue)) ||
(it->isFloatValue() && !settings.library.isFloatArgValid(ftok, argnr, it->floatValue))) {
if (!ret || ret->isInconclusive() || (ret->condition && !it->isInconclusive()))
ret = &(*it);
if (!ret->isInconclusive() && !ret->condition)
break;
}
}
if (ret) {
if (ret->isInconclusive() && !settings.certainty.isEnabled(Certainty::inconclusive))
return nullptr;
if (ret->condition && !settings.severity.isEnabled(Severity::warning))
return nullptr;
}
return ret;
}
const Token *Token::getValueTokenMinStrSize(const Settings &settings, MathLib::bigint* path) const
{
if (!mImpl->mValues)
return nullptr;
const Token *ret = nullptr;
int minsize = INT_MAX;
for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) {
if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) {
const int size = getStrSize(it->tokvalue, settings);
if (!ret || size < minsize) {
minsize = size;
ret = it->tokvalue;
if (path)
*path = it->path;
}
}
}
return ret;
}
const Token *Token::getValueTokenMaxStrLength() const
{
if (!mImpl->mValues)
return nullptr;
const Token *ret = nullptr;
int maxlength = 0;
for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) {
if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) {
const int length = getStrLength(it->tokvalue);
if (!ret || length > maxlength) {
maxlength = length;
ret = it->tokvalue;
}
}
}
return ret;
}
static bool isAdjacent(const ValueFlow::Value& x, const ValueFlow::Value& y)
{
if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound)
return true;
if (x.valueType == ValueFlow::Value::ValueType::FLOAT)
return false;
return std::abs(x.intvalue - y.intvalue) == 1;
}
static bool removePointValue(std::list<ValueFlow::Value>& values, std::list<ValueFlow::Value>::iterator& x)
{
const bool isPoint = x->bound == ValueFlow::Value::Bound::Point;
if (!isPoint)
x->decreaseRange();
else
x = values.erase(x);
return isPoint;
}
static bool removeContradiction(std::list<ValueFlow::Value>& values)
{
bool result = false;
for (auto itx = values.begin(); itx != values.end(); ++itx) {
if (itx->isNonValue())
continue;
auto ity = itx;
++ity;
for (; ity != values.end(); ++ity) {
if (ity->isNonValue())
continue;
if (*itx == *ity)
continue;
if (itx->valueType != ity->valueType)
continue;
if (itx->isImpossible() == ity->isImpossible())
continue;
if (itx->isSymbolicValue() && !ValueFlow::Value::sameToken(itx->tokvalue, ity->tokvalue))
continue;
if (!itx->equalValue(*ity)) {
auto compare = [](const std::list<ValueFlow::Value>::const_iterator& x, const std::list<ValueFlow::Value>::const_iterator& y) {
return x->compareValue(*y, less{});
};
auto itMax = std::max(itx, ity, compare);
auto itMin = std::min(itx, ity, compare);
// TODO: Adjust non-points instead of removing them
if (itMax->isImpossible() && itMax->bound == ValueFlow::Value::Bound::Upper) {
values.erase(itMin);
return true;
}
if (itMin->isImpossible() && itMin->bound == ValueFlow::Value::Bound::Lower) {
values.erase(itMax);
return true;
}
continue;
}
const bool removex = !itx->isImpossible() || ity->isKnown();
const bool removey = !ity->isImpossible() || itx->isKnown();
if (itx->bound == ity->bound) {
if (removex)
values.erase(itx);
if (removey)
values.erase(ity);
// itx and ity are invalidated
return true;
}
result = removex || removey;
bool bail = false;
if (removex && removePointValue(values, itx))
bail = true;
if (removey && removePointValue(values, ity))
bail = true;
if (bail)
return true;
}
}
return result;
}
using ValueIterator = std::list<ValueFlow::Value>::iterator;
template<class Iterator>
// NOLINTNEXTLINE(performance-unnecessary-value-param) - false positive
static ValueIterator removeAdjacentValues(std::list<ValueFlow::Value>& values, ValueIterator x, Iterator start, Iterator last)
{
if (!isAdjacent(*x, **start))
return std::next(x);
auto it = std::adjacent_find(start, last, [](ValueIterator x, ValueIterator y) {
return !isAdjacent(*x, *y);
});
if (it == last)
it--;
(*it)->bound = x->bound;
std::for_each(std::move(start), std::move(it), [&](ValueIterator y) {
values.erase(y);
});
return values.erase(x);
}
static void mergeAdjacent(std::list<ValueFlow::Value>& values)
{
for (auto x = values.begin(); x != values.end();) {
if (x->isNonValue()) {
x++;
continue;
}
if (x->bound == ValueFlow::Value::Bound::Point) {
x++;
continue;
}
std::vector<ValueIterator> adjValues;
for (auto y = values.begin(); y != values.end(); y++) {
if (x == y)
continue;
if (y->isNonValue())
continue;
if (x->valueType != y->valueType)
continue;
if (x->valueKind != y->valueKind)
continue;
if (x->isSymbolicValue() && !ValueFlow::Value::sameToken(x->tokvalue, y->tokvalue))
continue;
if (x->bound != y->bound) {
if (y->bound != ValueFlow::Value::Bound::Point && isAdjacent(*x, *y)) {
adjValues.clear();
break;
}
// No adjacent points for floating points
if (x->valueType == ValueFlow::Value::ValueType::FLOAT)
continue;
if (y->bound != ValueFlow::Value::Bound::Point)
continue;
}
if (x->bound == ValueFlow::Value::Bound::Lower && !y->compareValue(*x, less{}))
continue;
if (x->bound == ValueFlow::Value::Bound::Upper && !x->compareValue(*y, less{}))
continue;
adjValues.push_back(y);
}
if (adjValues.empty()) {
x++;
continue;
}
std::sort(adjValues.begin(), adjValues.end(), [&values](ValueIterator xx, ValueIterator yy) {
(void)values;
assert(xx != values.end() && yy != values.end());
return xx->compareValue(*yy, less{});
});
if (x->bound == ValueFlow::Value::Bound::Lower)
x = removeAdjacentValues(values, x, adjValues.rbegin(), adjValues.rend());
else if (x->bound == ValueFlow::Value::Bound::Upper)
x = removeAdjacentValues(values, x, adjValues.begin(), adjValues.end());
}
}
static void removeOverlaps(std::list<ValueFlow::Value>& values)
{
for (const ValueFlow::Value& x : values) {
if (x.isNonValue())
continue;
values.remove_if([&](const ValueFlow::Value& y) {
if (y.isNonValue())
return false;
if (&x == &y)
return false;
if (x.valueType != y.valueType)
return false;
if (x.valueKind != y.valueKind)
return false;
// TODO: Remove points covered in a lower or upper bound
// TODO: Remove lower or upper bound already covered by a lower and upper bound
if (!x.equalValue(y))
return false;
if (x.bound != y.bound)
return false;
return true;
});
}
mergeAdjacent(values);
}
// Removing contradictions is an NP-hard problem. Instead we run multiple
// passes to try to catch most contradictions
static void removeContradictions(std::list<ValueFlow::Value>& values)
{
removeOverlaps(values);
for (int i = 0; i < 4; i++) {
if (!removeContradiction(values))
return;
removeOverlaps(values);
}
}
static bool sameValueType(const ValueFlow::Value& x, const ValueFlow::Value& y)
{
if (x.valueType != y.valueType)
return false;
// Symbolic are the same type if they share the same tokvalue
if (x.isSymbolicValue())
return x.tokvalue->exprId() == 0 || x.tokvalue->exprId() == y.tokvalue->exprId();
return true;
}
bool Token::addValue(const ValueFlow::Value &value)
{
if (value.isKnown() && mImpl->mValues) {
// Clear all other values of the same type since value is known
mImpl->mValues->remove_if([&](const ValueFlow::Value& x) {
return sameValueType(x, value);
});
}
// Don't add a value if its already known
if (!value.isKnown() && mImpl->mValues &&
std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& x) {
return x.isKnown() && sameValueType(x, value) && !x.equalValue(value);
}))
return false;
// assert(value.isKnown() || !mImpl->mValues || std::none_of(mImpl->mValues->begin(), mImpl->mValues->end(),
// [&](const ValueFlow::Value& x) {
// return x.isKnown() && sameValueType(x, value);
// }));
if (mImpl->mValues) {
// Don't handle more than 10 values for performance reasons
// TODO: add setting?
if (mImpl->mValues->size() >= 10U)
return false;
// if value already exists, don't add it again
std::list<ValueFlow::Value>::iterator it;
for (it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) {
// different types => continue
if (it->valueType != value.valueType)
continue;
if (it->isImpossible() != value.isImpossible())
continue;
// different value => continue
if (!it->equalValue(value))
continue;
if ((value.isTokValue() || value.isLifetimeValue()) && (it->tokvalue != value.tokvalue) && (it->tokvalue->str() != value.tokvalue->str()))
continue;
// same value, but old value is inconclusive so replace it
if (it->isInconclusive() && !value.isInconclusive() && !value.isImpossible()) {
*it = value;
if (it->varId == 0)
it->varId = mImpl->mVarId;
break;
}
// Same value already exists, don't add new value
return false;
}
// Add value
if (it == mImpl->mValues->end()) {
ValueFlow::Value v(value);
if (v.varId == 0)
v.varId = mImpl->mVarId;
if (v.isKnown() && v.isIntValue())
mImpl->mValues->push_front(std::move(v));
else
mImpl->mValues->push_back(std::move(v));
}
} else {
ValueFlow::Value v(value);
if (v.varId == 0)
v.varId = mImpl->mVarId;
mImpl->mValues = new std::list<ValueFlow::Value>;
mImpl->mValues->push_back(std::move(v));
}
removeContradictions(*mImpl->mValues);
return true;
}
void Token::assignProgressValues(Token *tok)
{
int total_count = 0;
for (Token *tok2 = tok; tok2; tok2 = tok2->next())
++total_count;
int count = 0;
for (Token *tok2 = tok; tok2; tok2 = tok2->next())
tok2->mImpl->mProgressValue = count++ *100 / total_count;
}
void Token::assignIndexes()
{
// cppcheck-suppress shadowFunction - TODO: fix this
int index = (mPrevious ? mPrevious->mImpl->mIndex : 0) + 1;
for (Token *tok = this; tok; tok = tok->next())
tok->mImpl->mIndex = index++;
}
void Token::setValueType(ValueType *vt)
{
if (vt != mImpl->mValueType) {
delete mImpl->mValueType;
mImpl->mValueType = vt;
}
}
const ValueType *Token::argumentType() const {
const Token *top = this;
while (top && !Token::Match(top->astParent(), ",|("))
top = top->astParent();
return top ? top->mImpl->mValueType : nullptr;
}
void Token::type(const ::Type *t)
{
mImpl->mType = t;
if (t) {
tokType(eType);
isEnumType(mImpl->mType->isEnumType());
} else if (mTokType == eType)
tokType(eName);
}
const ::Type* Token::typeOf(const Token* tok, const Token** typeTok)
{
if (!tok)
return nullptr;
if (typeTok != nullptr)
*typeTok = tok;
const Token* lhsVarTok{};
if (tok->type())
return tok->type();
if (tok->variable())
return tok->variable()->type();
if (tok->function())
return tok->function()->retType;
if (Token::simpleMatch(tok, "return")) {
// cppcheck-suppress shadowFunction - TODO: fix this
const Scope *scope = tok->scope();
if (!scope)
return nullptr;
// cppcheck-suppress shadowFunction - TODO: fix this
const Function *function = scope->function;
if (!function)
return nullptr;
return function->retType;
}
if (Token::Match(tok->previous(), "%type%|= (|{"))
return typeOf(tok->previous(), typeTok);
if (Token::simpleMatch(tok, "=") && (lhsVarTok = getLHSVariableToken(tok)) != tok->next())
return Token::typeOf(lhsVarTok, typeTok);
if (Token::simpleMatch(tok, "."))
return Token::typeOf(tok->astOperand2(), typeTok);
if (Token::simpleMatch(tok, "["))
return Token::typeOf(tok->astOperand1(), typeTok);
if (Token::simpleMatch(tok, "{")) {
int argnr;
const Token* ftok = getTokenArgumentFunction(tok, argnr);
if (argnr < 0)
return nullptr;
if (!ftok)
return nullptr;
if (ftok == tok)
return nullptr;
std::vector<const Variable*> vars = getArgumentVars(ftok, argnr);
if (vars.empty())
return nullptr;
if (std::all_of(
vars.cbegin(), vars.cend(), [&](const Variable* var) {
return var->type() == vars.front()->type();
}))
return vars.front()->type();
}
return nullptr;
}
std::pair<const Token*, const Token*> Token::typeDecl(const Token* tok, bool pointedToType)
{
if (!tok)
return {};
if (tok->type())
return {tok, tok->next()};
if (tok->variable()) {
const Variable *var = tok->variable();
if (!var->typeStartToken() || !var->typeEndToken())
return {};
if (pointedToType && astIsSmartPointer(var->nameToken())) {
const ValueType* vt = var->valueType();
if (vt && vt->smartPointerTypeToken)
return { vt->smartPointerTypeToken, vt->smartPointerTypeToken->linkAt(-1) };
}
if (pointedToType && astIsIterator(var->nameToken())) {
const ValueType* vt = var->valueType();
if (vt && vt->containerTypeToken)
return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) };
}
std::pair<const Token*, const Token*> result;
if (Token::simpleMatch(var->typeStartToken(), "auto")) {
const Token * tok2 = var->declEndToken();
if (Token::Match(tok2, "; %varid% =", var->declarationId()))
tok2 = tok2->tokAt(2);
if (Token::simpleMatch(tok2, "=") && Token::Match(tok2->astOperand2(), "!!=") && tok != tok2->astOperand2()) {
tok2 = tok2->astOperand2();
if (Token::simpleMatch(tok2, "[") && tok2->astOperand1()) {
const ValueType* vt = tok2->astOperand1()->valueType();
if (vt && vt->containerTypeToken)
return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) };
}
const Token* varTok = tok2; // try to find a variable
if (Token::Match(varTok, ":: %name%"))
varTok = varTok->next();
while (Token::Match(varTok, "%name% ::"))
varTok = varTok->tokAt(2);
std::pair<const Token*, const Token*> r = typeDecl(varTok);
if (r.first)
return r;
if (pointedToType && tok2->astOperand1() && Token::simpleMatch(tok2, "new")) {
if (Token::simpleMatch(tok2->astOperand1(), "("))
return { tok2->next(), tok2->astOperand1() };
const Token* declEnd = nextAfterAstRightmostLeaf(tok2->astOperand1());
if (Token::simpleMatch(declEnd, "<") && declEnd->link())
declEnd = declEnd->link()->next();
return { tok2->next(), declEnd };
}
const Token *typeBeg{}, *typeEnd{};
if (tok2->str() == "::" && Token::simpleMatch(tok2->astOperand2(), "{")) { // empty initlist
typeBeg = previousBeforeAstLeftmostLeaf(tok2);
typeEnd = tok2->astOperand2();
}
else if (tok2->str() == "{") {
typeBeg = previousBeforeAstLeftmostLeaf(tok2);
typeEnd = tok2;
}
if (typeBeg)
result = { typeBeg->next(), typeEnd }; // handle smart pointers/iterators first
}
if (astIsRangeBasedForDecl(var->nameToken()) && astIsContainer(var->nameToken()->astParent()->astOperand2())) { // range-based for
const ValueType* vt = var->nameToken()->astParent()->astOperand2()->valueType();
if (vt && vt->containerTypeToken)
return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) };
}
}
if (result.first)
return result;
return {var->typeStartToken(), var->typeEndToken()->next()};
}
if (Token::simpleMatch(tok, "return")) {
// cppcheck-suppress shadowFunction - TODO: fix this
const Scope* scope = tok->scope();
if (!scope)
return {};
// cppcheck-suppress shadowFunction - TODO: fix this
const Function* function = scope->function;
if (!function)
return {};
return { function->retDef, function->returnDefEnd() };
}
if (tok->previous() && tok->previous()->function()) {
// cppcheck-suppress shadowFunction - TODO: fix this
const Function *function = tok->previous()->function();
return {function->retDef, function->returnDefEnd()};
}
if (Token::simpleMatch(tok, "="))
return Token::typeDecl(tok->astOperand1());
if (Token::simpleMatch(tok, "."))
return Token::typeDecl(tok->astOperand2());
const ::Type * t = typeOf(tok);
if (!t || !t->classDef)
return {};
return {t->classDef->next(), t->classDef->tokAt(2)};
}
std::string Token::typeStr(const Token* tok)
{
if (tok->valueType()) {
const ValueType * vt = tok->valueType();
std::string ret = vt->str();
if (!ret.empty())
return ret;
}
std::pair<const Token*, const Token*> r = Token::typeDecl(tok);
if (!r.first || !r.second)
return "";
return r.first->stringifyList(r.second, false);
}
void Token::scopeInfo(std::shared_ptr<ScopeInfo2> newScopeInfo)
{
mImpl->mScopeInfo = std::move(newScopeInfo);
}
std::shared_ptr<ScopeInfo2> Token::scopeInfo() const
{
return mImpl->mScopeInfo;
}
bool Token::hasKnownIntValue() const
{
if (!mImpl->mValues)
return false;
return std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [](const ValueFlow::Value& value) {
return value.isKnown() && value.isIntValue();
});
}
bool Token::hasKnownValue() const
{
return mImpl->mValues && std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), std::mem_fn(&ValueFlow::Value::isKnown));
}
bool Token::hasKnownValue(ValueFlow::Value::ValueType t) const
{
return mImpl->mValues &&
std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) {
return value.isKnown() && value.valueType == t;
});
}
bool Token::hasKnownSymbolicValue(const Token* tok) const
{
if (tok->exprId() == 0)
return false;
return mImpl->mValues &&
std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) {
return value.isKnown() && value.isSymbolicValue() && value.tokvalue &&
value.tokvalue->exprId() == tok->exprId();
});
}
const ValueFlow::Value* Token::getKnownValue(ValueFlow::Value::ValueType t) const
{
if (!mImpl->mValues)
return nullptr;
auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) {
return value.isKnown() && value.valueType == t;
});
return it == mImpl->mValues->end() ? nullptr : &*it;
}
const ValueFlow::Value* Token::getValue(const MathLib::bigint val) const
{
if (!mImpl->mValues)
return nullptr;
const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [=](const ValueFlow::Value& value) {
return value.isIntValue() && !value.isImpossible() && value.intvalue == val;
});
return it == mImpl->mValues->end() ? nullptr : &*it;
}
template<class Compare>
static const ValueFlow::Value* getCompareValue(const std::list<ValueFlow::Value>& values,
bool condition,
MathLib::bigint path,
Compare compare)
{
const ValueFlow::Value* ret = nullptr;
for (const ValueFlow::Value& value : values) {
if (!value.isIntValue())
continue;
if (value.isImpossible())
continue;
if (path > -0 && value.path != 0 && value.path != path)
continue;
if ((!ret || compare(value.intvalue, ret->intvalue)) && ((value.condition != nullptr) == condition))
ret = &value;
}
return ret;
}
const ValueFlow::Value* Token::getMaxValue(bool condition, MathLib::bigint path) const
{
if (!mImpl->mValues)
return nullptr;
return getCompareValue(*mImpl->mValues, condition, path, std::greater<MathLib::bigint>{});
}
const ValueFlow::Value* Token::getMinValue(bool condition, MathLib::bigint path) const
{
if (!mImpl->mValues)
return nullptr;
return getCompareValue(*mImpl->mValues, condition, path, std::less<MathLib::bigint>{});
}
const ValueFlow::Value* Token::getMovedValue() const
{
if (!mImpl->mValues)
return nullptr;
const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [](const ValueFlow::Value& value) {
return value.isMovedValue() && !value.isImpossible() &&
value.moveKind != ValueFlow::Value::MoveKind::NonMovedVariable;
});
return it == mImpl->mValues->end() ? nullptr : &*it;
}
// cppcheck-suppress unusedFunction
const ValueFlow::Value* Token::getContainerSizeValue(const MathLib::bigint val) const
{
if (!mImpl->mValues)
return nullptr;
const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [=](const ValueFlow::Value& value) {
return value.isContainerSizeValue() && !value.isImpossible() && value.intvalue == val;
});
return it == mImpl->mValues->end() ? nullptr : &*it;
}
TokenImpl::~TokenImpl()
{
delete mOriginalName;
delete mValueType;
delete mValues;
if (mTemplateSimplifierPointers) {
for (auto *templateSimplifierPointer : *mTemplateSimplifierPointers) {
templateSimplifierPointer->token(nullptr);
}
}
delete mTemplateSimplifierPointers;
while (mCppcheckAttributes) {
CppcheckAttributes *c = mCppcheckAttributes;
mCppcheckAttributes = mCppcheckAttributes->next;
delete c;
}
}
void TokenImpl::setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint value)
{
CppcheckAttributes *attr = mCppcheckAttributes;
while (attr && attr->type != type)
attr = attr->next;
if (attr)
attr->value = value;
else {
attr = new CppcheckAttributes;
attr->type = type;
attr->value = value;
attr->next = mCppcheckAttributes;
mCppcheckAttributes = attr;
}
}
bool TokenImpl::getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint &value) const
{
CppcheckAttributes *attr = mCppcheckAttributes;
while (attr && attr->type != type)
attr = attr->next;
if (attr)
value = attr->value;
return attr != nullptr;
}
Token* findTypeEnd(Token* tok)
{
while (Token::Match(tok, "%name%|.|::|*|&|&&|<|(|template|decltype|sizeof")) {
if (Token::Match(tok, "(|<"))
tok = tok->link();
if (!tok)
return nullptr;
tok = tok->next();
}
return tok;
}
Token* findLambdaEndScope(Token* tok)
{
if (!Token::simpleMatch(tok, "["))
return nullptr;
tok = tok->link();
if (!Token::Match(tok, "] (|{"))
return nullptr;
tok = tok->linkAt(1);
if (Token::simpleMatch(tok, "}"))
return tok;
if (Token::simpleMatch(tok, ") {"))
return tok->linkAt(1);
if (!Token::simpleMatch(tok, ")"))
return nullptr;
tok = tok->next();
while (Token::Match(tok, "mutable|constexpr|consteval|noexcept|.")) {
if (Token::simpleMatch(tok, "noexcept ("))
tok = tok->linkAt(1);
if (Token::simpleMatch(tok, ".")) {
tok = findTypeEnd(tok);
break;
}
tok = tok->next();
}
if (Token::simpleMatch(tok, "{"))
return tok->link();
return nullptr;
}
const Token* findLambdaEndScope(const Token* tok) {
return findLambdaEndScope(const_cast<Token*>(tok));
}
const std::string& Token::fileName() const {
return mTokensFrontBack.list.getFiles()[mImpl->mFileIndex];
}
| null |
810 | cpp | cppcheck | config.h | lib/config.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef configH
#define configH
#ifdef MAXTIME
#error "MAXTIME is no longer supported - please use command-line options --checks-max-time=, --template-max-time= and --typedef-max-time= instead"
#endif
#ifdef _WIN32
# ifdef CPPCHECKLIB_EXPORT
# define CPPCHECKLIB __declspec(dllexport)
# elif defined(CPPCHECKLIB_IMPORT)
# define CPPCHECKLIB __declspec(dllimport)
# else
# define CPPCHECKLIB
# endif
#else
# define CPPCHECKLIB
#endif
// MS Visual C++ memory leak debug tracing
#if !defined(DISABLE_CRTDBG_MAP_ALLOC) && defined(_MSC_VER) && defined(_DEBUG)
# define _CRTDBG_MAP_ALLOC
# include <crtdbg.h>
#endif
// compatibility macros
#ifndef __has_builtin
#define __has_builtin(x) 0
#endif
#ifndef __has_include
#define __has_include(x) 0
#endif
#ifndef __has_cpp_attribute
#define __has_cpp_attribute(x) 0
#endif
#ifndef __has_feature
#define __has_feature(x) 0
#endif
// C++11 noexcept
#if defined(__cpp_noexcept_function_type) || \
(defined(__GNUC__) && (__GNUC__ >= 5)) \
|| defined(__clang__) \
|| defined(__CPPCHECK__)
# define NOEXCEPT noexcept
#else
# define NOEXCEPT
#endif
// C++11 noreturn
#if __has_cpp_attribute (noreturn) \
|| (defined(__GNUC__) && (__GNUC__ >= 5)) \
|| defined(__clang__) \
|| defined(__CPPCHECK__)
# define NORETURN [[noreturn]]
#elif defined(__GNUC__)
# define NORETURN __attribute__((noreturn))
#else
# define NORETURN
#endif
// fallthrough
#if __cplusplus >= 201703L && __has_cpp_attribute (fallthrough)
# define FALLTHROUGH [[fallthrough]]
#elif defined(__clang__)
# define FALLTHROUGH [[clang::fallthrough]]
#elif (defined(__GNUC__) && (__GNUC__ >= 7))
# define FALLTHROUGH __attribute__((fallthrough))
#else
# define FALLTHROUGH
#endif
// unused
#if __cplusplus >= 201703L && __has_cpp_attribute (maybe_unused)
# define UNUSED [[maybe_unused]]
#elif defined(__GNUC__) \
|| defined(__clang__) \
|| defined(__CPPCHECK__)
# define UNUSED __attribute__((unused))
#else
# define UNUSED
#endif
// warn_unused
#if __has_cpp_attribute (gnu::warn_unused) || \
(defined(__clang__) && (__clang_major__ >= 15))
# define WARN_UNUSED [[gnu::warn_unused]]
#else
# define WARN_UNUSED
#endif
// deprecated
#if defined(__GNUC__) \
|| defined(__clang__) \
|| defined(__CPPCHECK__)
# define DEPRECATED __attribute__((deprecated))
#elif defined(_MSC_VER)
# define DEPRECATED __declspec(deprecated)
#else
# define DEPRECATED
#endif
// returns_nonnull
#if __has_cpp_attribute (gnu::returns_nonnull)
# define RET_NONNULL [[gnu::returns_nonnull]]
#elif (defined(__clang__) && ((__clang_major__ > 3) || ((__clang_major__ == 3) && (__clang_minor__ >= 7)))) \
|| (defined(__GNUC__) && (__GNUC__ >= 9))
# define RET_NONNULL __attribute__((returns_nonnull))
#else
# define RET_NONNULL
#endif
#define REQUIRES(msg, ...) class=typename std::enable_if<__VA_ARGS__::value>::type
#include <string>
static const std::string emptyString;
// Use the nonneg macro when you want to assert that a variable/argument is not negative
#ifdef __CPPCHECK__
#define nonneg __cppcheck_low__(0)
#elif defined(NONNEG)
// Enable non-negative values checking
// TODO : investigate using annotations/contracts for stronger value checking
#define nonneg unsigned
#else
// Disable non-negative values checking
#define nonneg
#endif
#if __has_feature(address_sanitizer)
#define ASAN 1
#endif
#ifndef ASAN
#ifdef __SANITIZE_ADDRESS__
#define ASAN 1
#else
#define ASAN 0
#endif
#endif
#if defined(_WIN32)
#define HAS_THREADING_MODEL_THREAD
#define STDCALL __stdcall
#elif ((defined(__GNUC__) || defined(__sun)) && !defined(__MINGW32__)) || defined(__CPPCHECK__)
#define HAS_THREADING_MODEL_FORK
#if !defined(DISALLOW_THREAD_EXECUTOR)
#define HAS_THREADING_MODEL_THREAD
#endif
#define STDCALL
#else
#error "No threading model defined"
#endif
#define STRINGISIZE(...) #__VA_ARGS__
#ifdef __clang__
#define SUPPRESS_WARNING_PUSH(warning) _Pragma("clang diagnostic push") _Pragma(STRINGISIZE(clang diagnostic ignored warning))
#define SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop")
#define SUPPRESS_WARNING_GCC_PUSH(warning)
#define SUPPRESS_WARNING_GCC_POP
#define SUPPRESS_WARNING_CLANG_PUSH(warning) SUPPRESS_WARNING_PUSH(warning)
#define SUPPRESS_WARNING_CLANG_POP SUPPRESS_WARNING_POP
#define FORCE_WARNING_PUSH(warn) _Pragma("clang diagnostic push") _Pragma(STRINGISIZE(clang diagnostic warning warn))
#define FORCE_WARNING_CLANG_PUSH(warning) FORCE_WARNING_PUSH(warning)
#define FORCE_WARNING_CLANG_POP SUPPRESS_WARNING_POP
#elif defined(__GNUC__)
#define SUPPRESS_WARNING_PUSH(warning) _Pragma("GCC diagnostic push") _Pragma(STRINGISIZE(GCC diagnostic ignored warning))
#define SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop")
#define SUPPRESS_WARNING_GCC_PUSH(warning) SUPPRESS_WARNING_PUSH(warning)
#define SUPPRESS_WARNING_GCC_POP SUPPRESS_WARNING_POP
#define SUPPRESS_WARNING_CLANG_PUSH(warning)
#define SUPPRESS_WARNING_CLANG_POP
#define FORCE_WARNING_PUSH(warning)
#define FORCE_WARNING_CLANG_PUSH(warning)
#define FORCE_WARNING_CLANG_POP
#else
#define SUPPRESS_WARNING_PUSH(warning)
#define SUPPRESS_WARNING_POP
#define SUPPRESS_WARNING_GCC_PUSH(warning)
#define SUPPRESS_WARNING_GCC_POP
#define SUPPRESS_WARNING_CLANG_PUSH(warning)
#define SUPPRESS_WARNING_CLANG_POP
#define FORCE_WARNING_PUSH(warning)
#define FORCE_WARNING_CLANG_PUSH(warning)
#define FORCE_WARNING_CLANG_POP
#endif
#if !defined(NO_WINDOWS_SEH) && defined(_WIN32) && defined(_MSC_VER)
#define USE_WINDOWS_SEH
#endif
// TODO: __GLIBC__ is dependent on the features.h include and not a built-in compiler define, so it might be problematic to depend on it
#if !defined(NO_UNIX_BACKTRACE_SUPPORT) && defined(__GNUC__) && defined(__GLIBC__) && !defined(__CYGWIN__) && !defined(__MINGW32__) && !defined(__NetBSD__) && !defined(__SVR4) && !defined(__QNX__)
#define USE_UNIX_BACKTRACE_SUPPORT
#endif
#if !defined(NO_UNIX_SIGNAL_HANDLING) && defined(__GNUC__) && !defined(__MINGW32__) && !defined(__OS2__)
#define USE_UNIX_SIGNAL_HANDLING
#endif
#endif // configH
| null |
811 | cpp | cppcheck | forwardanalyzer.cpp | lib/forwardanalyzer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "forwardanalyzer.h"
#include "analyzer.h"
#include "astutils.h"
#include "config.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueptr.h"
#include "vfvalue.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdint>
#include <functional>
#include <list>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace {
struct ForwardTraversal {
enum class Progress : std::uint8_t { Continue, Break, Skip };
ForwardTraversal(const ValuePtr<Analyzer>& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings)
: analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings)
{}
ValuePtr<Analyzer> analyzer;
const TokenList& tokenList;
ErrorLogger& errorLogger;
const Settings& settings;
Analyzer::Action actions;
bool analyzeOnly{};
bool analyzeTerminate{};
Analyzer::Terminate terminate = Analyzer::Terminate::None;
std::vector<Token*> loopEnds;
int branchCount = 0;
Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) {
if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None)
terminate = t;
return Progress::Break;
}
struct Branch {
explicit Branch(Token* tok = nullptr) : endBlock(tok) {}
Token* endBlock = nullptr;
Analyzer::Action action = Analyzer::Action::None;
bool check = false;
bool escape = false;
bool escapeUnknown = false;
bool active = false;
bool isEscape() const {
return escape || escapeUnknown;
}
bool isConclusiveEscape() const {
return escape && !escapeUnknown;
}
bool isModified() const {
return action.isModified() && !isConclusiveEscape();
}
bool isInconclusive() const {
return action.isInconclusive() && !isConclusiveEscape();
}
bool isDead() const {
return action.isModified() || action.isInconclusive() || isEscape();
}
};
bool stopUpdates() {
analyzeOnly = true;
return actions.isModified();
}
bool stopOnCondition(const Token* condTok) const
{
if (analyzer->isConditional() && findAstNode(condTok, [](const Token* tok) {
return tok->isIncompleteVar();
}))
return true;
return analyzer->stopOnCondition(condTok);
}
std::pair<bool, bool> evalCond(const Token* tok, const Token* ctx = nullptr) const {
if (!tok)
return std::make_pair(false, false);
std::vector<MathLib::bigint> result = analyzer->evaluate(tok, ctx);
// TODO: We should convert to bool
const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x != 0;
});
const bool checkElse = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x == 0;
});
return std::make_pair(checkThen, checkElse);
}
bool isConditionTrue(const Token* tok, const Token* ctx = nullptr) const {
return evalCond(tok, ctx).first;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseTok(T* tok, const F &f, bool traverseUnknown, T** out = nullptr) {
if (Token::Match(tok, "asm|goto"))
return Break(Analyzer::Terminate::Bail);
if (Token::Match(tok, "setjmp|longjmp (")) {
// Traverse the parameters of the function before escaping
traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown);
return Break(Analyzer::Terminate::Bail);
}
if (Token::simpleMatch(tok, "continue")) {
if (loopEnds.empty())
return Break(Analyzer::Terminate::Escape);
// If we are in a loop then jump to the end
if (out)
*out = loopEnds.back();
} else if (Token::Match(tok, "return|throw")) {
traverseRecursive(tok->astOperand2(), f, traverseUnknown);
traverseRecursive(tok->astOperand1(), f, traverseUnknown);
return Break(Analyzer::Terminate::Escape);
} else if (Token::Match(tok, "%name% (") && isEscapeFunction(tok, &settings.library)) {
// Traverse the parameters of the function before escaping
traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown);
return Break(Analyzer::Terminate::Escape);
} else if (isUnevaluated(tok->previous())) {
if (out)
*out = tok->link();
return Progress::Skip;
} else if (tok->astOperand1() && tok->astOperand2() && Token::Match(tok, "?|&&|%oror%")) {
if (traverseConditional(tok, f, traverseUnknown) == Progress::Break)
return Break();
if (out)
*out = nextAfterAstRightmostLeaf(tok);
return Progress::Skip;
// Skip lambdas
} else if (T* lambdaEndToken = findLambdaEndToken(tok)) {
if (checkScope(lambdaEndToken).isModified())
return Break(Analyzer::Terminate::Bail);
if (out)
*out = lambdaEndToken->next();
// Skip class scope
} else if (tok->str() == "{" && tok->scope() && tok->scope()->isClassOrStruct()) {
if (out)
*out = tok->link();
} else {
if (f(tok) == Progress::Break)
return Break();
}
return Progress::Continue;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseRecursive(T* tok, const F &f, bool traverseUnknown, unsigned int recursion=0) {
if (!tok)
return Progress::Continue;
if (recursion > 10000)
return Progress::Skip;
T* firstOp = tok->astOperand1();
T* secondOp = tok->astOperand2();
// Evaluate:
// 1. RHS of assignment before LHS
// 2. Unary op before operand
// 3. Function arguments before function call
if (tok->isAssignmentOp() || !secondOp || isFunctionCall(tok))
std::swap(firstOp, secondOp);
if (firstOp && traverseRecursive(firstOp, f, traverseUnknown, recursion+1) == Progress::Break)
return Break();
const Progress p = tok->isAssignmentOp() ? Progress::Continue : traverseTok(tok, f, traverseUnknown);
if (p == Progress::Break)
return Break();
if (p == Progress::Continue && secondOp && traverseRecursive(secondOp, f, traverseUnknown, recursion+1) == Progress::Break)
return Break();
if (tok->isAssignmentOp() && traverseTok(tok, f, traverseUnknown) == Progress::Break)
return Break();
return Progress::Continue;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseConditional(T* tok, F f, bool traverseUnknown) {
if (Token::Match(tok, "?|&&|%oror%") && tok->astOperand1() && tok->astOperand2()) {
const T* condTok = tok->astOperand1();
T* childTok = tok->astOperand2();
bool checkThen, checkElse;
std::tie(checkThen, checkElse) = evalCond(condTok);
if (!checkThen && !checkElse) {
if (!traverseUnknown && stopOnCondition(condTok) && stopUpdates()) {
return Progress::Continue;
}
checkThen = true;
checkElse = true;
}
if (childTok->str() == ":") {
if (checkThen && traverseRecursive(childTok->astOperand1(), f, traverseUnknown) == Progress::Break)
return Break();
if (checkElse && traverseRecursive(childTok->astOperand2(), f, traverseUnknown) == Progress::Break)
return Break();
} else {
if (!checkThen && tok->str() == "&&")
return Progress::Continue;
if (!checkElse && tok->str() == "||")
return Progress::Continue;
if (traverseRecursive(childTok, f, traverseUnknown) == Progress::Break)
return Break();
}
}
return Progress::Continue;
}
Progress update(Token* tok) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward);
actions |= action;
if (!action.isNone() && !analyzeOnly)
analyzer->update(tok, action, Analyzer::Direction::Forward);
if (action.isInconclusive() && !analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Inconclusive);
if (action.isInvalid())
return Break(Analyzer::Terminate::Modified);
if (action.isWrite() && !action.isRead())
// Analysis of this write will continue separately
return Break(Analyzer::Terminate::Modified);
return Progress::Continue;
}
Progress updateTok(Token* tok, Token** out = nullptr) {
auto f = [this](Token* tok2) {
return update(tok2);
};
return traverseTok(tok, f, false, out);
}
Progress updateRecursive(Token* tok) {
auto f = [this](Token* tok2) {
return update(tok2);
};
return traverseRecursive(tok, f, false);
}
Analyzer::Action analyzeRecursive(const Token* start) {
Analyzer::Action result = Analyzer::Action::None;
auto f = [&](const Token* tok) {
result = analyzer->analyze(tok, Analyzer::Direction::Forward);
if (result.isModified() || result.isInconclusive())
return Break();
return Progress::Continue;
};
traverseRecursive(start, f, true);
return result;
}
Analyzer::Action analyzeRange(const Token* start, const Token* end) const {
Analyzer::Action result = Analyzer::Action::None;
for (const Token* tok = start; tok && tok != end; tok = tok->next()) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward);
if (action.isModified() || action.isInconclusive())
return action;
result |= action;
}
return result;
}
ForwardTraversal fork(bool analyze = false) const {
ForwardTraversal ft = *this;
if (analyze) {
ft.analyzeOnly = true;
ft.analyzeTerminate = true;
}
ft.actions = Analyzer::Action::None;
return ft;
}
std::vector<ForwardTraversal> tryForkScope(Token* endBlock, bool isModified = false) const {
if (analyzer->updateScope(endBlock, isModified)) {
ForwardTraversal ft = fork();
return {std::move(ft)};
}
return std::vector<ForwardTraversal> {};
}
std::vector<ForwardTraversal> tryForkUpdateScope(Token* endBlock, bool isModified = false) const {
std::vector<ForwardTraversal> result = tryForkScope(endBlock, isModified);
for (ForwardTraversal& ft : result)
ft.updateScope(endBlock);
return result;
}
static bool hasGoto(const Token* endBlock) {
return Token::findsimplematch(endBlock->link(), "goto", endBlock);
}
static bool hasJump(const Token* endBlock) {
return Token::findmatch(endBlock->link(), "goto|break", endBlock);
}
bool hasInnerReturnScope(const Token* start, const Token* end) const {
for (const Token* tok=start; tok != end; tok = tok->previous()) {
if (Token::simpleMatch(tok, "}")) {
const Token* ftok = nullptr;
const bool r = isReturnScope(tok, settings.library, &ftok);
if (r)
return true;
}
}
return false;
}
bool isEscapeScope(const Token* endBlock, bool& unknown) const {
const Token* ftok = nullptr;
const bool r = isReturnScope(endBlock, settings.library, &ftok);
if (!r && ftok)
unknown = true;
return r;
}
Analyzer::Action analyzeScope(const Token* endBlock) const {
return analyzeRange(endBlock->link(), endBlock);
}
Analyzer::Action checkScope(Token* endBlock) const {
Analyzer::Action a = analyzeScope(endBlock);
tryForkUpdateScope(endBlock, a.isModified());
return a;
}
Analyzer::Action checkScope(const Token* endBlock) const {
Analyzer::Action a = analyzeScope(endBlock);
return a;
}
bool checkBranch(Branch& branch) const {
Analyzer::Action a = analyzeScope(branch.endBlock);
branch.action = a;
std::vector<ForwardTraversal> ft1 = tryForkUpdateScope(branch.endBlock, a.isModified());
const bool bail = hasGoto(branch.endBlock);
if (!a.isModified() && !bail) {
if (ft1.empty()) {
// Traverse into the branch to see if there is a conditional escape
if (!branch.escape && hasInnerReturnScope(branch.endBlock->previous(), branch.endBlock->link())) {
ForwardTraversal ft2 = fork(true);
ft2.updateScope(branch.endBlock);
if (ft2.terminate == Analyzer::Terminate::Escape) {
branch.escape = true;
branch.escapeUnknown = false;
}
}
} else {
if (ft1.front().terminate == Analyzer::Terminate::Escape) {
branch.escape = true;
branch.escapeUnknown = false;
}
}
}
return bail;
}
bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const {
if (!condTok)
return true;
if (Token::simpleMatch(condTok, ":"))
return true;
bool stepChangesCond = false;
if (stepTok) {
std::pair<const Token*, const Token*> exprToks = stepTok->findExpressionStartEndTokens();
if (exprToks.first != nullptr && exprToks.second != nullptr)
stepChangesCond |=
findExpressionChanged(condTok, exprToks.first, exprToks.second->next(), settings) != nullptr;
}
const bool bodyChangesCond = findExpressionChanged(condTok, endBlock->link(), endBlock, settings);
// Check for mutation in the condition
const bool condChanged =
nullptr != findAstNode(condTok, [&](const Token* tok) {
return isVariableChanged(tok, 0, settings);
});
const bool changed = stepChangesCond || bodyChangesCond || condChanged;
if (!changed)
return true;
ForwardTraversal ft = fork(true);
ft.updateScope(endBlock);
return ft.isConditionTrue(condTok) && bodyChangesCond;
}
Progress updateInnerLoop(Token* endBlock, Token* stepTok, Token* condTok) {
loopEnds.push_back(endBlock);
OnExit oe{[&] {
loopEnds.pop_back();
}};
if (endBlock && updateScope(endBlock) == Progress::Break)
return Break();
if (stepTok && updateRecursive(stepTok) == Progress::Break)
return Break();
if (condTok && !Token::simpleMatch(condTok, ":") && updateRecursive(condTok) == Progress::Break)
return Break();
return Progress::Continue;
}
Progress updateLoop(const Token* endToken,
Token* endBlock,
Token* condTok,
Token* initTok = nullptr,
Token* stepTok = nullptr,
bool exit = false) {
if (initTok && updateRecursive(initTok) == Progress::Break)
return Break();
const bool isDoWhile = precedes(endBlock, condTok);
bool checkThen = true;
bool checkElse = false;
if (condTok && !Token::simpleMatch(condTok, ":"))
std::tie(checkThen, checkElse) = evalCond(condTok, isDoWhile ? endBlock->previous() : nullptr);
// exiting a do while(false)
if (checkElse && exit) {
if (hasJump(endBlock)) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
if (analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
}
return Progress::Continue;
}
Analyzer::Action bodyAnalysis = analyzeScope(endBlock);
Analyzer::Action allAnalysis = bodyAnalysis;
Analyzer::Action condAnalysis;
if (condTok) {
condAnalysis = analyzeRecursive(condTok);
allAnalysis |= condAnalysis;
}
if (stepTok)
allAnalysis |= analyzeRecursive(stepTok);
actions |= allAnalysis;
// do while(false) is not really a loop
if (checkElse && isDoWhile &&
(condTok->hasKnownIntValue() ||
(!bodyAnalysis.isModified() && !condAnalysis.isModified() && condAnalysis.isRead()))) {
if (updateScope(endBlock) == Progress::Break)
return Break();
return updateRecursive(condTok);
}
if (allAnalysis.isInconclusive()) {
if (!analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Bail);
} else if (allAnalysis.isModified() || (exit && allAnalysis.isIdempotent())) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
}
if (condTok && !Token::simpleMatch(condTok, ":")) {
if (!isDoWhile || (!bodyAnalysis.isModified() && !bodyAnalysis.isIdempotent()))
if (updateRecursive(condTok) == Progress::Break)
return Break();
}
if (!checkThen && !checkElse && !isDoWhile && stopOnCondition(condTok) && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
// condition is false, we don't enter the loop
if (checkElse && !isDoWhile)
return Progress::Continue;
if (checkThen || isDoWhile) {
// Since we are re-entering the loop then assume the condition is true to update the state
if (exit)
analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute);
if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
return Break();
// If loop re-enters then it could be modified again
if (allAnalysis.isModified() && reentersLoop(endBlock, condTok, stepTok))
return Break(Analyzer::Terminate::Bail);
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
} else if (allAnalysis.isModified()) {
std::vector<ForwardTraversal> ftv = tryForkScope(endBlock, allAnalysis.isModified());
bool forkContinue = true;
for (ForwardTraversal& ft : ftv) {
if (condTok)
ft.analyzer->assume(condTok, false, Analyzer::Assume::Quiet);
if (ft.updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
forkContinue = false;
}
if (allAnalysis.isModified() || !forkContinue) {
// TODO: Don't bail on missing condition
if (!condTok)
return Break(Analyzer::Terminate::Bail);
if (analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
analyzer->assume(condTok, false);
}
if (forkContinue) {
for (ForwardTraversal& ft : ftv) {
if (!ft.actions.isIncremental())
ft.updateRange(endBlock, endToken);
}
}
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
} else {
if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
return Progress::Break;
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
}
return Progress::Continue;
}
Progress updateLoopExit(const Token* endToken,
Token* endBlock,
Token* condTok,
Token* initTok = nullptr,
Token* stepTok = nullptr) {
return updateLoop(endToken, endBlock, condTok, initTok, stepTok, true);
}
Progress updateScope(Token* endBlock, int depth = 20)
{
if (!endBlock)
return Break();
assert(endBlock->link());
Token* ctx = endBlock->link()->previous();
if (Token::simpleMatch(ctx, ")"))
ctx = ctx->link()->previous();
if (ctx)
analyzer->updateState(ctx);
return updateRange(endBlock->link(), endBlock, depth);
}
Progress updateRange(Token* start, const Token* end, int depth = 20) {
if (depth < 0)
return Break(Analyzer::Terminate::Bail);
std::size_t i = 0;
for (Token* tok = start; precedes(tok, end); tok = tok->next()) {
Token* next = nullptr;
if (tok->index() <= i)
throw InternalError(tok, "Cyclic forward analysis.");
i = tok->index();
if (tok->link()) {
// Skip casts..
if (tok->str() == "(" && !tok->astOperand2() && tok->isCast()) {
tok = tok->link();
continue;
}
// Skip template arguments..
if (tok->str() == "<") {
tok = tok->link();
continue;
}
}
// Evaluate RHS of assignment before LHS
if (Token* assignTok = assignExpr(tok)) {
if (updateRecursive(assignTok) == Progress::Break)
return Break();
tok = nextAfterAstRightmostLeaf(assignTok);
if (!tok)
return Break();
} else if (Token::simpleMatch(tok, ") {") && Token::Match(tok->link()->previous(), "for|while (") &&
!Token::simpleMatch(tok->link()->astOperand2(), ":")) {
// In the middle of a loop structure so bail
return Break(Analyzer::Terminate::Bail);
} else if (tok->str() == ";" && tok->astParent()) {
Token* top = tok->astTop();
if (Token::Match(top->previous(), "for|while (") && Token::simpleMatch(top->link(), ") {")) {
Token* endCond = top->link();
Token* endBlock = endCond->linkAt(1);
Token* condTok = getCondTok(top);
Token* stepTok = getStepTok(top);
// The semicolon should belong to the initTok otherwise something went wrong, so just bail
if (tok->astOperand2() != condTok && !Token::simpleMatch(tok->astOperand2(), ";"))
return Break(Analyzer::Terminate::Bail);
if (updateLoop(end, endBlock, condTok, nullptr, stepTok) == Progress::Break)
return Break();
}
} else if (tok->str() == "break") {
const Token *scopeEndToken = findNextTokenFromBreak(tok);
if (!scopeEndToken)
return Break();
tok = skipTo(tok, scopeEndToken, end);
if (!precedes(tok, end))
return Break(Analyzer::Terminate::Escape);
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
// TODO: Don't break, instead move to the outer scope
if (!tok)
return Break();
} else if (!tok->variable() && (Token::Match(tok, "%name% :") || tok->str() == "case")) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
} else if (tok->link() && tok->str() == "}" && tok == tok->scope()->bodyEnd) { // might be an init list
const Scope* scope = tok->scope();
if (contains({Scope::eDo, Scope::eFor, Scope::eWhile, Scope::eIf, Scope::eElse, Scope::eSwitch}, scope->type)) {
const bool inElse = scope->type == Scope::eElse;
const bool inDoWhile = scope->type == Scope::eDo;
const bool inLoop = contains({Scope::eDo, Scope::eFor, Scope::eWhile}, scope->type);
Token* condTok = getCondTokFromEnd(tok);
if (!condTok)
return Break();
if (!condTok->hasKnownIntValue() || inLoop) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
} else if (condTok->values().front().intvalue == inElse) {
return Break();
}
// Handle loop
if (inLoop) {
Token* stepTok = getStepTokFromEnd(tok);
bool checkThen, checkElse;
std::tie(checkThen, checkElse) = evalCond(condTok);
if (stepTok && !checkElse) {
if (updateRecursive(stepTok) == Progress::Break)
return Break();
if (updateRecursive(condTok) == Progress::Break)
return Break();
// Reevaluate condition
std::tie(checkThen, checkElse) = evalCond(condTok);
}
if (!checkElse) {
if (updateLoopExit(end, tok, condTok, nullptr, stepTok) == Progress::Break)
return Break();
}
}
analyzer->assume(condTok, !inElse, Analyzer::Assume::Quiet);
assert(!inDoWhile || Token::simpleMatch(tok, "} while ("));
if (Token::simpleMatch(tok, "} else {") || inDoWhile)
tok = tok->linkAt(2);
} else if (contains({Scope::eTry, Scope::eCatch}, scope->type)) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
} else if (scope->type == Scope::eLambda) {
return Break();
}
} else if (tok->isControlFlowKeyword() && Token::Match(tok, "if|while|for (") &&
Token::simpleMatch(tok->linkAt(1), ") {")) {
if ((settings.vfOptions.maxForwardBranches > 0) && (++branchCount > settings.vfOptions.maxForwardBranches)) {
// TODO: should be logged on function-level instead of file-level
reportError(Severity::information, "normalCheckLevelMaxBranches", "Limiting analysis of branches. Use --check-level=exhaustive to analyze all branches.");
return Break(Analyzer::Terminate::Bail);
}
Token* endCond = tok->linkAt(1);
Token* endBlock = endCond->linkAt(1);
Token* condTok = getCondTok(tok);
Token* initTok = getInitTok(tok);
if (initTok && updateRecursive(initTok) == Progress::Break)
return Break();
if (Token::Match(tok, "for|while (")) {
// For-range loop
if (Token::simpleMatch(condTok, ":")) {
Token* conTok = condTok->astOperand2();
if (conTok && updateRecursive(conTok) == Progress::Break)
return Break();
bool isEmpty = false;
std::vector<MathLib::bigint> result =
analyzer->evaluate(Analyzer::Evaluate::ContainerEmpty, conTok);
if (result.empty())
analyzer->assume(conTok, false, Analyzer::Assume::ContainerEmpty);
else
isEmpty = result.front() != 0;
if (!isEmpty && updateLoop(end, endBlock, condTok) == Progress::Break)
return Break();
} else {
Token* stepTok = getStepTok(tok);
// Dont pass initTok since it was already evaluated
if (updateLoop(end, endBlock, condTok, nullptr, stepTok) == Progress::Break)
return Break();
}
tok = endBlock;
} else {
// Traverse condition
if (updateRecursive(condTok) == Progress::Break)
return Break();
Branch thenBranch{endBlock};
Branch elseBranch{endBlock->tokAt(2) ? endBlock->linkAt(2) : nullptr};
// Check if condition is true or false
std::tie(thenBranch.check, elseBranch.check) = evalCond(condTok);
if (!thenBranch.check && !elseBranch.check && stopOnCondition(condTok) && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
const bool hasElse = Token::simpleMatch(endBlock, "} else {");
bool bail = false;
// Traverse then block
thenBranch.escape = isEscapeScope(endBlock, thenBranch.escapeUnknown);
if (thenBranch.check) {
thenBranch.active = true;
if (updateScope(endBlock, depth - 1) == Progress::Break)
return Break();
} else if (!elseBranch.check) {
thenBranch.active = true;
if (checkBranch(thenBranch))
bail = true;
}
// Traverse else block
if (hasElse) {
elseBranch.escape = isEscapeScope(endBlock->linkAt(2), elseBranch.escapeUnknown);
if (elseBranch.check) {
elseBranch.active = true;
const Progress result = updateScope(endBlock->linkAt(2), depth - 1);
if (result == Progress::Break)
return Break();
} else if (!thenBranch.check) {
elseBranch.active = true;
if (checkBranch(elseBranch))
bail = true;
}
tok = endBlock->linkAt(2);
} else {
tok = endBlock;
}
if (thenBranch.active)
actions |= thenBranch.action;
if (elseBranch.active)
actions |= elseBranch.action;
if (bail)
return Break(Analyzer::Terminate::Bail);
if (thenBranch.isDead() && elseBranch.isDead()) {
if (thenBranch.isModified() && elseBranch.isModified())
return Break(Analyzer::Terminate::Modified);
if (thenBranch.isConclusiveEscape() && elseBranch.isConclusiveEscape())
return Break(Analyzer::Terminate::Escape);
return Break(Analyzer::Terminate::Bail);
}
// Conditional return
if (thenBranch.active && thenBranch.isEscape() && !hasElse) {
if (!thenBranch.isConclusiveEscape()) {
if (!analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Bail);
} else if (thenBranch.check) {
return Break();
} else {
if (analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
analyzer->assume(condTok, false);
}
}
if (thenBranch.isInconclusive() || elseBranch.isInconclusive()) {
if (!analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Bail);
} else if (thenBranch.isModified() || elseBranch.isModified()) {
if (!hasElse && analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
analyzer->assume(condTok, elseBranch.isModified());
}
}
} else if (Token::simpleMatch(tok, "try {")) {
Token* endBlock = tok->linkAt(1);
ForwardTraversal tryTraversal = fork();
tryTraversal.updateScope(endBlock, depth - 1);
bool bail = tryTraversal.actions.isModified();
if (bail) {
actions = tryTraversal.actions;
terminate = tryTraversal.terminate;
return Break();
}
while (Token::simpleMatch(endBlock, "} catch (")) {
Token* endCatch = endBlock->linkAt(2);
if (!Token::simpleMatch(endCatch, ") {"))
return Break();
endBlock = endCatch->linkAt(1);
ForwardTraversal ft = fork();
ft.updateScope(endBlock, depth - 1);
bail |= ft.terminate != Analyzer::Terminate::None || ft.actions.isModified();
}
if (bail)
return Break();
tok = endBlock;
} else if (Token::simpleMatch(tok, "do {")) {
Token* endBlock = tok->linkAt(1);
Token* condTok = Token::simpleMatch(endBlock, "} while (") ? endBlock->tokAt(2)->astOperand2() : nullptr;
if (updateLoop(end, endBlock, condTok) == Progress::Break)
return Break();
if (condTok)
tok = endBlock->linkAt(2)->next();
else
tok = endBlock;
} else if (Token::Match(tok, "assert|ASSERT (")) {
const Token* condTok = tok->next()->astOperand2();
bool checkThen, checkElse;
std::tie(checkThen, checkElse) = evalCond(condTok);
if (checkElse)
return Break();
if (!checkThen)
analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute);
} else if (Token::simpleMatch(tok, "switch (")) {
if (updateRecursive(tok->next()->astOperand2()) == Progress::Break)
return Break();
actions |= Analyzer::Action::Write; // bailout for switch scope
return Break();
} else if (Token* callTok = callExpr(tok)) {
// TODO: Dont traverse tokens a second time
if (start != callTok && tok != callTok && updateRecursive(callTok->astOperand1()) == Progress::Break)
return Break();
// Since the call could be an unknown macro, traverse the tokens as a range instead of recursively
if (!Token::simpleMatch(callTok, "( )") &&
updateRange(callTok->next(), callTok->link(), depth - 1) == Progress::Break)
return Break();
if (updateTok(callTok) == Progress::Break)
return Break();
tok = callTok->link();
if (!tok)
return Break();
} else {
if (updateTok(tok, &next) == Progress::Break)
return Break();
if (next) {
if (precedes(next, end))
tok = next->previous();
else
return Progress::Continue;
}
}
// Prevent infinite recursion
if (tok->next() == start)
break;
}
return Progress::Continue;
}
void reportError(Severity severity, const std::string& id, const std::string& msg) {
ErrorMessage::FileLocation loc(tokenList.getSourceFilePath(), 0, 0);
const ErrorMessage errmsg({std::move(loc)}, tokenList.getSourceFilePath(), severity, msg, id, Certainty::normal);
errorLogger.reportErr(errmsg);
}
static bool isFunctionCall(const Token* tok)
{
if (!Token::simpleMatch(tok, "("))
return false;
if (tok->isCast())
return false;
if (!tok->isBinaryOp())
return false;
if (Token::simpleMatch(tok->link(), ") {"))
return false;
if (isUnevaluated(tok->previous()))
return false;
return Token::Match(tok->previous(), "%name%|)|]|>");
}
static Token* assignExpr(Token* tok) {
while (tok->astParent() && astIsLHS(tok)) {
if (tok->astParent()->isAssignmentOp())
return tok->astParent();
tok = tok->astParent();
}
return nullptr;
}
static Token* callExpr(Token* tok)
{
while (tok->astParent() && astIsLHS(tok)) {
if (!Token::Match(tok, "%name%|::|<|."))
break;
if (Token::simpleMatch(tok, "<") && !tok->link())
break;
tok = tok->astParent();
}
if (isFunctionCall(tok))
return tok;
return nullptr;
}
static Token* skipTo(Token* tok, const Token* dest, const Token* end = nullptr) {
if (end && dest->index() > end->index())
return nullptr;
const int i = dest->index() - tok->index();
if (i > 0)
return tok->tokAt(dest->index() - tok->index());
return nullptr;
}
static Token* getStepTokFromEnd(Token* tok) {
if (!Token::simpleMatch(tok, "}"))
return nullptr;
Token* end = tok->link()->previous();
if (!Token::simpleMatch(end, ")"))
return nullptr;
return getStepTok(end->link());
}
};
}
Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings)
{
if (a->invalid())
return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail};
ForwardTraversal ft{a, tokenList, errorLogger, settings};
if (start)
ft.analyzer->updateState(start);
ft.updateRange(start, end);
return Analyzer::Result{ ft.actions, ft.terminate };
}
Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings)
{
if (Settings::terminated())
throw TerminateException();
if (a->invalid())
return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail};
ForwardTraversal ft{a, tokenList, errorLogger, settings};
(void)ft.updateRecursive(start);
return Analyzer::Result{ ft.actions, ft.terminate };
}
| null |
812 | cpp | cppcheck | vf_settokenvalue.h | lib/vf_settokenvalue.h | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfSetTokenValueH
#define vfSetTokenValueH
#include "sourcelocation.h"
class Token;
class Settings;
namespace ValueFlow { class Value; }
namespace ValueFlow
{
void setTokenValue(Token* tok,
Value value,
const Settings& settings,
SourceLocation loc = SourceLocation::current());
}
#endif // vfSetTokenValueH
| null |
813 | cpp | cppcheck | json.h | lib/json.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef jsonH
#define jsonH
#include "config.h"
SUPPRESS_WARNING_PUSH("-Wfloat-equal")
SUPPRESS_WARNING_GCC_PUSH("-Wuseless-cast")
SUPPRESS_WARNING_CLANG_PUSH("-Wtautological-type-limit-compare")
SUPPRESS_WARNING_CLANG_PUSH("-Wextra-semi-stmt")
SUPPRESS_WARNING_CLANG_PUSH("-Wzero-as-null-pointer-constant")
SUPPRESS_WARNING_CLANG_PUSH("-Wformat")
#define PICOJSON_USE_INT64
#include <picojson.h>
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_GCC_POP
SUPPRESS_WARNING_POP
#endif // jsonH
| null |
814 | cpp | cppcheck | checkers.cpp | lib/checkers.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This file is auto-generated by tools/get_checkers.py:
// python3 tools/get_checkers.py > lib/checkers.cpp
#include "checkers.h"
namespace checkers {
const std::map<std::string, std::string> allCheckers{
{"CheckBool::checkIncrementBoolean","style"},
{"CheckBool::checkBitwiseOnBoolean","style,inconclusive"},
{"CheckBool::checkComparisonOfBoolWithInt","warning,c++"},
{"CheckBool::checkComparisonOfFuncReturningBool","style,c++"},
{"CheckBool::checkComparisonOfBoolWithBool","style,c++"},
{"CheckBool::checkAssignBoolToPointer",""},
{"CheckBool::checkComparisonOfBoolExpressionWithInt","warning"},
{"CheckBool::pointerArithBool",""},
{"CheckBool::checkAssignBoolToFloat","style,c++"},
{"CheckBool::returnValueOfFunctionReturningBool","style"},
{"CheckPostfixOperator::postfixOperator","performance"},
{"CheckSizeof::checkSizeofForNumericParameter","warning"},
{"CheckSizeof::checkSizeofForArrayParameter","warning"},
{"CheckSizeof::checkSizeofForPointerSize","warning"},
{"CheckSizeof::sizeofsizeof","warning"},
{"CheckSizeof::sizeofCalculation","warning"},
{"CheckSizeof::sizeofFunction","warning"},
{"CheckSizeof::suspiciousSizeofCalculation","warning,inconclusive"},
{"CheckSizeof::sizeofVoid","portability"},
{"Check64BitPortability::pointerassignment","portability"},
{"CheckStl::outOfBounds",""},
{"CheckStl::outOfBoundsIndexExpression",""},
{"CheckStl::iterators",""},
{"CheckStl::misMatchingContainers",""},
{"CheckStl::misMatchingContainerIterator",""},
{"CheckStl::invalidContainer",""},
{"CheckStl::stlOutOfBounds",""},
{"CheckStl::negativeIndex",""},
{"CheckStl::erase",""},
{"CheckStl::stlBoundaries",""},
{"CheckStl::if_find","warning,performance"},
{"CheckStl::checkFindInsert","performance"},
{"CheckStl::size","performance,c++03"},
{"CheckStl::redundantCondition","style"},
{"CheckStl::missingComparison","warning"},
{"CheckStl::string_c_str",""},
{"CheckStl::uselessCalls","performance,warning"},
{"CheckStl::checkDereferenceInvalidIterator","warning"},
{"CheckStl::checkDereferenceInvalidIterator2",""},
{"CheckStl::useStlAlgorithm","style"},
{"CheckStl::knownEmptyContainer","style"},
{"CheckStl::eraseIteratorOutOfBounds",""},
{"CheckStl::checkMutexes","warning"},
{"CheckBoost::checkBoostForeachModification",""},
{"CheckNullPointer::nullPointer",""},
{"CheckNullPointer::nullConstantDereference",""},
{"CheckNullPointer::arithmetic",""},
{"CheckNullPointer::analyseWholeProgram","unusedfunctions"},
{"CheckBufferOverrun::arrayIndex",""},
{"CheckBufferOverrun::pointerArithmetic","portability"},
{"CheckBufferOverrun::bufferOverflow",""},
{"CheckBufferOverrun::arrayIndexThenCheck",""},
{"CheckBufferOverrun::stringNotZeroTerminated","warning,inconclusive"},
{"CheckBufferOverrun::argumentSize","warning"},
{"CheckBufferOverrun::analyseWholeProgram",""},
{"CheckBufferOverrun::objectIndex",""},
{"CheckBufferOverrun::negativeArraySize",""},
{"CheckUninitVar::check",""},
{"CheckUninitVar::valueFlowUninit",""},
{"CheckOther::checkCastIntToCharAndBack","warning"},
{"CheckOther::clarifyCalculation","style"},
{"CheckOther::clarifyStatement","warning"},
{"CheckOther::checkSuspiciousSemicolon","warning,inconclusive"},
{"CheckOther::warningOldStylePointerCast","style,c++"},
{"CheckOther::suspiciousFloatingPointCast","style"},
{"CheckOther::invalidPointerCast","portability"},
{"CheckOther::checkRedundantAssignment","style"},
{"CheckOther::redundantBitwiseOperationInSwitch","warning"},
{"CheckOther::checkSuspiciousCaseInSwitch","warning,inconclusive"},
{"CheckOther::checkUnreachableCode","style"},
{"CheckOther::checkVariableScope","style,notclang"},
{"CheckOther::checkPassByReference","performance,c++"},
{"CheckOther::checkConstVariable","style,c++"},
{"CheckOther::checkConstPointer","style"},
{"CheckOther::checkCharVariable","warning,portability"},
{"CheckOther::checkIncompleteStatement","warning"},
{"CheckOther::checkZeroDivision",""},
{"CheckOther::checkNanInArithmeticExpression","style"},
{"CheckOther::checkMisusedScopedObject","style,c++"},
{"CheckOther::checkDuplicateBranch","style,inconclusive"},
{"CheckOther::checkInvalidFree",""},
{"CheckOther::checkDuplicateExpression","style,warning"},
{"CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse","warning"},
{"CheckOther::checkSignOfUnsignedVariable","style"},
{"CheckOther::checkRedundantCopy","c++,performance,inconclusive"},
{"CheckOther::checkNegativeBitwiseShift",""},
{"CheckOther::checkIncompleteArrayFill","warning,portability,inconclusive"},
{"CheckOther::checkVarFuncNullUB","portability"},
{"CheckOther::checkRedundantPointerOp","style"},
{"CheckOther::checkInterlockedDecrement","windows-platform"},
{"CheckOther::checkUnusedLabel","style,warning"},
{"CheckOther::checkEvaluationOrder",""},
{"CheckOther::checkAccessOfMovedVariable","c++11,warning"},
{"CheckOther::checkFuncArgNamesDifferent","style,warning,inconclusive"},
{"CheckOther::checkShadowVariables","style"},
{"CheckOther::checkKnownArgument","style"},
{"CheckOther::checkKnownPointerToBool","style"},
{"CheckOther::checkComparePointers",""},
{"CheckOther::checkModuloOfOne","style"},
{"CheckOther::checkOverlappingWrite",""},
{"CheckClass::checkConstructors","style,warning"},
{"CheckClass::checkExplicitConstructors","style"},
{"CheckClass::checkCopyConstructors","warning"},
{"CheckClass::initializationListUsage","performance"},
{"CheckClass::privateFunctions","style"},
{"CheckClass::checkMemset",""},
{"CheckClass::operatorEqRetRefThis","style"},
{"CheckClass::operatorEqToSelf","warning"},
{"CheckClass::virtualDestructor",""},
{"CheckClass::thisSubtraction","warning"},
{"CheckClass::checkConst","style,inconclusive"},
{"CheckClass::initializerListOrder","style,inconclusive"},
{"CheckClass::checkSelfInitialization",""},
{"CheckClass::checkVirtualFunctionCallInConstructor","warning"},
{"CheckClass::checkDuplInheritedMembers","warning"},
{"CheckClass::checkMissingOverride","style,c++03"},
{"CheckClass::checkUselessOverride","style"},
{"CheckClass::checkReturnByReference","performance"},
{"CheckClass::checkThisUseAfterFree","warning"},
{"CheckClass::checkUnsafeClassRefMember","warning,safeChecks"},
{"CheckClass::analyseWholeProgram",""},
{"CheckUnusedVar::checkFunctionVariableUsage","style"},
{"CheckUnusedVar::checkStructMemberUsage","style"},
{"CheckIO::checkCoutCerrMisusage","c"},
{"CheckIO::checkFileUsage",""},
{"CheckIO::invalidScanf",""},
{"CheckIO::checkWrongPrintfScanfArguments",""},
{"CheckCondition::assignIf","style"},
{"CheckCondition::checkBadBitmaskCheck","style"},
{"CheckCondition::comparison","style"},
{"CheckCondition::duplicateCondition","style"},
{"CheckCondition::multiCondition","style"},
{"CheckCondition::multiCondition2","warning"},
{"CheckCondition::checkIncorrectLogicOperator","style,warning"},
{"CheckCondition::checkModuloAlwaysTrueFalse","warning"},
{"CheckCondition::clarifyCondition","style"},
{"CheckCondition::alwaysTrueFalse","style"},
{"CheckCondition::checkInvalidTestForOverflow","warning"},
{"CheckCondition::checkPointerAdditionResultNotNull","warning"},
{"CheckCondition::checkDuplicateConditionalAssign","style"},
{"CheckCondition::checkAssignmentInCondition","style"},
{"CheckCondition::checkCompareValueOutOfTypeRange","style,platform"},
{"CheckFunctions::checkProhibitedFunctions",""},
{"CheckFunctions::invalidFunctionUsage",""},
{"CheckFunctions::checkIgnoredReturnValue","style,warning"},
{"CheckFunctions::checkMissingReturn",""},
{"CheckFunctions::checkMathFunctions","style,warning,c99,c++11"},
{"CheckFunctions::memsetZeroBytes","warning"},
{"CheckFunctions::memsetInvalid2ndParam","warning,portability"},
{"CheckFunctions::returnLocalStdMove","performance,c++11"},
{"CheckFunctions::useStandardLibrary","style"},
{"CheckVaarg::va_start_argument",""},
{"CheckVaarg::va_list_usage","notclang"},
{"CheckUnusedFunctions::check","unusedFunction"},
{"CheckType::checkTooBigBitwiseShift","platform"},
{"CheckType::checkIntegerOverflow","platform"},
{"CheckType::checkSignConversion","warning"},
{"CheckType::checkLongCast","style"},
{"CheckType::checkFloatToIntegerOverflow",""},
{"CheckString::stringLiteralWrite",""},
{"CheckString::checkAlwaysTrueOrFalseStringCompare","warning"},
{"CheckString::checkSuspiciousStringCompare","warning"},
{"CheckString::strPlusChar",""},
{"CheckString::checkIncorrectStringCompare","warning"},
{"CheckString::overlappingStrcmp","warning"},
{"CheckString::sprintfOverlappingData",""},
{"CheckAssert::assertWithSideEffects","warning"},
{"CheckExceptionSafety::destructors","warning"},
{"CheckExceptionSafety::deallocThrow","warning"},
{"CheckExceptionSafety::checkRethrowCopy","style"},
{"CheckExceptionSafety::checkCatchExceptionByValue","style"},
{"CheckExceptionSafety::nothrowThrows",""},
{"CheckExceptionSafety::unhandledExceptionSpecification","style,inconclusive"},
{"CheckExceptionSafety::rethrowNoCurrentException",""},
{"CheckAutoVariables::assignFunctionArg","style,warning"},
{"CheckAutoVariables::autoVariables",""},
{"CheckAutoVariables::checkVarLifetime",""},
{"CheckLeakAutoVar::check","notclang"},
{"CheckMemoryLeakInFunction::checkReallocUsage",""},
{"CheckMemoryLeakInClass::check",""},
{"CheckMemoryLeakStructMember::check",""},
{"CheckMemoryLeakNoVar::check",""},
{"CheckMemoryLeakNoVar::checkForUnsafeArgAlloc",""},
};
const std::map<std::string, std::string> premiumCheckers{
{"Autosar: A0-1-3",""},
{"Autosar: A0-1-4",""},
{"Autosar: A0-1-5",""},
{"Autosar: A0-1-6",""},
{"Autosar: A0-4-2",""},
{"Autosar: A0-4-4",""},
{"Autosar: A10-1-1",""},
{"Autosar: A11-0-2",""},
{"Autosar: A11-3-1",""},
{"Autosar: A13-2-1",""},
{"Autosar: A13-2-3",""},
{"Autosar: A13-5-2",""},
{"Autosar: A13-5-5",""},
{"Autosar: A15-1-2",""},
{"Autosar: A15-3-5",""},
{"Autosar: A16-6-1",""},
{"Autosar: A16-7-1",""},
{"Autosar: A18-0-3",""},
{"Autosar: A18-1-1",""},
{"Autosar: A18-1-2",""},
{"Autosar: A18-1-3",""},
{"Autosar: A18-5-1",""},
{"Autosar: A18-9-1",""},
{"Autosar: A2-11-1",""},
{"Autosar: A2-13-1",""},
{"Autosar: A2-13-3",""},
{"Autosar: A2-13-5",""},
{"Autosar: A2-5-2",""},
{"Autosar: A2-7-1",""},
{"Autosar: A20-8-2","warning"},
{"Autosar: A20-8-3","warning"},
{"Autosar: A20-8-4",""},
{"Autosar: A20-8-5",""},
{"Autosar: A20-8-6",""},
{"Autosar: A21-8-1","warning"},
{"Autosar: A23-0-1",""},
{"Autosar: A25-1-1","warning"},
{"Autosar: A25-4-1","warning"},
{"Autosar: A26-5-1",""},
{"Autosar: A26-5-2",""},
{"Autosar: A27-0-1","warning"},
{"Autosar: A27-0-2",""},
{"Autosar: A27-0-4",""},
{"Autosar: A3-1-3",""},
{"Autosar: A3-1-4",""},
{"Autosar: A3-3-1",""},
{"Autosar: A3-9-1",""},
{"Autosar: A4-10-1",""},
{"Autosar: A4-7-1",""},
{"Autosar: A5-0-2",""},
{"Autosar: A5-0-3",""},
{"Autosar: A5-0-4",""},
{"Autosar: A5-1-1",""},
{"Autosar: A5-1-2",""},
{"Autosar: A5-1-3",""},
{"Autosar: A5-1-6",""},
{"Autosar: A5-1-7",""},
{"Autosar: A5-16-1",""},
{"Autosar: A5-2-1",""},
{"Autosar: A5-2-3",""},
{"Autosar: A5-2-4",""},
{"Autosar: A5-3-3",""},
{"Autosar: A6-5-3",""},
{"Autosar: A7-1-4",""},
{"Autosar: A7-1-6",""},
{"Autosar: A7-1-7",""},
{"Autosar: A7-2-1",""},
{"Autosar: A7-2-2",""},
{"Autosar: A7-6-1",""},
{"Autosar: A8-4-1",""},
{"Autosar: A8-5-3",""},
{"Autosar: A9-3-1",""},
{"Cert C++: CON50-CPP",""},
{"Cert C++: CON51-CPP",""},
{"Cert C++: CON52-CPP",""},
{"Cert C++: CON53-CPP",""},
{"Cert C++: CON54-CPP",""},
{"Cert C++: CON55-CPP",""},
{"Cert C++: CON56-CPP",""},
{"Cert C++: CTR50-CPP",""},
{"Cert C++: CTR52-CPP",""},
{"Cert C++: CTR53-CPP",""},
{"Cert C++: CTR56-CPP",""},
{"Cert C++: CTR57-CPP","warning"},
{"Cert C++: CTR58-CPP","warning"},
{"Cert C++: DCL50-CPP",""},
{"Cert C++: DCL51-CPP",""},
{"Cert C++: DCL52-CPP",""},
{"Cert C++: DCL53-CPP",""},
{"Cert C++: DCL54-CPP",""},
{"Cert C++: DCL56-CPP",""},
{"Cert C++: DCL58-CPP",""},
{"Cert C++: DCL59-CPP",""},
{"Cert C++: ERR50-CPP",""},
{"Cert C++: ERR51-CPP",""},
{"Cert C++: ERR52-CPP",""},
{"Cert C++: ERR53-CPP",""},
{"Cert C++: ERR54-CPP",""},
{"Cert C++: ERR55-CPP",""},
{"Cert C++: ERR56-CPP",""},
{"Cert C++: ERR58-CPP",""},
{"Cert C++: ERR59-CPP","warning"},
{"Cert C++: ERR60-CPP","warning"},
{"Cert C++: ERR61-CPP",""},
{"Cert C++: ERR62-CPP",""},
{"Cert C++: EXP50-CPP",""},
{"Cert C++: EXP51-CPP",""},
{"Cert C++: EXP55-CPP",""},
{"Cert C++: EXP56-CPP",""},
{"Cert C++: EXP57-CPP",""},
{"Cert C++: EXP58-CPP",""},
{"Cert C++: EXP59-CPP",""},
{"Cert C++: EXP60-CPP",""},
{"Cert C++: FIO51-CPP",""},
{"Cert C++: INT50-CPP",""},
{"Cert C++: MEM52-CPP",""},
{"Cert C++: MEM53-CPP",""},
{"Cert C++: MEM54-CPP",""},
{"Cert C++: MEM55-CPP",""},
{"Cert C++: MEM57-CPP",""},
{"Cert C++: MSC50-CPP",""},
{"Cert C++: MSC51-CPP",""},
{"Cert C++: MSC53-CPP",""},
{"Cert C++: MSC54-CPP",""},
{"Cert C++: OOP51-CPP",""},
{"Cert C++: OOP55-CPP",""},
{"Cert C++: OOP56-CPP",""},
{"Cert C++: OOP57-CPP",""},
{"Cert C++: OOP58-CPP",""},
{"Cert C++: STR50-CPP",""},
{"Cert C++: STR53-CPP",""},
{"Cert C: ARR30-C",""},
{"Cert C: ARR32-C",""},
{"Cert C: ARR37-C",""},
{"Cert C: ARR38-C",""},
{"Cert C: ARR39-C",""},
{"Cert C: CON30-C",""},
{"Cert C: CON31-C",""},
{"Cert C: CON32-C",""},
{"Cert C: CON33-C",""},
{"Cert C: CON34-C",""},
{"Cert C: CON35-C",""},
{"Cert C: CON36-C",""},
{"Cert C: CON37-C",""},
{"Cert C: CON38-C",""},
{"Cert C: CON39-C",""},
{"Cert C: CON40-C",""},
{"Cert C: CON41-C",""},
{"Cert C: DCL31-C",""},
{"Cert C: DCL36-C",""},
{"Cert C: DCL37-C",""},
{"Cert C: DCL38-C",""},
{"Cert C: DCL39-C",""},
{"Cert C: DCL40-C",""},
{"Cert C: DCL41-C",""},
{"Cert C: ENV30-C",""},
{"Cert C: ENV31-C",""},
{"Cert C: ENV32-C",""},
{"Cert C: ENV33-C",""},
{"Cert C: ENV34-C",""},
{"Cert C: ERR30-C",""},
{"Cert C: ERR32-C",""},
{"Cert C: ERR33-C",""},
{"Cert C: EXP03-C",""},
{"Cert C: EXP05-C",""},
{"Cert C: EXP09-C",""},
{"Cert C: EXP13-C",""},
{"Cert C: EXP15-C",""},
{"Cert C: EXP19-C",""},
{"Cert C: EXP32-C",""},
{"Cert C: EXP35-C",""},
{"Cert C: EXP36-C",""},
{"Cert C: EXP37-C",""},
{"Cert C: EXP39-C",""},
{"Cert C: EXP40-C",""},
{"Cert C: EXP42-C",""},
{"Cert C: EXP43-C",""},
{"Cert C: EXP45-C",""},
{"Cert C: FIO30-C",""},
{"Cert C: FIO32-C",""},
{"Cert C: FIO34-C",""},
{"Cert C: FIO37-C",""},
{"Cert C: FIO38-C",""},
{"Cert C: FIO40-C",""},
{"Cert C: FIO41-C",""},
{"Cert C: FIO44-C",""},
{"Cert C: FIO45-C",""},
{"Cert C: FLP30-C",""},
{"Cert C: FLP36-C","portability"},
{"Cert C: FLP37-C",""},
{"Cert C: INT30-C",""},
{"Cert C: INT31-C",""},
{"Cert C: INT32-C",""},
{"Cert C: INT33-C",""},
{"Cert C: INT34-C",""},
{"Cert C: INT35-C",""},
{"Cert C: INT36-C",""},
{"Cert C: MEM33-C",""},
{"Cert C: MEM35-C",""},
{"Cert C: MEM36-C",""},
{"Cert C: MSC30-C",""},
{"Cert C: MSC32-C",""},
{"Cert C: MSC33-C",""},
{"Cert C: MSC38-C",""},
{"Cert C: MSC39-C",""},
{"Cert C: MSC40-C",""},
{"Cert C: PRE31-C",""},
{"Cert C: SIG30-C",""},
{"Cert C: SIG31-C",""},
{"Cert C: SIG34-C",""},
{"Cert C: SIG35-C",""},
{"Cert C: STR31-C",""},
{"Cert C: STR32-C",""},
{"Cert C: STR34-C",""},
{"Cert C: STR38-C",""},
{"Misra C++ 2008: 3-2-3",""},
{"Misra C++ 2008: 3-2-4",""},
{"Misra C++ 2008: 7-5-4",""},
{"Misra C++ 2008: M0-1-11",""},
{"Misra C++ 2008: M0-1-12",""},
{"Misra C++ 2008: M0-1-4",""},
{"Misra C++ 2008: M0-1-5",""},
{"Misra C++ 2008: M0-1-7",""},
{"Misra C++ 2008: M0-1-8",""},
{"Misra C++ 2008: M0-3-2",""},
{"Misra C++ 2008: M1-0-1","portability"},
{"Misra C++ 2008: M10-1-1",""},
{"Misra C++ 2008: M10-1-2",""},
{"Misra C++ 2008: M10-1-3",""},
{"Misra C++ 2008: M10-2-1",""},
{"Misra C++ 2008: M10-3-1",""},
{"Misra C++ 2008: M10-3-2",""},
{"Misra C++ 2008: M10-3-3",""},
{"Misra C++ 2008: M11-0-1",""},
{"Misra C++ 2008: M12-1-2",""},
{"Misra C++ 2008: M12-8-1",""},
{"Misra C++ 2008: M12-8-2",""},
{"Misra C++ 2008: M14-5-1","warning"},
{"Misra C++ 2008: M14-5-2","warning"},
{"Misra C++ 2008: M14-5-3","warning"},
{"Misra C++ 2008: M14-6-1","warning"},
{"Misra C++ 2008: M14-6-2","warning"},
{"Misra C++ 2008: M14-7-1",""},
{"Misra C++ 2008: M14-7-2",""},
{"Misra C++ 2008: M14-7-3",""},
{"Misra C++ 2008: M14-8-1",""},
{"Misra C++ 2008: M14-8-2",""},
{"Misra C++ 2008: M15-0-3",""},
{"Misra C++ 2008: M15-1-1",""},
{"Misra C++ 2008: M15-1-2",""},
{"Misra C++ 2008: M15-1-3",""},
{"Misra C++ 2008: M15-3-2","warning"},
{"Misra C++ 2008: M15-3-3",""},
{"Misra C++ 2008: M15-3-4",""},
{"Misra C++ 2008: M15-3-6",""},
{"Misra C++ 2008: M15-3-7",""},
{"Misra C++ 2008: M15-4-1",""},
{"Misra C++ 2008: M15-5-2",""},
{"Misra C++ 2008: M16-0-1",""},
{"Misra C++ 2008: M16-0-2",""},
{"Misra C++ 2008: M16-0-3",""},
{"Misra C++ 2008: M16-0-4",""},
{"Misra C++ 2008: M16-0-6",""},
{"Misra C++ 2008: M16-0-7",""},
{"Misra C++ 2008: M16-0-8",""},
{"Misra C++ 2008: M16-1-1",""},
{"Misra C++ 2008: M16-1-2",""},
{"Misra C++ 2008: M16-2-1",""},
{"Misra C++ 2008: M16-2-2",""},
{"Misra C++ 2008: M16-2-3",""},
{"Misra C++ 2008: M16-2-4",""},
{"Misra C++ 2008: M16-2-5",""},
{"Misra C++ 2008: M16-2-6",""},
{"Misra C++ 2008: M16-3-1",""},
{"Misra C++ 2008: M16-3-2",""},
{"Misra C++ 2008: M17-0-1",""},
{"Misra C++ 2008: M17-0-2",""},
{"Misra C++ 2008: M17-0-3",""},
{"Misra C++ 2008: M17-0-5",""},
{"Misra C++ 2008: M18-0-1",""},
{"Misra C++ 2008: M18-0-2",""},
{"Misra C++ 2008: M18-0-3",""},
{"Misra C++ 2008: M18-0-4",""},
{"Misra C++ 2008: M18-0-5",""},
{"Misra C++ 2008: M18-2-1",""},
{"Misra C++ 2008: M18-4-1",""},
{"Misra C++ 2008: M18-7-1",""},
{"Misra C++ 2008: M19-3-1",""},
{"Misra C++ 2008: M2-10-1",""},
{"Misra C++ 2008: M2-10-3",""},
{"Misra C++ 2008: M2-10-4",""},
{"Misra C++ 2008: M2-10-5",""},
{"Misra C++ 2008: M2-10-6",""},
{"Misra C++ 2008: M2-13-2",""},
{"Misra C++ 2008: M2-13-3",""},
{"Misra C++ 2008: M2-13-4",""},
{"Misra C++ 2008: M2-13-5",""},
{"Misra C++ 2008: M2-3-1",""},
{"Misra C++ 2008: M2-7-1",""},
{"Misra C++ 2008: M2-7-2",""},
{"Misra C++ 2008: M2-7-3",""},
{"Misra C++ 2008: M27-0-1",""},
{"Misra C++ 2008: M3-1-1",""},
{"Misra C++ 2008: M3-1-2",""},
{"Misra C++ 2008: M3-1-3",""},
{"Misra C++ 2008: M3-2-1",""},
{"Misra C++ 2008: M3-3-1",""},
{"Misra C++ 2008: M3-3-2",""},
{"Misra C++ 2008: M3-9-1",""},
{"Misra C++ 2008: M3-9-2",""},
{"Misra C++ 2008: M3-9-3",""},
{"Misra C++ 2008: M4-10-1",""},
{"Misra C++ 2008: M4-10-2",""},
{"Misra C++ 2008: M4-5-1",""},
{"Misra C++ 2008: M4-5-2",""},
{"Misra C++ 2008: M4-5-3",""},
{"Misra C++ 2008: M5-0-10",""},
{"Misra C++ 2008: M5-0-11",""},
{"Misra C++ 2008: M5-0-12",""},
{"Misra C++ 2008: M5-0-14",""},
{"Misra C++ 2008: M5-0-15",""},
{"Misra C++ 2008: M5-0-2",""},
{"Misra C++ 2008: M5-0-20",""},
{"Misra C++ 2008: M5-0-21",""},
{"Misra C++ 2008: M5-0-3",""},
{"Misra C++ 2008: M5-0-4",""},
{"Misra C++ 2008: M5-0-5",""},
{"Misra C++ 2008: M5-0-6",""},
{"Misra C++ 2008: M5-0-7",""},
{"Misra C++ 2008: M5-0-8",""},
{"Misra C++ 2008: M5-0-9",""},
{"Misra C++ 2008: M5-14-1",""},
{"Misra C++ 2008: M5-17-1",""},
{"Misra C++ 2008: M5-18-1",""},
{"Misra C++ 2008: M5-19-1",""},
{"Misra C++ 2008: M5-2-1",""},
{"Misra C++ 2008: M5-2-10",""},
{"Misra C++ 2008: M5-2-11",""},
{"Misra C++ 2008: M5-2-12",""},
{"Misra C++ 2008: M5-2-2",""},
{"Misra C++ 2008: M5-2-3",""},
{"Misra C++ 2008: M5-2-5",""},
{"Misra C++ 2008: M5-2-6",""},
{"Misra C++ 2008: M5-2-7",""},
{"Misra C++ 2008: M5-2-8",""},
{"Misra C++ 2008: M5-2-9",""},
{"Misra C++ 2008: M5-3-1",""},
{"Misra C++ 2008: M5-3-2",""},
{"Misra C++ 2008: M5-3-3",""},
{"Misra C++ 2008: M6-2-1",""},
{"Misra C++ 2008: M6-2-2",""},
{"Misra C++ 2008: M6-2-3",""},
{"Misra C++ 2008: M6-3-1",""},
{"Misra C++ 2008: M6-4-1",""},
{"Misra C++ 2008: M6-4-2",""},
{"Misra C++ 2008: M6-4-3",""},
{"Misra C++ 2008: M6-4-4",""},
{"Misra C++ 2008: M6-4-5",""},
{"Misra C++ 2008: M6-4-6",""},
{"Misra C++ 2008: M6-4-7",""},
{"Misra C++ 2008: M6-4-8",""},
{"Misra C++ 2008: M6-5-1",""},
{"Misra C++ 2008: M6-5-2",""},
{"Misra C++ 2008: M6-5-3",""},
{"Misra C++ 2008: M6-5-4",""},
{"Misra C++ 2008: M6-5-5",""},
{"Misra C++ 2008: M6-5-6",""},
{"Misra C++ 2008: M6-6-1",""},
{"Misra C++ 2008: M6-6-2",""},
{"Misra C++ 2008: M6-6-3",""},
{"Misra C++ 2008: M6-6-4",""},
{"Misra C++ 2008: M6-6-5",""},
{"Misra C++ 2008: M7-2-1",""},
{"Misra C++ 2008: M7-3-1",""},
{"Misra C++ 2008: M7-3-2",""},
{"Misra C++ 2008: M7-3-3",""},
{"Misra C++ 2008: M7-3-4",""},
{"Misra C++ 2008: M7-3-5",""},
{"Misra C++ 2008: M7-3-6",""},
{"Misra C++ 2008: M7-4-2",""},
{"Misra C++ 2008: M7-4-3",""},
{"Misra C++ 2008: M7-5-3",""},
{"Misra C++ 2008: M8-0-1",""},
{"Misra C++ 2008: M8-3-1",""},
{"Misra C++ 2008: M8-4-4",""},
{"Misra C++ 2008: M8-5-2",""},
{"Misra C++ 2008: M8-5-3",""},
{"Misra C++ 2008: M9-3-1",""},
{"Misra C++ 2008: M9-5-1",""},
{"Misra C++ 2008: M9-6-2",""},
{"Misra C++ 2008: M9-6-3",""},
{"Misra C++ 2008: M9-6-4",""},
{"Misra C++ 2023: 0.1.2",""},
{"Misra C++ 2023: 0.2.1",""},
{"Misra C++ 2023: 0.2.2",""},
{"Misra C++ 2023: 0.2.3",""},
{"Misra C++ 2023: 0.2.4",""},
{"Misra C++ 2023: 10.0.1",""},
{"Misra C++ 2023: 10.1.2",""},
{"Misra C++ 2023: 10.2.1",""},
{"Misra C++ 2023: 10.2.2",""},
{"Misra C++ 2023: 10.2.3",""},
{"Misra C++ 2023: 10.3.1",""},
{"Misra C++ 2023: 10.4.1",""},
{"Misra C++ 2023: 11.3.1",""},
{"Misra C++ 2023: 11.3.2",""},
{"Misra C++ 2023: 11.6.1",""},
{"Misra C++ 2023: 11.6.3",""},
{"Misra C++ 2023: 12.2.1",""},
{"Misra C++ 2023: 12.2.2",""},
{"Misra C++ 2023: 12.2.3",""},
{"Misra C++ 2023: 12.3.1",""},
{"Misra C++ 2023: 13.1.1",""},
{"Misra C++ 2023: 13.1.2",""},
{"Misra C++ 2023: 13.3.1",""},
{"Misra C++ 2023: 13.3.2",""},
{"Misra C++ 2023: 13.3.3",""},
{"Misra C++ 2023: 13.3.4",""},
{"Misra C++ 2023: 14.1.1",""},
{"Misra C++ 2023: 15.0.1",""},
{"Misra C++ 2023: 15.0.2",""},
{"Misra C++ 2023: 15.1.2",""},
{"Misra C++ 2023: 15.1.3",""},
{"Misra C++ 2023: 15.1.5",""},
{"Misra C++ 2023: 16.5.1",""},
{"Misra C++ 2023: 16.5.2",""},
{"Misra C++ 2023: 16.6.1",""},
{"Misra C++ 2023: 17.8.1",""},
{"Misra C++ 2023: 18.1.1",""},
{"Misra C++ 2023: 18.1.2",""},
{"Misra C++ 2023: 18.3.1",""},
{"Misra C++ 2023: 18.3.2",""},
{"Misra C++ 2023: 18.3.3",""},
{"Misra C++ 2023: 18.4.1",""},
{"Misra C++ 2023: 18.5.1",""},
{"Misra C++ 2023: 18.5.2",""},
{"Misra C++ 2023: 19.0.1",""},
{"Misra C++ 2023: 19.0.2",""},
{"Misra C++ 2023: 19.0.3",""},
{"Misra C++ 2023: 19.0.4",""},
{"Misra C++ 2023: 19.1.1",""},
{"Misra C++ 2023: 19.1.2",""},
{"Misra C++ 2023: 19.1.3",""},
{"Misra C++ 2023: 19.2.1",""},
{"Misra C++ 2023: 19.2.2",""},
{"Misra C++ 2023: 19.2.3",""},
{"Misra C++ 2023: 19.3.1",""},
{"Misra C++ 2023: 19.3.2",""},
{"Misra C++ 2023: 19.3.3",""},
{"Misra C++ 2023: 19.3.4",""},
{"Misra C++ 2023: 19.6.1",""},
{"Misra C++ 2023: 21.10.1",""},
{"Misra C++ 2023: 21.10.2",""},
{"Misra C++ 2023: 21.10.3",""},
{"Misra C++ 2023: 21.2.1",""},
{"Misra C++ 2023: 21.2.2",""},
{"Misra C++ 2023: 21.2.3",""},
{"Misra C++ 2023: 21.2.4",""},
{"Misra C++ 2023: 21.6.1",""},
{"Misra C++ 2023: 21.6.2",""},
{"Misra C++ 2023: 21.6.3",""},
{"Misra C++ 2023: 21.6.4",""},
{"Misra C++ 2023: 21.6.5",""},
{"Misra C++ 2023: 22.3.1",""},
{"Misra C++ 2023: 22.4.1",""},
{"Misra C++ 2023: 23.11.1",""},
{"Misra C++ 2023: 24.5.1",""},
{"Misra C++ 2023: 24.5.2",""},
{"Misra C++ 2023: 25.5.1",""},
{"Misra C++ 2023: 25.5.2",""},
{"Misra C++ 2023: 25.5.3",""},
{"Misra C++ 2023: 26.3.1",""},
{"Misra C++ 2023: 28.3.1",""},
{"Misra C++ 2023: 28.6.1",""},
{"Misra C++ 2023: 28.6.2",""},
{"Misra C++ 2023: 30.0.1",""},
{"Misra C++ 2023: 30.0.2",""},
{"Misra C++ 2023: 4.1.1",""},
{"Misra C++ 2023: 4.1.2",""},
{"Misra C++ 2023: 5.0.1",""},
{"Misra C++ 2023: 5.10.1",""},
{"Misra C++ 2023: 5.13.1",""},
{"Misra C++ 2023: 5.13.2",""},
{"Misra C++ 2023: 5.13.3",""},
{"Misra C++ 2023: 5.13.4",""},
{"Misra C++ 2023: 5.13.5",""},
{"Misra C++ 2023: 5.13.6",""},
{"Misra C++ 2023: 5.13.7",""},
{"Misra C++ 2023: 5.7.1",""},
{"Misra C++ 2023: 5.7.2",""},
{"Misra C++ 2023: 5.7.3",""},
{"Misra C++ 2023: 6.0.1",""},
{"Misra C++ 2023: 6.0.2",""},
{"Misra C++ 2023: 6.0.3",""},
{"Misra C++ 2023: 6.0.4",""},
{"Misra C++ 2023: 6.2.2",""},
{"Misra C++ 2023: 6.2.3",""},
{"Misra C++ 2023: 6.2.4",""},
{"Misra C++ 2023: 6.4.2",""},
{"Misra C++ 2023: 6.4.3",""},
{"Misra C++ 2023: 6.5.1",""},
{"Misra C++ 2023: 6.5.2",""},
{"Misra C++ 2023: 6.7.1",""},
{"Misra C++ 2023: 6.7.2",""},
{"Misra C++ 2023: 6.8.3",""},
{"Misra C++ 2023: 6.8.4",""},
{"Misra C++ 2023: 6.9.1",""},
{"Misra C++ 2023: 6.9.2",""},
{"Misra C++ 2023: 7.0.1",""},
{"Misra C++ 2023: 7.0.2",""},
{"Misra C++ 2023: 7.0.3",""},
{"Misra C++ 2023: 7.0.4",""},
{"Misra C++ 2023: 7.0.5",""},
{"Misra C++ 2023: 7.0.6",""},
{"Misra C++ 2023: 7.11.1",""},
{"Misra C++ 2023: 7.11.2",""},
{"Misra C++ 2023: 7.11.3",""},
{"Misra C++ 2023: 8.0.1",""},
{"Misra C++ 2023: 8.1.1",""},
{"Misra C++ 2023: 8.1.2",""},
{"Misra C++ 2023: 8.14.1",""},
{"Misra C++ 2023: 8.18.2",""},
{"Misra C++ 2023: 8.19.1",""},
{"Misra C++ 2023: 8.2.1",""},
{"Misra C++ 2023: 8.2.10",""},
{"Misra C++ 2023: 8.2.11",""},
{"Misra C++ 2023: 8.2.2",""},
{"Misra C++ 2023: 8.2.3",""},
{"Misra C++ 2023: 8.2.4",""},
{"Misra C++ 2023: 8.2.5",""},
{"Misra C++ 2023: 8.2.6",""},
{"Misra C++ 2023: 8.2.7",""},
{"Misra C++ 2023: 8.2.8",""},
{"Misra C++ 2023: 8.2.9",""},
{"Misra C++ 2023: 8.20.1",""},
{"Misra C++ 2023: 8.3.1",""},
{"Misra C++ 2023: 8.3.2",""},
{"Misra C++ 2023: 9.2.1",""},
{"Misra C++ 2023: 9.3.1",""},
{"Misra C++ 2023: 9.4.1",""},
{"Misra C++ 2023: 9.4.2",""},
{"Misra C++ 2023: 9.5.1",""},
{"Misra C++ 2023: 9.5.2",""},
{"Misra C++ 2023: 9.6.1",""},
{"Misra C++ 2023: 9.6.2",""},
{"Misra C++ 2023: 9.6.3",""},
{"Misra C++ 2023: 9.6.4",""},
{"Misra C: 1.4",""},
{"Misra C: 1.5",""},
{"Misra C: 10.1",""},
{"Misra C: 10.2",""},
{"Misra C: 10.3",""},
{"Misra C: 10.4",""},
{"Misra C: 10.5",""},
{"Misra C: 10.6",""},
{"Misra C: 10.7",""},
{"Misra C: 10.8",""},
{"Misra C: 11.1",""},
{"Misra C: 11.10",""},
{"Misra C: 11.2",""},
{"Misra C: 11.3",""},
{"Misra C: 11.4",""},
{"Misra C: 11.8",""},
{"Misra C: 12.3",""},
{"Misra C: 12.6",""},
{"Misra C: 13.1",""},
{"Misra C: 13.2",""},
{"Misra C: 13.3",""},
{"Misra C: 13.4",""},
{"Misra C: 13.5",""},
{"Misra C: 13.6",""},
{"Misra C: 15.5",""},
{"Misra C: 16.3",""},
{"Misra C: 17.10",""},
{"Misra C: 17.11",""},
{"Misra C: 17.12",""},
{"Misra C: 17.13",""},
{"Misra C: 17.2",""},
{"Misra C: 17.3",""},
{"Misra C: 17.4",""},
{"Misra C: 17.9",""},
{"Misra C: 18.10",""},
{"Misra C: 18.5",""},
{"Misra C: 18.8",""},
{"Misra C: 18.9",""},
{"Misra C: 20.3",""},
{"Misra C: 21.1",""},
{"Misra C: 21.12",""},
{"Misra C: 21.16",""},
{"Misra C: 21.2",""},
{"Misra C: 21.20",""},
{"Misra C: 21.22",""},
{"Misra C: 21.23",""},
{"Misra C: 21.24",""},
{"Misra C: 21.25","warning"},
{"Misra C: 21.26","warning"},
{"Misra C: 22.11",""},
{"Misra C: 22.12",""},
{"Misra C: 22.13",""},
{"Misra C: 22.14",""},
{"Misra C: 22.15",""},
{"Misra C: 22.16","warning"},
{"Misra C: 22.17","warning"},
{"Misra C: 22.18","warning"},
{"Misra C: 22.19","warning"},
{"Misra C: 22.20",""},
{"Misra C: 23.1",""},
{"Misra C: 23.2",""},
{"Misra C: 23.3",""},
{"Misra C: 23.4",""},
{"Misra C: 23.5",""},
{"Misra C: 23.6",""},
{"Misra C: 23.7",""},
{"Misra C: 23.8",""},
{"Misra C: 5.1",""},
{"Misra C: 5.2",""},
{"Misra C: 6.1",""},
{"Misra C: 6.3",""},
{"Misra C: 7.4","style"},
{"Misra C: 7.5",""},
{"Misra C: 7.6",""},
{"Misra C: 8.1",""},
{"Misra C: 8.10",""},
{"Misra C: 8.15",""},
{"Misra C: 8.15",""},
{"Misra C: 8.16",""},
{"Misra C: 8.17",""},
{"Misra C: 8.3",""},
{"Misra C: 8.4",""},
{"Misra C: 8.6",""},
{"Misra C: 8.7",""},
{"Misra C: 8.8",""},
{"Misra C: 9.6",""},
{"Misra C: 9.7",""},
{"Misra C: Dir 4.3",""},
{"Misra C: Dir 4.4",""},
{"Misra C: Dir 4.5",""},
{"Misra C: Dir 4.6",""},
{"Misra C: Dir 4.9",""},
{"PremiumCheckBufferOverrun::addressOfPointerArithmetic","warning"},
{"PremiumCheckBufferOverrun::negativeBufferSizeCheckedNonZero","warning"},
{"PremiumCheckBufferOverrun::negativeBufferSizeCheckedNonZero","warning"},
{"PremiumCheckHang::infiniteLoop",""},
{"PremiumCheckHang::infiniteLoopContinue",""},
{"PremiumCheckOther::arrayPointerComparison","style"},
{"PremiumCheckOther::knownResult","style"},
{"PremiumCheckOther::lossOfPrecision","style"},
{"PremiumCheckOther::pointerCast","style"},
{"PremiumCheckOther::reassignInLoop","style"},
{"PremiumCheckOther::unreachableCode","style"},
{"PremiumCheckStrictAlias::strictAliasCondition","warning"},
{"PremiumCheckUninitVar::uninitmember",""},
{"PremiumCheckUninitVar::uninitvar",""},
{"PremiumCheckUnusedVar::unreadVariable","style"},
{"PremiumCheckUnusedVar::unusedPrivateMember","style"}
};
const char Req[] = "Required";
const char Adv[] = "Advisory";
const char Man[] = "Mandatory";
const char Doc[] = "Document";
const std::vector<MisraInfo> misraC2012Directives =
{
{1,1,Req,0},
{2,1,Req,0},
{3,1,Req,0},
{4,1,Req,0},
{4,2,Adv,0},
{4,3,Req,0},
{4,4,Adv,0},
{4,5,Adv,0},
{4,6,Adv,3},
{4,7,Req,0},
{4,8,Adv,0},
{4,9,Adv,3},
{4,10,Req,0},
{4,11,Req,3},
{4,12,Req,0},
{4,13,Adv,0},
{4,14,Req,2},
{4,15,Req,3},
{5,1,Req,4},
{5,2,Req,4},
{5,3,Req,4},
};
const std::vector<MisraInfo> misraC2012Rules =
{
{1,1,Req,0},
{1,2,Adv,0},
{1,3,Req,0},
{1,4,Req,2}, // amendment 2
{1,5,Req,3}, // Amendment 3
{2,1,Req,0},
{2,2,Req,0},
{2,3,Adv,0},
{2,4,Adv,0},
{2,5,Adv,0},
{2,6,Adv,0},
{2,7,Adv,0},
{2,8,Adv,0},
{3,1,Req,0},
{3,2,Req,0},
{4,1,Req,0},
{4,2,Adv,0},
{5,1,Req,0},
{5,2,Req,0},
{5,3,Req,0},
{5,4,Req,0},
{5,5,Req,0},
{5,6,Req,0},
{5,7,Req,0},
{5,8,Req,0},
{5,9,Adv,0},
{6,1,Req,0},
{6,2,Req,0},
{6,3,Req,0},
{7,1,Req,0},
{7,2,Req,0},
{7,3,Req,0},
{7,4,Req,0},
{7,5,Man,0},
{7,6,Req,0},
{8,1,Req,0},
{8,2,Req,0},
{8,3,Req,0},
{8,4,Req,0},
{8,5,Req,0},
{8,6,Req,0},
{8,7,Adv,0},
{8,8,Req,0},
{8,9,Adv,0},
{8,10,Req,0},
{8,11,Adv,0},
{8,12,Req,0},
{8,13,Adv,0},
{8,14,Req,0},
{8,15,Req,0},
{8,16,Adv,0},
{8,17,Adv,0},
{9,1,Man,0},
{9,2,Req,0},
{9,3,Req,0},
{9,4,Req,0},
{9,5,Req,0},
{9,6,Req,0},
{9,7,Man,0},
{10,1,Req,0},
{10,2,Req,0},
{10,3,Req,0},
{10,4,Req,0},
{10,5,Adv,0},
{10,6,Req,0},
{10,7,Req,0},
{10,8,Req,0},
{11,1,Req,0},
{11,2,Req,0},
{11,3,Req,0},
{11,4,Adv,0},
{11,5,Adv,0},
{11,6,Req,0},
{11,7,Req,0},
{11,8,Req,0},
{11,9,Req,0},
{11,10,Req,0},
{12,1,Adv,0},
{12,2,Req,0},
{12,3,Adv,0},
{12,4,Adv,0},
{12,5,Man,1}, // amendment 1
{12,6,Req,4}, // amendment 4
{13,1,Req,0},
{13,2,Req,0},
{13,3,Adv,0},
{13,4,Adv,0},
{13,5,Req,0},
{13,6,Man,0},
{14,1,Req,0},
{14,2,Req,0},
{14,3,Req,0},
{14,4,Req,0},
{15,1,Adv,0},
{15,2,Req,0},
{15,3,Req,0},
{15,4,Adv,0},
{15,5,Adv,0},
{15,6,Req,0},
{15,7,Req,0},
{16,1,Req,0},
{16,2,Req,0},
{16,3,Req,0},
{16,4,Req,0},
{16,5,Req,0},
{16,6,Req,0},
{16,7,Req,0},
{17,1,Req,0},
{17,2,Req,0},
{17,3,Man,0},
{17,4,Man,0},
{17,5,Adv,0},
{17,6,Man,0},
{17,7,Req,0},
{17,8,Adv,0},
{17,9,Man,0},
{17,10,Req,0},
{17,11,Adv,0},
{17,12,Adv,0},
{17,13,Req,0},
{18,1,Req,0},
{18,2,Req,0},
{18,3,Req,0},
{18,4,Adv,0},
{18,5,Adv,0},
{18,6,Req,0},
{18,7,Req,0},
{18,8,Req,0},
{18,9,Req,0},
{18,10,Man,0},
{19,1,Man,0},
{19,2,Adv,0},
{20,1,Adv,0},
{20,2,Req,0},
{20,3,Req,0},
{20,4,Req,0},
{20,5,Adv,0},
{20,6,Req,0},
{20,7,Req,0},
{20,8,Req,0},
{20,9,Req,0},
{20,10,Adv,0},
{20,11,Req,0},
{20,12,Req,0},
{20,13,Req,0},
{20,14,Req,0},
{21,1,Req,0},
{21,2,Req,0},
{21,3,Req,0},
{21,4,Req,0},
{21,5,Req,0},
{21,6,Req,0},
{21,7,Req,0},
{21,8,Req,0},
{21,9,Req,0},
{21,10,Req,0},
{21,11,Req,0},
{21,12,Adv,0},
{21,13,Man,1}, // Amendment 1
{21,14,Req,1}, // Amendment 1
{21,15,Req,1}, // Amendment 1
{21,16,Req,1}, // Amendment 1
{21,17,Req,1}, // Amendment 1
{21,18,Man,1}, // Amendment 1
{21,19,Man,1}, // Amendment 1
{21,20,Man,1}, // Amendment 1
{21,21,Req,3}, // Amendment 3
{21,22,Man,3}, // Amendment 3
{21,23,Req,3}, // Amendment 3
{21,24,Req,3}, // Amendment 3
{21,25,Req,4}, // Amendment 4
{21,26,Req,4}, // Amendment 4
{22,1,Req,0},
{22,2,Man,0},
{22,3,Req,0},
{22,4,Man,0},
{22,5,Man,0},
{22,6,Man,0},
{22,7,Req,1}, // Amendment 1
{22,8,Req,1}, // Amendment 1
{22,9,Req,1}, // Amendment 1
{22,10,Req,1}, // Amendment 1
{22,11,Req,4}, // Amendment 4
{22,12,Man,4}, // Amendment 4
{22,13,Req,4}, // Amendment 4
{22,14,Man,4}, // Amendment 4
{22,15,Req,4}, // Amendment 4
{22,16,Req,4}, // Amendment 4
{22,17,Req,4}, // Amendment 4
{22,18,Req,4}, // Amendment 4
{22,19,Req,4}, // Amendment 4
{22,20,Man,4}, // Amendment 4
{23,1,Adv,3}, // Amendment 3
{23,2,Req,3}, // Amendment 3
{23,3,Adv,3}, // Amendment 3
{23,4,Req,3}, // Amendment 3
{23,5,Adv,3}, // Amendment 3
{23,6,Req,3}, // Amendment 3
{23,7,Adv,3}, // Amendment 3
{23,8,Req,3}, // Amendment 3
};
const std::map<std::string, std::string> misraRuleSeverity{
{"1.1", "error"}, //{"syntaxError", "unknownMacro"}},
{"1.3", "error"}, //most "error"
{"2.1", "style"}, //{"alwaysFalse", "duplicateBreak"}},
{"2.2", "style"}, //{"alwaysTrue", "redundantCondition", "redundantAssignment", "redundantAssignInSwitch", "unreadVariable"}},
{"2.6", "style"}, //{"unusedLabel"}},
{"2.8", "style"}, //{"unusedVariable"}},
{"5.3", "style"}, //{"shadowVariable"}},
{"8.3", "style"}, //{"funcArgNamesDifferent"}}, // inconclusive
{"8.13", "style"}, //{"constPointer"}},
{"9.1", "error"}, //{"uninitvar"}},
{"14.3", "style"}, //{"alwaysTrue", "alwaysFalse", "compareValueOutOfTypeRangeError", "knownConditionTrueFalse"}},
{"13.2", "error"}, //{"unknownEvaluationOrder"}},
{"13.6", "style"}, //{"sizeofCalculation"}},
{"17.4", "error"}, //{"missingReturn"}},
{"17.5", "warning"}, //{"argumentSize"}},
{"18.1", "error"}, //{"pointerOutOfBounds"}},
{"18.2", "error"}, //{"comparePointers"}},
{"18.3", "error"}, //{"comparePointers"}},
{"18.6", "error"}, //{"danglingLifetime"}},
{"19.1", "error"}, //{"overlappingWriteUnion", "overlappingWriteFunction"}},
{"20.6", "error"}, //{"preprocessorErrorDirective"}},
{"21.13", "error"}, //{"invalidFunctionArg"}},
{"21.17", "error"}, //{"bufferAccessOutOfBounds"}},
{"21.18", "error"}, //{"bufferAccessOutOfBounds"}},
{"22.1", "error"}, //{"memleak", "resourceLeak", "memleakOnRealloc", "leakReturnValNotUsed", "leakNoVarFunctionCall"}},
{"22.2", "error"}, //{"autovarInvalidDeallocation"}},
{"22.3", "error"}, //{"incompatibleFileOpen"}},
{"22.4", "error"}, //{"writeReadOnlyFile"}},
{"22.6", "error"}, //{"useClosedFile"}}
};
const std::vector<MisraCppInfo> misraCpp2008Rules =
{
{0,1,1,Req},
{0,1,2,Req},
{0,1,3,Req},
{0,1,4,Req},
{0,1,5,Req},
{0,1,6,Req},
{0,1,7,Req},
{0,1,8,Req},
{0,1,9,Req},
{0,1,10,Req},
{0,1,11,Req},
{0,1,12,Req},
{0,2,1,Req},
{0,3,1,Doc},
{0,3,2,Req},
{0,4,1,Doc},
{0,4,2,Doc},
{0,4,3,Doc},
{1,0,1,Req},
{1,0,2,Doc},
{1,0,3,Doc},
{2,2,1,Doc},
{2,3,1,Req},
{2,5,1,Adv},
{2,7,1,Req},
{2,7,2,Req},
{2,7,3,Adv},
{2,10,1,Req},
{2,10,2,Req},
{2,10,3,Req},
{2,10,4,Req},
{2,10,5,Adv},
{2,10,6,Req},
{2,13,1,Req},
{2,13,2,Req},
{2,13,3,Req},
{2,13,4,Req},
{2,13,5,Req},
{3,1,1,Req},
{3,1,2,Req},
{3,1,3,Req},
{3,2,1,Req},
{3,2,2,Req},
{3,2,3,Req},
{3,2,4,Req},
{3,3,1,Req},
{3,3,2,Req},
{3,4,1,Req},
{3,9,1,Req},
{3,9,2,Adv},
{3,9,3,Req},
{4,5,1,Req},
{4,5,2,Req},
{4,5,3,Req},
{4,10,1,Req},
{4,10,2,Req},
{5,0,1,Req},
{5,0,2,Adv},
{5,0,3,Req},
{5,0,4,Req},
{5,0,5,Req},
{5,0,6,Req},
{5,0,7,Req},
{5,0,8,Req},
{5,0,9,Req},
{5,0,10,Req},
{5,0,11,Req},
{5,0,12,Req},
{5,0,13,Req},
{5,0,14,Req},
{5,0,15,Req},
{5,0,16,Req},
{5,0,17,Req},
{5,0,18,Req},
{5,0,19,Req},
{5,0,20,Req},
{5,0,21,Req},
{5,2,1,Req},
{5,2,2,Req},
{5,2,3,Adv},
{5,2,4,Req},
{5,2,5,Req},
{5,2,6,Req},
{5,2,7,Req},
{5,2,8,Req},
{5,2,9,Adv},
{5,2,10,Adv},
{5,2,11,Req},
{5,2,12,Req},
{5,3,1,Req},
{5,3,2,Req},
{5,3,3,Req},
{5,3,4,Req},
{5,8,1,Req},
{5,14,1,Req},
{5,17,1,Req},
{5,18,1,Req},
{5,19,1,Adv},
{6,2,1,Req},
{6,2,2,Req},
{6,2,3,Req},
{6,3,1,Req},
{6,4,1,Req},
{6,4,2,Req},
{6,4,3,Req},
{6,4,4,Req},
{6,4,5,Req},
{6,4,6,Req},
{6,4,7,Req},
{6,4,8,Req},
{6,5,1,Req},
{6,5,2,Req},
{6,5,3,Req},
{6,5,4,Req},
{6,5,5,Req},
{6,5,6,Req},
{6,6,1,Req},
{6,6,2,Req},
{6,6,3,Req},
{6,6,4,Req},
{6,6,5,Req},
{7,1,1,Req},
{7,1,2,Req},
{7,2,1,Req},
{7,3,1,Req},
{7,3,2,Req},
{7,3,3,Req},
{7,3,4,Req},
{7,3,5,Req},
{7,3,6,Req},
{7,4,1,Doc},
{7,4,2,Req},
{7,4,3,Req},
{7,5,1,Req},
{7,5,2,Req},
{7,5,3,Req},
{7,5,4,Adv},
{8,4,1,Req},
{8,4,2,Req},
{8,4,3,Req},
{8,4,4,Req},
{8,5,1,Req},
{8,5,2,Req},
{8,5,3,Req},
{9,3,1,Req},
{9,3,2,Req},
{9,3,3,Req},
{9,5,1,Req},
{9,6,1,Doc},
{9,6,2,Req},
{9,6,3,Req},
{9,6,4,Req},
{10,1,1,Adv},
{10,1,2,Req},
{10,1,3,Req},
{10,2,1,Adv},
{10,3,1,Req},
{10,3,2,Req},
{10,3,3,Req},
{11,0,1,Req},
{12,1,1,Req},
{12,1,2,Adv},
{12,1,3,Req},
{12,8,1,Req},
{12,8,2,Req},
{14,5,1,Req},
{14,5,2,Req},
{14,5,3,Req},
{14,6,1,Req},
{14,6,2,Req},
{14,7,1,Req},
{14,7,2,Req},
{14,7,3,Req},
{14,8,1,Req},
{14,8,2,Req},
{15,0,1,Req},
{15,0,2,Req},
{15,0,3,Req},
{15,1,1,Req},
{15,1,2,Req},
{15,1,3,Req},
{15,3,1,Req},
{15,3,2,Adv},
{15,3,3,Req},
{15,3,4,Req},
{15,3,5,Req},
{15,3,6,Req},
{15,3,7,Req},
{15,4,1,Req},
{15,5,1,Req},
{15,5,2,Req},
{15,5,3,Req},
{16,0,1,Req},
{16,0,2,Req},
{16,0,3,Req},
{16,0,4,Req},
{16,0,5,Req},
{16,0,6,Req},
{16,0,7,Req},
{16,0,8,Req},
{16,1,1,Req},
{16,1,2,Req},
{16,2,1,Req},
{16,2,2,Req},
{16,2,3,Req},
{16,2,4,Req},
{16,2,5,Adv},
{16,2,6,Req},
{16,3,1,Req},
{16,3,2,Adv},
{16,6,1,Doc},
{17,0,1,Req},
{17,0,2,Req},
{17,0,3,Req},
{17,0,4,Doc},
{17,0,5,Req},
{18,0,1,Req},
{18,0,2,Req},
{18,0,3,Req},
{18,0,4,Req},
{18,0,5,Req},
{18,2,1,Req},
{18,4,1,Req},
{18,7,1,Req},
{19,3,1,Req},
{27,0,1,Req}
};
const std::vector<MisraCppInfo> misraCpp2023Rules =
{
{0,0,1,Req},
{0,0,2,Adv},
{0,1,1,Adv},
{0,1,2,Req},
{0,2,1,Adv},
{0,2,2,Req},
{0,2,3,Adv},
{0,2,4,Adv},
{0,3,1,Adv},
{0,3,2,Req},
{4,1,1,Req},
{4,1,2,Adv},
{4,1,3,Req},
{4,6,1,Req},
{5,0,1,Adv},
{5,7,1,Req},
{5,7,2,Adv},
{5,7,3,Req},
{5,10,1,Req},
{5,13,1,Req},
{5,13,2,Req},
{5,13,3,Req},
{5,13,4,Req},
{5,13,5,Req},
{5,13,6,Req},
{5,13,7,Req},
{6,0,1,Req},
{6,0,2,Adv},
{6,0,3,Adv},
{6,0,4,Req},
{6,2,1,Req},
{6,2,2,Req},
{6,2,3,Req},
{6,2,4,Req},
{6,4,1,Req},
{6,4,2,Req},
{6,4,3,Req},
{6,5,1,Adv},
{6,5,2,Adv},
{6,7,1,Req},
{6,7,2,Req},
{6,8,1,Req},
{6,8,2,Man},
{6,8,3,Req},
{6,8,4,Adv},
{6,9,1,Req},
{6,9,2,Adv},
{7,0,1,Req},
{7,0,2,Req},
{7,0,3,Req},
{7,0,4,Req},
{7,0,5,Req},
{7,0,6,Req},
{7,11,1,Req},
{7,11,2,Req},
{7,11,3,Req},
{8,0,1,Adv},
{8,1,1,Req},
{8,1,2,Adv},
{8,2,1,Req},
{8,2,2,Req},
{8,2,3,Req},
{8,2,4,Req},
{8,2,5,Req},
{8,2,6,Req},
{8,2,7,Adv},
{8,2,8,Req},
{8,2,9,Req},
{8,2,10,Req},
{8,2,11,Req},
{8,3,1,Adv},
{8,3,2,Adv},
{8,7,1,Req},
{8,7,2,Req},
{8,9,1,Req},
{8,14,1,Adv},
{8,18,1,Man},
{8,18,2,Adv},
{8,19,1,Adv},
{8,20,1,Adv},
{9,2,1,Req},
{9,3,1,Req},
{9,4,1,Req},
{9,4,2,Req},
{9,5,2,Adv},
{9,5,3,Req},
{9,6,1,Adv},
{9,6,2,Req},
{9,6,3,Req},
{9,6,4,Req},
{9,6,5,Req},
{10,0,1,Adv},
{10,1,1,Adv},
{10,1,2,Req},
{10,2,1,Req},
{10,2,2,Adv},
{10,2,3,Req},
{10,3,1,Adv},
{10,4,1,Req},
{11,3,1,Adv},
{11,3,2,Adv},
{11,6,1,Adv},
{11,6,2,Man},
{11,6,3,Req},
{12,2,1,Adv},
{12,2,2,Req},
{12,2,3,Req},
{12,3,1,Req},
{13,1,1,Adv},
{13,1,2,Req},
{13,3,1,Req},
{13,3,2,Req},
{13,3,3,Req},
{13,3,4,Req},
{14,1,1,Adv},
{15,0,1,Req},
{15,0,2,Adv},
{15,1,1,Req},
{15,1,2,Adv},
{15,1,3,Req},
{15,1,4,Adv},
{15,1,5,Req},
{15,8,1,Req},
{16,5,2,Req},
{16,6,1,Adv},
{17,8,1,Req},
{18,1,1,Req},
{18,1,2,Req},
{18,3,1,Adv},
{18,3,2,Req},
{18,3,3,Req},
{18,4,1,Req},
{18,5,1,Adv},
{18,5,2,Adv},
{19,0,1,Req},
{19,0,2,Req},
{19,0,3,Adv},
{19,0,4,Adv},
{19,1,1,Req},
{19,1,2,Req},
{19,1,3,Req},
{19,2,1,Req},
{19,2,2,Req},
{19,2,3,Req},
{19,3,1,Adv},
{19,3,2,Req},
{19,3,3,Req},
{19,3,4,Req},
{19,3,5,Req},
{19,6,1,Adv},
{21,2,1,Req},
{21,2,2,Req},
{21,2,3,Req},
{21,2,4,Req},
{21,6,1,Adv},
{21,6,2,Req},
{21,6,3,Req},
{21,6,4,Req},
{21,6,5,Req},
{21,10,1,Req},
{21,10,2,Req},
{21,10,3,Req},
{22,3,1,Req},
{22,4,1,Req},
{23,11,1,Adv},
{24,5,1,Req},
{24,5,2,Req},
{25,5,1,Req},
{25,5,2,Man},
{25,5,3,Man},
{26,3,1,Adv},
{28,3,1,Req},
{28,6,1,Req},
{28,6,2,Req},
{28,6,3,Req},
{28,6,4,Req},
{30,0,1,Req},
{30,0,2,Req}
};
}
std::vector<checkers::Info> checkers::autosarInfo{
{"m0-1-1", checkers::Req},
{"m0-1-2", checkers::Req},
{"m0-1-3", checkers::Req},
{"m0-1-4", checkers::Req},
{"a0-1-1", checkers::Req},
{"a0-1-2", checkers::Req},
{"m0-1-8", checkers::Req},
{"m0-1-9", checkers::Req},
{"m0-1-10", checkers::Adv},
{"a0-1-3", checkers::Req},
{"a0-1-4", checkers::Req},
{"a0-1-5", checkers::Req},
{"a0-1-6", checkers::Adv},
{"m0-2-1", checkers::Req},
{"a0-4-2", checkers::Req},
{"a0-4-3", checkers::Req},
{"a0-4-4", checkers::Req},
{"a1-1-1", checkers::Req},
{"a1-4-3", checkers::Adv},
{"a2-3-1", checkers::Req},
{"a2-5-1", checkers::Req},
{"a2-5-2", checkers::Req},
{"m2-7-1", checkers::Req},
{"a2-7-1", checkers::Req},
{"a2-7-3", checkers::Req},
{"a2-8-2", checkers::Adv},
{"m2-10-1", checkers::Req},
{"a2-10-1", checkers::Req},
{"a2-10-6", checkers::Req},
{"a2-10-4", checkers::Req},
{"a2-10-5", checkers::Adv},
{"a2-11-1", checkers::Req},
{"a2-13-1", checkers::Req},
{"a2-13-6", checkers::Req},
{"a2-13-5", checkers::Adv},
{"m2-13-2", checkers::Req},
{"m2-13-3", checkers::Req},
{"m2-13-4", checkers::Req},
{"a2-13-2", checkers::Req},
{"a2-13-3", checkers::Req},
{"a2-13-4", checkers::Req},
{"a3-1-1", checkers::Req},
{"a3-1-2", checkers::Req},
{"a3-1-3", checkers::Adv},
{"m3-1-2", checkers::Req},
{"a3-1-4", checkers::Req},
{"a3-1-6", checkers::Adv},
{"m3-2-1", checkers::Req},
{"m3-2-2", checkers::Req},
{"m3-2-3", checkers::Req},
{"m3-2-4", checkers::Req},
{"a3-3-1", checkers::Req},
{"a3-3-2", checkers::Req},
{"m3-3-2", checkers::Req},
{"m3-4-1", checkers::Req},
{"m3-9-1", checkers::Req},
{"a3-9-1", checkers::Req},
{"m3-9-3", checkers::Req},
{"m4-5-1", checkers::Req},
{"a4-5-1", checkers::Req},
{"m4-5-3", checkers::Req},
{"a4-7-1", checkers::Req},
{"m4-10-1", checkers::Req},
{"a4-10-1", checkers::Req},
{"m4-10-2", checkers::Req},
{"a5-0-1", checkers::Req},
{"m5-0-2", checkers::Adv},
{"m5-0-3", checkers::Req},
{"m5-0-4", checkers::Req},
{"m5-0-5", checkers::Req},
{"m5-0-6", checkers::Req},
{"m5-0-7", checkers::Req},
{"m5-0-8", checkers::Req},
{"m5-0-9", checkers::Req},
{"m5-0-10", checkers::Req},
{"m5-0-11", checkers::Req},
{"m5-0-12", checkers::Req},
{"a5-0-2", checkers::Req},
{"m5-0-14", checkers::Req},
{"m5-0-15", checkers::Req},
{"m5-0-16", checkers::Req},
{"m5-0-17", checkers::Req},
{"a5-0-4", checkers::Req},
{"m5-0-18", checkers::Req},
{"a5-0-3", checkers::Req},
{"m5-0-20", checkers::Req},
{"m5-0-21", checkers::Req},
{"a5-1-1", checkers::Req},
{"a5-1-2", checkers::Req},
{"a5-1-3", checkers::Req},
{"a5-1-4", checkers::Req},
{"a5-1-6", checkers::Adv},
{"a5-1-7", checkers::Req},
{"a5-1-8", checkers::Adv},
{"a5-1-9", checkers::Adv},
{"m5-2-2", checkers::Req},
{"m5-2-3", checkers::Adv},
{"a5-2-1", checkers::Adv},
{"a5-2-2", checkers::Req},
{"a5-2-3", checkers::Req},
{"m5-2-6", checkers::Req},
{"a5-2-4", checkers::Req},
{"a5-2-6", checkers::Req},
{"m5-2-8", checkers::Req},
{"m5-2-9", checkers::Req},
{"m5-2-10", checkers::Req},
{"m5-2-11", checkers::Req},
{"a5-2-5", checkers::Req},
{"m5-2-12", checkers::Req},
{"m5-3-1", checkers::Req},
{"m5-3-2", checkers::Req},
{"m5-3-3", checkers::Req},
{"m5-3-4", checkers::Req},
{"a5-3-1", checkers::Req},
{"a5-3-2", checkers::Req},
{"a5-3-3", checkers::Req},
{"a5-5-1", checkers::Req},
{"a5-6-1", checkers::Req},
{"m5-8-1", checkers::Req},
{"a5-10-1", checkers::Req},
{"m5-14-1", checkers::Req},
{"a5-16-1", checkers::Req},
{"m5-18-1", checkers::Req},
{"m5-19-1", checkers::Req},
{"m6-2-1", checkers::Req},
{"a6-2-1", checkers::Req},
{"a6-2-2", checkers::Req},
{"m6-2-2", checkers::Req},
{"m6-2-3", checkers::Req},
{"m6-3-1", checkers::Req},
{"m6-4-1", checkers::Req},
{"m6-4-2", checkers::Req},
{"m6-4-3", checkers::Req},
{"m6-4-4", checkers::Req},
{"m6-4-5", checkers::Req},
{"m6-4-6", checkers::Req},
{"m6-4-7", checkers::Req},
{"a6-4-1", checkers::Req},
{"a6-5-1", checkers::Req},
{"a6-5-2", checkers::Req},
{"m6-5-2", checkers::Req},
{"m6-5-3", checkers::Req},
{"m6-5-4", checkers::Req},
{"m6-5-5", checkers::Req},
{"m6-5-6", checkers::Req},
{"a6-5-3", checkers::Adv},
{"a6-5-4", checkers::Adv},
{"a6-6-1", checkers::Req},
{"m6-6-1", checkers::Req},
{"m6-6-2", checkers::Req},
{"m6-6-3", checkers::Req},
{"a7-1-1", checkers::Req},
{"a7-1-2", checkers::Req},
{"m7-1-2", checkers::Req},
{"a7-1-3", checkers::Req},
{"a7-1-4", checkers::Req},
{"a7-1-5", checkers::Req},
{"a7-1-6", checkers::Req},
{"a7-1-7", checkers::Req},
{"a7-1-8", checkers::Req},
{"a7-1-9", checkers::Req},
{"a7-2-1", checkers::Req},
{"a7-2-2", checkers::Req},
{"a7-2-3", checkers::Req},
{"a7-2-4", checkers::Req},
{"m7-3-1", checkers::Req},
{"m7-3-2", checkers::Req},
{"m7-3-3", checkers::Req},
{"m7-3-4", checkers::Req},
{"a7-3-1", checkers::Req},
{"m7-3-6", checkers::Req},
{"a7-4-1", checkers::Req},
{"m7-4-2", checkers::Req},
{"m7-4-3", checkers::Req},
{"a7-5-1", checkers::Req},
{"a7-5-2", checkers::Req},
{"a7-6-1", checkers::Req},
{"m8-0-1", checkers::Req},
{"a8-2-1", checkers::Req},
{"m8-3-1", checkers::Req},
{"a8-4-1", checkers::Req},
{"m8-4-2", checkers::Req},
{"a8-4-2", checkers::Req},
{"m8-4-4", checkers::Req},
{"a8-4-4", checkers::Adv},
{"a8-4-5", checkers::Req},
{"a8-4-6", checkers::Req},
{"a8-4-7", checkers::Req},
{"a8-4-8", checkers::Req},
{"a8-4-9", checkers::Req},
{"a8-4-10", checkers::Req},
{"a8-4-11", checkers::Req},
{"a8-4-12", checkers::Req},
{"a8-4-13", checkers::Req},
{"a8-4-14", checkers::Req},
{"a8-5-0", checkers::Req},
{"a8-5-1", checkers::Req},
{"m8-5-2", checkers::Req},
{"a8-5-2", checkers::Req},
{"a8-5-3", checkers::Req},
{"a8-5-4", checkers::Adv},
{"m9-3-1", checkers::Req},
{"a9-3-1", checkers::Req},
{"m9-3-3", checkers::Req},
{"a9-5-1", checkers::Req},
{"a9-6-1", checkers::Req},
{"m9-6-4", checkers::Req},
{"a10-1-1", checkers::Req},
{"m10-1-1", checkers::Adv},
{"m10-1-2", checkers::Req},
{"m10-1-3", checkers::Req},
{"m10-2-1", checkers::Adv},
{"a10-2-1", checkers::Req},
{"a10-3-1", checkers::Req},
{"a10-3-2", checkers::Req},
{"a10-3-3", checkers::Req},
{"a10-3-5", checkers::Req},
{"m10-3-3", checkers::Req},
{"a10-4-1", checkers::Req},
{"m11-0-1", checkers::Req},
{"a11-0-1", checkers::Adv},
{"a11-0-2", checkers::Req},
{"a11-3-1", checkers::Req},
{"a12-0-1", checkers::Req},
{"a12-0-2", checkers::Req},
{"a12-1-1", checkers::Req},
{"m12-1-1", checkers::Req},
{"a12-1-2", checkers::Req},
{"a12-1-3", checkers::Req},
{"a12-1-4", checkers::Req},
{"a12-1-5", checkers::Req},
{"a12-1-6", checkers::Req},
{"a12-4-1", checkers::Req},
{"a12-4-2", checkers::Adv},
{"a12-6-1", checkers::Req},
{"a12-7-1", checkers::Req},
{"a12-8-1", checkers::Req},
{"a12-8-2", checkers::Adv},
{"a12-8-3", checkers::Req},
{"a12-8-4", checkers::Req},
{"a12-8-5", checkers::Req},
{"a12-8-6", checkers::Req},
{"a12-8-7", checkers::Adv},
{"a13-1-2", checkers::Req},
{"a13-1-3", checkers::Req},
{"a13-2-1", checkers::Req},
{"a13-2-2", checkers::Req},
{"a13-2-3", checkers::Req},
{"a13-3-1", checkers::Req},
{"a13-5-1", checkers::Req},
{"a13-5-2", checkers::Req},
{"a13-5-3", checkers::Adv},
{"a13-5-4", checkers::Req},
{"a13-5-5", checkers::Req},
{"a13-6-1", checkers::Req},
{"a14-1-1", checkers::Adv},
{"a14-5-1", checkers::Req},
{"a14-5-2", checkers::Req},
{"a14-5-3", checkers::Req},
{"m14-5-3", checkers::Req},
{"m14-6-1", checkers::Req},
{"a14-7-1", checkers::Req},
{"a14-7-2", checkers::Req},
{"a14-8-2", checkers::Req},
{"a15-0-2", checkers::Req},
{"a15-1-2", checkers::Req},
{"m15-0-3", checkers::Req},
{"m15-1-1", checkers::Req},
{"m15-1-2", checkers::Req},
{"m15-1-3", checkers::Req},
{"a15-1-3", checkers::Adv},
{"a15-1-4", checkers::Req},
{"a15-2-1", checkers::Req},
{"a15-2-2", checkers::Req},
{"m15-3-1", checkers::Req},
{"a15-3-2", checkers::Req},
{"a15-3-3", checkers::Req},
{"m15-3-3", checkers::Req},
{"m15-3-4", checkers::Req},
{"a15-3-5", checkers::Req},
{"m15-3-6", checkers::Req},
{"m15-3-7", checkers::Req},
{"a15-4-1", checkers::Req},
{"a15-4-2", checkers::Req},
{"a15-4-3", checkers::Req},
{"a15-4-4", checkers::Req},
{"a15-4-5", checkers::Req},
{"a15-5-1", checkers::Req},
{"a15-5-2", checkers::Req},
{"a15-5-3", checkers::Req},
{"a16-0-1", checkers::Req},
{"m16-0-1", checkers::Req},
{"m16-0-2", checkers::Req},
{"m16-0-5", checkers::Req},
{"m16-0-6", checkers::Req},
{"m16-0-7", checkers::Req},
{"m16-0-8", checkers::Req},
{"m16-1-1", checkers::Req},
{"m16-1-2", checkers::Req},
{"m16-2-3", checkers::Req},
{"a16-2-1", checkers::Req},
{"a16-2-2", checkers::Req},
{"a16-2-3", checkers::Req},
{"m16-3-1", checkers::Req},
{"m16-3-2", checkers::Adv},
{"a16-6-1", checkers::Req},
{"a16-7-1", checkers::Req},
{"a17-0-1", checkers::Req},
{"m17-0-2", checkers::Req},
{"m17-0-3", checkers::Req},
{"m17-0-5", checkers::Req},
{"a17-1-1", checkers::Req},
{"a17-6-1", checkers::Req},
{"a18-0-1", checkers::Req},
{"a18-0-2", checkers::Req},
{"m18-0-3", checkers::Req},
{"m18-0-4", checkers::Req},
{"m18-0-5", checkers::Req},
{"a18-0-3", checkers::Req},
{"a18-1-1", checkers::Req},
{"a18-1-2", checkers::Req},
{"a18-1-3", checkers::Req},
{"a18-1-4", checkers::Req},
{"a18-1-6", checkers::Req},
{"m18-2-1", checkers::Req},
{"a18-5-1", checkers::Req},
{"a18-5-2", checkers::Req},
{"a18-5-3", checkers::Req},
{"a18-5-4", checkers::Req},
{"a18-5-5", checkers::Req},
{"a18-5-6", checkers::Req},
{"a18-5-7", checkers::Req},
{"a18-5-8", checkers::Req},
{"a18-5-9", checkers::Req},
{"a18-5-10", checkers::Req},
{"a18-5-11", checkers::Req},
{"m18-7-1", checkers::Req},
{"a18-9-1", checkers::Req},
{"a18-9-2", checkers::Req},
{"a18-9-3", checkers::Req},
{"a18-9-4", checkers::Req},
{"m19-3-1", checkers::Req},
{"a20-8-1", checkers::Req},
{"a20-8-2", checkers::Req},
{"a20-8-3", checkers::Req},
{"a20-8-4", checkers::Req},
{"a20-8-5", checkers::Req},
{"a20-8-6", checkers::Req},
{"a20-8-7", checkers::Req},
{"a21-8-1", checkers::Req},
{"a23-0-1", checkers::Req},
{"a23-0-2", checkers::Req},
{"a25-1-1", checkers::Req},
{"a25-4-1", checkers::Req},
{"a26-5-1", checkers::Req},
{"a26-5-2", checkers::Req},
{"m27-0-1", checkers::Req},
{"a27-0-1", checkers::Req},
{"a27-0-4", checkers::Req},
{"a27-0-2", checkers::Adv},
{"a27-0-3", checkers::Req},
};
std::vector<checkers::Info> checkers::certCInfo{
{"PRE30-C", "L3"},
{"PRE31-C", "L3"},
{"PRE32-C", "L3"},
{"DCL30-C", "L2"},
{"DCL31-C", "L3"},
{"DCL36-C", "L2"},
{"DCL37-C", "L3"},
{"DCL38-C", "L3"},
{"DCL39-C", "L3"},
{"DCL40-C", "L3"},
{"DCL41-C", "L3"},
{"EXP30-C", "L2"},
{"EXP32-C", "L2"},
{"EXP33-C", "L1"},
{"EXP34-C", "L1"},
{"EXP35-C", "L3"},
{"EXP36-C", "L3"},
{"EXP37-C", "L3"},
{"EXP39-C", "L3"},
{"EXP40-C", "L3"},
{"EXP42-C", "L2"},
{"EXP43-C", "L3"},
{"EXP44-C", "L3"},
{"EXP45-C", "L2"},
{"EXP46-C", "L2"},
{"INT30-C", "L2"},
{"INT31-C", "L2"},
{"INT32-C", "L2"},
{"INT33-C", "L2"},
{"INT34-C", "L3"},
{"INT35-C", "L3"},
{"INT36-C", "L3"},
{"FLP30-C", "L2"},
{"FLP32-C", "L2"},
{"FLP34-C", "L3"},
{"FLP36-C", "L3"},
{"FLP37-C", "L3"},
{"ARR30-C", "L2"},
{"ARR32-C", "L2"},
{"ARR36-C", "L2"},
{"ARR37-C", "L2"},
{"ARR38-C", "L1"},
{"ARR39-C", "L2"},
{"STR30-C", "L2"},
{"STR31-C", "L1"},
{"STR32-C", "L1"},
{"STR34-C", "L2"},
{"STR37-C", "L3"},
{"STR38-C", "L1"},
{"MEM30-C", "L1"},
{"MEM31-C", "L2"},
{"MEM33-C", "L3"},
{"MEM34-C", "L1"},
{"MEM35-C", "L2"},
{"MEM36-C", "L3"},
{"FIO30-C", "L1"},
{"FIO32-C", "L3"},
{"FIO34-C", "L1"},
{"FIO37-C", "L1"},
{"FIO38-C", "L3"},
{"FIO39-C", "L2"},
{"FIO40-C", "L3"},
{"FIO41-C", "L3"},
{"FIO42-C", "L3"},
{"FIO44-C", "L3"},
{"FIO45-C", "L2"},
{"FIO46-C", "L3"},
{"FIO47-C", "L2"},
{"ENV30-C", "L3"},
{"ENV31-C", "L3"},
{"ENV32-C", "L1"},
{"ENV33-C", "L1"},
{"ENV34-C", "L3"},
{"SIG30-C", "L1"},
{"SIG31-C", "L2"},
{"SIG34-C", "L3"},
{"SIG35-C", "L3"},
{"ERR30-C", "L2"},
{"ERR32-C", "L3"},
{"ERR33-C", "L1"},
{"CON30-C", "L3"},
{"CON31-C", "L3"},
{"CON32-C", "L2"},
{"CON33-C", "L3"},
{"CON34-C", "L3"},
{"CON35-C", "L3"},
{"CON36-C", "L3"},
{"CON37-C", "L2"},
{"CON38-C", "L3"},
{"CON39-C", "L2"},
{"CON40-C", "L2"},
{"CON41-C", "L3"},
{"MSC30-C", "L2"},
{"MSC32-C", "L1"},
{"MSC33-C", "L1"},
{"MSC37-C", "L2"},
{"MSC38-C", "L3"},
{"MSC39-C", "L3"},
{"MSC40-C", "L3"},
};
std::vector<checkers::Info> checkers::certCppInfo{
{"DCL50-CPP", "L1"},
{"DCL51-CPP", "L3"},
{"DCL52-CPP", "L3"},
{"DCL53-CPP", "L3"},
{"DCL54-CPP", "L2"},
{"DCL55-CPP", "L3"},
{"DCL56-CPP", "L3"},
{"DCL57-CPP", "L3"},
{"DCL58-CPP", "L3"},
{"DCL59-CPP", "L3"},
{"DCL60-CPP", "L3"},
{"EXP50-CPP", "L2"},
{"EXP51-CPP", "L3"},
{"EXP52-CPP", "L3"},
{"EXP53-CPP", "L1"},
{"EXP54-CPP", "L2"},
{"EXP55-CPP", "L2"},
{"EXP56-CPP", "L3"},
{"EXP57-CPP", "L3"},
{"EXP58-CPP", "L3"},
{"EXP59-CPP", "L3"},
{"EXP60-CPP", "L1"},
{"EXP61-CPP", "L2"},
{"EXP62-CPP", "L2"},
{"EXP63-CPP", "L2"},
{"INT50-CPP", "L3"},
{"CTR50-CPP", "L2"},
{"CTR51-CPP", "L2"},
{"CTR52-CPP", "L1"},
{"CTR53-CPP", "L2"},
{"CTR54-CPP", "L2"},
{"CTR55-CPP", "L1"},
{"CTR56-CPP", "L2"},
{"CTR57-CPP", "L3"},
{"CTR58-CPP", "L3"},
{"STR50-CPP", "L1"},
{"STR51-CPP", "L1"},
{"STR52-CPP", "L2"},
{"STR53-CPP", "L2"},
{"MEM50-CPP", "L1"},
{"MEM51-CPP", "L1"},
{"MEM52-CPP", "L1"},
{"MEM53-CPP", "L1"},
{"MEM54-CPP", "L1"},
{"MEM55-CPP", "L1"},
{"MEM56-CPP", "L1"},
{"MEM57-CPP", "L2"},
{"FIO50-CPP", "L2"},
{"FIO51-CPP", "L3"},
{"ERR50-CPP", "L3"},
{"ERR51-CPP", "L3"},
{"ERR52-CPP", "L3"},
{"ERR53-CPP", "L3"},
{"ERR54-CPP", "L1"},
{"ERR55-CPP", "L2"},
{"ERR56-CPP", "L2"},
{"ERR57-CPP", "L3"},
{"ERR58-CPP", "L2"},
{"ERR59-CPP", "L1"},
{"ERR60-CPP", "L3"},
{"ERR61-CPP", "L3"},
{"ERR62-CPP", "L3"},
{"OOP50-CPP", "L3"},
{"OOP51-CPP", "L3"},
{"OOP52-CPP", "L2"},
{"OOP53-CPP", "L3"},
{"OOP54-CPP", "L3"},
{"OOP55-CPP", "L2"},
{"OOP56-CPP", "L3"},
{"OOP57-CPP", "L2"},
{"OOP58-CPP", "L2"},
{"CON50-CPP", "L3"},
{"CON51-CPP", "L2"},
{"CON52-CPP", "L2"},
{"CON53-CPP", "L3"},
{"CON54-CPP", "L3"},
{"CON55-CPP", "L3"},
{"CON56-CPP", "L3"},
{"MSC50-CPP", "L2"},
{"MSC51-CPP", "L1"},
{"MSC52-CPP", "L3"},
{"MSC53-CPP", "L2"},
{"MSC54-CPP", "L2"},
};
| null |
815 | cpp | cppcheck | smallvector.h | lib/smallvector.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef smallvectorH
#define smallvectorH
#include <cstddef>
static constexpr std::size_t DefaultSmallVectorSize = 3;
#ifdef HAVE_BOOST
#include <boost/container/small_vector.hpp>
template<typename T, std::size_t N = DefaultSmallVectorSize>
using SmallVector = boost::container::small_vector<T, N>;
#else
#include <utility>
#include <vector>
template<class T, std::size_t N>
struct TaggedAllocator : std::allocator<T>
{
template<class ... Ts>
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
TaggedAllocator(Ts&&... ts)
: std::allocator<T>(std::forward<Ts>(ts)...)
{}
template<class U>
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
TaggedAllocator(const TaggedAllocator<U, N> /*unused*/) {}
template<class U>
struct rebind
{
using other = TaggedAllocator<U, N>;
};
};
template<typename T, std::size_t N = DefaultSmallVectorSize>
class SmallVector : public std::vector<T, TaggedAllocator<T, N>>
{
public:
template<class ... Ts>
// NOLINTNEXTLINE(google-explicit-constructor)
SmallVector(Ts&&... ts)
: std::vector<T, TaggedAllocator<T, N>>(std::forward<Ts>(ts)...)
{
this->reserve(N);
}
};
#endif
#endif
| null |
816 | cpp | cppcheck | cppcheck.cpp | lib/cppcheck.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "cppcheck.h"
#include "addoninfo.h"
#include "analyzerinfo.h"
#include "check.h"
#include "checkunusedfunctions.h"
#include "clangimport.h"
#include "color.h"
#include "ctu.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "library.h"
#include "path.h"
#include "platform.h"
#include "preprocessor.h"
#include "standards.h"
#include "suppressions.h"
#include "timer.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include "version.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdint>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <ctime>
#include <exception> // IWYU pragma: keep
#include <fstream>
#include <iostream>
#include <map>
#include <new>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include <utility>
#include <vector>
#include "json.h"
#include <simplecpp.h>
#include "xml.h"
#ifdef HAVE_RULES
#ifdef _WIN32
#define PCRE_STATIC
#endif
#include <pcre.h>
#endif
class SymbolDatabase;
static constexpr char Version[] = CPPCHECK_VERSION_STRING;
static constexpr char ExtraVersion[] = "";
static constexpr char FILELIST[] = "cppcheck-addon-ctu-file-list";
static TimerResults s_timerResults;
// CWE ids used
static const CWE CWE398(398U); // Indicator of Poor Code Quality
class CppCheck::CppCheckLogger : public ErrorLogger
{
public:
CppCheckLogger(ErrorLogger& errorLogger, const Settings& settings, Suppressions& suppressions, bool useGlobalSuppressions)
: mErrorLogger(errorLogger)
, mSettings(settings)
, mSuppressions(suppressions)
, mUseGlobalSuppressions(useGlobalSuppressions)
{}
~CppCheckLogger() override
{
closePlist();
}
void setRemarkComments(std::vector<RemarkComment> remarkComments)
{
mRemarkComments = std::move(remarkComments);
}
void setLocationMacros(const Token* startTok, const std::vector<std::string>& files)
{
mLocationMacros.clear();
for (const Token* tok = startTok; tok; tok = tok->next()) {
if (!tok->getMacroName().empty())
mLocationMacros[Location(files[tok->fileIndex()], tok->linenr())].emplace(tok->getMacroName());
}
}
void resetExitCode()
{
mExitCode = 0;
}
void clear()
{
mErrorList.clear();
}
void openPlist(const std::string& filename, const std::vector<std::string>& files)
{
mPlistFile.open(filename);
mPlistFile << ErrorLogger::plistHeader(version(), files);
}
void closePlist()
{
if (mPlistFile.is_open()) {
mPlistFile << ErrorLogger::plistFooter();
mPlistFile.close();
}
}
unsigned int exitcode() const
{
return mExitCode;
}
void setAnalyzerInfo(AnalyzerInformation* info)
{
mAnalyzerInformation = info;
}
private:
/**
* @brief Errors and warnings are directed here.
*
* @param msg Errors messages are normally in format
* "[filepath:line number] Message", e.g.
* "[main.cpp:4] Uninitialized member variable"
*/
// TODO: part of this logic is duplicated in Executor::hasToLog()
void reportErr(const ErrorMessage &msg) override
{
if (msg.severity == Severity::internal) {
mErrorLogger.reportErr(msg);
return;
}
if (!mSettings.library.reportErrors(msg.file0))
return;
std::set<std::string> macroNames;
if (!msg.callStack.empty()) {
const std::string &file = msg.callStack.back().getfile(false);
int lineNumber = msg.callStack.back().line;
const auto it = mLocationMacros.find(Location(file, lineNumber));
if (it != mLocationMacros.cend())
macroNames = it->second;
}
// TODO: only convert if necessary
const auto errorMessage = SuppressionList::ErrorMessage::fromErrorMessage(msg, macroNames);
if (mSuppressions.nomsg.isSuppressed(errorMessage, mUseGlobalSuppressions)) {
// Safety: Report critical errors to ErrorLogger
if (mSettings.safety && ErrorLogger::isCriticalErrorId(msg.id)) {
mExitCode = 1;
if (mSuppressions.nomsg.isSuppressedExplicitly(errorMessage, mUseGlobalSuppressions)) {
// Report with internal severity to signal that there is this critical error but
// it is suppressed
ErrorMessage temp(msg);
temp.severity = Severity::internal;
mErrorLogger.reportErr(temp);
} else {
// Report critical error that is not explicitly suppressed
mErrorLogger.reportErr(msg);
}
}
return;
}
// TODO: there should be no need for the verbose and default messages here
std::string errmsg = msg.toString(mSettings.verbose);
if (errmsg.empty())
return;
// Alert only about unique errors.
// This makes sure the errors of a single check() call are unique.
// TODO: get rid of this? This is forwarded to another ErrorLogger which is also doing this
if (!mErrorList.emplace(std::move(errmsg)).second)
return;
if (mAnalyzerInformation)
mAnalyzerInformation->reportErr(msg);
if (!mSuppressions.nofail.isSuppressed(errorMessage) && !mSuppressions.nomsg.isSuppressed(errorMessage)) {
mExitCode = 1;
}
std::string remark;
if (!msg.callStack.empty()) {
for (const auto& r: mRemarkComments) {
if (r.file != msg.callStack.back().getfile(false))
continue;
if (r.lineNumber != msg.callStack.back().line)
continue;
remark = r.str;
break;
}
}
if (!remark.empty()) {
ErrorMessage msg2(msg);
msg2.remark = std::move(remark);
mErrorLogger.reportErr(msg2);
} else {
mErrorLogger.reportErr(msg);
}
// check if plistOutput should be populated and the current output file is open and the error is not suppressed
if (!mSettings.plistOutput.empty() && mPlistFile.is_open() && !mSuppressions.nomsg.isSuppressed(errorMessage)) {
// add error to plist output file
mPlistFile << ErrorLogger::plistData(msg);
}
}
/**
* @brief Information about progress is directed here.
*
* @param outmsg Message to show, e.g. "Checking main.cpp..."
*/
void reportOut(const std::string &outmsg, Color c = Color::Reset) override
{
mErrorLogger.reportOut(outmsg, c);
}
void reportProgress(const std::string &filename, const char stage[], const std::size_t value) override
{
mErrorLogger.reportProgress(filename, stage, value);
}
ErrorLogger &mErrorLogger;
const Settings& mSettings;
Suppressions& mSuppressions;
bool mUseGlobalSuppressions;
// TODO: store hashes instead of the full messages
std::unordered_set<std::string> mErrorList;
std::vector<RemarkComment> mRemarkComments;
using Location = std::pair<std::string, int>;
std::map<Location, std::set<std::string>> mLocationMacros; // What macros are used on a location?
std::ofstream mPlistFile;
unsigned int mExitCode{};
AnalyzerInformation* mAnalyzerInformation{};
};
// File deleter
namespace {
class FilesDeleter {
public:
FilesDeleter() = default;
~FilesDeleter() {
for (const std::string& fileName: mFilenames)
std::remove(fileName.c_str());
}
void addFile(const std::string& fileName) {
mFilenames.push_back(fileName);
}
private:
std::vector<std::string> mFilenames;
};
}
static std::string cmdFileName(std::string f)
{
f = Path::toNativeSeparators(std::move(f));
if (f.find(' ') != std::string::npos)
return "\"" + f + "\"";
return f;
}
static std::vector<std::string> split(const std::string &str, const std::string &sep=" ")
{
std::vector<std::string> ret;
for (std::string::size_type startPos = 0U; startPos < str.size();) {
startPos = str.find_first_not_of(sep, startPos);
if (startPos == std::string::npos)
break;
if (str[startPos] == '\"') {
const std::string::size_type endPos = str.find('\"', startPos + 1);
ret.push_back(str.substr(startPos + 1, endPos - startPos - 1));
startPos = (endPos < str.size()) ? (endPos + 1) : endPos;
continue;
}
const std::string::size_type endPos = str.find(sep, startPos + 1);
ret.push_back(str.substr(startPos, endPos - startPos));
startPos = endPos;
}
return ret;
}
static std::string getDumpFileName(const Settings& settings, const std::string& filename)
{
std::string extension;
if (settings.dump || !settings.buildDir.empty())
extension = ".dump";
else
extension = "." + std::to_string(settings.pid) + ".dump";
if (!settings.dump && !settings.buildDir.empty())
return AnalyzerInformation::getAnalyzerInfoFile(settings.buildDir, filename, emptyString) + extension;
return filename + extension;
}
static std::string getCtuInfoFileName(const std::string &dumpFile)
{
return dumpFile.substr(0, dumpFile.size()-4) + "ctu-info";
}
static void createDumpFile(const Settings& settings,
const FileWithDetails& file,
std::ofstream& fdump,
std::string& dumpFile)
{
if (!settings.dump && settings.addons.empty())
return;
dumpFile = getDumpFileName(settings, file.spath());
fdump.open(dumpFile);
if (!fdump.is_open())
return;
if (!settings.buildDir.empty()) {
std::ofstream fout(getCtuInfoFileName(dumpFile));
}
// TODO: enforcedLang should be already applied in FileWithDetails object
std::string language;
switch (settings.enforcedLang) {
case Standards::Language::C:
language = " language=\"c\"";
break;
case Standards::Language::CPP:
language = " language=\"cpp\"";
break;
case Standards::Language::None:
{
// TODO: get language from FileWithDetails object
// TODO: error out on unknown language?
const Standards::Language lang = Path::identify(file.spath(), settings.cppHeaderProbe);
if (lang == Standards::Language::CPP)
language = " language=\"cpp\"";
else if (lang == Standards::Language::C)
language = " language=\"c\"";
break;
}
}
fdump << "<?xml version=\"1.0\"?>\n";
fdump << "<dumps" << language << ">\n";
fdump << " <platform"
<< " name=\"" << settings.platform.toString() << '\"'
<< " char_bit=\"" << settings.platform.char_bit << '\"'
<< " short_bit=\"" << settings.platform.short_bit << '\"'
<< " int_bit=\"" << settings.platform.int_bit << '\"'
<< " long_bit=\"" << settings.platform.long_bit << '\"'
<< " long_long_bit=\"" << settings.platform.long_long_bit << '\"'
<< " pointer_bit=\"" << (settings.platform.sizeof_pointer * settings.platform.char_bit) << '\"'
<< " wchar_t_bit=\"" << (settings.platform.sizeof_wchar_t * settings.platform.char_bit) << '\"'
<< " size_t_bit=\"" << (settings.platform.sizeof_size_t * settings.platform.char_bit) << '\"'
<< "/>" << '\n';
}
static std::string detectPython(const CppCheck::ExecuteCmdFn &executeCommand)
{
#ifdef _WIN32
const char *py_exes[] = { "python3.exe", "python.exe" };
#else
const char *py_exes[] = { "python3", "python" };
#endif
for (const char* py_exe : py_exes) {
std::string out;
#ifdef _MSC_VER
// FIXME: hack to avoid debug assertion with _popen() in executeCommand() for non-existing commands
const std::string cmd = std::string(py_exe) + " --version >NUL 2>&1";
if (system(cmd.c_str()) != 0) {
// TODO: get more detailed error?
continue;
}
#endif
if (executeCommand(py_exe, split("--version"), "2>&1", out) == EXIT_SUCCESS && startsWith(out, "Python ") && std::isdigit(out[7])) {
return py_exe;
}
}
return "";
}
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)
{
const std::string redirect = "2>&1";
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
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), redirect, result)) {
std::string message("Failed to execute addon '" + addonInfo.name + "' - exitcode is " + std::to_string(exitcode));
std::string details = pythonExe + " " + args;
if (result.size() > 2) {
details += "\nOutput:\n";
details += result;
const auto pos = details.find_last_not_of("\n\r");
if (pos != std::string::npos)
details.resize(pos + 1);
}
throw InternalError(nullptr, std::move(message), std::move(details));
}
std::vector<picojson::value> addonResult;
// Validate output..
std::istringstream istr(result);
std::string line;
while (std::getline(istr, line)) {
// TODO: also bail out?
if (line.empty()) {
//std::cout << "addon '" << addonInfo.name << "' 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;
continue;
}
if (line[0] != '{') {
//std::cout << "addon '" << addonInfo.name << "' 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);
}
//std::cout << "addon '" << addonInfo.name << "' 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;
continue;
}
if (!res.is<picojson::object>()) {
//std::cout << "addon '" << addonInfo.name << "' result is not a JSON object" << std::endl;
continue;
}
addonResult.emplace_back(std::move(res));
}
// Valid results
return addonResult;
}
static std::string getDefinesFlags(const std::string &semicolonSeparatedString)
{
std::string flags;
for (const std::string &d: split(semicolonSeparatedString, ";"))
flags += "-D" + d + " ";
return flags;
}
CppCheck::CppCheck(ErrorLogger &errorLogger,
bool useGlobalSuppressions,
ExecuteCmdFn executeCommand)
: mLogger(new CppCheckLogger(errorLogger, mSettings, mSettings.supprs, useGlobalSuppressions))
, mErrorLogger(*mLogger)
, mErrorLoggerDirect(errorLogger)
, mUseGlobalSuppressions(useGlobalSuppressions)
, mExecuteCommand(std::move(executeCommand))
{}
CppCheck::~CppCheck()
{
mLogger->setAnalyzerInfo(nullptr);
while (!mFileInfo.empty()) {
delete mFileInfo.back();
mFileInfo.pop_back();
}
}
const char * CppCheck::version()
{
return Version;
}
const char * CppCheck::extraVersion()
{
return ExtraVersion;
}
static bool reportClangErrors(std::istream &is, const std::function<void(const ErrorMessage&)>& reportErr, std::vector<ErrorMessage> &warnings)
{
std::string line;
while (std::getline(is, line)) {
if (line.empty() || line[0] == ' ' || line[0] == '`' || line[0] == '-')
continue;
std::string::size_type pos3 = line.find(": error: ");
if (pos3 == std::string::npos)
pos3 = line.find(": fatal error:");
if (pos3 == std::string::npos)
pos3 = line.find(": warning:");
if (pos3 == std::string::npos)
continue;
// file:line:column: error: ....
const std::string::size_type pos2 = line.rfind(':', pos3 - 1);
const std::string::size_type pos1 = line.rfind(':', pos2 - 1);
if (pos1 >= pos2 || pos2 >= pos3)
continue;
const std::string filename = line.substr(0, pos1);
const std::string linenr = line.substr(pos1+1, pos2-pos1-1);
const std::string colnr = line.substr(pos2+1, pos3-pos2-1);
const std::string msg = line.substr(line.find(':', pos3+1) + 2);
const std::string locFile = Path::toNativeSeparators(filename);
const int line_i = strToInt<int>(linenr);
const int column = strToInt<unsigned int>(colnr);
ErrorMessage::FileLocation loc(locFile, line_i, column);
ErrorMessage errmsg({std::move(loc)},
locFile,
Severity::error,
msg,
"syntaxError",
Certainty::normal);
if (line.compare(pos3, 10, ": warning:") == 0) {
warnings.push_back(std::move(errmsg));
continue;
}
reportErr(errmsg);
return true;
}
return false;
}
std::string CppCheck::getLibraryDumpData() const {
std::string out;
for (const std::string &s : mSettings.libraries) {
out += " <library lib=\"" + s + "\"/>\n";
}
return out;
}
std::string CppCheck::getClangFlags(Standards::Language fileLang) const {
std::string flags;
const Standards::Language lang = mSettings.enforcedLang != Standards::None ? mSettings.enforcedLang : fileLang;
switch (lang) {
case Standards::Language::None:
case Standards::Language::C:
flags = "-x c ";
if (!mSettings.standards.stdValueC.empty())
flags += "-std=" + mSettings.standards.stdValueC + " ";
break;
case Standards::Language::CPP:
flags += "-x c++ ";
if (!mSettings.standards.stdValueCPP.empty())
flags += "-std=" + mSettings.standards.stdValueCPP + " ";
break;
}
for (const std::string &i: mSettings.includePaths)
flags += "-I" + i + " ";
flags += getDefinesFlags(mSettings.userDefines);
for (const std::string &i: mSettings.userIncludes)
flags += "--include " + cmdFileName(i) + " ";
return flags;
}
// TODO: clear error list before returning
unsigned int CppCheck::checkClang(const FileWithDetails &file)
{
// TODO: clear exitcode
if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck)
mUnusedFunctionsCheck.reset(new CheckUnusedFunctions());
if (!mSettings.quiet)
mErrorLogger.reportOut(std::string("Checking ") + file.spath() + " ...", Color::FgGreen);
// TODO: get language from FileWithDetails object
const std::string analyzerInfo = mSettings.buildDir.empty() ? std::string() : AnalyzerInformation::getAnalyzerInfoFile(mSettings.buildDir, file.spath(), emptyString);
const std::string clangcmd = analyzerInfo + ".clang-cmd";
const std::string clangStderr = analyzerInfo + ".clang-stderr";
const std::string clangAst = analyzerInfo + ".clang-ast";
std::string exe = mSettings.clangExecutable;
#ifdef _WIN32
// append .exe if it is not a path
if (Path::fromNativeSeparators(mSettings.clangExecutable).find('/') == std::string::npos) {
exe += ".exe";
}
#endif
const std::string args2 = "-fsyntax-only -Xclang -ast-dump -fno-color-diagnostics " +
getClangFlags(Path::identify(file.spath(), mSettings.cppHeaderProbe)) +
file.spath();
const std::string redirect2 = analyzerInfo.empty() ? std::string("2>&1") : ("2> " + clangStderr);
if (!mSettings.buildDir.empty()) {
std::ofstream fout(clangcmd);
fout << exe << " " << args2 << " " << redirect2 << std::endl;
}
if (mSettings.verbose && !mSettings.quiet) {
mErrorLogger.reportOut(exe + " " + args2);
}
std::string output2;
const int exitcode = mExecuteCommand(exe,split(args2),redirect2,output2);
if (exitcode != EXIT_SUCCESS) {
// TODO: report as proper error
std::cerr << "Failed to execute '" << exe << " " << args2 << " " << redirect2 << "' - (exitcode: " << exitcode << " / output: " << output2 << ")" << std::endl;
return 0; // TODO: report as failure?
}
if (output2.find("TranslationUnitDecl") == std::string::npos) {
// TODO: report as proper error
std::cerr << "Failed to execute '" << exe << " " << args2 << " " << redirect2 << "' - (no TranslationUnitDecl in output)" << std::endl;
return 0; // TODO: report as failure?
}
// Ensure there are not syntax errors...
std::vector<ErrorMessage> compilerWarnings;
if (!mSettings.buildDir.empty()) {
std::ifstream fin(clangStderr);
auto reportError = [this](const ErrorMessage& errorMessage) {
mErrorLogger.reportErr(errorMessage);
};
if (reportClangErrors(fin, reportError, compilerWarnings))
return 0; // TODO: report as failure?
} else {
std::istringstream istr(output2);
auto reportError = [this](const ErrorMessage& errorMessage) {
mErrorLogger.reportErr(errorMessage);
};
if (reportClangErrors(istr, reportError, compilerWarnings))
return 0; // TODO: report as failure?
}
if (!mSettings.buildDir.empty()) {
std::ofstream fout(clangAst);
fout << output2 << std::endl;
}
try {
Tokenizer tokenizer(mSettings, mErrorLogger);
tokenizer.list.appendFileIfNew(file.spath());
std::istringstream ast(output2);
clangimport::parseClangAstDump(tokenizer, ast);
ValueFlow::setValues(tokenizer.list,
const_cast<SymbolDatabase&>(*tokenizer.getSymbolDatabase()),
mErrorLogger,
mSettings,
&s_timerResults);
if (mSettings.debugnormal)
tokenizer.printDebugOutput(1, std::cout);
checkNormalTokens(tokenizer, nullptr); // TODO: provide analyzer information
// create dumpfile
std::ofstream fdump;
std::string dumpFile;
createDumpFile(mSettings, file, fdump, dumpFile);
if (fdump.is_open()) {
// TODO: use tinyxml2 to create XML
fdump << "<dump cfg=\"\">\n";
for (const ErrorMessage& errmsg: compilerWarnings)
fdump << " <clang-warning file=\"" << ErrorLogger::toxml(errmsg.callStack.front().getfile()) << "\" line=\"" << errmsg.callStack.front().line << "\" column=\"" << errmsg.callStack.front().column << "\" message=\"" << ErrorLogger::toxml(errmsg.shortMessage()) << "\"/>\n";
fdump << " <standards>\n";
fdump << " <c version=\"" << mSettings.standards.getC() << "\"/>\n";
fdump << " <cpp version=\"" << mSettings.standards.getCPP() << "\"/>\n";
fdump << " </standards>\n";
fdump << getLibraryDumpData();
tokenizer.dump(fdump);
fdump << "</dump>\n";
fdump << "</dumps>\n";
fdump.close();
}
// run addons
executeAddons(dumpFile, file);
} catch (const InternalError &e) {
const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, file.spath(), "Bailing out from analysis: Processing Clang AST dump failed");
mErrorLogger.reportErr(errmsg);
} catch (const TerminateException &) {
// Analysis is terminated
} catch (const std::exception &e) {
internalError(file.spath(), std::string("Processing Clang AST dump failed: ") + e.what());
}
return mLogger->exitcode();
}
unsigned int CppCheck::check(const FileWithDetails &file)
{
if (mSettings.clang)
return checkClang(file);
return checkFile(file, emptyString);
}
unsigned int CppCheck::check(const FileWithDetails &file, const std::string &content)
{
std::istringstream iss(content);
return checkFile(file, emptyString, &iss);
}
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());
// need to pass the externally provided ErrorLogger instead of our internal wrapper
CppCheck temp(mErrorLoggerDirect, mUseGlobalSuppressions, mExecuteCommand);
temp.mSettings = mSettings;
if (!temp.mSettings.userDefines.empty())
temp.mSettings.userDefines += ';';
if (mSettings.clang)
temp.mSettings.userDefines += fs.defines;
else
temp.mSettings.userDefines += fs.cppcheckDefines();
temp.mSettings.includePaths = fs.includePaths;
temp.mSettings.userUndefs.insert(fs.undefs.cbegin(), fs.undefs.cend());
if (fs.standard.find("++") != std::string::npos)
temp.mSettings.standards.setCPP(fs.standard);
else if (!fs.standard.empty())
temp.mSettings.standards.setC(fs.standard);
if (fs.platformType != Platform::Type::Unspecified)
temp.mSettings.platform.set(fs.platformType);
if (mSettings.clang) {
temp.mSettings.includePaths.insert(temp.mSettings.includePaths.end(), fs.systemIncludePaths.cbegin(), fs.systemIncludePaths.cend());
// TODO: propagate back suppressions
// TODO: propagate back mFileInfo
const unsigned int returnValue = temp.check(fs.file);
if (mUnusedFunctionsCheck)
mUnusedFunctionsCheck->updateFunctionData(*temp.mUnusedFunctionsCheck);
return returnValue;
}
const unsigned int returnValue = temp.checkFile(fs.file, fs.cfg);
mSettings.supprs.nomsg.addSuppressions(temp.mSettings.supprs.nomsg.getSuppressions());
if (mUnusedFunctionsCheck)
mUnusedFunctionsCheck->updateFunctionData(*temp.mUnusedFunctionsCheck);
while (!temp.mFileInfo.empty()) {
mFileInfo.push_back(temp.mFileInfo.back());
temp.mFileInfo.pop_back();
}
// TODO: propagate back more data?
return returnValue;
}
static simplecpp::TokenList createTokenList(const std::string& filename, std::vector<std::string>& files, simplecpp::OutputList* outputList, std::istream* fileStream)
{
if (fileStream)
return {*fileStream, files, filename, outputList};
return {filename, files, outputList};
}
static std::size_t calculateHash(const Preprocessor& preprocessor, const simplecpp::TokenList& tokens, const Settings& settings)
{
std::ostringstream toolinfo;
toolinfo << CPPCHECK_VERSION_STRING;
toolinfo << (settings.severity.isEnabled(Severity::warning) ? 'w' : ' ');
toolinfo << (settings.severity.isEnabled(Severity::style) ? 's' : ' ');
toolinfo << (settings.severity.isEnabled(Severity::performance) ? 'p' : ' ');
toolinfo << (settings.severity.isEnabled(Severity::portability) ? 'p' : ' ');
toolinfo << (settings.severity.isEnabled(Severity::information) ? 'i' : ' ');
toolinfo << settings.userDefines;
toolinfo << std::to_string(static_cast<std::uint8_t>(settings.checkLevel));
// TODO: do we need to add more options?
settings.supprs.nomsg.dump(toolinfo);
return preprocessor.calculateHash(tokens, toolinfo.str());
}
unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string &cfgname, std::istream* fileStream)
{
// TODO: move to constructor when CppCheck no longer owns the settings
if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck)
mUnusedFunctionsCheck.reset(new CheckUnusedFunctions());
mLogger->resetExitCode();
if (Settings::terminated())
return mLogger->exitcode();
const Timer fileTotalTimer(mSettings.showtime == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL, file.spath());
if (!mSettings.quiet) {
std::string fixedpath = Path::toNativeSeparators(file.spath());
mErrorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."), Color::FgGreen);
if (mSettings.verbose) {
mErrorLogger.reportOut("Defines:" + mSettings.userDefines);
std::string undefs;
for (const std::string& U : mSettings.userUndefs) {
if (!undefs.empty())
undefs += ';';
undefs += ' ' + U;
}
mErrorLogger.reportOut("Undefines:" + undefs);
std::string includePaths;
for (const std::string &I : mSettings.includePaths)
includePaths += " -I" + I;
mErrorLogger.reportOut("Includes:" + includePaths);
mErrorLogger.reportOut(std::string("Platform:") + mSettings.platform.toString());
}
}
mLogger->closePlist();
std::unique_ptr<AnalyzerInformation> analyzerInformation;
try {
if (mSettings.library.markupFile(file.spath())) {
// TODO: if an exception occurs in this block it will continue in an unexpected code path
if (!mSettings.buildDir.empty())
{
analyzerInformation.reset(new AnalyzerInformation);
mLogger->setAnalyzerInfo(analyzerInformation.get());
}
if (mUnusedFunctionsCheck && (mSettings.useSingleJob() || analyzerInformation)) {
std::size_t hash = 0;
// this is not a real source file - we just want to tokenize it. treat it as C anyways as the language needs to be determined.
Tokenizer tokenizer(mSettings, mErrorLogger);
// enforce the language since markup files are special and do not adhere to the enforced language
tokenizer.list.setLang(Standards::Language::C, true);
if (fileStream) {
std::vector<std::string> files{file.spath()};
simplecpp::TokenList tokens(*fileStream, files);
if (analyzerInformation) {
const Preprocessor preprocessor(mSettings, mErrorLogger);
hash = calculateHash(preprocessor, tokens, mSettings);
}
tokenizer.list.createTokens(std::move(tokens));
}
else {
std::vector<std::string> files{file.spath()};
simplecpp::TokenList tokens(file.spath(), files);
if (analyzerInformation) {
const Preprocessor preprocessor(mSettings, mErrorLogger);
hash = calculateHash(preprocessor, tokens, mSettings);
}
tokenizer.list.createTokens(std::move(tokens));
}
mUnusedFunctionsCheck->parseTokens(tokenizer, mSettings);
if (analyzerInformation) {
mLogger->setAnalyzerInfo(nullptr);
std::list<ErrorMessage> errors;
analyzerInformation->analyzeFile(mSettings.buildDir, file.spath(), cfgname, hash, errors);
analyzerInformation->setFileInfo("CheckUnusedFunctions", mUnusedFunctionsCheck->analyzerInfo());
analyzerInformation->close();
}
}
return EXIT_SUCCESS;
}
simplecpp::OutputList outputList;
std::vector<std::string> files;
simplecpp::TokenList tokens1 = createTokenList(file.spath(), files, &outputList, fileStream);
// If there is a syntax error, report it and stop
const auto output_it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output){
return Preprocessor::hasErrors(output);
});
if (output_it != outputList.cend()) {
const simplecpp::Output &output = *output_it;
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);
mErrorLogger.reportErr(errmsg);
return mLogger->exitcode();
}
Preprocessor preprocessor(mSettings, mErrorLogger);
if (!preprocessor.loadFiles(tokens1, files))
return mLogger->exitcode();
if (!mSettings.plistOutput.empty()) {
std::string filename2;
if (file.spath().find('/') != std::string::npos)
filename2 = file.spath().substr(file.spath().rfind('/') + 1);
else
filename2 = file.spath();
const std::size_t fileNameHash = std::hash<std::string> {}(file.spath());
filename2 = mSettings.plistOutput + filename2.substr(0, filename2.find('.')) + "_" + std::to_string(fileNameHash) + ".plist";
mLogger->openPlist(filename2, files);
}
std::string dumpProlog;
if (mSettings.dump || !mSettings.addons.empty()) {
dumpProlog += getDumpFileContentsRawTokens(files, tokens1);
}
// Parse comments and then remove them
mLogger->setRemarkComments(preprocessor.getRemarkComments(tokens1));
preprocessor.inlineSuppressions(tokens1, mSettings.supprs.nomsg);
if (mSettings.dump || !mSettings.addons.empty()) {
std::ostringstream oss;
mSettings.supprs.nomsg.dump(oss);
dumpProlog += oss.str();
}
preprocessor.removeComments(tokens1);
if (!mSettings.buildDir.empty()) {
analyzerInformation.reset(new AnalyzerInformation);
mLogger->setAnalyzerInfo(analyzerInformation.get());
}
if (analyzerInformation) {
// Calculate hash so it can be compared with old hash / future hashes
const std::size_t hash = calculateHash(preprocessor, tokens1, mSettings);
std::list<ErrorMessage> errors;
if (!analyzerInformation->analyzeFile(mSettings.buildDir, file.spath(), cfgname, hash, errors)) {
while (!errors.empty()) {
mErrorLogger.reportErr(errors.front());
errors.pop_front();
}
mLogger->setAnalyzerInfo(nullptr);
return mLogger->exitcode(); // known results => no need to reanalyze file
}
}
// Get directives
std::list<Directive> directives = preprocessor.createDirectives(tokens1);
preprocessor.simplifyPragmaAsm(tokens1);
Preprocessor::setPlatformInfo(tokens1, mSettings);
// Get configurations..
std::set<std::string> configurations;
if ((mSettings.checkAllConfigurations && mSettings.userDefines.empty()) || mSettings.force) {
Timer::run("Preprocessor::getConfigs", mSettings.showtime, &s_timerResults, [&]() {
configurations = preprocessor.getConfigs(tokens1);
});
} else {
configurations.insert(mSettings.userDefines);
}
if (mSettings.checkConfiguration) {
for (const std::string &config : configurations)
(void)preprocessor.getcode(tokens1, config, files, true);
if (analyzerInformation)
mLogger->setAnalyzerInfo(nullptr);
return 0;
}
#ifdef HAVE_RULES
// Run define rules on raw code
if (hasRule("define")) {
std::string code;
for (const Directive &dir : directives) {
if (startsWith(dir.str,"#define ") || startsWith(dir.str,"#include "))
code += "#line " + std::to_string(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n';
}
TokenList tokenlist(&mSettings);
std::istringstream istr2(code);
// TODO: asserts when file has unknown extension
tokenlist.createTokens(istr2, Path::identify(*files.begin(), false)); // TODO: check result?
executeRules("define", tokenlist);
}
#endif
if (!mSettings.force && configurations.size() > mSettings.maxConfigs) {
if (mSettings.severity.isEnabled(Severity::information)) {
tooManyConfigsError(Path::toNativeSeparators(file.spath()),configurations.size());
} else {
mTooManyConfigs = true;
}
}
FilesDeleter filesDeleter;
// write dump file xml prolog
std::ofstream fdump;
std::string dumpFile;
createDumpFile(mSettings, file, fdump, dumpFile);
if (fdump.is_open()) {
fdump << dumpProlog;
if (!mSettings.dump)
filesDeleter.addFile(dumpFile);
}
std::set<unsigned long long> hashes;
int checkCount = 0;
bool hasValidConfig = false;
std::list<std::string> configurationError;
for (const std::string &currCfg : configurations) {
// bail out if terminated
if (Settings::terminated())
break;
// Check only a few configurations (default 12), after that bail out, unless --force
// was used.
if (!mSettings.force && ++checkCount > mSettings.maxConfigs)
break;
if (!mSettings.userDefines.empty()) {
mCurrentConfig = mSettings.userDefines;
const std::vector<std::string> v1(split(mSettings.userDefines, ";"));
for (const std::string &cfg: split(currCfg, ";")) {
if (std::find(v1.cbegin(), v1.cend(), cfg) == v1.cend()) {
mCurrentConfig += ";" + cfg;
}
}
} else {
mCurrentConfig = currCfg;
}
if (mSettings.preprocessOnly) {
std::string codeWithoutCfg;
Timer::run("Preprocessor::getcode", mSettings.showtime, &s_timerResults, [&]() {
codeWithoutCfg = preprocessor.getcode(tokens1, mCurrentConfig, files, true);
});
if (startsWith(codeWithoutCfg,"#file"))
codeWithoutCfg.insert(0U, "//");
std::string::size_type pos = 0;
while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos)
codeWithoutCfg.insert(pos+1U, "//");
pos = 0;
while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos)
codeWithoutCfg.insert(pos+1U, "//");
pos = 0;
while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos)
codeWithoutCfg[pos] = ' ';
mErrorLogger.reportOut(codeWithoutCfg);
continue;
}
Tokenizer tokenizer(mSettings, mErrorLogger);
if (mSettings.showtime != SHOWTIME_MODES::SHOWTIME_NONE)
tokenizer.setTimerResults(&s_timerResults);
tokenizer.setDirectives(directives); // TODO: how to avoid repeated copies?
try {
// Create tokens, skip rest of iteration if failed
Timer::run("Tokenizer::createTokens", mSettings.showtime, &s_timerResults, [&]() {
simplecpp::TokenList tokensP = preprocessor.preprocess(tokens1, mCurrentConfig, files, true);
tokenizer.list.createTokens(std::move(tokensP));
});
hasValidConfig = true;
// locations macros
mLogger->setLocationMacros(tokenizer.tokens(), files);
// If only errors are printed, print filename after the check
if (!mSettings.quiet && (!mCurrentConfig.empty() || checkCount > 1)) {
std::string fixedpath = Path::toNativeSeparators(file.spath());
mErrorLogger.reportOut("Checking " + fixedpath + ": " + mCurrentConfig + "...", Color::FgGreen);
}
if (!tokenizer.tokens())
continue;
// skip rest of iteration if just checking configuration
if (mSettings.checkConfiguration)
continue;
#ifdef HAVE_RULES
// Execute rules for "raw" code
executeRules("raw", tokenizer.list);
#endif
// Simplify tokens into normal form, skip rest of iteration if failed
if (!tokenizer.simplifyTokens1(mCurrentConfig))
continue;
// dump xml if --dump
if ((mSettings.dump || !mSettings.addons.empty()) && fdump.is_open()) {
fdump << "<dump cfg=\"" << ErrorLogger::toxml(mCurrentConfig) << "\">" << std::endl;
fdump << " <standards>" << std::endl;
fdump << " <c version=\"" << mSettings.standards.getC() << "\"/>" << std::endl;
fdump << " <cpp version=\"" << mSettings.standards.getCPP() << "\"/>" << std::endl;
fdump << " </standards>" << std::endl;
fdump << getLibraryDumpData();
preprocessor.dump(fdump);
tokenizer.dump(fdump);
fdump << "</dump>" << std::endl;
}
// Need to call this even if the hash will skip this configuration
mSettings.supprs.nomsg.markUnmatchedInlineSuppressionsAsChecked(tokenizer);
// Skip if we already met the same simplified token list
if (mSettings.force || mSettings.maxConfigs > 1) {
const std::size_t hash = tokenizer.list.calculateHash();
if (hashes.find(hash) != hashes.end()) {
if (mSettings.debugwarnings)
purgedConfigurationMessage(file.spath(), mCurrentConfig);
continue;
}
hashes.insert(hash);
}
// Check normal tokens
checkNormalTokens(tokenizer, analyzerInformation.get());
} catch (const simplecpp::Output &o) {
// #error etc during preprocessing
configurationError.push_back((mCurrentConfig.empty() ? "\'\'" : mCurrentConfig) + " : [" + o.location.file() + ':' + std::to_string(o.location.line) + "] " + o.msg);
--checkCount; // don't count invalid configurations
if (!hasValidConfig && currCfg == *configurations.rbegin()) {
// If there is no valid configuration then report error..
std::string locfile = Path::fromNativeSeparators(o.location.file());
if (mSettings.relativePaths)
locfile = Path::getRelativePath(locfile, mSettings.basePaths);
ErrorMessage::FileLocation loc1(locfile, o.location.line, o.location.col);
ErrorMessage errmsg({std::move(loc1)},
file.spath(),
Severity::error,
o.msg,
"preprocessorErrorDirective",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
continue;
} catch (const TerminateException &) {
// Analysis is terminated
if (analyzerInformation)
mLogger->setAnalyzerInfo(nullptr);
return mLogger->exitcode();
} catch (const InternalError &e) {
ErrorMessage errmsg = ErrorMessage::fromInternalError(e, &tokenizer.list, file.spath());
mErrorLogger.reportErr(errmsg);
}
}
if (!hasValidConfig && configurations.size() > 1 && mSettings.severity.isEnabled(Severity::information)) {
std::string msg;
msg = "This file is not analyzed. Cppcheck failed to extract a valid configuration. Use -v for more details.";
msg += "\nThis file is not analyzed. Cppcheck failed to extract a valid configuration. The tested configurations have these preprocessor errors:";
for (const std::string &s : configurationError)
msg += '\n' + s;
const std::string locFile = Path::toNativeSeparators(file.spath());
ErrorMessage::FileLocation loc(locFile, 0, 0);
ErrorMessage errmsg({std::move(loc)},
locFile,
Severity::information,
msg,
"noValidConfiguration",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
// TODO: will not be closed if we encountered an exception
// dumped all configs, close root </dumps> element now
if (fdump.is_open()) {
fdump << "</dumps>" << std::endl;
fdump.close();
}
executeAddons(dumpFile, file);
} catch (const TerminateException &) {
// Analysis is terminated
if (analyzerInformation)
mLogger->setAnalyzerInfo(nullptr);
return mLogger->exitcode();
} catch (const std::runtime_error &e) {
internalError(file.spath(), std::string("Checking file failed: ") + e.what());
} catch (const std::bad_alloc &) {
internalError(file.spath(), "Checking file failed: out of memory");
} catch (const InternalError &e) {
const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, file.spath(), "Bailing out from analysis: Checking file failed");
mErrorLogger.reportErr(errmsg);
}
if (analyzerInformation) {
mLogger->setAnalyzerInfo(nullptr);
analyzerInformation.reset();
}
// In jointSuppressionReport mode, unmatched suppressions are
// collected after all files are processed
if (!mSettings.useSingleJob() && (mSettings.severity.isEnabled(Severity::information) || mSettings.checkConfiguration)) {
SuppressionList::reportUnmatchedSuppressions(mSettings.supprs.nomsg.getUnmatchedLocalSuppressions(file, (bool)mUnusedFunctionsCheck), mErrorLogger);
}
// TODO: clear earlier?
mLogger->clear();
if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_FILE || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_FILE)
printTimerResults(mSettings.showtime);
return mLogger->exitcode();
}
// 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);
}
//---------------------------------------------------------------------------
// CppCheck - A function that checks a normal token list
//---------------------------------------------------------------------------
void CppCheck::checkNormalTokens(const Tokenizer &tokenizer, AnalyzerInformation* analyzerInformation)
{
CheckUnusedFunctions unusedFunctionsChecker;
// TODO: this should actually be the behavior if only "--enable=unusedFunction" is specified - see #10648
// TODO: log message when this is active?
const char* unusedFunctionOnly = std::getenv("UNUSEDFUNCTION_ONLY");
const bool doUnusedFunctionOnly = unusedFunctionOnly && (std::strcmp(unusedFunctionOnly, "1") == 0);
if (!doUnusedFunctionOnly) {
const std::time_t maxTime = mSettings.checksMaxTime > 0 ? std::time(nullptr) + mSettings.checksMaxTime : 0;
// call all "runChecks" in all registered Check classes
// cppcheck-suppress shadowFunction - TODO: fix this
for (Check *check : Check::instances()) {
if (Settings::terminated())
return;
if (maxTime > 0 && std::time(nullptr) > maxTime) {
if (mSettings.debugwarnings) {
ErrorMessage::FileLocation loc(tokenizer.list.getFiles()[0], 0, 0);
ErrorMessage errmsg({std::move(loc)},
emptyString,
Severity::debug,
"Checks maximum time exceeded",
"checksMaxTime",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
return;
}
Timer::run(check->name() + "::runChecks", mSettings.showtime, &s_timerResults, [&]() {
check->runChecks(tokenizer, &mErrorLogger);
});
}
}
if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mSettings.buildDir.empty()) {
unusedFunctionsChecker.parseTokens(tokenizer, mSettings);
}
if (mUnusedFunctionsCheck && mSettings.useSingleJob() && mSettings.buildDir.empty()) {
mUnusedFunctionsCheck->parseTokens(tokenizer, mSettings);
}
if (mSettings.clang) {
// TODO: Use CTU for Clang analysis
return;
}
if (mSettings.useSingleJob() || analyzerInformation) {
// Analyse the tokens..
{
CTU::FileInfo * const fi1 = CTU::getFileInfo(tokenizer);
if (analyzerInformation)
analyzerInformation->setFileInfo("ctu", fi1->toString());
if (mSettings.useSingleJob())
mFileInfo.push_back(fi1);
else
delete fi1;
}
if (!doUnusedFunctionOnly) {
// cppcheck-suppress shadowFunction - TODO: fix this
for (const Check *check : Check::instances()) {
if (Check::FileInfo * const fi = check->getFileInfo(tokenizer, mSettings)) {
if (analyzerInformation)
analyzerInformation->setFileInfo(check->name(), fi->toString());
if (mSettings.useSingleJob())
mFileInfo.push_back(fi);
else
delete fi;
}
}
}
}
if (mSettings.checks.isEnabled(Checks::unusedFunction) && analyzerInformation) {
analyzerInformation->setFileInfo("CheckUnusedFunctions", unusedFunctionsChecker.analyzerInfo());
}
#ifdef HAVE_RULES
executeRules("normal", tokenizer.list);
#endif
}
//---------------------------------------------------------------------------
#ifdef HAVE_RULES
bool CppCheck::hasRule(const std::string &tokenlist) const
{
return std::any_of(mSettings.rules.cbegin(), mSettings.rules.cend(), [&](const Settings::Rule& rule) {
return rule.tokenlist == tokenlist;
});
}
static const char * pcreErrorCodeToString(const int pcreExecRet)
{
switch (pcreExecRet) {
case PCRE_ERROR_NULL:
return "Either code or subject was passed as NULL, or ovector was NULL "
"and ovecsize was not zero (PCRE_ERROR_NULL)";
case PCRE_ERROR_BADOPTION:
return "An unrecognized bit was set in the options argument (PCRE_ERROR_BADOPTION)";
case PCRE_ERROR_BADMAGIC:
return "PCRE stores a 4-byte \"magic number\" at the start of the compiled code, "
"to catch the case when it is passed a junk pointer and to detect when a "
"pattern that was compiled in an environment of one endianness is run in "
"an environment with the other endianness. This is the error that PCRE "
"gives when the magic number is not present (PCRE_ERROR_BADMAGIC)";
case PCRE_ERROR_UNKNOWN_NODE:
return "While running the pattern match, an unknown item was encountered in the "
"compiled pattern. This error could be caused by a bug in PCRE or by "
"overwriting of the compiled pattern (PCRE_ERROR_UNKNOWN_NODE)";
case PCRE_ERROR_NOMEMORY:
return "If a pattern contains back references, but the ovector that is passed "
"to pcre_exec() is not big enough to remember the referenced substrings, "
"PCRE gets a block of memory at the start of matching to use for this purpose. "
"If the call via pcre_malloc() fails, this error is given. The memory is "
"automatically freed at the end of matching. This error is also given if "
"pcre_stack_malloc() fails in pcre_exec(). "
"This can happen only when PCRE has been compiled with "
"--disable-stack-for-recursion (PCRE_ERROR_NOMEMORY)";
case PCRE_ERROR_NOSUBSTRING:
return "This error is used by the pcre_copy_substring(), pcre_get_substring(), "
"and pcre_get_substring_list() functions (see below). "
"It is never returned by pcre_exec() (PCRE_ERROR_NOSUBSTRING)";
case PCRE_ERROR_MATCHLIMIT:
return "The backtracking limit, as specified by the match_limit field in a pcre_extra "
"structure (or defaulted) was reached. "
"See the description above (PCRE_ERROR_MATCHLIMIT)";
case PCRE_ERROR_CALLOUT:
return "This error is never generated by pcre_exec() itself. "
"It is provided for use by callout functions that want to yield a distinctive "
"error code. See the pcrecallout documentation for details (PCRE_ERROR_CALLOUT)";
case PCRE_ERROR_BADUTF8:
return "A string that contains an invalid UTF-8 byte sequence was passed as a subject, "
"and the PCRE_NO_UTF8_CHECK option was not set. If the size of the output vector "
"(ovecsize) is at least 2, the byte offset to the start of the the invalid UTF-8 "
"character is placed in the first element, and a reason code is placed in the "
"second element. The reason codes are listed in the following section. For "
"backward compatibility, if PCRE_PARTIAL_HARD is set and the problem is a truncated "
"UTF-8 character at the end of the subject (reason codes 1 to 5), "
"PCRE_ERROR_SHORTUTF8 is returned instead of PCRE_ERROR_BADUTF8";
case PCRE_ERROR_BADUTF8_OFFSET:
return "The UTF-8 byte sequence that was passed as a subject was checked and found to "
"be valid (the PCRE_NO_UTF8_CHECK option was not set), but the value of "
"startoffset did not point to the beginning of a UTF-8 character or the end of "
"the subject (PCRE_ERROR_BADUTF8_OFFSET)";
case PCRE_ERROR_PARTIAL:
return "The subject string did not match, but it did match partially. See the "
"pcrepartial documentation for details of partial matching (PCRE_ERROR_PARTIAL)";
case PCRE_ERROR_BADPARTIAL:
return "This code is no longer in use. It was formerly returned when the PCRE_PARTIAL "
"option was used with a compiled pattern containing items that were not supported "
"for partial matching. From release 8.00 onwards, there are no restrictions on "
"partial matching (PCRE_ERROR_BADPARTIAL)";
case PCRE_ERROR_INTERNAL:
return "An unexpected internal error has occurred. This error could be caused by a bug "
"in PCRE or by overwriting of the compiled pattern (PCRE_ERROR_INTERNAL)";
case PCRE_ERROR_BADCOUNT:
return "This error is given if the value of the ovecsize argument is negative "
"(PCRE_ERROR_BADCOUNT)";
case PCRE_ERROR_RECURSIONLIMIT:
return "The internal recursion limit, as specified by the match_limit_recursion "
"field in a pcre_extra structure (or defaulted) was reached. "
"See the description above (PCRE_ERROR_RECURSIONLIMIT)";
case PCRE_ERROR_DFA_UITEM:
return "PCRE_ERROR_DFA_UITEM";
case PCRE_ERROR_DFA_UCOND:
return "PCRE_ERROR_DFA_UCOND";
case PCRE_ERROR_DFA_WSSIZE:
return "PCRE_ERROR_DFA_WSSIZE";
case PCRE_ERROR_DFA_RECURSE:
return "PCRE_ERROR_DFA_RECURSE";
case PCRE_ERROR_NULLWSLIMIT:
return "PCRE_ERROR_NULLWSLIMIT";
case PCRE_ERROR_BADNEWLINE:
return "An invalid combination of PCRE_NEWLINE_xxx options was "
"given (PCRE_ERROR_BADNEWLINE)";
case PCRE_ERROR_BADOFFSET:
return "The value of startoffset was negative or greater than the length "
"of the subject, that is, the value in length (PCRE_ERROR_BADOFFSET)";
case PCRE_ERROR_SHORTUTF8:
return "This error is returned instead of PCRE_ERROR_BADUTF8 when the subject "
"string ends with a truncated UTF-8 character and the PCRE_PARTIAL_HARD option is set. "
"Information about the failure is returned as for PCRE_ERROR_BADUTF8. "
"It is in fact sufficient to detect this case, but this special error code for "
"PCRE_PARTIAL_HARD precedes the implementation of returned information; "
"it is retained for backwards compatibility (PCRE_ERROR_SHORTUTF8)";
case PCRE_ERROR_RECURSELOOP:
return "This error is returned when pcre_exec() detects a recursion loop "
"within the pattern. Specifically, it means that either the whole pattern "
"or a subpattern has been called recursively for the second time at the same "
"position in the subject string. Some simple patterns that might do this "
"are detected and faulted at compile time, but more complicated cases, "
"in particular mutual recursions between two different subpatterns, "
"cannot be detected until run time (PCRE_ERROR_RECURSELOOP)";
case PCRE_ERROR_JIT_STACKLIMIT:
return "This error is returned when a pattern that was successfully studied "
"using a JIT compile option is being matched, but the memory available "
"for the just-in-time processing stack is not large enough. See the pcrejit "
"documentation for more details (PCRE_ERROR_JIT_STACKLIMIT)";
case PCRE_ERROR_BADMODE:
return "This error is given if a pattern that was compiled by the 8-bit library "
"is passed to a 16-bit or 32-bit library function, or vice versa (PCRE_ERROR_BADMODE)";
case PCRE_ERROR_BADENDIANNESS:
return "This error is given if a pattern that was compiled and saved is reloaded on a "
"host with different endianness. The utility function pcre_pattern_to_host_byte_order() "
"can be used to convert such a pattern so that it runs on the new host (PCRE_ERROR_BADENDIANNESS)";
case PCRE_ERROR_DFA_BADRESTART:
return "PCRE_ERROR_DFA_BADRESTART";
#if PCRE_MAJOR >= 8 && PCRE_MINOR >= 32
case PCRE_ERROR_BADLENGTH:
return "This error is given if pcre_exec() is called with a negative value for the length argument (PCRE_ERROR_BADLENGTH)";
case PCRE_ERROR_JIT_BADOPTION:
return "This error is returned when a pattern that was successfully studied using a JIT compile "
"option is being matched, but the matching mode (partial or complete match) does not correspond "
"to any JIT compilation mode. When the JIT fast path function is used, this error may be "
"also given for invalid options. See the pcrejit documentation for more details (PCRE_ERROR_JIT_BADOPTION)";
#endif
}
return "";
}
void CppCheck::executeRules(const std::string &tokenlist, const TokenList &list)
{
// There is no rule to execute
if (!hasRule(tokenlist))
return;
// Write all tokens in a string that can be parsed by pcre
std::string str;
for (const Token *tok = list.front(); tok; tok = tok->next()) {
str += " ";
str += tok->str();
}
for (const Settings::Rule &rule : mSettings.rules) {
if (rule.tokenlist != tokenlist)
continue;
if (!mSettings.quiet) {
mErrorLogger.reportOut("Processing rule: " + rule.pattern, Color::FgGreen);
}
const char *pcreCompileErrorStr = nullptr;
int erroffset = 0;
pcre * const re = pcre_compile(rule.pattern.c_str(),0,&pcreCompileErrorStr,&erroffset,nullptr);
if (!re) {
if (pcreCompileErrorStr) {
const std::string msg = "pcre_compile failed: " + std::string(pcreCompileErrorStr);
const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(),
emptyString,
Severity::error,
msg,
"pcre_compile",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
continue;
}
// Optimize the regex, but only if PCRE_CONFIG_JIT is available
#ifdef PCRE_CONFIG_JIT
const char *pcreStudyErrorStr = nullptr;
pcre_extra * const pcreExtra = pcre_study(re, PCRE_STUDY_JIT_COMPILE, &pcreStudyErrorStr);
// pcre_study() returns NULL for both errors and when it can not optimize the regex.
// The last argument is how one checks for errors.
// It is NULL if everything works, and points to an error string otherwise.
if (pcreStudyErrorStr) {
const std::string msg = "pcre_study failed: " + std::string(pcreStudyErrorStr);
const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(),
emptyString,
Severity::error,
msg,
"pcre_study",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
// pcre_compile() worked, but pcre_study() returned an error. Free the resources allocated by pcre_compile().
pcre_free(re);
continue;
}
#else
const pcre_extra * const pcreExtra = nullptr;
#endif
int pos = 0;
int ovector[30]= {0};
while (pos < (int)str.size()) {
const int pcreExecRet = pcre_exec(re, pcreExtra, str.c_str(), (int)str.size(), pos, 0, ovector, 30);
if (pcreExecRet < 0) {
const std::string errorMessage = pcreErrorCodeToString(pcreExecRet);
if (!errorMessage.empty()) {
const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(),
emptyString,
Severity::error,
std::string("pcre_exec failed: ") + errorMessage,
"pcre_exec",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
break;
}
const auto pos1 = (unsigned int)ovector[0];
const auto pos2 = (unsigned int)ovector[1];
// jump to the end of the match for the next pcre_exec
pos = (int)pos2;
// determine location..
int fileIndex = 0;
int line = 0;
std::size_t len = 0;
for (const Token *tok = list.front(); tok; tok = tok->next()) {
len = len + 1U + tok->str().size();
if (len > pos1) {
fileIndex = tok->fileIndex();
line = tok->linenr();
break;
}
}
const std::string& file = list.getFiles()[fileIndex];
ErrorMessage::FileLocation loc(file, line, 0);
// Create error message
const ErrorMessage errmsg({std::move(loc)},
list.getSourceFilePath(),
rule.severity,
!rule.summary.empty() ? rule.summary : "found '" + str.substr(pos1, pos2 - pos1) + "'",
rule.id,
Certainty::normal);
// Report error
mErrorLogger.reportErr(errmsg);
}
pcre_free(re);
#ifdef PCRE_CONFIG_JIT
// Free up the EXTRA PCRE value (may be NULL at this point)
if (pcreExtra) {
pcre_free_study(pcreExtra);
}
#endif
}
}
#endif
void CppCheck::executeAddons(const std::string& dumpFile, const FileWithDetails& file)
{
if (!dumpFile.empty()) {
std::vector<std::string> f{dumpFile};
executeAddons(f, file.spath());
}
}
void CppCheck::executeAddons(const std::vector<std::string>& files, const std::string& file0)
{
if (mSettings.addons.empty() || files.empty())
return;
const bool isCtuInfo = endsWith(files[0], ".ctu-info");
FilesDeleter filesDeleter;
std::string fileList;
if (files.size() >= 2) {
fileList = Path::getPathFromFilename(files[0]) + FILELIST + ("-" + std::to_string(mSettings.pid)) + ".txt";
std::ofstream fout(fileList);
filesDeleter.addFile(fileList);
// TODO: check if file could be created
for (const std::string& f: files)
fout << f << std::endl;
}
// ensure all addons have already been resolved - TODO: remove when settings are const after creation
assert(mSettings.addonInfos.size() == mSettings.addons.size());
std::string ctuInfo;
for (const AddonInfo &addonInfo : mSettings.addonInfos) {
if (isCtuInfo && addonInfo.name != "misra" && !addonInfo.ctu)
continue;
const std::vector<picojson::value> results =
executeAddon(addonInfo, mSettings.addonPython, fileList.empty() ? files[0] : fileList, mSettings.premiumArgs, mExecuteCommand);
const bool misraC2023 = mSettings.premiumArgs.find("--misra-c-2023") != std::string::npos;
for (const picojson::value& res : results) {
// TODO: get rid of copy?
// this is a copy so we can access missing fields and get a default value
picojson::object obj = res.get<picojson::object>();
ErrorMessage errmsg;
if (obj.count("summary") > 0) {
if (!mSettings.buildDir.empty()) {
ctuInfo += res.serialize() + "\n";
} else {
errmsg.severity = Severity::internal;
errmsg.id = "ctuinfo";
errmsg.setmsg(res.serialize());
mErrorLogger.reportErr(errmsg);
}
continue;
}
if (obj.count("file") > 0) {
std::string fileName = obj["file"].get<std::string>();
const int64_t lineNumber = obj["linenr"].get<int64_t>();
const int64_t column = obj["column"].get<int64_t>();
errmsg.callStack.emplace_back(std::move(fileName), lineNumber, column);
} else if (obj.count("loc") > 0) {
for (const picojson::value &locvalue: obj["loc"].get<picojson::array>()) {
picojson::object loc = locvalue.get<picojson::object>();
std::string fileName = loc["file"].get<std::string>();
const int64_t lineNumber = loc["linenr"].get<int64_t>();
const int64_t column = loc["column"].get<int64_t>();
std::string info = loc["info"].get<std::string>();
errmsg.callStack.emplace_back(std::move(fileName), std::move(info), lineNumber, column);
}
}
errmsg.id = obj["addon"].get<std::string>() + "-" + obj["errorId"].get<std::string>();
if (misraC2023 && startsWith(errmsg.id, "misra-c2012-"))
errmsg.id = "misra-c2023-" + errmsg.id.substr(12);
errmsg.setmsg(mSettings.getMisraRuleText(errmsg.id, obj["message"].get<std::string>()));
const std::string severity = obj["severity"].get<std::string>();
errmsg.severity = severityFromString(severity);
if (errmsg.severity == Severity::none || errmsg.severity == Severity::internal) {
if (!endsWith(errmsg.id, "-logChecker"))
continue;
errmsg.severity = Severity::internal;
}
else if (!mSettings.severity.isEnabled(errmsg.severity)) {
// Do not filter out premium misra/cert/autosar messages that has been
// explicitly enabled with a --premium option
if (!isPremiumCodingStandardId(errmsg.id))
continue;
}
errmsg.file0 = file0;
mErrorLogger.reportErr(errmsg);
}
}
if (!mSettings.buildDir.empty() && !isCtuInfo) {
const std::string& ctuInfoFile = getCtuInfoFileName(files[0]);
std::ofstream fout(ctuInfoFile);
fout << ctuInfo;
}
}
void CppCheck::executeAddonsWholeProgram(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo)
{
if (mSettings.addons.empty())
return;
if (mSettings.buildDir.empty()) {
const std::string fileName = std::to_string(mSettings.pid) + ".ctu-info";
FilesDeleter filesDeleter;
filesDeleter.addFile(fileName);
std::ofstream fout(fileName);
fout << ctuInfo;
fout.close();
executeAddons({fileName}, "");
return;
}
std::vector<std::string> ctuInfoFiles;
for (const auto &f: files) {
const std::string &dumpFileName = getDumpFileName(mSettings, f.path());
ctuInfoFiles.push_back(getCtuInfoFileName(dumpFileName));
}
for (const auto &f: fileSettings) {
const std::string &dumpFileName = getDumpFileName(mSettings, f.filename());
ctuInfoFiles.push_back(getCtuInfoFileName(dumpFileName));
}
try {
executeAddons(ctuInfoFiles, "");
} catch (const InternalError& e) {
const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, "", "Bailing out from analysis: Whole program analysis failed");
mErrorLogger.reportErr(errmsg);
}
}
Settings &CppCheck::settings()
{
return mSettings;
}
void CppCheck::tooManyConfigsError(const std::string &file, const int numberOfConfigurations)
{
if (!mSettings.severity.isEnabled(Severity::information) && !mTooManyConfigs)
return;
mTooManyConfigs = false;
if (mSettings.severity.isEnabled(Severity::information) && file.empty())
return;
std::list<ErrorMessage::FileLocation> loclist;
if (!file.empty()) {
loclist.emplace_back(file, 0, 0);
}
std::ostringstream msg;
msg << "Too many #ifdef configurations - cppcheck only checks " << mSettings.maxConfigs;
if (numberOfConfigurations > mSettings.maxConfigs)
msg << " of " << numberOfConfigurations << " configurations. Use --force to check all configurations.\n";
if (file.empty())
msg << " configurations. Use --force to check all configurations. For more details, use --enable=information.\n";
msg << "The checking of the file will be interrupted because there are too many "
"#ifdef configurations. Checking of all #ifdef configurations can be forced "
"by --force command line option or from GUI preferences. However that may "
"increase the checking time.";
if (file.empty())
msg << " For more details, use --enable=information.";
ErrorMessage errmsg(std::move(loclist),
emptyString,
Severity::information,
msg.str(),
"toomanyconfigs", CWE398,
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
void CppCheck::purgedConfigurationMessage(const std::string &file, const std::string& configuration)
{
mTooManyConfigs = false;
if (mSettings.severity.isEnabled(Severity::information) && file.empty())
return;
std::list<ErrorMessage::FileLocation> loclist;
if (!file.empty()) {
loclist.emplace_back(file, 0, 0);
}
ErrorMessage errmsg(std::move(loclist),
emptyString,
Severity::information,
"The configuration '" + configuration + "' was not checked because its code equals another one.",
"purgedConfiguration",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
//---------------------------------------------------------------------------
void CppCheck::getErrorMessages(ErrorLogger &errorlogger)
{
Settings s;
s.addEnabled("all");
CppCheck cppcheck(errorlogger, true, nullptr);
cppcheck.purgedConfigurationMessage(emptyString,emptyString);
cppcheck.mTooManyConfigs = true;
cppcheck.tooManyConfigsError(emptyString,0U);
// TODO: add functions to get remaining error messages
// call all "getErrorMessages" in all registered Check classes
for (std::list<Check *>::const_iterator it = Check::instances().cbegin(); it != Check::instances().cend(); ++it)
(*it)->getErrorMessages(&errorlogger, &s);
CheckUnusedFunctions::getErrorMessages(errorlogger);
Preprocessor::getErrorMessages(errorlogger, s);
}
void CppCheck::analyseClangTidy(const FileSettings &fileSettings)
{
std::string allIncludes;
for (const std::string &inc : fileSettings.includePaths) {
allIncludes = allIncludes + "-I\"" + inc + "\" ";
}
const std::string allDefines = getDefinesFlags(fileSettings.defines);
#ifdef _WIN32
constexpr char exe[] = "clang-tidy.exe";
#else
constexpr char exe[] = "clang-tidy";
#endif
const std::string args = "-quiet -checks=*,-clang-analyzer-*,-llvm* \"" + fileSettings.filename() + "\" -- " + allIncludes + allDefines;
std::string output;
if (const int exitcode = mExecuteCommand(exe, split(args), emptyString, output)) {
std::cerr << "Failed to execute '" << exe << "' (exitcode: " << std::to_string(exitcode) << ")" << std::endl;
return;
}
// parse output and create error messages
std::istringstream istr(output);
std::string line;
if (!mSettings.buildDir.empty()) {
const std::string analyzerInfoFile = AnalyzerInformation::getAnalyzerInfoFile(mSettings.buildDir, fileSettings.filename(), emptyString);
std::ofstream fcmd(analyzerInfoFile + ".clang-tidy-cmd");
fcmd << istr.str();
}
while (std::getline(istr, line)) {
if (line.find("error") == std::string::npos && line.find("warning") == std::string::npos)
continue;
std::size_t endColumnPos = line.find(": error:");
if (endColumnPos == std::string::npos) {
endColumnPos = line.find(": warning:");
}
const std::size_t endLinePos = line.rfind(':', endColumnPos-1);
const std::size_t endNamePos = line.rfind(':', endLinePos - 1);
const std::size_t endMsgTypePos = line.find(':', endColumnPos + 2);
const std::size_t endErrorPos = line.rfind('[', std::string::npos);
if (endLinePos==std::string::npos || endNamePos==std::string::npos || endMsgTypePos==std::string::npos || endErrorPos==std::string::npos)
continue;
const std::string lineNumString = line.substr(endNamePos + 1, endLinePos - endNamePos - 1);
const std::string columnNumString = line.substr(endLinePos + 1, endColumnPos - endLinePos - 1);
const std::string messageString = line.substr(endMsgTypePos + 1, endErrorPos - endMsgTypePos - 1);
const std::string errorString = line.substr(endErrorPos, line.length());
std::string fixedpath = Path::simplifyPath(line.substr(0, endNamePos));
const auto lineNumber = strToInt<int64_t>(lineNumString);
const auto column = strToInt<int64_t>(columnNumString);
fixedpath = Path::toNativeSeparators(std::move(fixedpath));
ErrorMessage errmsg;
errmsg.callStack.emplace_back(fixedpath, lineNumber, column);
errmsg.id = "clang-tidy-" + errorString.substr(1, errorString.length() - 2);
if (errmsg.id.find("performance") != std::string::npos)
errmsg.severity = Severity::performance;
else if (errmsg.id.find("portability") != std::string::npos)
errmsg.severity = Severity::portability;
else if (errmsg.id.find("cert") != std::string::npos || errmsg.id.find("misc") != std::string::npos || errmsg.id.find("unused") != std::string::npos)
errmsg.severity = Severity::warning;
else
errmsg.severity = Severity::style;
errmsg.file0 = std::move(fixedpath);
errmsg.setmsg(messageString);
mErrorLogger.reportErr(errmsg);
}
}
bool CppCheck::analyseWholeProgram()
{
bool errors = false;
// Analyse the tokens
CTU::FileInfo ctu;
if (mSettings.useSingleJob() || !mSettings.buildDir.empty())
{
for (const Check::FileInfo *fi : mFileInfo) {
const auto *fi2 = dynamic_cast<const CTU::FileInfo *>(fi);
if (fi2) {
ctu.functionCalls.insert(ctu.functionCalls.end(), fi2->functionCalls.cbegin(), fi2->functionCalls.cend());
ctu.nestedCalls.insert(ctu.nestedCalls.end(), fi2->nestedCalls.cbegin(), fi2->nestedCalls.cend());
}
}
}
// cppcheck-suppress shadowFunction - TODO: fix this
for (Check *check : Check::instances())
errors |= check->analyseWholeProgram(&ctu, mFileInfo, mSettings, mErrorLogger); // TODO: ctu
if (mUnusedFunctionsCheck)
errors |= mUnusedFunctionsCheck->check(mSettings, mErrorLogger);
return errors && (mLogger->exitcode() > 0);
}
unsigned int CppCheck::analyseWholeProgram(const std::string &buildDir, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo)
{
executeAddonsWholeProgram(files, fileSettings, ctuInfo);
if (mSettings.checks.isEnabled(Checks::unusedFunction))
CheckUnusedFunctions::analyseWholeProgram(mSettings, mErrorLogger, buildDir);
std::list<Check::FileInfo*> fileInfoList;
CTU::FileInfo ctuFileInfo;
// Load all analyzer info data..
const std::string filesTxt(buildDir + "/files.txt");
std::ifstream fin(filesTxt);
std::string filesTxtLine;
while (std::getline(fin, filesTxtLine)) {
const std::string::size_type firstColon = filesTxtLine.find(':');
if (firstColon == std::string::npos)
continue;
const std::string::size_type lastColon = filesTxtLine.rfind(':');
if (firstColon == lastColon)
continue;
const std::string xmlfile = buildDir + '/' + filesTxtLine.substr(0,firstColon);
//const std::string sourcefile = filesTxtLine.substr(lastColon+1);
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str());
if (error != tinyxml2::XML_SUCCESS)
continue;
const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement();
if (rootNode == nullptr)
continue;
for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "FileInfo") != 0)
continue;
const char *checkClassAttr = e->Attribute("check");
if (!checkClassAttr)
continue;
if (std::strcmp(checkClassAttr, "ctu") == 0) {
ctuFileInfo.loadFromXml(e);
continue;
}
// cppcheck-suppress shadowFunction - TODO: fix this
for (const Check *check : Check::instances()) {
if (checkClassAttr == check->name())
fileInfoList.push_back(check->loadFileInfoFromXml(e));
}
}
}
// Analyse the tokens
// cppcheck-suppress shadowFunction - TODO: fix this
for (Check *check : Check::instances())
check->analyseWholeProgram(&ctuFileInfo, fileInfoList, mSettings, mErrorLogger);
if (mUnusedFunctionsCheck)
mUnusedFunctionsCheck->check(mSettings, mErrorLogger);
for (Check::FileInfo *fi : fileInfoList)
delete fi;
return mLogger->exitcode();
}
// cppcheck-suppress unusedFunction - only used in tests
void CppCheck::resetTimerResults()
{
s_timerResults.reset();
}
void CppCheck::printTimerResults(SHOWTIME_MODES mode)
{
s_timerResults.showResults(mode);
}
bool CppCheck::isPremiumCodingStandardId(const std::string& id) const {
if (mSettings.premiumArgs.find("--misra") != std::string::npos) {
if (startsWith(id, "misra-") || startsWith(id, "premium-misra-"))
return true;
}
if (mSettings.premiumArgs.find("--cert") != std::string::npos && startsWith(id, "premium-cert-"))
return true;
if (mSettings.premiumArgs.find("--autosar") != std::string::npos && startsWith(id, "premium-autosar-"))
return true;
return false;
}
std::string CppCheck::getDumpFileContentsRawTokens(const std::vector<std::string>& files, const simplecpp::TokenList& tokens1) const {
std::string dumpProlog;
dumpProlog += " <rawtokens>\n";
for (unsigned int i = 0; i < files.size(); ++i) {
dumpProlog += " <file index=\"";
dumpProlog += std::to_string(i);
dumpProlog += "\" name=\"";
dumpProlog += ErrorLogger::toxml(Path::getRelativePath(files[i], mSettings.basePaths));
dumpProlog += "\"/>\n";
}
for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) {
dumpProlog += " <tok ";
dumpProlog += "fileIndex=\"";
dumpProlog += std::to_string(tok->location.fileIndex);
dumpProlog += "\" ";
dumpProlog += "linenr=\"";
dumpProlog += std::to_string(tok->location.line);
dumpProlog += "\" ";
dumpProlog +="column=\"";
dumpProlog += std::to_string(tok->location.col);
dumpProlog += "\" ";
dumpProlog += "str=\"";
dumpProlog += ErrorLogger::toxml(tok->str());
dumpProlog += "\"";
dumpProlog += "/>\n";
}
dumpProlog += " </rawtokens>\n";
return dumpProlog;
}
| null |
817 | cpp | cppcheck | checkunusedvar.cpp | lib/checkunusedvar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkunusedvar.h"
#include "astutils.h"
#include "errortypes.h"
#include "fwdanalysis.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include "valueflow.h"
#include <algorithm>
#include <cstdint>
#include <list>
#include <set>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckUnusedVar instance;
}
static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable')
static const CWE CWE665(665U); // Improper Initialization
/** Is scope a raii class scope */
static bool isRaiiClassScope(const Scope *classScope)
{
return classScope && classScope->getDestructor() != nullptr;
}
/** Is ValueType a raii class? */
static bool isRaiiClass(const ValueType *valueType, bool cpp, bool defaultReturn = true)
{
if (!cpp)
return false;
if (!valueType)
return defaultReturn;
if ((valueType->smartPointerType && isRaiiClassScope(valueType->smartPointerType->classScope)) || (!valueType->smartPointerType && valueType->type == ValueType::Type::SMART_POINTER))
return true;
switch (valueType->type) {
case ValueType::Type::UNKNOWN_TYPE:
case ValueType::Type::NONSTD:
return defaultReturn;
case ValueType::Type::RECORD:
if (isRaiiClassScope(valueType->typeScope))
return true;
return defaultReturn;
case ValueType::Type::POD:
case ValueType::Type::SMART_POINTER:
case ValueType::Type::CONTAINER:
case ValueType::Type::ITERATOR:
case ValueType::Type::VOID:
case ValueType::Type::BOOL:
case ValueType::Type::CHAR:
case ValueType::Type::SHORT:
case ValueType::Type::WCHAR_T:
case ValueType::Type::INT:
case ValueType::Type::LONG:
case ValueType::Type::LONGLONG:
case ValueType::Type::UNKNOWN_INT:
case ValueType::Type::FLOAT:
case ValueType::Type::DOUBLE:
case ValueType::Type::LONGDOUBLE:
return false;
}
return defaultReturn;
}
/**
* @brief This class is used create a list of variables within a function.
*/
class Variables {
public:
enum VariableType : std::uint8_t { standard, array, pointer, reference, pointerArray, referenceArray, pointerPointer, none };
/** Store information about variable usage */
class VariableUsage {
public:
explicit VariableUsage(const Variable *var = nullptr,
VariableType type = standard,
bool read = false,
bool write = false,
bool modified = false,
bool allocateMemory = false) :
_var(var),
_lastAccess(var ? var->nameToken() : nullptr),
mType(type),
_read(read),
_write(write),
_modified(modified),
_allocateMemory(allocateMemory) {}
/** variable is used.. set both read+write */
void use() {
_read = true;
_write = true;
}
/** is variable unused? */
bool unused() const {
return (!_read && !_write);
}
std::set<nonneg int> _aliases;
std::set<const Scope*> _assignments;
const Variable* _var;
const Token* _lastAccess;
VariableType mType;
bool _read;
bool _write;
bool _modified; // read/modify/write
bool _allocateMemory;
};
void clear() {
mVarUsage.clear();
}
const std::map<nonneg int, VariableUsage> &varUsage() const {
return mVarUsage;
}
void addVar(const Variable *var, VariableType type, bool write_);
void allocateMemory(nonneg int varid, const Token* tok);
void read(nonneg int varid, const Token* tok);
void readAliases(nonneg int varid, const Token* tok);
void readAll(nonneg int varid, const Token* tok);
void write(nonneg int varid, const Token* tok);
void writeAliases(nonneg int varid, const Token* tok);
void writeAll(nonneg int varid, const Token* tok);
void use(nonneg int varid, const Token* tok);
void modified(nonneg int varid, const Token* tok);
VariableUsage *find(nonneg int varid);
void alias(nonneg int varid1, nonneg int varid2, bool replace);
void erase(nonneg int varid) {
mVarUsage.erase(varid);
}
void eraseAliases(nonneg int varid);
void eraseAll(nonneg int varid);
void clearAliases(nonneg int varid);
private:
std::map<nonneg int, VariableUsage> mVarUsage;
};
/**
* Alias the 2 given variables. Either replace the existing aliases if
* they exist or merge them. You would replace an existing alias when this
* assignment is in the same scope as the previous assignment. You might
* merge the aliases when this assignment is in a different scope from the
* previous assignment depending on the relationship of the 2 scopes.
*/
void Variables::alias(nonneg int varid1, nonneg int varid2, bool replace)
{
VariableUsage *var1 = find(varid1);
VariableUsage *var2 = find(varid2);
if (!var1 || !var2)
return;
// alias to self
if (varid1 == varid2) {
var1->use();
return;
}
if (replace) {
// remove var1 from all aliases
for (auto i = var1->_aliases.cbegin(); i != var1->_aliases.cend(); ++i) {
VariableUsage *temp = find(*i);
if (temp)
temp->_aliases.erase(var1->_var->declarationId());
}
// remove all aliases from var1
var1->_aliases.clear();
}
// var1 gets all var2s aliases
for (auto i = var2->_aliases.cbegin(); i != var2->_aliases.cend(); ++i) {
if (*i != varid1)
var1->_aliases.insert(*i);
}
// var2 is an alias of var1
var2->_aliases.insert(varid1);
var1->_aliases.insert(varid2);
if (var2->mType == Variables::pointer) {
var2->_read = true;
}
}
void Variables::clearAliases(nonneg int varid)
{
VariableUsage *usage = find(varid);
if (usage) {
// remove usage from all aliases
for (auto i = usage->_aliases.cbegin(); i != usage->_aliases.cend(); ++i) {
VariableUsage *temp = find(*i);
if (temp)
temp->_aliases.erase(usage->_var->declarationId());
}
// remove all aliases from usage
usage->_aliases.clear();
}
}
void Variables::eraseAliases(nonneg int varid)
{
VariableUsage *usage = find(varid);
if (usage) {
for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases)
erase(*aliases);
}
}
void Variables::eraseAll(nonneg int varid)
{
eraseAliases(varid);
erase(varid);
}
void Variables::addVar(const Variable *var,
VariableType type,
bool write_)
{
if (var->declarationId() > 0) {
mVarUsage.emplace(var->declarationId(), VariableUsage(var, type, false, write_, false));
}
}
void Variables::allocateMemory(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
usage->_allocateMemory = true;
usage->_lastAccess = tok;
}
}
void Variables::read(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
usage->_read = true;
if (tok)
usage->_lastAccess = tok;
}
}
void Variables::readAliases(nonneg int varid, const Token* tok)
{
const VariableUsage *usage = find(varid);
if (usage) {
for (nonneg int const aliases : usage->_aliases) {
VariableUsage *aliased = find(aliases);
if (aliased) {
aliased->_read = true;
aliased->_lastAccess = tok;
}
}
}
}
void Variables::readAll(nonneg int varid, const Token* tok)
{
read(varid, tok);
readAliases(varid, tok);
}
void Variables::write(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
usage->_write = true;
if (!usage->_var->isStatic() && !Token::simpleMatch(tok->next(), "= 0 ;"))
usage->_read = false;
usage->_lastAccess = tok;
}
}
void Variables::writeAliases(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) {
VariableUsage *aliased = find(*aliases);
if (aliased) {
aliased->_write = true;
aliased->_lastAccess = tok;
}
}
}
}
void Variables::writeAll(nonneg int varid, const Token* tok)
{
write(varid, tok);
writeAliases(varid, tok);
}
void Variables::use(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
usage->use();
usage->_lastAccess = tok;
for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) {
VariableUsage *aliased = find(*aliases);
if (aliased) {
aliased->use();
aliased->_lastAccess = tok;
}
}
}
}
void Variables::modified(nonneg int varid, const Token* tok)
{
VariableUsage *usage = find(varid);
if (usage) {
if (!usage->_var->isStatic())
usage->_read = false;
usage->_modified = true;
usage->_lastAccess = tok;
for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) {
VariableUsage *aliased = find(*aliases);
if (aliased) {
aliased->_modified = true;
aliased->_lastAccess = tok;
}
}
}
}
Variables::VariableUsage *Variables::find(nonneg int varid)
{
if (varid) {
const std::map<nonneg int, VariableUsage>::iterator i = mVarUsage.find(varid);
if (i != mVarUsage.end())
return &i->second;
}
return nullptr;
}
static const Token* doAssignment(Variables &variables, const Token *tok, bool dereference, const Scope *scope)
{
// a = a + b;
if (Token::Match(tok, "%var% = %var% !!;")) {
const Token* rhsVarTok = tok->tokAt(2);
if (tok->varId() == rhsVarTok->varId()) {
return rhsVarTok;
}
}
if (Token::Match(tok, "%var% %assign%") && tok->strAt(1) != "=")
return tok->next();
const Token* const tokOld = tok;
// check for aliased variable
const nonneg int varid1 = tok->varId();
Variables::VariableUsage *var1 = variables.find(varid1);
if (var1) {
// jump behind '='
tok = tok->next();
while (!tok->isAssignmentOp()) {
if (tok->varId())
variables.read(tok->varId(), tok);
tok = tok->next();
}
tok = tok->next();
if (Token::Match(tok, "( const| struct|union| %type% * ) ( ("))
tok = tok->link()->next();
if (Token::Match(tok, "( [(<] const| struct|union| %type% *| [>)]"))
tok = tok->next();
if (Token::Match(tok, "(| &| %name%") ||
(Token::Match(tok->next(), "< const| struct|union| %type% *| > ( &| %name%"))) {
bool addressOf = false;
if (Token::Match(tok, "%var% ."))
variables.use(tok->varId(), tok); // use = read + write
// check for C style cast
if (tok->str() == "(") {
tok = tok->next();
if (tok->str() == "const")
tok = tok->next();
if (Token::Match(tok, "struct|union"))
tok = tok->next();
while ((tok->isName() && tok->varId() == 0) || (tok->str() == "*") || (tok->str() == ")"))
tok = tok->next();
if (tok->str() == "&") {
addressOf = true;
tok = tok->next();
} else if (tok->str() == "(") {
tok = tok->next();
if (tok->str() == "&") {
addressOf = true;
tok = tok->next();
}
} else if (Token::Match(tok, "%cop% %var%")) {
variables.read(tok->next()->varId(), tok);
}
}
// check for C++ style cast
else if (tok->str().find("cast") != std::string::npos &&
tok->strAt(1) == "<") {
tok = tok->tokAt(2);
if (tok->str() == "const")
tok = tok->next();
if (Token::Match(tok, "struct|union"))
tok = tok->next();
tok = tok->next();
if (!tok)
return tokOld;
if (tok->str() == "*")
tok = tok->next();
tok = tok->tokAt(2);
if (!tok)
return tokOld;
if (tok->str() == "&") {
addressOf = true;
tok = tok->next();
}
}
// no cast, no ?
else if (!Token::Match(tok, "%name% ?")) {
if (tok->str() == "&") {
addressOf = true;
tok = tok->next();
} else if (tok->str() == "new")
return tokOld;
}
// check if variable is local
const nonneg int varid2 = tok->varId();
const Variables::VariableUsage* var2 = variables.find(varid2);
if (var2) { // local variable (alias or read it)
if (var1->mType == Variables::pointer || var1->mType == Variables::pointerArray) {
if (dereference)
variables.read(varid2, tok);
else {
if (addressOf ||
var2->mType == Variables::array ||
var2->mType == Variables::pointer) {
bool replace = true;
// pointerArray => don't replace
if (var1->mType == Variables::pointerArray)
replace = false;
// check if variable declared in same scope
else if (scope == var1->_var->scope())
replace = true;
// not in same scope as declaration
else {
// no other assignment in this scope
if (var1->_assignments.find(scope) == var1->_assignments.end() ||
scope->type == Scope::eSwitch) {
// nothing to replace
// cppcheck-suppress duplicateBranch - remove when TODO below is address
if (var1->_assignments.empty())
replace = false;
// this variable has previous assignments
else {
// TODO: determine if existing aliases should be replaced or merged
replace = false;
}
}
// assignment in this scope
else {
// replace when only one other assignment, merge them otherwise
replace = (var1->_assignments.size() == 1);
}
}
variables.alias(varid1, varid2, replace);
} else if (tok->strAt(1) == "?") {
if (var2->mType == Variables::reference)
variables.readAliases(varid2, tok);
else
variables.read(varid2, tok);
} else {
variables.readAll(varid2, tok);
}
}
} else if (var1->mType == Variables::reference) {
variables.alias(varid1, varid2, true);
} else if (var1->mType == Variables::standard && addressOf) {
variables.alias(varid1, varid2, true);
} else {
if ((var2->mType == Variables::pointer || var2->mType == Variables::pointerArray) && tok->strAt(1) == "[")
variables.readAliases(varid2, tok);
variables.read(varid2, tok);
}
} else { // not a local variable (or an unsupported local variable)
if (var1->mType == Variables::pointer && !dereference) {
// check if variable declaration is in this scope
if (var1->_var->scope() == scope) {
// If variable is used in RHS then "use" variable
for (const Token *rhs = tok; rhs && rhs->str() != ";"; rhs = rhs->next()) {
if (rhs->varId() == varid1) {
variables.use(varid1, tok);
break;
}
}
variables.clearAliases(varid1);
} else {
// no other assignment in this scope
if (var1->_assignments.find(scope) == var1->_assignments.end()) {
/**
* @todo determine if existing aliases should be discarded
*/
}
// this assignment replaces the last assignment in this scope
else {
// aliased variables in a larger scope are not supported
// remove all aliases
variables.clearAliases(varid1);
}
}
}
}
} else
tok = tokOld;
var1->_assignments.insert(scope);
}
// check for alias to struct member
// char c[10]; a.b = c;
else if (Token::Match(tok->tokAt(-2), "%name% .")) {
const Token *rhsVarTok = tok->tokAt(2);
if (rhsVarTok && rhsVarTok->varId()) {
const nonneg int varid2 = rhsVarTok->varId();
const Variables::VariableUsage *var2 = variables.find(varid2);
// struct member aliased to local variable
if (var2 && (var2->mType == Variables::array ||
var2->mType == Variables::pointer)) {
// erase aliased variable and all variables that alias it
// to prevent false positives
variables.eraseAll(varid2);
}
}
}
// Possible pointer alias
else if (Token::Match(tok, "%name% = %name% ;")) {
const nonneg int varid2 = tok->tokAt(2)->varId();
const Variables::VariableUsage *var2 = variables.find(varid2);
if (var2 && (var2->mType == Variables::array ||
var2->mType == Variables::pointer)) {
variables.use(varid2,tok);
}
}
return tok;
}
static bool isPartOfClassStructUnion(const Token* tok)
{
for (; tok; tok = tok->previous()) {
if (tok->str() == "}" || tok->str() == ")")
tok = tok->link();
else if (tok->str() == "(")
return false;
else if (tok->str() == "{") {
return (tok->strAt(-1) == "struct" || tok->strAt(-2) == "struct" || tok->strAt(-1) == "class" || tok->strAt(-2) == "class" || tok->strAt(-1) == "union" || tok->strAt(-2) == "union");
}
}
return false;
}
static bool isVarDecl(const Token *tok)
{
return tok && tok->variable() && tok->variable()->nameToken() == tok;
}
// Skip [ .. ]
static const Token * skipBrackets(const Token *tok)
{
while (tok && tok->str() == "[")
tok = tok->link()->next();
return tok;
}
// Skip [ .. ] . x
static const Token * skipBracketsAndMembers(const Token *tok)
{
while (tok) {
if (tok->str() == "[")
tok = tok->link()->next();
else if (Token::Match(tok, ". %name%"))
tok = tok->tokAt(2);
else
break;
}
return tok;
}
static void useFunctionArgs(const Token *tok, Variables& variables)
{
// TODO: Match function args to see if they are const or not. Assume that const data is not written.
if (!tok)
return;
if (tok->str() == ",") {
useFunctionArgs(tok->astOperand1(), variables);
useFunctionArgs(tok->astOperand2(), variables);
} else if (Token::Match(tok, "[+:]") && (!tok->valueType() || tok->valueType()->pointer)) {
useFunctionArgs(tok->astOperand1(), variables);
useFunctionArgs(tok->astOperand2(), variables);
} else if (tok->variable() && tok->variable()->isArray()) {
variables.use(tok->varId(), tok);
}
}
//---------------------------------------------------------------------------
// Usage of function variables
//---------------------------------------------------------------------------
void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const scope, Variables& variables)
{
// Find declarations if the scope is executable..
if (scope->isExecutable()) {
// Find declarations
for (auto i = scope->varlist.cbegin(); i != scope->varlist.cend(); ++i) {
if (i->isThrow() || i->isExtern())
continue;
Variables::VariableType type = Variables::none;
if (i->isArray() && (i->nameToken()->strAt(-1) == "*" || i->nameToken()->strAt(-2) == "*"))
type = Variables::pointerArray;
else if (i->isArray() && i->nameToken()->strAt(-1) == "&")
type = Variables::referenceArray;
else if (i->isArray())
type = Variables::array;
else if (i->isReference() && !(i->valueType() && i->valueType()->type == ValueType::UNKNOWN_TYPE && Token::simpleMatch(i->typeStartToken(), "auto")))
type = Variables::reference;
else if (i->nameToken()->strAt(-1) == "*" && i->nameToken()->strAt(-2) == "*")
type = Variables::pointerPointer;
else if (i->isPointerToArray())
type = Variables::pointerPointer;
else if (i->isPointer())
type = Variables::pointer;
else if (mTokenizer->isC() ||
i->typeEndToken()->isStandardType() ||
i->isStlType() ||
isRecordTypeWithoutSideEffects(i->type()) ||
mSettings->library.detectContainer(i->typeStartToken()) ||
mSettings->library.getTypeCheck("unusedvar", i->typeStartToken()->str()) == Library::TypeCheck::check)
type = Variables::standard;
if (type == Variables::none || isPartOfClassStructUnion(i->typeStartToken()))
continue;
const Token* defValTok = i->nameToken()->next();
if (Token::Match(i->nameToken()->previous(), "* %var% ) (")) // function pointer. Jump behind parameter list.
defValTok = defValTok->linkAt(1)->next();
for (; defValTok; defValTok = defValTok->next()) {
if (defValTok->str() == "[")
defValTok = defValTok->link();
else if (defValTok->str() == "(" || defValTok->str() == "{" || defValTok->str() == "=" || defValTok->str() == ":") {
variables.addVar(&*i, type, true);
break;
} else if (defValTok->str() == ";" || defValTok->str() == "," || defValTok->str() == ")") {
variables.addVar(&*i, type, i->isStatic() && i->scope()->type != Scope::eFunction);
break;
}
}
if (i->isArray() && i->isClass() && // Array of class/struct members. Initialized by ctor except for std::array
!(i->isStlType() && i->valueType() && i->valueType()->containerTypeToken && i->valueType()->containerTypeToken->isStandardType()))
variables.write(i->declarationId(), i->nameToken());
if (i->isArray() && Token::Match(i->nameToken(), "%name% [ %var% ]")) // Array index variable read.
variables.read(i->nameToken()->tokAt(2)->varId(), i->nameToken());
if (defValTok && defValTok->next()) {
// simple assignment "var = 123"
if (defValTok->str() == "=" && defValTok->strAt(1) != "{") {
doAssignment(variables, i->nameToken(), false, scope);
} else {
// could be "var = {...}" OR "var{...}" (since C++11)
const Token* tokBraceStart = nullptr;
if (Token::simpleMatch(defValTok, "= {")) {
// "var = {...}"
tokBraceStart = defValTok->next();
} else if (defValTok->str() == "{") {
// "var{...}"
tokBraceStart = defValTok;
}
if (tokBraceStart) {
for (const Token* tok = tokBraceStart->next(); tok && tok != tokBraceStart->link(); tok = tok->next()) {
if (tok->varId()) {
// Variables used to initialize the array read.
variables.read(tok->varId(), i->nameToken());
}
}
}
}
}
}
}
// Check variable usage
const Token *tok;
if (scope->type == Scope::eFunction)
tok = scope->bodyStart->next();
else
tok = scope->classDef->next();
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "{" && tok != scope->bodyStart && !tok->previous()->varId()) {
if (std::any_of(scope->nestedList.cbegin(), scope->nestedList.cend(), [&](const Scope* s) {
return s->bodyStart == tok;
})) {
checkFunctionVariableUsage_iterateScopes(tok->scope(), variables); // Scan child scope
tok = tok->link();
}
if (!tok)
break;
}
if (Token::Match(tok, "asm ( %str% )")) {
variables.clear();
break;
}
// templates
if (tok->isName() && endsWith(tok->str(), '>')) {
// TODO: This is a quick fix to handle when constants are used
// as template parameters. Try to handle this better, perhaps
// only remove constants.
variables.clear();
}
else if (Token::Match(tok->previous(), "[;{}]")) {
for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId()) {
// Is this a variable declaration?
const Variable *var = tok2->variable();
if (!var || var->nameToken() != tok2)
continue;
// Mark template parameters used in declaration as use..
if (tok2->strAt(-1) == ">") {
for (const Token *tok3 = tok; tok3 != tok2; tok3 = tok3->next()) {
if (tok3->varId())
variables.use(tok3->varId(), tok3);
}
}
// Skip variable declaration..
tok = tok2->next();
if (Token::Match(tok, "( %name% )")) // Simple initialization through copy ctor
tok = tok->next();
else if (Token::Match(tok, "= %var% ;")) { // Simple initialization
tok = tok->next();
if (!var->isReference())
variables.read(tok->varId(), tok);
} else if (tok->str() == "[" && Token::simpleMatch(skipBrackets(tok),"= {")) {
const Token * const rhs1 = skipBrackets(tok)->next();
for (const Token *rhs = rhs1->link(); rhs != rhs1; rhs = rhs->previous()) {
if (rhs->varId())
variables.readAll(rhs->varId(), rhs);
}
} else if (var->typeEndToken()->str() == ">") // Be careful with types like std::vector
tok = tok->previous();
break;
}
if (Token::Match(tok2, "[;({=]"))
break;
}
}
// Freeing memory (not considered "using" the pointer if it was also allocated in this function)
if ((Token::Match(tok, "%name% ( %var% )") && mSettings->library.getDeallocFuncInfo(tok)) ||
(tok->isCpp() && (Token::Match(tok, "delete %var% ;") || Token::Match(tok, "delete [ ] %var% ;")))) {
nonneg int varid = 0;
if (tok->str() != "delete") {
const Token *varTok = tok->tokAt(2);
varid = varTok->varId();
tok = varTok->next();
} else if (tok->strAt(1) == "[") {
const Token *varTok = tok->tokAt(3);
varid = varTok->varId();
tok = varTok;
} else {
varid = tok->next()->varId();
tok = tok->next();
}
const Variables::VariableUsage *const var = variables.find(varid);
if (var) {
if (!var->_aliases.empty())
variables.use(varid, tok);
else if (!var->_allocateMemory)
variables.readAll(varid, tok);
}
}
else if (Token::Match(tok, "return|throw")) {
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId())
variables.readAll(tok2->varId(), tok);
else if (tok2->str() == ";")
break;
}
}
// assignment
else if (Token::Match(tok, "*| ++|--| %name% ++|--| %assign%") ||
Token::Match(tok, "*| ( const| %type% *| ) %name% %assign%")) {
bool dereference = false;
bool pre = false;
bool post = false;
if (tok->str() == "*") {
dereference = true;
tok = tok->next();
}
if (Token::Match(tok, "( const| %type% *| ) %name% %assign%"))
tok = tok->link()->next();
else if (tok->str() == "(")
tok = tok->next();
if (tok->tokType() == Token::eIncDecOp) {
pre = true;
tok = tok->next();
}
if (tok->next()->tokType() == Token::eIncDecOp)
post = true;
const nonneg int varid1 = tok->varId();
const Token * const start = tok;
// assignment in while head..
bool inwhile = false;
{
const Token *parent = tok->astParent();
while (parent) {
if (Token::simpleMatch(parent->previous(), "while (")) {
inwhile = true;
break;
}
parent = parent->astParent();
}
}
tok = doAssignment(variables, tok, dereference, scope);
if (tok && tok->isAssignmentOp() && tok->str() != "=") {
variables.use(varid1, tok);
if (Token::Match(tok, "%assign% %name%")) {
tok = tok->next();
variables.read(tok->varId(), tok);
}
}
if (pre || post)
variables.use(varid1, tok);
if (dereference) {
const Variables::VariableUsage *const var = variables.find(varid1);
if (var && var->mType == Variables::array)
variables.write(varid1, tok);
variables.writeAliases(varid1, tok);
variables.read(varid1, tok);
} else {
const Variables::VariableUsage *const var = variables.find(varid1);
if (var && (inwhile || start->strAt(-1) == ",")) {
variables.use(varid1, tok);
} else if (var && var->mType == Variables::reference) {
variables.writeAliases(varid1, tok);
variables.read(varid1, tok);
}
// Consider allocating memory separately because allocating/freeing alone does not constitute using the variable
else if (var && var->mType == Variables::pointer &&
Token::Match(start, "%name% =") &&
findAllocFuncCallToken(start->next()->astOperand2(), mSettings->library)) {
const Token *allocFuncCallToken = findAllocFuncCallToken(start->next()->astOperand2(), mSettings->library);
const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(allocFuncCallToken);
bool allocateMemory = !allocFunc || Library::ismemory(allocFunc->groupId);
if (allocFuncCallToken->str() == "new") {
const Token *type = allocFuncCallToken->next();
// skip nothrow
if (type->isCpp() && (Token::simpleMatch(type, "( nothrow )") ||
Token::simpleMatch(type, "( std :: nothrow )")))
type = type->link()->next();
// is it a user defined type?
if (!type->isStandardType()) {
const Variable *variable = start->variable();
if (!variable || !isRecordTypeWithoutSideEffects(variable->type()))
allocateMemory = false;
}
}
if (allocateMemory)
variables.allocateMemory(varid1, tok);
else
variables.write(varid1, tok);
} else if (varid1 && Token::Match(tok, "%varid% .", varid1)) {
variables.read(varid1, tok);
variables.write(varid1, start);
} else {
variables.write(varid1, tok);
}
}
const Variables::VariableUsage * const var2 = variables.find(tok->varId());
if (var2) {
if (var2->mType == Variables::reference) {
variables.writeAliases(tok->varId(), tok);
variables.read(tok->varId(), tok);
} else if (tok->varId() != varid1 && Token::Match(tok, "%name% .|["))
variables.read(tok->varId(), tok);
else if (tok->varId() != varid1 &&
var2->mType == Variables::standard &&
tok->strAt(-1) != "&")
variables.use(tok->varId(), tok);
}
const Token * const equal = skipBracketsAndMembers(tok->next());
// checked for chained assignments
if (tok != start && equal && equal->str() == "=") {
const nonneg int varId = tok->varId();
const Variables::VariableUsage * const var = variables.find(varId);
if (var && var->mType != Variables::reference) {
variables.read(varId,tok);
}
tok = tok->previous();
}
}
// assignment
else if ((Token::Match(tok, "%name% [") && Token::simpleMatch(skipBracketsAndMembers(tok->next()), "=")) ||
(tok->isUnaryOp("*") && astIsLHS(tok) && Token::simpleMatch(tok->astParent(), "=") && Token::simpleMatch(tok->astOperand1(), "+"))) {
const Token *eq = tok;
while (eq && !eq->isAssignmentOp())
eq = eq->astParent();
const bool deref = eq && eq->astOperand1() && eq->astOperand1()->valueType() && eq->astOperand1()->valueType()->pointer == 0U;
if (tok->str() == "*") {
tok = tok->tokAt(2);
if (tok->str() == "(")
tok = tok->link()->next();
}
const nonneg int varid = tok->varId();
const Variables::VariableUsage *var = variables.find(varid);
if (var) {
// Consider allocating memory separately because allocating/freeing alone does not constitute using the variable
if (var->mType == Variables::pointer &&
((tok->isCpp() && Token::simpleMatch(skipBrackets(tok->next()), "= new")) ||
(Token::Match(skipBrackets(tok->next()), "= %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2))))) {
variables.allocateMemory(varid, tok);
} else if (var->mType == Variables::pointer || var->mType == Variables::reference) {
variables.read(varid, tok);
variables.writeAliases(varid, tok);
} else if (var->mType == Variables::pointerArray) {
tok = doAssignment(variables, tok, deref, scope);
} else
variables.writeAll(varid, tok);
}
}
else if (tok->isCpp() && Token::Match(tok, "[;{}] %var% <<")) {
variables.erase(tok->next()->varId());
}
else if (Token::Match(tok, "& %var%")) {
if (tok->astOperand2()) { // bitop
variables.read(tok->next()->varId(), tok);
} else // addressof
variables.use(tok->next()->varId(), tok); // use = read + write
} else if (Token::Match(tok, ">>|>>= %name%")) {
if (isLikelyStreamRead(tok))
variables.use(tok->next()->varId(), tok); // use = read + write
else
variables.read(tok->next()->varId(), tok);
} else if (Token::Match(tok, "%var% >>|&") && Token::Match(tok->previous(), "[{};:]")) {
variables.read(tok->varId(), tok);
} else if (isLikelyStreamRead(tok->previous())) {
variables.use(tok->varId(), tok);
}
// function parameter
else if (Token::Match(tok, "[(,] %var% [")) {
variables.use(tok->next()->varId(), tok); // use = read + write
} else if (Token::Match(tok, "[(,] %var% [,)]") && tok->strAt(-1) != "*") {
variables.use(tok->next()->varId(), tok); // use = read + write
} else if (Token::Match(tok, "[(,] & %var% [,)]")) {
variables.eraseAll(tok->tokAt(2)->varId());
} else if (Token::Match(tok, "[(,] (") &&
Token::Match(tok->linkAt(1), ") %var% [,)[]")) {
variables.use(tok->linkAt(1)->next()->varId(), tok); // use = read + write
} else if (Token::Match(tok, "[(,] *| *| %var%")) {
const Token* vartok = tok->next();
while (vartok->str() == "*")
vartok = vartok->next();
if (!(vartok->variable() && vartok == vartok->variable()->nameToken()) &&
!(tok->str() == "(" && !Token::Match(tok->previous(), "%name%")))
variables.use(vartok->varId(), vartok);
}
// function
else if (Token::Match(tok, "%name% (")) {
if (tok->varId() && !tok->function()) // operator()
variables.use(tok->varId(), tok);
else
variables.read(tok->varId(), tok);
useFunctionArgs(tok->next()->astOperand2(), variables);
} else if (Token::Match(tok, "std :: ref ( %var% )")) {
variables.eraseAll(tok->tokAt(4)->varId());
}
else if (Token::Match(tok->previous(), "[{,] %var% [,}]")) {
variables.use(tok->varId(), tok);
}
else if (tok->varId() && Token::Match(tok, "%var% .")) {
variables.use(tok->varId(), tok); // use = read + write
}
else if (tok->str() == ":" && (!tok->valueType() || tok->valueType()->pointer)) {
if (tok->astOperand1())
variables.use(tok->astOperand1()->varId(), tok->astOperand1());
if (tok->astOperand2())
variables.use(tok->astOperand2()->varId(), tok->astOperand2());
}
else if (tok->isExtendedOp() && tok->next() && tok->next()->varId() && tok->strAt(2) != "=" && !isVarDecl(tok->next())) {
variables.readAll(tok->next()->varId(), tok);
}
else if (tok->varId() && !isVarDecl(tok) && tok->next() && (tok->strAt(1) == ")" || tok->next()->isExtendedOp())) {
if (Token::Match(tok->tokAt(-2), "%name% ( %var% [,)]") &&
!(tok->tokAt(-2)->variable() && tok->tokAt(-2)->variable()->isReference()))
variables.use(tok->varId(), tok);
else
variables.readAll(tok->varId(), tok);
}
else if (Token::Match(tok, "%var% ;") && Token::Match(tok->previous(), "[;{}:]")) {
variables.readAll(tok->varId(), tok);
}
// ++|--
else if (tok->next() && tok->next()->tokType() == Token::eIncDecOp && tok->next()->astOperand1() && tok->next()->astOperand1()->varId()) {
if (tok->next()->astParent())
variables.use(tok->next()->astOperand1()->varId(), tok);
else
variables.modified(tok->next()->astOperand1()->varId(), tok);
}
else if (tok->isAssignmentOp()) {
for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) {
if (tok2->varId()) {
if (tok2->strAt(1) == "=")
variables.write(tok2->varId(), tok);
else if (tok2->next() && tok2->next()->isAssignmentOp())
variables.use(tok2->varId(), tok);
else
variables.read(tok2->varId(), tok);
}
}
} else if (tok->variable() && tok->variable()->isClass() && tok->variable()->type() &&
(tok->variable()->type()->needInitialization == Type::NeedInitialization::False) &&
tok->strAt(1) == ";") {
variables.write(tok->varId(), tok);
}
}
}
static bool isReturnedByRef(const Variable* var, const Function* func)
{
if (!func || !Function::returnsReference(func, true))
return false;
const std::vector<const Token*> returns = Function::findReturns(func);
return std::any_of(returns.begin(), returns.end(), [var](const Token* tok) {
return tok->varId() == var->declarationId();
});
}
void CheckUnusedVar::checkFunctionVariableUsage()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->checkLibrary && !mSettings->isPremiumEnabled("unusedVariable"))
return;
logChecker("CheckUnusedVar::checkFunctionVariableUsage"); // style
// Parse all executing scopes..
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
auto reportLibraryCfgError = [this](const Token* tok, const std::string& typeName) {
if (mSettings->checkLibrary) {
reportError(tok,
Severity::information,
"checkLibraryCheckType",
"--check-library: Provide <type-checks><unusedvar> configuration for " + typeName);
}
};
// only check functions
for (const Scope * scope : symbolDatabase->functionScopes) {
// Bailout when there are lambdas or inline functions
// TODO: Handle lambdas and inline functions properly
const Token* lambdaOrInlineStart{};
const bool hasLambdaOrInline = scope->hasInlineOrLambdaFunction(&lambdaOrInlineStart);
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (findLambdaEndToken(tok))
// todo: handle lambdas
break;
if (Token::simpleMatch(tok, "try {"))
// todo: check try blocks
tok = tok->linkAt(1);
const Token *varDecl = nullptr;
if (tok->variable() && tok->variable()->nameToken() == tok) {
const Token * eq = tok->next();
while (Token::simpleMatch(eq, "["))
eq = eq->link()->next();
if (Token::simpleMatch(eq, ") (") && Token::simpleMatch(eq->linkAt(1), ") ="))
eq = eq->linkAt(1)->next();
if (Token::simpleMatch(eq, "=")) {
varDecl = tok;
tok = eq;
}
}
// not assignment/initialization/increment => continue
const bool isAssignment = tok->isAssignmentOp() && tok->astOperand1();
const bool isInitialization = (Token::Match(tok, "%var% (|{") && tok->variable() && tok->variable()->nameToken() == tok);
const bool isIncrementOrDecrement = (tok->tokType() == Token::Type::eIncDecOp);
if (!isAssignment && !isInitialization && !isIncrementOrDecrement)
continue;
bool isTrivialInit = false;
if (isInitialization && Token::Match(tok, "%var% { }")) // don't warn for trivial initialization
isTrivialInit = true;
if (isIncrementOrDecrement && tok->astParent() && precedes(tok, tok->astOperand1()))
continue;
if (tok->str() == "=" && !(tok->valueType() && tok->valueType()->pointer) && isRaiiClass(tok->valueType(), tok->isCpp(), false))
continue;
const bool isPointer = tok->valueType() && (tok->valueType()->pointer || tok->valueType()->type == ValueType::SMART_POINTER);
if (tok->isName()) {
if (isRaiiClass(tok->valueType(), tok->isCpp(), false) ||
(tok->valueType() && tok->valueType()->type == ValueType::RECORD &&
(!tok->valueType()->typeScope || !isRecordTypeWithoutSideEffects(tok->valueType()->typeScope->definedType))))
continue;
tok = tok->next();
}
if (!isInitialization && tok->astParent() && !tok->astParent()->isAssignmentOp() && tok->str() != "(") {
const Token *parent = tok->astParent();
while (Token::Match(parent, "%oror%|%comp%|!|&&"))
parent = parent->astParent();
if (!parent)
continue;
if (!Token::simpleMatch(parent->previous(), "if ("))
continue;
}
// Do not warn about assignment with NULL
if (isPointer && isNullOperand(tok->astOperand2()))
continue;
if (!tok->astOperand1())
continue;
const Token *iteratorToken = tok->astOperand1();
while (Token::Match(iteratorToken, "[.*]"))
iteratorToken = iteratorToken->astOperand1();
if (iteratorToken && iteratorToken->variable() && iteratorToken->variable()->typeEndToken()->str().find("iterator") != std::string::npos)
continue;
const Token *op1tok = tok->astOperand1();
while (Token::Match(op1tok, ".|[|*"))
op1tok = op1tok->astOperand1();
// Assignment in macro => do not warn
if (isAssignment && tok->isExpandedMacro() && op1tok && op1tok->isExpandedMacro())
continue;
const Variable *op1Var = op1tok ? op1tok->variable() : nullptr;
if (!op1Var && Token::Match(tok, "(|{") && tok->previous() && tok->previous()->variable())
op1Var = tok->previous()->variable();
if (hasLambdaOrInline) {
if (!op1Var || !lambdaOrInlineStart)
continue;
if (precedes(op1Var->nameToken(), lambdaOrInlineStart))
continue;
}
std::string bailoutTypeName;
if (op1Var) {
if (op1Var->isReference() && op1Var->nameToken() != tok->astOperand1())
// todo: check references
continue;
if (op1Var->isStatic())
// todo: check static variables
continue;
if (op1Var->nameToken()->isAttributeUnused())
continue;
// Avoid FP for union..
if (op1Var->type() && op1Var->type()->isUnionType())
continue;
// Bailout for unknown template classes, we have no idea what side effects such assignments have
if (mTokenizer->isCPP() &&
op1Var->isClass() &&
(!op1Var->valueType() || op1Var->valueType()->type == ValueType::Type::UNKNOWN_TYPE)) {
// Check in the library if we should bailout or not..
std::string typeName = op1Var->getTypeName();
if (startsWith(typeName, "::"))
typeName.erase(typeName.begin(), typeName.begin() + 2);
switch (mSettings->library.getTypeCheck("unusedvar", typeName)) {
case Library::TypeCheck::def:
bailoutTypeName = typeName;
break;
case Library::TypeCheck::check:
break;
case Library::TypeCheck::suppress:
case Library::TypeCheck::checkFiniteLifetime:
continue;
}
}
}
// Is there a redundant assignment?
const Token *start = tok->findExpressionStartEndTokens().second->next();
const Token *expr = varDecl ? varDecl : tok->astOperand1();
if (isInitialization)
expr = tok->previous();
// Is variable in lhs a union member?
if (tok->previous() && tok->previous()->variable() && tok->previous()->variable()->nameToken()->scope()->type == Scope::eUnion)
continue;
FwdAnalysis fwdAnalysis(*mSettings);
const Token* scopeEnd = ValueFlow::getEndOfExprScope(expr, scope, /*smallest*/ false);
if (fwdAnalysis.unusedValue(expr, start, scopeEnd)) {
if (!bailoutTypeName.empty()) {
if (bailoutTypeName != "auto")
reportLibraryCfgError(tok, bailoutTypeName);
continue;
}
if (isTrivialInit && findExpressionChanged(expr, start, scopeEnd, *mSettings))
continue;
// warn
if (!expr->variable() || !expr->variable()->isMaybeUnused())
unreadVariableError(tok, expr->expressionString(), false);
}
}
// varId, usage {read, write, modified}
Variables variables;
checkFunctionVariableUsage_iterateScopes(scope, variables);
// Check usage of all variables in the current scope..
for (auto it = variables.varUsage().cbegin();
it != variables.varUsage().cend();
++it) {
const Variables::VariableUsage &usage = it->second;
// variable has been marked as unused so ignore it
if (usage._var->nameToken()->isAttributeUnused() || usage._var->nameToken()->isAttributeUsed())
continue;
// skip things that are only partially implemented to prevent false positives
if (usage.mType == Variables::pointerPointer ||
usage.mType == Variables::pointerArray ||
usage.mType == Variables::referenceArray)
continue;
const std::string &varname = usage._var->name();
const Variable* var = symbolDatabase->getVariableFromVarId(it->first);
// variable has had memory allocated for it, but hasn't done
// anything with that memory other than, perhaps, freeing it
if (usage.unused() && !usage._modified && usage._allocateMemory)
allocatedButUnusedVariableError(usage._lastAccess, varname);
// variable has not been written, read, or modified
else if (usage.unused() && !usage._modified) {
if (!usage._var->isMaybeUnused()) {
unusedVariableError(usage._var->nameToken(), varname);
}
}
// variable has not been written but has been modified
else if (usage._modified && !usage._write && !usage._allocateMemory && var && !var->isStlType()) {
if (var->isStatic()) // static variables are initialized by default
continue;
unassignedVariableError(usage._var->nameToken(), varname);
}
// variable has been read but not written
else if (!usage._write && !usage._allocateMemory && var && !var->isStlType() && !isEmptyType(var->type()) &&
!(var->type() && var->type()->needInitialization == Type::NeedInitialization::False) &&
!(var->valueType() && var->valueType()->container) &&
!(var->isStatic() && isReturnedByRef(var, scope->function)))
unassignedVariableError(usage._var->nameToken(), varname);
else if (!usage._var->isMaybeUnused() && !usage._modified && !usage._read && var) {
const Token* vnt = var->nameToken();
bool error = false;
if (vnt->next()->isSplittedVarDeclEq() || (!var->isReference() && vnt->strAt(1) == "=")) {
const Token* nextStmt = vnt->tokAt(2);
if (nextStmt->isExpandedMacro()) {
const Token* parent = nextStmt;
while (parent->astParent() && parent == parent->astParent()->astOperand1())
parent = parent->astParent();
if (parent->isAssignmentOp() && parent->isExpandedMacro())
continue;
}
while (nextStmt && nextStmt->str() != ";")
nextStmt = nextStmt->next();
error = precedes(usage._lastAccess, nextStmt);
}
if (error) {
if (mTokenizer->isCPP() && var->isClass() &&
(!var->valueType() || var->valueType()->type == ValueType::Type::UNKNOWN_TYPE)) {
const std::string typeName = var->getTypeName();
switch (mSettings->library.getTypeCheck("unusedvar", typeName)) {
case Library::TypeCheck::def:
reportLibraryCfgError(vnt, typeName);
break;
case Library::TypeCheck::check:
break;
case Library::TypeCheck::suppress:
case Library::TypeCheck::checkFiniteLifetime:
error = false;
}
}
if (error)
unreadVariableError(vnt, varname, false);
}
}
}
}
}
void CheckUnusedVar::unusedVariableError(const Token *tok, const std::string &varname)
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable"))
return;
reportError(tok, Severity::style, "unusedVariable", "$symbol:" + varname + "\nUnused variable: $symbol", CWE563, Certainty::normal);
}
void CheckUnusedVar::allocatedButUnusedVariableError(const Token *tok, const std::string &varname)
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable"))
return;
reportError(tok, Severity::style, "unusedAllocatedMemory", "$symbol:" + varname + "\nVariable '$symbol' is allocated memory that is never used.", CWE563, Certainty::normal);
}
void CheckUnusedVar::unreadVariableError(const Token *tok, const std::string &varname, bool modified)
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable"))
return;
if (modified)
reportError(tok, Severity::style, "unreadVariable", "$symbol:" + varname + "\nVariable '$symbol' is modified but its new value is never used.", CWE563, Certainty::normal);
else
reportError(tok, Severity::style, "unreadVariable", "$symbol:" + varname + "\nVariable '$symbol' is assigned a value that is never used.", CWE563, Certainty::normal);
}
void CheckUnusedVar::unassignedVariableError(const Token *tok, const std::string &varname)
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable"))
return;
reportError(tok, Severity::style, "unassignedVariable", "$symbol:" + varname + "\nVariable '$symbol' is not assigned a value.", CWE665, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check that all struct members are used
//---------------------------------------------------------------------------
void CheckUnusedVar::checkStructMemberUsage()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedStructMember") && !mSettings->isPremiumEnabled("unusedVariable"))
return;
logChecker("CheckUnusedVar::checkStructMemberUsage"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eStruct && scope.type != Scope::eClass && scope.type != Scope::eUnion)
continue;
if (scope.bodyStart->fileIndex() != 0 || scope.className.empty())
continue;
if (scope.classDef->isExpandedMacro())
continue;
// Packed struct => possibly used by lowlevel code. Struct members might be required by hardware.
if (scope.bodyEnd->isAttributePacked())
continue;
if (mTokenizer->isPacked(scope.bodyStart))
continue;
// Bail out for template struct, members might be used in non-matching instantiations
if (scope.className.find('<') != std::string::npos)
continue;
// bail out if struct is inherited
const bool isInherited = std::any_of(symbolDatabase->scopeList.cbegin(), symbolDatabase->scopeList.cend(), [&](const Scope& derivedScope) {
const Type* dType = derivedScope.definedType;
return dType && std::any_of(dType->derivedFrom.cbegin(), dType->derivedFrom.cend(), [&](const Type::BaseInfo& derivedFrom) {
return derivedFrom.type == scope.definedType && derivedFrom.access != AccessControl::Private;
});
});
// bail out for extern/global struct
bool bailout = false;
for (const Variable* var : symbolDatabase->variableList()) {
if (var && (var->isExtern() || (var->isGlobal() && !var->isStatic())) && var->typeEndToken()->str() == scope.className) {
bailout = true;
break;
}
if (bailout)
break;
}
if (bailout)
continue;
// Bail out if some data is casted to struct..
const std::string castPattern("( struct| " + scope.className + " * ) &| %name%");
if (Token::findmatch(scope.bodyEnd, castPattern.c_str()))
continue;
// (struct S){..}
const std::string initPattern("( struct| " + scope.className + " ) {");
if (Token::findmatch(scope.bodyEnd, initPattern.c_str()))
continue;
// Bail out if struct is used in sizeof..
for (const Token *tok = scope.bodyEnd; nullptr != (tok = Token::findsimplematch(tok, "sizeof ("));) {
tok = tok->tokAt(2);
if (Token::Match(tok, ("struct| " + scope.className).c_str())) {
bailout = true;
break;
}
}
if (bailout)
continue;
for (const Variable &var : scope.varlist) {
// only warn for variables without side effects
if (!var.typeStartToken()->isStandardType() && !var.isPointer() && !astIsContainer(var.nameToken()) && !isRecordTypeWithoutSideEffects(var.type()))
continue;
if (isInherited && !var.isPrivate())
continue;
// Check if the struct member variable is used anywhere in the file
bool use = false;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, ". %name%") && !tok->next()->variable() && !tok->next()->function() && tok->strAt(1) == var.name()) {
// not known => assume variable is used
use = true;
break;
}
// Member referenced in offsetof
if (Token::Match(tok, ("offsetof ( struct| " + scope.className + " , %name%").c_str())) {
tok = Token::simpleMatch(tok->tokAt(2), "struct") ? tok->tokAt(5) : tok->tokAt(4);
if (tok->str() == var.name()) {
use = true;
break;
}
}
if (tok->variable() != &var)
continue;
if (tok != var.nameToken()) {
use = true;
break;
}
}
if (!use) {
std::string prefix = "struct";
if (scope.type == Scope::ScopeType::eClass)
prefix = "class";
else if (scope.type == Scope::ScopeType::eUnion)
prefix = "union";
unusedStructMemberError(var.nameToken(), scope.className, var.name(), prefix);
}
}
}
}
void CheckUnusedVar::unusedStructMemberError(const Token* tok, const std::string& structname, const std::string& varname, const std::string& prefix)
{
reportError(tok, Severity::style, "unusedStructMember", "$symbol:" + structname + "::" + varname + '\n' + prefix + " member '$symbol' is never used.", CWE563, Certainty::normal);
}
bool CheckUnusedVar::isRecordTypeWithoutSideEffects(const Type* type)
{
// a type that has no side effects (no constructors and no members with constructors)
/** @todo false negative: check constructors for side effects */
const std::pair<std::map<const Type *,bool>::iterator,bool> found=mIsRecordTypeWithoutSideEffectsMap.insert(
std::pair<const Type *,bool>(type,false)); //Initialize with side effects for possible recursions
bool & withoutSideEffects = found.first->second;
if (!found.second)
return withoutSideEffects;
// unknown types are assumed to have side effects
if (!type || !type->classScope)
return (withoutSideEffects = false);
// Non-empty constructors => possible side effects
for (const Function& f : type->classScope->functionList) {
if (!f.isConstructor() && !f.isDestructor())
continue;
if (f.argDef && Token::simpleMatch(f.argDef->link(), ") ="))
continue; // ignore default/deleted constructors
const bool emptyBody = (f.functionScope && Token::simpleMatch(f.functionScope->bodyStart, "{ }"));
const Token* nextToken = f.argDef ? f.argDef->link() : nullptr;
if (Token::simpleMatch(nextToken, ") :")) {
// validating initialization list
nextToken = nextToken->next(); // goto ":"
for (const Token *initListToken = nextToken; Token::Match(initListToken, "[:,] %var% [({]"); initListToken = initListToken->linkAt(2)->next()) {
const Token* varToken = initListToken->next();
const Variable* variable = varToken->variable();
if (variable && !isVariableWithoutSideEffects(*variable)) {
return withoutSideEffects = false;
}
const Token* valueEnd = initListToken->linkAt(2);
for (const Token* valueToken = initListToken->tokAt(3); valueToken != valueEnd; valueToken = valueToken->next()) {
const Variable* initValueVar = valueToken->variable();
if (initValueVar && !isVariableWithoutSideEffects(*initValueVar)) {
return withoutSideEffects = false;
}
if ((valueToken->tokType() == Token::Type::eName) ||
(valueToken->tokType() == Token::Type::eLambda) ||
(valueToken->tokType() == Token::Type::eOther)) {
return withoutSideEffects = false;
}
const Function* initValueFunc = valueToken->function();
if (initValueFunc && !isFunctionWithoutSideEffects(*initValueFunc, valueToken,
std::list<const Function*> {})) {
return withoutSideEffects = false;
}
}
}
}
if (!emptyBody)
return (withoutSideEffects = false);
}
// Derived from type that has side effects?
if (std::any_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [this](const Type::BaseInfo& derivedFrom) {
return !isRecordTypeWithoutSideEffects(derivedFrom.type);
}))
return (withoutSideEffects = false);
// Is there a member variable with possible side effects
for (const Variable& var : type->classScope->varlist) {
withoutSideEffects = isVariableWithoutSideEffects(var, type);
if (!withoutSideEffects) {
return withoutSideEffects;
}
}
return (withoutSideEffects = true);
}
bool CheckUnusedVar::isVariableWithoutSideEffects(const Variable& var, const Type* type)
{
const Type* variableType = var.type();
if (variableType && variableType != type) {
if (!isRecordTypeWithoutSideEffects(variableType))
return false;
} else {
if (WRONG_DATA(!var.valueType(), var.typeStartToken()))
return false;
const ValueType::Type valueType = var.valueType()->type;
if ((valueType == ValueType::Type::UNKNOWN_TYPE) || (valueType == ValueType::Type::NONSTD))
return false;
}
return true;
}
bool CheckUnusedVar::isEmptyType(const Type* type)
{
// a type that has no variables and no constructor
const std::pair<std::map<const Type *,bool>::iterator,bool> found=mIsEmptyTypeMap.insert(
std::pair<const Type *,bool>(type,false));
bool & emptyType=found.first->second;
if (!found.second)
return emptyType;
if (type && type->classScope && type->classScope->numConstructors == 0 &&
(type->classScope->varlist.empty())) {
return (emptyType = std::all_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [this](const Type::BaseInfo& bi) {
return isEmptyType(bi.type);
}));
}
// unknown types are assumed to be nonempty
return (emptyType = false);
}
bool CheckUnusedVar::isFunctionWithoutSideEffects(const Function& func, const Token* functionUsageToken,
std::list<const Function*> checkedFuncs)
{
// no body to analyze
if (!func.hasBody()) {
return false;
}
for (const Token* argsToken = functionUsageToken->next(); !Token::simpleMatch(argsToken, ")"); argsToken = argsToken->next()) {
const Variable* argVar = argsToken->variable();
if (argVar && argVar->isGlobal()) {
return false; // TODO: analyze global variable usage
}
}
bool sideEffectReturnFound = false;
std::set<const Variable*> pointersToGlobals;
for (const Token* bodyToken = func.functionScope->bodyStart->next(); bodyToken != func.functionScope->bodyEnd;
bodyToken = bodyToken->next()) {
// check variable inside function body
const Variable* bodyVariable = bodyToken->variable();
if (bodyVariable) {
if (!isVariableWithoutSideEffects(*bodyVariable)) {
return false;
}
// check if global variable is changed
if (bodyVariable->isGlobal() || (pointersToGlobals.find(bodyVariable) != pointersToGlobals.end())) {
const int indirect = bodyVariable->isArray() ? bodyVariable->dimensions().size() : bodyVariable->isPointer();
if (isVariableChanged(bodyToken, indirect, *mSettings)) {
return false;
}
// check if pointer to global variable assigned to another variable (another_var = &global_var)
if (Token::simpleMatch(bodyToken->tokAt(-1), "&") && Token::simpleMatch(bodyToken->tokAt(-2), "=")) {
const Token* assigned_var_token = bodyToken->tokAt(-3);
if (assigned_var_token && assigned_var_token->variable()) {
pointersToGlobals.insert(assigned_var_token->variable());
}
}
}
}
// check nested function
const Function* bodyFunction = bodyToken->function();
if (bodyFunction) {
if (std::find(checkedFuncs.cbegin(), checkedFuncs.cend(), bodyFunction) != checkedFuncs.cend()) { // recursion found
continue;
}
checkedFuncs.push_back(bodyFunction);
if (!isFunctionWithoutSideEffects(*bodyFunction, bodyToken, checkedFuncs)) {
return false;
}
}
// check returned value
if (Token::simpleMatch(bodyToken, "return")) {
const Token* returnValueToken = bodyToken->next();
// TODO: handle complex return expressions
if (!Token::simpleMatch(returnValueToken->next(), ";")) {
sideEffectReturnFound = true;
continue;
}
// simple one-token return
const Variable* returnVariable = returnValueToken->variable();
if (returnValueToken->isLiteral() ||
(returnVariable && isVariableWithoutSideEffects(*returnVariable))) {
continue;
}
sideEffectReturnFound = true;
}
// unknown name
if (bodyToken->isNameOnly()) {
return false;
}
}
return !sideEffectReturnFound;
}
| null |
818 | cpp | cppcheck | checkbool.cpp | lib/checkbool.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkbool.h"
#include "astutils.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckBool instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE571(571U); // Expression is Always True
static const CWE CWE587(587U); // Assignment of a Fixed Address to a Pointer
static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
static bool isBool(const Variable* var)
{
return (var && Token::Match(var->typeEndToken(), "bool|_Bool"));
}
//---------------------------------------------------------------------------
void CheckBool::checkIncrementBoolean()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("incrementboolean"))
return;
logChecker("CheckBool::checkIncrementBoolean"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (astIsBool(tok) && tok->astParent() && tok->astParent()->str() == "++") {
incrementBooleanError(tok);
}
}
}
}
void CheckBool::incrementBooleanError(const Token *tok)
{
reportError(
tok,
Severity::style,
"incrementboolean",
"Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n"
"The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value 'true' instead.",
CWE398, Certainty::normal
);
}
static bool isConvertedToBool(const Token* tok)
{
if (!tok->astParent())
return false;
return astIsBool(tok->astParent()) || Token::Match(tok->astParent()->previous(), "if|while (");
}
//---------------------------------------------------------------------------
// if (bool & bool) -> if (bool && bool)
// if (bool | bool) -> if (bool || bool)
//---------------------------------------------------------------------------
void CheckBool::checkBitwiseOnBoolean()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
// danmar: this is inconclusive because I don't like that there are
// warnings for calculations. Example: set_flag(a & b);
if (!mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckBool::checkBitwiseOnBoolean"); // style,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->isBinaryOp()) {
bool isCompound{};
if (tok->str() == "&" || tok->str() == "|")
isCompound = false;
else if (tok->str() == "&=" || tok->str() == "|=")
isCompound = true;
else
continue;
const bool isBoolOp1 = astIsBool(tok->astOperand1());
const bool isBoolOp2 = astIsBool(tok->astOperand2());
if (!tok->astOperand1()->valueType() || !tok->astOperand2()->valueType())
continue;
if (!(isBoolOp1 || isBoolOp2))
continue;
if (isCompound && (!isBoolOp1 || isBoolOp2))
continue;
if (tok->str() == "|" && !isConvertedToBool(tok) && !(isBoolOp1 && isBoolOp2))
continue;
// first operand will always be evaluated
if (!isConstExpression(tok->astOperand2(), mSettings->library))
continue;
if (tok->astOperand2()->variable() && tok->astOperand2()->variable()->nameToken() == tok->astOperand2())
continue;
const std::string expression = (isBoolOp1 ? tok->astOperand1() : tok->astOperand2())->expressionString();
bitwiseOnBooleanError(tok, expression, tok->str() == "&" ? "&&" : "||", isCompound);
}
}
}
}
void CheckBool::bitwiseOnBooleanError(const Token* tok, const std::string& expression, const std::string& op, bool isCompound)
{
std::string msg = "Boolean expression '" + expression + "' is used in bitwise operation.";
if (!isCompound)
msg += " Did you mean '" + op + "'?";
reportError(tok,
Severity::style,
"bitwiseOnBoolean",
msg,
CWE398,
Certainty::inconclusive);
}
//---------------------------------------------------------------------------
// if (!x==3) <- Probably meant to be "x!=3"
//---------------------------------------------------------------------------
void CheckBool::checkComparisonOfBoolWithInt()
{
if (!mSettings->severity.isEnabled(Severity::warning) || !mTokenizer->isCPP())
return;
logChecker("CheckBool::checkComparisonOfBoolWithInt"); // warning,c++
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp() || !tok->isBinaryOp())
continue;
const Token* const left = tok->astOperand1();
const Token* const right = tok->astOperand2();
if (left->isBoolean() && right->varId()) { // Comparing boolean constant with variable
if (tok->str() != "==" && tok->str() != "!=") {
comparisonOfBoolWithInvalidComparator(right, left->str());
}
} else if (left->varId() && right->isBoolean()) { // Comparing variable with boolean constant
if (tok->str() != "==" && tok->str() != "!=") {
comparisonOfBoolWithInvalidComparator(right, left->str());
}
}
}
}
}
void CheckBool::comparisonOfBoolWithInvalidComparator(const Token *tok, const std::string &expression)
{
reportError(tok, Severity::warning, "comparisonOfBoolWithInvalidComparator",
"Comparison of a boolean value using relational operator (<, >, <= or >=).\n"
"The result of the expression '" + expression + "' is of type 'bool'. "
"Comparing 'bool' value using relational (<, >, <= or >=)"
" operator could cause unexpected results.");
}
//-------------------------------------------------------------------------------
// Comparing functions which are returning value of type bool
//-------------------------------------------------------------------------------
static bool tokenIsFunctionReturningBool(const Token* tok)
{
const Function* func = tok ? tok->function() : nullptr;
if (func && Token::Match(tok, "%name% (")) {
if (func->tokenDef && Token::Match(func->tokenDef->previous(), "bool|_Bool")) {
return true;
}
}
return false;
}
void CheckBool::checkComparisonOfFuncReturningBool()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
if (!mTokenizer->isCPP())
return;
logChecker("CheckBool::checkComparisonOfFuncReturningBool"); // style,c++
const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
auto getFunctionTok = [](const Token* tok) -> const Token* {
while (Token::simpleMatch(tok, "!") || (tok && tok->isCast() && !isCPPCast(tok)))
tok = tok->astOperand1();
if (isCPPCast(tok))
tok = tok->astOperand2();
if (tok)
return tok->previous();
return nullptr;
};
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp() || tok->str() == "==" || tok->str() == "!=")
continue;
const Token* firstToken = getFunctionTok(tok->astOperand1());
const Token* secondToken = getFunctionTok(tok->astOperand2());
if (!firstToken || !secondToken)
continue;
const bool firstIsFunctionReturningBool = tokenIsFunctionReturningBool(firstToken);
const bool secondIsFunctionReturningBool = tokenIsFunctionReturningBool(secondToken);
if (firstIsFunctionReturningBool && secondIsFunctionReturningBool) {
comparisonOfTwoFuncsReturningBoolError(firstToken->next(), firstToken->str(), secondToken->str());
} else if (firstIsFunctionReturningBool) {
comparisonOfFuncReturningBoolError(firstToken->next(), firstToken->str());
} else if (secondIsFunctionReturningBool) {
comparisonOfFuncReturningBoolError(secondToken->previous(), secondToken->str());
}
}
}
}
void CheckBool::comparisonOfFuncReturningBoolError(const Token *tok, const std::string &expression)
{
reportError(tok, Severity::style, "comparisonOfFuncReturningBoolError",
"Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n"
"The return type of function '" + expression + "' is 'bool' "
"and result is of type 'bool'. Comparing 'bool' value using relational (<, >, <= or >=)"
" operator could cause unexpected results.", CWE398, Certainty::normal);
}
void CheckBool::comparisonOfTwoFuncsReturningBoolError(const Token *tok, const std::string &expression1, const std::string &expression2)
{
reportError(tok, Severity::style, "comparisonOfTwoFuncsReturningBoolError",
"Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n"
"The return type of function '" + expression1 + "' and function '" + expression2 + "' is 'bool' "
"and result is of type 'bool'. Comparing 'bool' value using relational (<, >, <= or >=)"
" operator could cause unexpected results.", CWE398, Certainty::normal);
}
//-------------------------------------------------------------------------------
// Comparison of bool with bool
//-------------------------------------------------------------------------------
void CheckBool::checkComparisonOfBoolWithBool()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
if (!mTokenizer->isCPP())
return;
logChecker("CheckBool::checkComparisonOfBoolWithBool"); // style,c++
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp() || tok->str() == "==" || tok->str() == "!=")
continue;
bool firstTokenBool = false;
const Token *firstToken = tok->previous();
if (firstToken->varId()) {
if (isBool(firstToken->variable())) {
firstTokenBool = true;
}
}
if (!firstTokenBool)
continue;
bool secondTokenBool = false;
const Token *secondToken = tok->next();
if (secondToken->varId()) {
if (isBool(secondToken->variable())) {
secondTokenBool = true;
}
}
if (secondTokenBool) {
comparisonOfBoolWithBoolError(firstToken->next(), secondToken->str());
}
}
}
}
void CheckBool::comparisonOfBoolWithBoolError(const Token *tok, const std::string &expression)
{
reportError(tok, Severity::style, "comparisonOfBoolWithBoolError",
"Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n"
"The variable '" + expression + "' is of type 'bool' "
"and comparing 'bool' value using relational (<, >, <= or >=)"
" operator could cause unexpected results.", CWE398, Certainty::normal);
}
//-----------------------------------------------------------------------------
void CheckBool::checkAssignBoolToPointer()
{
logChecker("CheckBool::checkAssignBoolToPointer");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "=" && astIsPointer(tok->astOperand1()) && astIsBool(tok->astOperand2())) {
assignBoolToPointerError(tok);
}
}
}
}
void CheckBool::assignBoolToPointerError(const Token *tok)
{
reportError(tok, Severity::error, "assignBoolToPointer",
"Boolean value assigned to pointer.", CWE587, Certainty::normal);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CheckBool::checkComparisonOfBoolExpressionWithInt()
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("compareBoolExpressionWithInt"))
return;
logChecker("CheckBool::checkComparisonOfBoolExpressionWithInt"); // warning
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp())
continue;
const Token* numTok = nullptr;
const Token* boolExpr = nullptr;
bool numInRhs;
if (astIsBool(tok->astOperand1())) {
boolExpr = tok->astOperand1();
numTok = tok->astOperand2();
numInRhs = true;
} else if (astIsBool(tok->astOperand2())) {
boolExpr = tok->astOperand2();
numTok = tok->astOperand1();
numInRhs = false;
} else {
continue;
}
if (!numTok || !boolExpr)
continue;
if (boolExpr->isOp() && numTok->isName() && Token::Match(tok, "==|!="))
// there is weird code such as: ((a<b)==c)
// but it is probably written this way by design.
continue;
if (astIsBool(numTok))
continue;
const ValueFlow::Value *minval = numTok->getValueLE(0, *mSettings);
if (minval && minval->intvalue == 0 &&
(numInRhs ? Token::Match(tok, ">|==|!=")
: Token::Match(tok, "<|==|!=")))
minval = nullptr;
const ValueFlow::Value *maxval = numTok->getValueGE(1, *mSettings);
if (maxval && maxval->intvalue == 1 &&
(numInRhs ? Token::Match(tok, "<|==|!=")
: Token::Match(tok, ">|==|!=")))
maxval = nullptr;
if (minval || maxval) {
const bool not0or1 = (minval && minval->intvalue < 0) || (maxval && maxval->intvalue > 1);
comparisonOfBoolExpressionWithIntError(tok, not0or1);
}
}
}
}
void CheckBool::comparisonOfBoolExpressionWithIntError(const Token *tok, bool not0or1)
{
if (not0or1)
reportError(tok, Severity::warning, "compareBoolExpressionWithInt",
"Comparison of a boolean expression with an integer other than 0 or 1.", CWE398, Certainty::normal);
else
reportError(tok, Severity::warning, "compareBoolExpressionWithInt",
"Comparison of a boolean expression with an integer.", CWE398, Certainty::normal);
}
void CheckBool::pointerArithBool()
{
logChecker("CheckBool::pointerArithBool");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf && !scope.isLoopScope())
continue;
const Token* tok = scope.classDef->next()->astOperand2();
if (scope.type == Scope::eFor) {
tok = Token::findsimplematch(scope.classDef->tokAt(2), ";");
if (tok)
tok = tok->astOperand2();
if (tok)
tok = tok->astOperand1();
} else if (scope.type == Scope::eDo)
tok = (scope.bodyEnd->tokAt(2)) ? scope.bodyEnd->tokAt(2)->astOperand2() : nullptr;
pointerArithBoolCond(tok);
}
}
void CheckBool::pointerArithBoolCond(const Token *tok)
{
if (!tok)
return;
if (Token::Match(tok, "&&|%oror%")) {
pointerArithBoolCond(tok->astOperand1());
pointerArithBoolCond(tok->astOperand2());
return;
}
if (tok->str() != "+" && tok->str() != "-")
return;
if (tok->isBinaryOp() &&
tok->astOperand1()->isName() &&
tok->astOperand1()->variable() &&
tok->astOperand1()->variable()->isPointer() &&
tok->astOperand2()->isNumber())
pointerArithBoolError(tok);
}
void CheckBool::pointerArithBoolError(const Token *tok)
{
reportError(tok,
Severity::error,
"pointerArithBool",
"Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n"
"Converting pointer arithmetic result to bool. The boolean result is always true unless there is pointer arithmetic overflow, and overflow is undefined behaviour. Probably a dereference is forgotten.", CWE571, Certainty::normal);
}
void CheckBool::checkAssignBoolToFloat()
{
if (!mTokenizer->isCPP())
return;
if (!mSettings->severity.isEnabled(Severity::style))
return;
logChecker("CheckBool::checkAssignBoolToFloat"); // style,c++
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "=" && astIsFloat(tok->astOperand1(), false) && astIsBool(tok->astOperand2())) {
assignBoolToFloatError(tok);
}
}
}
}
void CheckBool::assignBoolToFloatError(const Token *tok)
{
reportError(tok, Severity::style, "assignBoolToFloat",
"Boolean value assigned to floating point variable.", CWE704, Certainty::normal);
}
void CheckBool::returnValueOfFunctionReturningBool()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
logChecker("CheckBool::returnValueOfFunctionReturningBool"); // style
const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
if (!(scope->function && Token::Match(scope->function->retDef, "bool|_Bool")))
continue;
for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) {
// Skip lambdas
const Token* tok2 = findLambdaEndToken(tok);
if (tok2)
tok = tok2;
else if (tok->scope() && tok->scope()->isClassOrStruct())
tok = tok->scope()->bodyEnd;
else if (Token::simpleMatch(tok, "return") && tok->astOperand1() &&
(tok->astOperand1()->getValueGE(2, *mSettings) || tok->astOperand1()->getValueLE(-1, *mSettings)) &&
!(tok->astOperand1()->astOperand1() && Token::Match(tok->astOperand1(), "&|%or%")))
returnValueBoolError(tok);
}
}
}
void CheckBool::returnValueBoolError(const Token *tok)
{
reportError(tok, Severity::style, "returnNonBoolInBooleanFunction", "Non-boolean value returned from function returning bool");
}
| null |
819 | cpp | cppcheck | clangimport.h | lib/clangimport.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef clangimportH
#define clangimportH
//---------------------------------------------------------------------------
#include "config.h"
#include <istream>
class Tokenizer;
namespace clangimport {
void CPPCHECKLIB parseClangAstDump(Tokenizer &tokenizer, std::istream &f);
}
#endif
| null |
820 | cpp | cppcheck | analyzerinfo.h | lib/analyzerinfo.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef analyzerinfoH
#define analyzerinfoH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstddef>
#include <fstream>
#include <list>
#include <string>
class ErrorMessage;
struct FileSettings;
/// @addtogroup Core
/// @{
/**
* @brief Analyzer information
*
* Store various analysis information:
* - checksum
* - error messages
* - whole program analysis data
*
* The information can be used for various purposes. It allows:
* - 'make' - only analyze TUs that are changed and generate full report
* - should be possible to add distributed analysis later
* - multi-threaded whole program analysis
*/
class CPPCHECKLIB AnalyzerInformation {
public:
~AnalyzerInformation();
static void writeFilesTxt(const std::string &buildDir, const std::list<std::string> &sourcefiles, const std::string &userDefines, const std::list<FileSettings> &fileSettings);
/** Close current TU.analyzerinfo file */
void close();
bool analyzeFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg, std::size_t hash, std::list<ErrorMessage> &errors);
void reportErr(const ErrorMessage &msg);
void setFileInfo(const std::string &check, const std::string &fileInfo);
static std::string getAnalyzerInfoFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg);
protected:
static std::string getAnalyzerInfoFileFromFilesTxt(std::istream& filesTxt, const std::string &sourcefile, const std::string &cfg);
private:
std::ofstream mOutputStream;
std::string mAnalyzerInfoFile;
};
/// @}
//---------------------------------------------------------------------------
#endif // analyzerinfoH
| null |
821 | cpp | cppcheck | preprocessor.cpp | lib/preprocessor.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "preprocessor.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "library.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "suppressions.h"
#include "utils.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <iterator>
#include <sstream>
#include <utility>
#include <simplecpp.h>
static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2)
{
return tok1 && tok2 && tok1->location.sameline(tok2->location);
}
Directive::Directive(const simplecpp::Location & _loc, std::string _str) :
file(_loc.file()),
linenr(_loc.line),
str(std::move(_str))
{}
Directive::Directive(std::string _file, const int _linenr, std::string _str) :
file(std::move(_file)),
linenr(_linenr),
str(std::move(_str))
{}
Directive::DirectiveToken::DirectiveToken(const simplecpp::Token & _tok) :
line(_tok.location.line),
column(_tok.location.col),
tokStr(_tok.str())
{}
char Preprocessor::macroChar = char(1);
Preprocessor::Preprocessor(const Settings& settings, ErrorLogger &errorLogger) : mSettings(settings), mErrorLogger(errorLogger)
{}
Preprocessor::~Preprocessor()
{
for (const std::pair<const std::string, simplecpp::TokenList*>& tokenList : mTokenLists)
delete tokenList.second;
}
namespace {
struct BadInlineSuppression {
BadInlineSuppression(std::string file, const int line, std::string msg) : file(std::move(file)), line(line), errmsg(std::move(msg)) {}
std::string file;
int line;
std::string errmsg;
};
}
static bool parseInlineSuppressionCommentToken(const simplecpp::Token *tok, std::list<SuppressionList::Suppression> &inlineSuppressions, std::list<BadInlineSuppression> &bad)
{
const std::string cppchecksuppress("cppcheck-suppress");
const std::string &comment = tok->str();
if (comment.size() < cppchecksuppress.size())
return false;
const std::string::size_type pos1 = comment.find_first_not_of("/* \t");
if (pos1 == std::string::npos)
return false;
if (pos1 + cppchecksuppress.size() >= comment.size())
return false;
if (comment.substr(pos1, cppchecksuppress.size()) != cppchecksuppress)
return false;
// check if it has a prefix
const std::string::size_type posEndComment = comment.find_first_of(" [", pos1+cppchecksuppress.size());
// skip spaces after "cppcheck-suppress" and its possible prefix
const std::string::size_type pos2 = comment.find_first_not_of(' ', posEndComment);
if (pos2 == std::string::npos)
return false;
SuppressionList::Type errorType = SuppressionList::Type::unique;
// determine prefix if specified
if (posEndComment >= (pos1 + cppchecksuppress.size() + 1)) {
if (comment.at(pos1 + cppchecksuppress.size()) != '-')
return false;
const unsigned int argumentLength =
posEndComment - (pos1 + cppchecksuppress.size() + 1);
const std::string suppressTypeString =
comment.substr(pos1 + cppchecksuppress.size() + 1, argumentLength);
if ("file" == suppressTypeString)
errorType = SuppressionList::Type::file;
else if ("begin" == suppressTypeString)
errorType = SuppressionList::Type::blockBegin;
else if ("end" == suppressTypeString)
errorType = SuppressionList::Type::blockEnd;
else if ("macro" == suppressTypeString)
errorType = SuppressionList::Type::macro;
else
return false;
}
if (comment[pos2] == '[') {
// multi suppress format
std::string errmsg;
std::vector<SuppressionList::Suppression> suppressions = SuppressionList::parseMultiSuppressComment(comment, &errmsg);
for (SuppressionList::Suppression &s : suppressions) {
s.type = errorType;
s.lineNumber = tok->location.line;
}
if (!errmsg.empty())
bad.emplace_back(tok->location.file(), tok->location.line, std::move(errmsg));
std::copy_if(suppressions.cbegin(), suppressions.cend(), std::back_inserter(inlineSuppressions), [](const SuppressionList::Suppression& s) {
return !s.errorId.empty();
});
} else {
//single suppress format
std::string errmsg;
SuppressionList::Suppression s;
if (!s.parseComment(comment, &errmsg))
return false;
s.type = errorType;
s.lineNumber = tok->location.line;
if (!s.errorId.empty())
inlineSuppressions.push_back(std::move(s));
if (!errmsg.empty())
bad.emplace_back(tok->location.file(), tok->location.line, std::move(errmsg));
}
return true;
}
static std::string getRelativeFilename(const simplecpp::Token* tok, const Settings &settings) {
std::string relativeFilename(tok->location.file());
if (settings.relativePaths) {
for (const std::string & basePath : settings.basePaths) {
const std::string bp = basePath + "/";
if (relativeFilename.compare(0,bp.size(),bp)==0) {
relativeFilename = relativeFilename.substr(bp.size());
}
}
}
return Path::simplifyPath(std::move(relativeFilename));
}
static void addInlineSuppressions(const simplecpp::TokenList &tokens, const Settings &settings, SuppressionList &suppressions, std::list<BadInlineSuppression> &bad)
{
std::list<SuppressionList::Suppression> inlineSuppressionsBlockBegin;
bool onlyComments = true;
for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) {
if (!tok->comment) {
onlyComments = false;
continue;
}
std::list<SuppressionList::Suppression> inlineSuppressions;
if (!parseInlineSuppressionCommentToken(tok, inlineSuppressions, bad))
continue;
if (!sameline(tok->previous, tok)) {
// find code after comment..
if (tok->next) {
tok = tok->next;
while (tok->comment) {
parseInlineSuppressionCommentToken(tok, inlineSuppressions, bad);
if (tok->next) {
tok = tok->next;
} else {
break;
}
}
}
}
if (inlineSuppressions.empty())
continue;
// It should never happen
if (!tok)
continue;
// Relative filename
const std::string relativeFilename = getRelativeFilename(tok, settings);
// Macro name
std::string macroName;
if (tok->str() == "#" && tok->next && tok->next->str() == "define") {
const simplecpp::Token *macroNameTok = tok->next->next;
if (sameline(tok, macroNameTok) && macroNameTok->name) {
macroName = macroNameTok->str();
}
}
// Add the suppressions.
for (SuppressionList::Suppression &suppr : inlineSuppressions) {
suppr.fileName = relativeFilename;
if (SuppressionList::Type::blockBegin == suppr.type)
{
inlineSuppressionsBlockBegin.push_back(std::move(suppr));
} else if (SuppressionList::Type::blockEnd == suppr.type) {
bool throwError = true;
if (!inlineSuppressionsBlockBegin.empty()) {
const SuppressionList::Suppression lastBeginSuppression = inlineSuppressionsBlockBegin.back();
auto supprBegin = inlineSuppressionsBlockBegin.begin();
while (supprBegin != inlineSuppressionsBlockBegin.end())
{
if (lastBeginSuppression.lineNumber != supprBegin->lineNumber) {
++supprBegin;
continue;
}
if (suppr.symbolName == supprBegin->symbolName && suppr.lineNumber > supprBegin->lineNumber) {
suppr.lineBegin = supprBegin->lineNumber;
suppr.lineEnd = suppr.lineNumber;
suppr.lineNumber = supprBegin->lineNumber;
suppr.type = SuppressionList::Type::block;
inlineSuppressionsBlockBegin.erase(supprBegin);
suppressions.addSuppression(std::move(suppr));
throwError = false;
break;
}
++supprBegin;
}
}
if (throwError) {
// NOLINTNEXTLINE(bugprone-use-after-move) - moved only when thrownError is false
bad.emplace_back(suppr.fileName, suppr.lineNumber, "Suppress End: No matching begin");
}
} else if (SuppressionList::Type::unique == suppr.type || suppr.type == SuppressionList::Type::macro) {
// special handling when suppressing { warnings for backwards compatibility
const bool thisAndNextLine = tok->previous &&
tok->previous->previous &&
tok->next &&
!sameline(tok->previous->previous, tok->previous) &&
tok->location.line + 1 == tok->next->location.line &&
tok->location.fileIndex == tok->next->location.fileIndex &&
tok->previous->str() == "{";
suppr.thisAndNextLine = thisAndNextLine;
suppr.lineNumber = tok->location.line;
suppr.macroName = macroName;
suppressions.addSuppression(std::move(suppr));
} else if (SuppressionList::Type::file == suppr.type) {
if (onlyComments)
suppressions.addSuppression(std::move(suppr));
else
bad.emplace_back(suppr.fileName, suppr.lineNumber, "File suppression should be at the top of the file");
}
}
}
for (const SuppressionList::Suppression & suppr: inlineSuppressionsBlockBegin)
// cppcheck-suppress useStlAlgorithm
bad.emplace_back(suppr.fileName, suppr.lineNumber, "Suppress Begin: No matching end");
}
void Preprocessor::inlineSuppressions(const simplecpp::TokenList &tokens, SuppressionList &suppressions)
{
if (!mSettings.inlineSuppressions)
return;
std::list<BadInlineSuppression> err;
::addInlineSuppressions(tokens, mSettings, suppressions, err);
for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) {
if (it->second)
::addInlineSuppressions(*it->second, mSettings, suppressions, err);
}
for (const BadInlineSuppression &bad : err) {
error(bad.file, bad.line, bad.errmsg);
}
}
std::vector<RemarkComment> Preprocessor::getRemarkComments(const simplecpp::TokenList &tokens) const
{
std::vector<RemarkComment> ret;
addRemarkComments(tokens, ret);
for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) {
if (it->second)
addRemarkComments(*it->second, ret);
}
return ret;
}
std::list<Directive> Preprocessor::createDirectives(const simplecpp::TokenList &tokens) const
{
// directive list..
std::list<Directive> directives;
std::vector<const simplecpp::TokenList *> list;
list.reserve(1U + mTokenLists.size());
list.push_back(&tokens);
for (std::map<std::string, simplecpp::TokenList *>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) {
list.push_back(it->second);
}
for (const simplecpp::TokenList *tokenList : list) {
for (const simplecpp::Token *tok = tokenList->cfront(); tok; tok = tok->next) {
if ((tok->op != '#') || (tok->previous && tok->previous->location.line == tok->location.line))
continue;
if (tok->next && tok->next->str() == "endfile")
continue;
Directive directive(tok->location, emptyString);
for (const simplecpp::Token *tok2 = tok; tok2 && tok2->location.line == directive.linenr; tok2 = tok2->next) {
if (tok2->comment)
continue;
if (!directive.str.empty() && (tok2->location.col > tok2->previous->location.col + tok2->previous->str().size()))
directive.str += ' ';
if (directive.str == "#" && tok2->str() == "file")
directive.str += "include";
else
directive.str += tok2->str();
directive.strTokens.emplace_back(*tok2);
}
directives.push_back(std::move(directive));
}
}
return directives;
}
static std::string readcondition(const simplecpp::Token *iftok, const std::set<std::string> &defined, const std::set<std::string> &undefined)
{
const simplecpp::Token *cond = iftok->next;
if (!sameline(iftok,cond))
return "";
const simplecpp::Token *next1 = cond->next;
const simplecpp::Token *next2 = next1 ? next1->next : nullptr;
const simplecpp::Token *next3 = next2 ? next2->next : nullptr;
unsigned int len = 1;
if (sameline(iftok,next1))
len = 2;
if (sameline(iftok,next2))
len = 3;
if (sameline(iftok,next3))
len = 4;
if (len == 1 && cond->str() == "0")
return "0";
if (len == 1 && cond->name) {
if (defined.find(cond->str()) == defined.end())
return cond->str();
}
if (len == 2 && cond->op == '!' && next1->name) {
if (defined.find(next1->str()) == defined.end())
return next1->str() + "=0";
}
if (len == 3 && cond->op == '(' && next1->name && next2->op == ')') {
if (defined.find(next1->str()) == defined.end() && undefined.find(next1->str()) == undefined.end())
return next1->str();
}
if (len == 3 && cond->name && next1->str() == "==" && next2->number) {
if (defined.find(cond->str()) == defined.end())
return cond->str() + '=' + cond->next->next->str();
}
std::set<std::string> configset;
for (; sameline(iftok,cond); cond = cond->next) {
if (cond->op == '!') {
if (!sameline(iftok,cond->next) || !cond->next->name)
break;
if (cond->next->str() == "defined")
continue;
configset.insert(cond->next->str() + "=0");
continue;
}
if (cond->str() != "defined")
continue;
const simplecpp::Token *dtok = cond->next;
if (!dtok)
break;
if (dtok->op == '(')
dtok = dtok->next;
if (sameline(iftok,dtok) && dtok->name && defined.find(dtok->str()) == defined.end() && undefined.find(dtok->str()) == undefined.end())
configset.insert(dtok->str());
}
std::string cfgStr;
for (const std::string &s : configset) {
if (!cfgStr.empty())
cfgStr += ';';
cfgStr += s;
}
return cfgStr;
}
static bool hasDefine(const std::string &userDefines, const std::string &cfg)
{
if (cfg.empty()) {
return false;
}
std::string::size_type pos = 0;
while (pos < userDefines.size()) {
pos = userDefines.find(cfg, pos);
if (pos == std::string::npos)
break;
const std::string::size_type pos2 = pos + cfg.size();
if ((pos == 0 || userDefines[pos-1U] == ';') && (pos2 == userDefines.size() || userDefines[pos2] == '='))
return true;
pos = pos2;
}
return false;
}
static std::string cfg(const std::vector<std::string> &configs, const std::string &userDefines)
{
std::set<std::string> configs2(configs.cbegin(), configs.cend());
std::string ret;
for (const std::string &c : configs2) {
if (c.empty())
continue;
if (c == "0")
return "";
if (hasDefine(userDefines, c))
continue;
if (!ret.empty())
ret += ';';
ret += c;
}
return ret;
}
static bool isUndefined(const std::string &cfg, const std::set<std::string> &undefined)
{
for (std::string::size_type pos1 = 0U; pos1 < cfg.size();) {
const std::string::size_type pos2 = cfg.find(';',pos1);
const std::string def = (pos2 == std::string::npos) ? cfg.substr(pos1) : cfg.substr(pos1, pos2 - pos1);
const std::string::size_type eq = def.find('=');
if (eq == std::string::npos && undefined.find(def) != undefined.end())
return true;
if (eq != std::string::npos && undefined.find(def.substr(0,eq)) != undefined.end() && def.substr(eq) != "=0")
return true;
pos1 = (pos2 == std::string::npos) ? pos2 : pos2 + 1U;
}
return false;
}
static bool getConfigsElseIsFalse(const std::vector<std::string> &configs_if, const std::string &userDefines)
{
return std::any_of(configs_if.cbegin(), configs_if.cend(),
[&](const std::string &cfg) {
return hasDefine(userDefines, cfg);
});
}
static const simplecpp::Token *gotoEndIf(const simplecpp::Token *cmdtok)
{
int level = 0;
while (nullptr != (cmdtok = cmdtok->next)) {
if (cmdtok->op == '#' && !sameline(cmdtok->previous,cmdtok) && sameline(cmdtok, cmdtok->next)) {
if (startsWith(cmdtok->next->str(),"if"))
++level;
else if (cmdtok->next->str() == "endif") {
--level;
if (level < 0)
return cmdtok;
}
}
}
return nullptr;
}
static void getConfigs(const simplecpp::TokenList &tokens, std::set<std::string> &defined, const std::string &userDefines, const std::set<std::string> &undefined, std::set<std::string> &ret)
{
std::vector<std::string> configs_if;
std::vector<std::string> configs_ifndef;
std::string elseError;
for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) {
if (tok->op != '#' || sameline(tok->previous, tok))
continue;
const simplecpp::Token *cmdtok = tok->next;
if (!sameline(tok, cmdtok))
continue;
if (cmdtok->str() == "ifdef" || cmdtok->str() == "ifndef" || cmdtok->str() == "if") {
std::string config;
if (cmdtok->str() == "ifdef" || cmdtok->str() == "ifndef") {
const simplecpp::Token *expr1 = cmdtok->next;
if (sameline(tok,expr1) && expr1->name && !sameline(tok,expr1->next))
config = expr1->str();
if (defined.find(config) != defined.end())
config.clear();
} else if (cmdtok->str() == "if") {
config = readcondition(cmdtok, defined, undefined);
}
// skip undefined configurations..
if (isUndefined(config, undefined))
config.clear();
bool ifndef = false;
if (cmdtok->str() == "ifndef")
ifndef = true;
else {
const std::array<std::string, 6> match{"if", "!", "defined", "(", config, ")"};
std::size_t i = 0;
ifndef = true;
for (const simplecpp::Token *t = cmdtok; i < match.size(); t = t->next) {
if (!t || t->str() != match[i++]) {
ifndef = false;
break;
}
}
}
// include guard..
if (ifndef && tok->location.fileIndex > 0) {
bool includeGuard = true;
for (const simplecpp::Token *t = tok->previous; t; t = t->previous) {
if (t->location.fileIndex == tok->location.fileIndex) {
includeGuard = false;
break;
}
}
if (includeGuard) {
configs_if.emplace_back(/*std::string()*/);
configs_ifndef.emplace_back(/*std::string()*/);
continue;
}
}
configs_if.push_back((cmdtok->str() == "ifndef") ? std::string() : config);
configs_ifndef.push_back((cmdtok->str() == "ifndef") ? std::move(config) : std::string());
ret.insert(cfg(configs_if,userDefines));
} else if (cmdtok->str() == "elif" || cmdtok->str() == "else") {
if (getConfigsElseIsFalse(configs_if,userDefines)) {
tok = gotoEndIf(tok);
if (!tok)
break;
tok = tok->previous;
continue;
}
if (cmdtok->str() == "else" &&
cmdtok->next &&
!sameline(cmdtok,cmdtok->next) &&
sameline(cmdtok->next, cmdtok->next->next) &&
cmdtok->next->op == '#' &&
cmdtok->next->next->str() == "error") {
const std::string &ifcfg = cfg(configs_if, userDefines);
if (!ifcfg.empty()) {
if (!elseError.empty())
elseError += ';';
elseError += ifcfg;
}
}
if (!configs_if.empty())
configs_if.pop_back();
if (cmdtok->str() == "elif") {
std::string config = readcondition(cmdtok, defined, undefined);
if (isUndefined(config,undefined))
config.clear();
configs_if.push_back(std::move(config));
ret.insert(cfg(configs_if, userDefines));
} else if (!configs_ifndef.empty()) {
configs_if.push_back(configs_ifndef.back());
ret.insert(cfg(configs_if, userDefines));
}
} else if (cmdtok->str() == "endif" && !sameline(tok, cmdtok->next)) {
if (!configs_if.empty())
configs_if.pop_back();
if (!configs_ifndef.empty())
configs_ifndef.pop_back();
} else if (cmdtok->str() == "error") {
if (!configs_ifndef.empty() && !configs_ifndef.back().empty()) {
if (configs_ifndef.size() == 1U)
ret.erase(emptyString);
std::vector<std::string> configs(configs_if);
configs.push_back(configs_ifndef.back());
ret.erase(cfg(configs, userDefines));
std::set<std::string> temp;
temp.swap(ret);
for (const std::string &c: temp) {
if (c.find(configs_ifndef.back()) != std::string::npos)
ret.insert(c);
else if (c.empty())
ret.insert("");
else
ret.insert(c + ";" + configs_ifndef.back());
}
if (!elseError.empty())
elseError += ';';
elseError += cfg(configs_ifndef, userDefines);
}
if (!configs_if.empty() && !configs_if.back().empty()) {
const std::string &last = configs_if.back();
if (last.size() > 2U && last.compare(last.size()-2U,2,"=0") == 0) {
std::vector<std::string> configs(configs_if);
ret.erase(cfg(configs, userDefines));
configs[configs.size() - 1U] = last.substr(0,last.size()-2U);
if (configs.size() == 1U)
ret.erase("");
if (!elseError.empty())
elseError += ';';
elseError += cfg(configs, userDefines);
}
}
} else if (cmdtok->str() == "define" && sameline(tok, cmdtok->next) && cmdtok->next->name) {
defined.insert(cmdtok->next->str());
}
}
if (!elseError.empty())
ret.insert(std::move(elseError));
}
std::set<std::string> Preprocessor::getConfigs(const simplecpp::TokenList &tokens) const
{
std::set<std::string> ret = { "" };
if (!tokens.cfront())
return ret;
std::set<std::string> defined = { "__cplusplus" };
::getConfigs(tokens, defined, mSettings.userDefines, mSettings.userUndefs, ret);
for (std::map<std::string, simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) {
if (!mSettings.configurationExcluded(it->first))
::getConfigs(*(it->second), defined, mSettings.userDefines, mSettings.userUndefs, ret);
}
return ret;
}
static void splitcfg(const std::string &cfg, std::list<std::string> &defines, const std::string &defaultValue)
{
for (std::string::size_type defineStartPos = 0U; defineStartPos < cfg.size();) {
const std::string::size_type defineEndPos = cfg.find(';', defineStartPos);
std::string def = (defineEndPos == std::string::npos) ? cfg.substr(defineStartPos) : cfg.substr(defineStartPos, defineEndPos - defineStartPos);
if (!defaultValue.empty() && def.find('=') == std::string::npos)
def += '=' + defaultValue;
defines.push_back(std::move(def));
if (defineEndPos == std::string::npos)
break;
defineStartPos = defineEndPos + 1U;
}
}
static simplecpp::DUI createDUI(const Settings &mSettings, const std::string &cfg, const std::string &filename)
{
// TODO: make it possible to specify platform-dependent sizes
simplecpp::DUI dui;
splitcfg(mSettings.userDefines, dui.defines, "1");
if (!cfg.empty())
splitcfg(cfg, dui.defines, emptyString);
for (const std::string &def : mSettings.library.defines()) {
const std::string::size_type pos = def.find_first_of(" (");
if (pos == std::string::npos) {
dui.defines.push_back(def);
continue;
}
std::string s = def;
if (s[pos] == ' ') {
s[pos] = '=';
} else {
s[s.find(')')+1] = '=';
}
dui.defines.push_back(std::move(s));
}
dui.undefined = mSettings.userUndefs; // -U
dui.includePaths = mSettings.includePaths; // -I
dui.includes = mSettings.userIncludes; // --include
// TODO: use mSettings.standards.stdValue instead
// TODO: error out on unknown language?
const Standards::Language lang = Path::identify(filename, mSettings.cppHeaderProbe);
if (lang == Standards::Language::CPP) {
dui.std = mSettings.standards.getCPP();
splitcfg(mSettings.platform.getLimitsDefines(Standards::getCPP(dui.std)), dui.defines, "");
}
else if (lang == Standards::Language::C) {
dui.std = mSettings.standards.getC();
splitcfg(mSettings.platform.getLimitsDefines(Standards::getC(dui.std)), dui.defines, "");
}
dui.clearIncludeCache = mSettings.clearIncludeCache;
return dui;
}
bool Preprocessor::hasErrors(const simplecpp::Output &output)
{
switch (output.type) {
case simplecpp::Output::ERROR:
case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY:
case simplecpp::Output::SYNTAX_ERROR:
case simplecpp::Output::UNHANDLED_CHAR_ERROR:
case simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND:
case simplecpp::Output::FILE_NOT_FOUND:
case simplecpp::Output::DUI_ERROR:
return true;
case simplecpp::Output::WARNING:
case simplecpp::Output::MISSING_HEADER:
case simplecpp::Output::PORTABILITY_BACKSLASH:
break;
}
return false;
}
bool Preprocessor::hasErrors(const simplecpp::OutputList &outputList)
{
const auto it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output) {
return hasErrors(output);
});
return it != outputList.cend();
}
void Preprocessor::handleErrors(const simplecpp::OutputList& outputList, bool throwError)
{
const bool showerror = (!mSettings.userDefines.empty() && !mSettings.force);
reportOutput(outputList, showerror);
if (throwError) {
const auto it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output){
return hasErrors(output);
});
if (it != outputList.cend()) {
throw *it;
}
}
}
bool Preprocessor::loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files)
{
const simplecpp::DUI dui = createDUI(mSettings, emptyString, files[0]);
simplecpp::OutputList outputList;
mTokenLists = simplecpp::load(rawtokens, files, dui, &outputList);
handleErrors(outputList, false);
return !hasErrors(outputList);
}
void Preprocessor::removeComments(simplecpp::TokenList &tokens)
{
tokens.removeComments();
for (std::pair<const std::string, simplecpp::TokenList*>& tokenList : mTokenLists) {
if (tokenList.second)
tokenList.second->removeComments();
}
}
void Preprocessor::setPlatformInfo(simplecpp::TokenList &tokens, const Settings& settings)
{
tokens.sizeOfType["bool"] = settings.platform.sizeof_bool;
tokens.sizeOfType["short"] = settings.platform.sizeof_short;
tokens.sizeOfType["int"] = settings.platform.sizeof_int;
tokens.sizeOfType["long"] = settings.platform.sizeof_long;
tokens.sizeOfType["long long"] = settings.platform.sizeof_long_long;
tokens.sizeOfType["float"] = settings.platform.sizeof_float;
tokens.sizeOfType["double"] = settings.platform.sizeof_double;
tokens.sizeOfType["long double"] = settings.platform.sizeof_long_double;
tokens.sizeOfType["bool *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["short *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["int *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["long *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["long long *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["float *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["double *"] = settings.platform.sizeof_pointer;
tokens.sizeOfType["long double *"] = settings.platform.sizeof_pointer;
}
simplecpp::TokenList Preprocessor::preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError)
{
const simplecpp::DUI dui = createDUI(mSettings, cfg, files[0]);
simplecpp::OutputList outputList;
std::list<simplecpp::MacroUsage> macroUsage;
std::list<simplecpp::IfCond> ifCond;
simplecpp::TokenList tokens2(files);
simplecpp::preprocess(tokens2, tokens1, files, mTokenLists, dui, &outputList, ¯oUsage, &ifCond);
mMacroUsage = std::move(macroUsage);
mIfCond = std::move(ifCond);
handleErrors(outputList, throwError);
tokens2.removeComments();
return tokens2;
}
std::string Preprocessor::getcode(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, const bool writeLocations)
{
simplecpp::TokenList tokens2 = preprocess(tokens1, cfg, files, false);
unsigned int prevfile = 0;
unsigned int line = 1;
std::ostringstream ret;
for (const simplecpp::Token *tok = tokens2.cfront(); tok; tok = tok->next) {
if (writeLocations && tok->location.fileIndex != prevfile) {
ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n";
prevfile = tok->location.fileIndex;
line = tok->location.line;
}
if (tok->previous && line >= tok->location.line) // #7912
ret << ' ';
while (tok->location.line > line) {
ret << '\n';
line++;
}
if (!tok->macro.empty())
ret << Preprocessor::macroChar;
ret << tok->str();
}
return ret.str();
}
void Preprocessor::reportOutput(const simplecpp::OutputList &outputList, bool showerror)
{
for (const simplecpp::Output &out : outputList) {
switch (out.type) {
case simplecpp::Output::ERROR:
if (!startsWith(out.msg,"#error") || showerror)
error(out.location.file(), out.location.line, out.msg);
break;
case simplecpp::Output::WARNING:
case simplecpp::Output::PORTABILITY_BACKSLASH:
break;
case simplecpp::Output::MISSING_HEADER: {
const std::string::size_type pos1 = out.msg.find_first_of("<\"");
const std::string::size_type pos2 = out.msg.find_first_of(">\"", pos1 + 1U);
if (pos1 < pos2 && pos2 != std::string::npos)
missingInclude(out.location.file(), out.location.line, out.msg.substr(pos1+1, pos2-pos1-1), out.msg[pos1] == '\"' ? UserHeader : SystemHeader);
}
break;
case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY:
case simplecpp::Output::SYNTAX_ERROR:
case simplecpp::Output::UNHANDLED_CHAR_ERROR:
error(out.location.file(), out.location.line, out.msg);
break;
case simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND:
case simplecpp::Output::FILE_NOT_FOUND:
case simplecpp::Output::DUI_ERROR:
error(emptyString, 0, out.msg);
break;
}
}
}
void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg)
{
std::list<ErrorMessage::FileLocation> locationList;
if (!filename.empty()) {
std::string file = Path::fromNativeSeparators(filename);
if (mSettings.relativePaths)
file = Path::getRelativePath(file, mSettings.basePaths);
locationList.emplace_back(file, linenr, 0);
}
mErrorLogger.reportErr(ErrorMessage(std::move(locationList),
mFile0,
Severity::error,
msg,
"preprocessorErrorDirective",
Certainty::normal));
}
// Report that include is missing
void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType)
{
if (!mSettings.checks.isEnabled(Checks::missingInclude))
return;
std::list<ErrorMessage::FileLocation> locationList;
if (!filename.empty()) {
locationList.emplace_back(filename, linenr, 0);
}
ErrorMessage errmsg(std::move(locationList), mFile0, Severity::information,
(headerType==SystemHeader) ?
"Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results." :
"Include file: \"" + header + "\" not found.",
(headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
void Preprocessor::getErrorMessages(ErrorLogger &errorLogger, const Settings &settings)
{
Preprocessor preprocessor(settings, errorLogger);
preprocessor.missingInclude(emptyString, 1, emptyString, UserHeader);
preprocessor.missingInclude(emptyString, 1, emptyString, SystemHeader);
preprocessor.error(emptyString, 1, "#error message"); // #error ..
}
void Preprocessor::dump(std::ostream &out) const
{
// Create a xml dump.
if (!mMacroUsage.empty()) {
out << " <macro-usage>" << std::endl;
for (const simplecpp::MacroUsage ¯oUsage: mMacroUsage) {
out << " <macro"
<< " name=\"" << macroUsage.macroName << "\""
<< " file=\"" << ErrorLogger::toxml(macroUsage.macroLocation.file()) << "\""
<< " line=\"" << macroUsage.macroLocation.line << "\""
<< " column=\"" << macroUsage.macroLocation.col << "\""
<< " usefile=\"" << ErrorLogger::toxml(macroUsage.useLocation.file()) << "\""
<< " useline=\"" << macroUsage.useLocation.line << "\""
<< " usecolumn=\"" << macroUsage.useLocation.col << "\""
<< " is-known-value=\"" << bool_to_string(macroUsage.macroValueKnown) << "\""
<< "/>" << std::endl;
}
out << " </macro-usage>" << std::endl;
}
if (!mIfCond.empty()) {
out << " <simplecpp-if-cond>" << std::endl;
for (const simplecpp::IfCond &ifCond: mIfCond) {
out << " <if-cond"
<< " file=\"" << ErrorLogger::toxml(ifCond.location.file()) << "\""
<< " line=\"" << ifCond.location.line << "\""
<< " column=\"" << ifCond.location.col << "\""
<< " E=\"" << ErrorLogger::toxml(ifCond.E) << "\""
<< " result=\"" << ifCond.result << "\""
<< "/>" << std::endl;
}
out << " </simplecpp-if-cond>" << std::endl;
}
}
std::size_t Preprocessor::calculateHash(const simplecpp::TokenList &tokens1, const std::string &toolinfo) const
{
std::string hashData = toolinfo;
for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) {
if (!tok->comment) {
hashData += tok->str();
hashData += static_cast<char>(tok->location.line);
hashData += static_cast<char>(tok->location.col);
}
}
for (std::map<std::string, simplecpp::TokenList *>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) {
for (const simplecpp::Token *tok = it->second->cfront(); tok; tok = tok->next) {
if (!tok->comment) {
hashData += tok->str();
hashData += static_cast<char>(tok->location.line);
hashData += static_cast<char>(tok->location.col);
}
}
}
return (std::hash<std::string>{})(hashData);
}
void Preprocessor::simplifyPragmaAsm(simplecpp::TokenList &tokenList) const
{
Preprocessor::simplifyPragmaAsmPrivate(tokenList);
for (const std::pair<const std::string, simplecpp::TokenList*>& list : mTokenLists) {
Preprocessor::simplifyPragmaAsmPrivate(*list.second);
}
}
void Preprocessor::simplifyPragmaAsmPrivate(simplecpp::TokenList &tokenList)
{
// assembler code..
for (simplecpp::Token *tok = tokenList.front(); tok; tok = tok->next) {
if (tok->op != '#')
continue;
if (sameline(tok, tok->previousSkipComments()))
continue;
const simplecpp::Token * const tok2 = tok->nextSkipComments();
if (!tok2 || !sameline(tok, tok2) || tok2->str() != "pragma")
continue;
const simplecpp::Token * const tok3 = tok2->nextSkipComments();
if (!tok3 || !sameline(tok, tok3) || tok3->str() != "asm")
continue;
const simplecpp::Token *endasm = tok3;
while ((endasm = endasm->next) != nullptr) {
if (endasm->op != '#' || sameline(endasm,endasm->previousSkipComments()))
continue;
const simplecpp::Token * const endasm2 = endasm->nextSkipComments();
if (!endasm2 || !sameline(endasm, endasm2) || endasm2->str() != "pragma")
continue;
const simplecpp::Token * const endasm3 = endasm2->nextSkipComments();
if (!endasm3 || !sameline(endasm2, endasm3) || endasm3->str() != "endasm")
continue;
while (sameline(endasm,endasm3))
endasm = endasm->next;
break;
}
const simplecpp::Token * const tok4 = tok3->next;
tok->setstr("asm");
const_cast<simplecpp::Token *>(tok2)->setstr("(");
const_cast<simplecpp::Token *>(tok3)->setstr(")");
const_cast<simplecpp::Token *>(tok4)->setstr(";");
while (tok4->next != endasm)
tokenList.deleteToken(tok4->next);
}
}
void Preprocessor::addRemarkComments(const simplecpp::TokenList &tokens, std::vector<RemarkComment> &remarkComments) const
{
for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) {
if (!tok->comment)
continue;
const std::string& comment = tok->str();
// is it a remark comment?
const std::string::size_type pos1 = comment.find_first_not_of("/* \t");
if (pos1 == std::string::npos)
continue;
const std::string::size_type pos2 = comment.find_first_of(": \t", pos1);
if (pos2 != pos1 + 6 || comment.compare(pos1, 6, "REMARK") != 0)
continue;
const std::string::size_type pos3 = comment.find_first_not_of(": \t", pos2);
if (pos3 == std::string::npos)
continue;
if (comment.compare(0,2,"/*") == 0 && pos3 + 2 >= tok->str().size())
continue;
const std::string::size_type pos4 = (comment.compare(0,2,"/*") == 0) ? comment.size()-2 : comment.size();
const std::string remarkText = comment.substr(pos3, pos4-pos3);
// Get remarked token
const simplecpp::Token* remarkedToken = nullptr;
for (const simplecpp::Token* after = tok->next; after; after = after->next) {
if (after->comment)
continue;
remarkedToken = after;
break;
}
for (const simplecpp::Token* prev = tok->previous; prev; prev = prev->previous) {
if (prev->comment)
continue;
if (sameline(prev, tok))
remarkedToken = prev;
break;
}
// Relative filename
const std::string relativeFilename = getRelativeFilename(remarkedToken, mSettings);
// Add the suppressions.
remarkComments.emplace_back(relativeFilename, remarkedToken->location.line, remarkText);
}
}
| null |
822 | cpp | cppcheck | mathlib.h | lib/mathlib.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef mathlibH
#define mathlibH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <string>
#if defined(HAVE_BOOST) && defined(HAVE_BOOST_INT128)
#include <boost/multiprecision/cpp_int.hpp>
#endif
/// @addtogroup Core
/// @{
/** @brief simple math functions that uses operands stored in std::string. useful when performing math on tokens. */
class CPPCHECKLIB MathLib {
friend class TestMathLib;
public:
#if defined(HAVE_BOOST) && defined(HAVE_BOOST_INT128)
using bigint = boost::multiprecision::int128_t;
using biguint = boost::multiprecision::uint128_t;
#else
using bigint = long long;
using biguint = unsigned long long;
#endif
/** @brief value class */
class value {
private:
bigint mIntValue{};
double mDoubleValue{};
enum class Type : std::uint8_t { INT, LONG, LONGLONG, FLOAT } mType;
bool mIsUnsigned{};
void promote(const value &v);
public:
explicit value(const std::string &s);
std::string str() const;
bool isInt() const {
return mType != Type::FLOAT;
}
bool isFloat() const {
return mType == Type::FLOAT;
}
double getDoubleValue() const {
return isFloat() ? mDoubleValue : (double)mIntValue;
}
static value calc(char op, const value &v1, const value &v2);
int compare(const value &v) const;
value add(int v) const;
value shiftLeft(const value &v) const;
value shiftRight(const value &v) const;
};
static const int bigint_bits;
/** @brief for conversion of numeric literals - for atoi-like conversions please use strToInt() */
static bigint toBigNumber(const std::string & str);
/** @brief for conversion of numeric literals - for atoi-like conversions please use strToInt() */
static biguint toBigUNumber(const std::string & str);
template<class T> static std::string toString(T value) = delete;
/** @brief for conversion of numeric literals */
static double toDoubleNumber(const std::string & str);
static bool isInt(const std::string & str);
static bool isFloat(const std::string &str);
static bool isDecimalFloat(const std::string &str);
static bool isNegative(const std::string &str);
static bool isPositive(const std::string &str);
static bool isDec(const std::string & str);
static bool isFloatHex(const std::string& str);
static bool isIntHex(const std::string& str);
static bool isOct(const std::string& str);
static bool isBin(const std::string& str);
static std::string getSuffix(const std::string& value);
/**
* Only used in unit tests
*
* \param[in] str string
* \param[in] supportMicrosoftExtensions support Microsoft extension: i64
* \return true if str is a non-empty valid integer suffix
*/
static bool isValidIntegerSuffix(const std::string& str, bool supportMicrosoftExtensions=true);
static std::string add(const std::string & first, const std::string & second);
static std::string subtract(const std::string & first, const std::string & second);
static std::string multiply(const std::string & first, const std::string & second);
static std::string divide(const std::string & first, const std::string & second);
static std::string mod(const std::string & first, const std::string & second);
static std::string calculate(const std::string & first, const std::string & second, char action);
static std::string sin(const std::string & tok);
static std::string cos(const std::string & tok);
static std::string tan(const std::string & tok);
static std::string abs(const std::string & tok);
static bool isEqual(const std::string & first, const std::string & second);
static bool isNotEqual(const std::string & first, const std::string & second);
static bool isGreater(const std::string & first, const std::string & second);
static bool isGreaterEqual(const std::string & first, const std::string & second);
static bool isLess(const std::string & first, const std::string & second);
static bool isLessEqual(const std::string & first, const std::string & second);
static bool isNullValue(const std::string & str);
/**
* Return true if given character is 0,1,2,3,4,5,6 or 7.
* @param[in] c The character to check
* @return true if given character is octal digit.
*/
static bool isOctalDigit(char c);
static unsigned int encodeMultiChar(const std::string& str);
};
MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator-(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator*(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator/(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator%(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator&(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator|(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator^(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator<<(const MathLib::value &v1, const MathLib::value &v2);
MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2);
template<> CPPCHECKLIB std::string MathLib::toString<double>(double value);
/// @}
//---------------------------------------------------------------------------
#endif // mathlibH
| null |
823 | cpp | cppcheck | checkbufferoverrun.cpp | lib/checkbufferoverrun.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Buffer overrun..
//---------------------------------------------------------------------------
#include "checkbufferoverrun.h"
#include "astutils.h"
#include "errorlogger.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include "valueflow.h"
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <iterator>
#include <numeric> // std::accumulate
#include <sstream>
#include <utility>
#include "xml.h"
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckBufferOverrun instance;
}
//---------------------------------------------------------------------------
// CWE ids used:
static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size
static const CWE CWE170(170U); // Improper Null Termination
static const CWE CWE_ARGUMENT_SIZE(398U); // Indicator of Poor Code Quality
static const CWE CWE_ARRAY_INDEX_THEN_CHECK(398U); // Indicator of Poor Code Quality
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE_POINTER_ARITHMETIC_OVERFLOW(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE_BUFFER_UNDERRUN(786U); // Access of Memory Location Before Start of Buffer
static const CWE CWE_BUFFER_OVERRUN(788U); // Access of Memory Location After End of Buffer
//---------------------------------------------------------------------------
static const ValueFlow::Value *getBufferSizeValue(const Token *tok)
{
const std::list<ValueFlow::Value> &tokenValues = tok->values();
const auto it = std::find_if(tokenValues.cbegin(), tokenValues.cend(), std::mem_fn(&ValueFlow::Value::isBufferSizeValue));
return it == tokenValues.cend() ? nullptr : &*it;
}
static int getMinFormatStringOutputLength(const std::vector<const Token*> ¶meters, nonneg int formatStringArgNr)
{
if (formatStringArgNr <= 0 || formatStringArgNr > parameters.size())
return 0;
if (parameters[formatStringArgNr - 1]->tokType() != Token::eString)
return 0;
const std::string &formatString = parameters[formatStringArgNr - 1]->str();
bool percentCharFound = false;
int outputStringSize = 0;
bool handleNextParameter = false;
std::string digits_string;
bool i_d_x_f_found = false;
int parameterLength = 0;
int inputArgNr = formatStringArgNr;
for (std::size_t i = 1; i + 1 < formatString.length(); ++i) {
if (formatString[i] == '\\') {
if (i < formatString.length() - 1 && formatString[i + 1] == '0')
break;
++outputStringSize;
++i;
continue;
}
if (percentCharFound) {
switch (formatString[i]) {
case 'f':
case 'x':
case 'X':
case 'i':
i_d_x_f_found = true;
handleNextParameter = true;
parameterLength = 1; // TODO
break;
case 'c':
case 'e':
case 'E':
case 'g':
case 'o':
case 'u':
case 'p':
case 'n':
handleNextParameter = true;
parameterLength = 1; // TODO
break;
case 'd':
i_d_x_f_found = true;
parameterLength = 1;
if (inputArgNr < parameters.size() && parameters[inputArgNr]->hasKnownIntValue())
parameterLength = std::to_string(parameters[inputArgNr]->getKnownIntValue()).length();
handleNextParameter = true;
break;
case 's':
parameterLength = 0;
if (inputArgNr < parameters.size() && parameters[inputArgNr]->tokType() == Token::eString)
parameterLength = Token::getStrLength(parameters[inputArgNr]);
handleNextParameter = true;
break;
}
}
if (formatString[i] == '%')
percentCharFound = !percentCharFound;
else if (percentCharFound) {
digits_string.append(1, formatString[i]);
}
if (!percentCharFound)
outputStringSize++;
if (handleNextParameter) {
// NOLINTNEXTLINE(cert-err34-c) - intentional use
int tempDigits = std::abs(std::atoi(digits_string.c_str()));
if (i_d_x_f_found)
tempDigits = std::max(tempDigits, 1);
if (digits_string.find('.') != std::string::npos) {
const std::string endStr = digits_string.substr(digits_string.find('.') + 1);
// NOLINTNEXTLINE(cert-err34-c) - intentional use
const int maxLen = std::max(std::abs(std::atoi(endStr.c_str())), 1);
if (formatString[i] == 's') {
// For strings, the length after the dot "%.2s" will limit
// the length of the string.
parameterLength = std::min(parameterLength, maxLen);
} else {
// For integers, the length after the dot "%.2d" can
// increase required length
tempDigits = std::max(tempDigits, maxLen);
}
}
if (tempDigits < parameterLength)
outputStringSize += parameterLength;
else
outputStringSize += tempDigits;
parameterLength = 0;
digits_string.clear();
i_d_x_f_found = false;
percentCharFound = false;
handleNextParameter = false;
++inputArgNr;
}
}
return outputStringSize;
}
//---------------------------------------------------------------------------
static bool getDimensionsEtc(const Token * const arrayToken, const Settings &settings, std::vector<Dimension> &dimensions, ErrorPath &errorPath, bool &mightBeLarger, MathLib::bigint &path)
{
const Token *array = arrayToken;
while (Token::Match(array, ".|::"))
array = array->astOperand2();
if (array->variable() && array->variable()->isArray() && !array->variable()->dimensions().empty()) {
dimensions = array->variable()->dimensions();
if (dimensions[0].num <= 1 || !dimensions[0].tok) {
visitAstNodes(arrayToken,
[&](const Token *child) {
if (child->originalName() == "->") {
mightBeLarger = true;
return ChildrenToVisit::none;
}
return ChildrenToVisit::op1_and_op2;
});
}
} else if (const Token *stringLiteral = array->getValueTokenMinStrSize(settings, &path)) {
Dimension dim;
dim.tok = nullptr;
dim.num = Token::getStrArraySize(stringLiteral);
dim.known = array->hasKnownValue();
dimensions.emplace_back(dim);
} else if (array->valueType() && array->valueType()->pointer >= 1 && (array->valueType()->isIntegral() || array->valueType()->isFloat())) {
const ValueFlow::Value *value = getBufferSizeValue(array);
if (!value)
return false;
path = value->path;
errorPath = value->errorPath;
Dimension dim;
dim.known = value->isKnown();
dim.tok = nullptr;
const MathLib::bigint typeSize = array->valueType()->typeSize(settings.platform, array->valueType()->pointer > 1);
if (typeSize == 0)
return false;
dim.num = value->intvalue / typeSize;
dimensions.emplace_back(dim);
}
return !dimensions.empty();
}
static ValueFlow::Value makeSizeValue(MathLib::bigint size, MathLib::bigint path)
{
ValueFlow::Value v(size);
v.path = path;
return v;
}
static std::vector<ValueFlow::Value> getOverrunIndexValues(const Token* tok,
const Token* arrayToken,
const std::vector<Dimension>& dimensions,
const std::vector<const Token*>& indexTokens,
MathLib::bigint path)
{
const Token *array = arrayToken;
while (Token::Match(array, ".|::"))
array = array->astOperand2();
bool isArrayIndex = tok->str() == "[";
if (isArrayIndex) {
const Token* parent = tok;
while (Token::simpleMatch(parent, "["))
parent = parent->astParent();
if (!parent || parent->isUnaryOp("&"))
isArrayIndex = false;
}
bool overflow = false;
std::vector<ValueFlow::Value> indexValues;
for (std::size_t i = 0; i < dimensions.size() && i < indexTokens.size(); ++i) {
MathLib::bigint size = dimensions[i].num;
if (!isArrayIndex)
size++;
const bool zeroArray = array->variable() && array->variable()->isArray() && dimensions[i].num == 0;
std::vector<ValueFlow::Value> values = !zeroArray
? ValueFlow::isOutOfBounds(makeSizeValue(size, path), indexTokens[i])
: std::vector<ValueFlow::Value>{};
if (values.empty()) {
if (indexTokens[i]->hasKnownIntValue())
indexValues.push_back(indexTokens[i]->values().front());
else
indexValues.push_back(ValueFlow::Value::unknown());
continue;
}
overflow = true;
indexValues.push_back(values.front());
}
if (overflow)
return indexValues;
return {};
}
void CheckBufferOverrun::arrayIndex()
{
logChecker("CheckBufferOverrun::arrayIndex");
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "[")
continue;
const Token *array = tok->astOperand1();
while (Token::Match(array, ".|::"))
array = array->astOperand2();
if (!array || ((!array->variable() || array->variable()->nameToken() == array) && array->tokType() != Token::eString))
continue;
if (!array->scope()->isExecutable()) {
// LHS in non-executable scope => This is just a definition
const Token *parent = tok;
while (parent && !Token::simpleMatch(parent->astParent(), "="))
parent = parent->astParent();
if (!parent || parent == parent->astParent()->astOperand1())
continue;
}
if (astIsContainer(array))
continue;
std::vector<const Token *> indexTokens;
for (const Token *tok2 = tok; tok2 && tok2->str() == "["; tok2 = tok2->link()->next()) {
if (!tok2->astOperand2()) {
indexTokens.clear();
break;
}
indexTokens.emplace_back(tok2->astOperand2());
}
if (indexTokens.empty())
continue;
std::vector<Dimension> dimensions;
ErrorPath errorPath;
bool mightBeLarger = false;
MathLib::bigint path = 0;
if (!getDimensionsEtc(tok->astOperand1(), *mSettings, dimensions, errorPath, mightBeLarger, path))
continue;
const Variable* const var = array->variable();
if (var && var->isArgument() && var->scope()) {
const Token* changeTok = var->scope()->bodyStart;
bool isChanged = false;
while ((changeTok = findVariableChanged(changeTok->next(), var->scope()->bodyEnd, /*indirect*/ 0, var->declarationId(),
/*globalvar*/ false, *mSettings))) {
if (!Token::simpleMatch(changeTok->astParent(), "[")) {
isChanged = true;
break;
}
}
if (isChanged)
continue;
}
// Positive index
if (!mightBeLarger) { // TODO check arrays with dim 1 also
const std::vector<ValueFlow::Value>& indexValues =
getOverrunIndexValues(tok, tok->astOperand1(), dimensions, indexTokens, path);
if (!indexValues.empty())
arrayIndexError(tok, dimensions, indexValues);
}
// Negative index
bool neg = false;
std::vector<ValueFlow::Value> negativeIndexes;
for (const Token * indexToken : indexTokens) {
const ValueFlow::Value *negativeValue = indexToken->getValueLE(-1, *mSettings);
if (negativeValue) {
negativeIndexes.emplace_back(*negativeValue);
neg = true;
} else {
negativeIndexes.emplace_back(ValueFlow::Value::unknown());
}
}
if (neg) {
negativeIndexError(tok, dimensions, negativeIndexes);
}
}
}
static std::string stringifyIndexes(const std::string& array, const std::vector<ValueFlow::Value>& indexValues)
{
if (indexValues.size() == 1)
return std::to_string(indexValues[0].intvalue);
std::ostringstream ret;
ret << array;
for (const ValueFlow::Value& index : indexValues) {
ret << "[";
if (index.isNonValue())
ret << "*";
else
ret << index.intvalue;
ret << "]";
}
return ret.str();
}
static std::string arrayIndexMessage(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexValues,
const Token* condition)
{
auto add_dim = [](const std::string &s, const Dimension &dim) {
return s + "[" + std::to_string(dim.num) + "]";
};
const std::string array = std::accumulate(dimensions.cbegin(), dimensions.cend(), tok->astOperand1()->expressionString(), std::move(add_dim));
std::ostringstream errmsg;
if (condition)
errmsg << ValueFlow::eitherTheConditionIsRedundant(condition)
<< " or the array '" << array << "' is accessed at index " << stringifyIndexes(tok->astOperand1()->expressionString(), indexValues) << ", which is out of bounds.";
else
errmsg << "Array '" << array << "' accessed at index " << stringifyIndexes(tok->astOperand1()->expressionString(), indexValues) << ", which is out of bounds.";
return errmsg.str();
}
void CheckBufferOverrun::arrayIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes)
{
if (!tok) {
reportError(tok, Severity::error, "arrayIndexOutOfBounds", "Array 'arr[16]' accessed at index 16, which is out of bounds.", CWE_BUFFER_OVERRUN, Certainty::normal);
reportError(tok, Severity::warning, "arrayIndexOutOfBoundsCond", "Array 'arr[16]' accessed at index 16, which is out of bounds.", CWE_BUFFER_OVERRUN, Certainty::normal);
return;
}
const Token *condition = nullptr;
const ValueFlow::Value *index = nullptr;
for (const ValueFlow::Value& indexValue : indexes) {
if (!indexValue.errorSeverity() && !mSettings->severity.isEnabled(Severity::warning))
return;
if (indexValue.condition)
condition = indexValue.condition;
if (!index || !indexValue.errorPath.empty())
index = &indexValue;
}
reportError(getErrorPath(tok, index, "Array index out of bounds"),
index->errorSeverity() ? Severity::error : Severity::warning,
index->condition ? "arrayIndexOutOfBoundsCond" : "arrayIndexOutOfBounds",
arrayIndexMessage(tok, dimensions, indexes, condition),
CWE_BUFFER_OVERRUN,
index->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
void CheckBufferOverrun::negativeIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes)
{
if (!tok) {
reportError(tok, Severity::error, "negativeIndex", "Negative array index", CWE_BUFFER_UNDERRUN, Certainty::normal);
return;
}
const Token *condition = nullptr;
const ValueFlow::Value *negativeValue = nullptr;
for (const ValueFlow::Value& indexValue : indexes) {
if (!indexValue.errorSeverity() && !mSettings->severity.isEnabled(Severity::warning))
return;
if (indexValue.condition)
condition = indexValue.condition;
if (!negativeValue || !indexValue.errorPath.empty())
negativeValue = &indexValue;
}
reportError(getErrorPath(tok, negativeValue, "Negative array index"),
negativeValue->errorSeverity() ? Severity::error : Severity::warning,
"negativeIndex",
arrayIndexMessage(tok, dimensions, indexes, condition),
CWE_BUFFER_UNDERRUN,
negativeValue->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
void CheckBufferOverrun::pointerArithmetic()
{
if (!mSettings->severity.isEnabled(Severity::portability) && !mSettings->isPremiumEnabled("pointerOutOfBounds"))
return;
logChecker("CheckBufferOverrun::pointerArithmetic"); // portability
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "+|-"))
continue;
if (!tok->valueType() || tok->valueType()->pointer == 0)
continue;
if (!tok->isBinaryOp())
continue;
if (!tok->astOperand1()->valueType() || !tok->astOperand2()->valueType())
continue;
const Token *arrayToken, *indexToken;
if (tok->astOperand1()->valueType()->pointer > 0) {
arrayToken = tok->astOperand1();
indexToken = tok->astOperand2();
} else {
arrayToken = tok->astOperand2();
indexToken = tok->astOperand1();
}
if (!indexToken || !indexToken->valueType() || indexToken->valueType()->pointer > 0 || !indexToken->valueType()->isIntegral())
continue;
std::vector<Dimension> dimensions;
ErrorPath errorPath;
bool mightBeLarger = false;
MathLib::bigint path = 0;
if (!getDimensionsEtc(arrayToken, *mSettings, dimensions, errorPath, mightBeLarger, path))
continue;
if (tok->str() == "+") {
// Positive index
if (!mightBeLarger) { // TODO check arrays with dim 1 also
const std::vector<const Token *> indexTokens{indexToken};
const std::vector<ValueFlow::Value>& indexValues =
getOverrunIndexValues(tok, arrayToken, dimensions, indexTokens, path);
if (!indexValues.empty() && !isUnreachableOperand(tok))
pointerArithmeticError(tok, indexToken, &indexValues.front());
}
if (const ValueFlow::Value *neg = indexToken->getValueLE(-1, *mSettings))
pointerArithmeticError(tok, indexToken, neg);
} else if (tok->str() == "-") {
if (arrayToken->variable() && arrayToken->variable()->isArgument())
continue;
const Token *array = arrayToken;
while (Token::Match(array, ".|::"))
array = array->astOperand2();
if (array->variable() && array->variable()->isArray()) {
const ValueFlow::Value *v = indexToken->getValueGE(1, *mSettings);
if (v)
pointerArithmeticError(tok, indexToken, v);
}
}
}
}
void CheckBufferOverrun::pointerArithmeticError(const Token *tok, const Token *indexToken, const ValueFlow::Value *indexValue)
{
if (!tok) {
reportError(tok, Severity::portability, "pointerOutOfBounds", "Pointer arithmetic overflow.", CWE_POINTER_ARITHMETIC_OVERFLOW, Certainty::normal);
reportError(tok, Severity::portability, "pointerOutOfBoundsCond", "Pointer arithmetic overflow.", CWE_POINTER_ARITHMETIC_OVERFLOW, Certainty::normal);
return;
}
std::string errmsg;
if (indexValue->condition)
errmsg = "Undefined behaviour, when '" + indexToken->expressionString() + "' is " + std::to_string(indexValue->intvalue) + " the pointer arithmetic '" + tok->expressionString() + "' is out of bounds.";
else
errmsg = "Undefined behaviour, pointer arithmetic '" + tok->expressionString() + "' is out of bounds.";
reportError(getErrorPath(tok, indexValue, "Pointer arithmetic overflow"),
Severity::portability,
indexValue->condition ? "pointerOutOfBoundsCond" : "pointerOutOfBounds",
errmsg,
CWE_POINTER_ARITHMETIC_OVERFLOW,
indexValue->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
ValueFlow::Value CheckBufferOverrun::getBufferSize(const Token *bufTok) const
{
if (!bufTok->valueType())
return ValueFlow::Value(-1);
const Variable *var = bufTok->variable();
if (!var || var->dimensions().empty()) {
const ValueFlow::Value *value = getBufferSizeValue(bufTok);
if (value)
return *value;
}
if (!var)
return ValueFlow::Value(-1);
const MathLib::bigint dim = std::accumulate(var->dimensions().cbegin(), var->dimensions().cend(), 1LL, [](MathLib::bigint i1, const Dimension &dim) {
return i1 * dim.num;
});
ValueFlow::Value v;
v.setKnown();
v.valueType = ValueFlow::Value::ValueType::BUFFER_SIZE;
if (var->isPointerArray())
v.intvalue = dim * mSettings->platform.sizeof_pointer;
else if (var->isPointer())
return ValueFlow::Value(-1);
else {
const MathLib::bigint typeSize = bufTok->valueType()->typeSize(mSettings->platform);
v.intvalue = dim * typeSize;
}
return v;
}
//---------------------------------------------------------------------------
static bool checkBufferSize(const Token *ftok, const Library::ArgumentChecks::MinSize &minsize, const std::vector<const Token *> &args, const MathLib::bigint bufferSize, const Settings &settings, const Tokenizer* tokenizer)
{
const Token * const arg = (minsize.arg > 0 && minsize.arg - 1 < args.size()) ? args[minsize.arg - 1] : nullptr;
const Token * const arg2 = (minsize.arg2 > 0 && minsize.arg2 - 1 < args.size()) ? args[minsize.arg2 - 1] : nullptr;
switch (minsize.type) {
case Library::ArgumentChecks::MinSize::Type::STRLEN:
if (settings.library.isargformatstr(ftok, minsize.arg)) {
return getMinFormatStringOutputLength(args, minsize.arg) < bufferSize;
} else if (arg) {
const Token *strtoken = arg->getValueTokenMaxStrLength();
if (strtoken)
return Token::getStrLength(strtoken) < bufferSize;
}
break;
case Library::ArgumentChecks::MinSize::Type::ARGVALUE: {
if (arg && arg->hasKnownIntValue()) {
MathLib::bigint myMinsize = arg->getKnownIntValue();
const int baseSize = tokenizer->sizeOfType(minsize.baseType);
if (baseSize != 0)
myMinsize *= baseSize;
return myMinsize <= bufferSize;
}
break;
}
case Library::ArgumentChecks::MinSize::Type::SIZEOF:
// TODO
break;
case Library::ArgumentChecks::MinSize::Type::MUL:
if (arg && arg2 && arg->hasKnownIntValue() && arg2->hasKnownIntValue())
return (arg->getKnownIntValue() * arg2->getKnownIntValue()) <= bufferSize;
break;
case Library::ArgumentChecks::MinSize::Type::VALUE: {
MathLib::bigint myMinsize = minsize.value;
const int baseSize = tokenizer->sizeOfType(minsize.baseType);
if (baseSize != 0)
myMinsize *= baseSize;
return myMinsize <= bufferSize;
}
case Library::ArgumentChecks::MinSize::Type::NONE:
break;
}
return true;
}
void CheckBufferOverrun::bufferOverflow()
{
logChecker("CheckBufferOverrun::bufferOverflow");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% (") || Token::simpleMatch(tok, ") {"))
continue;
if (!mSettings->library.hasminsize(tok))
continue;
const std::vector<const Token *> args = getArguments(tok);
for (int argnr = 0; argnr < args.size(); ++argnr) {
if (!args[argnr]->valueType() || args[argnr]->valueType()->pointer == 0)
continue;
const std::vector<Library::ArgumentChecks::MinSize> *minsizes = mSettings->library.argminsizes(tok, argnr + 1);
if (!minsizes || minsizes->empty())
continue;
// Get buffer size..
const Token *argtok = args[argnr];
while (argtok && argtok->isCast())
argtok = argtok->astOperand2() ? argtok->astOperand2() : argtok->astOperand1();
while (Token::Match(argtok, ".|::"))
argtok = argtok->astOperand2();
if (!argtok || !argtok->variable())
continue;
if (argtok->valueType() && argtok->valueType()->pointer == 0)
continue;
// TODO: strcpy(buf+10, "hello");
const ValueFlow::Value bufferSize = getBufferSize(argtok);
if (bufferSize.intvalue <= 0)
continue;
// buffer size == 1 => do not warn for dynamic memory
if (bufferSize.intvalue == 1 && Token::simpleMatch(argtok->astParent(), ".")) { // TODO: check if parent was allocated dynamically
const Token *tok2 = argtok;
while (Token::simpleMatch(tok2->astParent(), "."))
tok2 = tok2->astParent();
while (Token::Match(tok2, "[|."))
tok2 = tok2->astOperand1();
const Variable *var = tok2 ? tok2->variable() : nullptr;
if (var) {
if (var->isPointer())
continue;
if (var->isArgument() && var->isReference())
continue;
}
}
const bool error = std::none_of(minsizes->begin(), minsizes->end(), [&](const Library::ArgumentChecks::MinSize &minsize) {
return checkBufferSize(tok, minsize, args, bufferSize.intvalue, *mSettings, mTokenizer);
});
if (error)
bufferOverflowError(args[argnr], &bufferSize, Certainty::normal);
}
}
}
}
void CheckBufferOverrun::bufferOverflowError(const Token *tok, const ValueFlow::Value *value, Certainty certainty)
{
reportError(getErrorPath(tok, value, "Buffer overrun"), Severity::error, "bufferAccessOutOfBounds", "Buffer is accessed out of bounds: " + (tok ? tok->expressionString() : "buf"), CWE_BUFFER_OVERRUN, certainty);
}
//---------------------------------------------------------------------------
void CheckBufferOverrun::arrayIndexThenCheck()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("CheckBufferOverrun::arrayIndexThenCheck");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * const scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
tok = tok->linkAt(1);
continue;
}
if (Token::Match(tok, "%name% [ %var% ]")) {
tok = tok->next();
const int indexID = tok->next()->varId();
const std::string& indexName(tok->strAt(1));
// Iterate AST upwards
const Token* tok2 = tok;
const Token* tok3 = tok2;
while (tok2->astParent() && tok2->tokType() != Token::eLogicalOp && tok2->str() != "?") {
tok3 = tok2;
tok2 = tok2->astParent();
}
// Ensure that we ended at a logical operator and that we came from its left side
if (tok2->tokType() != Token::eLogicalOp || tok2->astOperand1() != tok3)
continue;
// check if array index is ok
// statement can be closed in parentheses, so "(| " is using
if (Token::Match(tok2, "&& (| %varid% <|<=", indexID))
arrayIndexThenCheckError(tok, indexName);
else if (Token::Match(tok2, "&& (| %any% >|>= %varid% !!+", indexID))
arrayIndexThenCheckError(tok, indexName);
}
}
}
}
void CheckBufferOverrun::arrayIndexThenCheckError(const Token *tok, const std::string &indexName)
{
reportError(tok, Severity::style, "arrayIndexThenCheck",
"$symbol:" + indexName + "\n"
"Array index '$symbol' is used before limits check.\n"
"Defensive programming: The variable '$symbol' is used as an array index before it "
"is checked that is within limits. This can mean that the array might be accessed out of bounds. "
"Reorder conditions such as '(a[i] && i < 10)' to '(i < 10 && a[i])'. That way the array will "
"not be accessed if the index is out of limits.", CWE_ARRAY_INDEX_THEN_CHECK, Certainty::normal);
}
//---------------------------------------------------------------------------
void CheckBufferOverrun::stringNotZeroTerminated()
{
// this is currently 'inconclusive'. See TestBufferOverrun::terminateStrncpy3
if (!mSettings->severity.isEnabled(Severity::warning) || !mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckBufferOverrun::stringNotZeroTerminated"); // warning,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * const scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "strncpy ("))
continue;
const std::vector<const Token *> args = getArguments(tok);
if (args.size() != 3)
continue;
const Token *sizeToken = args[2];
if (!sizeToken->hasKnownIntValue())
continue;
const ValueFlow::Value &bufferSize = getBufferSize(args[0]);
if (bufferSize.intvalue < 0 || sizeToken->getKnownIntValue() < bufferSize.intvalue)
continue;
if (Token::simpleMatch(args[1], "(") && Token::simpleMatch(args[1]->astOperand1(), ". c_str") && args[1]->astOperand1()->astOperand1()) {
const std::list<ValueFlow::Value>& contValues = args[1]->astOperand1()->astOperand1()->values();
auto it = std::find_if(contValues.cbegin(), contValues.cend(), [](const ValueFlow::Value& value) {
return value.isContainerSizeValue() && !value.isImpossible();
});
if (it != contValues.end() && it->intvalue < sizeToken->getKnownIntValue())
continue;
} else {
const Token* srcValue = args[1]->getValueTokenMaxStrLength();
if (srcValue && Token::getStrLength(srcValue) < sizeToken->getKnownIntValue())
continue;
}
// Is the buffer zero terminated after the call?
bool isZeroTerminated = false;
for (const Token *tok2 = tok->linkAt(1); tok2 != scope->bodyEnd; tok2 = tok2->next()) {
if (!Token::simpleMatch(tok2, "] ="))
continue;
const Token *rhs = tok2->next()->astOperand2();
if (!rhs || !rhs->hasKnownIntValue() || rhs->getKnownIntValue() != 0)
continue;
if (isSameExpression(false, args[0], tok2->link()->astOperand1(), *mSettings, false, false))
isZeroTerminated = true;
}
if (isZeroTerminated)
continue;
// TODO: Locate unsafe string usage..
terminateStrncpyError(tok, args[0]->expressionString());
}
}
}
void CheckBufferOverrun::terminateStrncpyError(const Token *tok, const std::string &varname)
{
const std::string shortMessage = "The buffer '$symbol' may not be null-terminated after the call to strncpy().";
reportError(tok, Severity::warning, "terminateStrncpy",
"$symbol:" + varname + '\n' +
shortMessage + '\n' +
shortMessage + ' ' +
"If the source string's size fits or exceeds the given size, strncpy() does not add a "
"zero at the end of the buffer. This causes bugs later in the code if the code "
"assumes buffer is null-terminated.", CWE170, Certainty::inconclusive);
}
//---------------------------------------------------------------------------
void CheckBufferOverrun::argumentSize()
{
// Check '%type% x[10]' arguments
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("argumentSize"))
return;
logChecker("CheckBufferOverrun::argumentSize"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * const scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->function() || !Token::Match(tok, "%name% ("))
continue;
// If argument is '%type% a[num]' then check bounds against num
const Function *callfunc = tok->function();
const std::vector<const Token *> callargs = getArguments(tok);
for (nonneg int paramIndex = 0; paramIndex < callargs.size() && paramIndex < callfunc->argCount(); ++paramIndex) {
const Variable* const argument = callfunc->getArgumentVar(paramIndex);
if (!argument || !argument->nameToken() || !argument->isArray())
continue;
if (!argument->valueType() || !callargs[paramIndex]->valueType())
continue;
if (argument->valueType()->type != callargs[paramIndex]->valueType()->type)
continue;
const Token * calldata = callargs[paramIndex];
while (Token::Match(calldata, "::|."))
calldata = calldata->astOperand2();
if (!calldata->variable() || !calldata->variable()->isArray())
continue;
if (calldata->variable()->dimensions().size() != argument->dimensions().size())
continue;
bool err = false;
for (std::size_t d = 0; d < argument->dimensions().size(); ++d) {
const auto& dim1 = calldata->variable()->dimensions()[d];
const auto& dim2 = argument->dimensions()[d];
if (!dim1.known || !dim2.known)
break;
if (dim1.num < dim2.num)
err = true;
}
if (err)
argumentSizeError(tok, tok->str(), paramIndex, callargs[paramIndex]->expressionString(), calldata->variable(), argument);
}
}
}
}
void CheckBufferOverrun::argumentSizeError(const Token *tok, const std::string &functionName, nonneg int paramIndex, const std::string ¶mExpression, const Variable *paramVar, const Variable *functionArg)
{
const std::string strParamNum = std::to_string(paramIndex + 1) + getOrdinalText(paramIndex + 1);
ErrorPath errorPath;
errorPath.emplace_back(tok, "Function '" + functionName + "' is called");
if (functionArg)
errorPath.emplace_back(functionArg->nameToken(), "Declaration of " + strParamNum + " function argument.");
if (paramVar)
errorPath.emplace_back(paramVar->nameToken(), "Passing buffer '" + paramVar->name() + "' to function that is declared here");
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::warning, "argumentSize",
"$symbol:" + functionName + '\n' +
"Buffer '" + paramExpression + "' is too small, the function '" + functionName + "' expects a bigger buffer in " + strParamNum + " argument", CWE_ARGUMENT_SIZE, Certainty::normal);
}
//---------------------------------------------------------------------------
// CTU..
//---------------------------------------------------------------------------
// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now
// see https://trac.cppcheck.net/ticket/12108 for more details
#ifdef __clang__
inline namespace CheckBufferOverrun_internal
#else
namespace
#endif
{
/** data for multifile checking */
class MyFileInfo : public Check::FileInfo {
public:
/** unsafe array index usage */
std::list<CTU::FileInfo::UnsafeUsage> unsafeArrayIndex;
/** unsafe pointer arithmetics */
std::list<CTU::FileInfo::UnsafeUsage> unsafePointerArith;
/** Convert data into xml string */
std::string toString() const override
{
std::string xml;
if (!unsafeArrayIndex.empty())
xml = " <array-index>\n" + CTU::toString(unsafeArrayIndex) + " </array-index>\n";
if (!unsafePointerArith.empty())
xml += " <pointer-arith>\n" + CTU::toString(unsafePointerArith) + " </pointer-arith>\n";
return xml;
}
};
}
bool CheckBufferOverrun::isCtuUnsafeBufferUsage(const Settings &settings, const Token *argtok, MathLib::bigint *offset, int type)
{
if (!offset)
return false;
if (!argtok->valueType() || argtok->valueType()->typeSize(settings.platform) == 0)
return false;
const Token *indexTok = nullptr;
if (type == 1 && Token::Match(argtok, "%name% [") && argtok->astParent() == argtok->next() && !Token::simpleMatch(argtok->linkAt(1), "] ["))
indexTok = argtok->next()->astOperand2();
else if (type == 2 && Token::simpleMatch(argtok->astParent(), "+"))
indexTok = (argtok == argtok->astParent()->astOperand1()) ?
argtok->astParent()->astOperand2() :
argtok->astParent()->astOperand1();
if (!indexTok)
return false;
if (!indexTok->hasKnownIntValue())
return false;
*offset = indexTok->getKnownIntValue() * argtok->valueType()->typeSize(settings.platform);
return true;
}
bool CheckBufferOverrun::isCtuUnsafeArrayIndex(const Settings &settings, const Token *argtok, MathLib::bigint *offset)
{
return isCtuUnsafeBufferUsage(settings, argtok, offset, 1);
}
bool CheckBufferOverrun::isCtuUnsafePointerArith(const Settings &settings, const Token *argtok, MathLib::bigint *offset)
{
return isCtuUnsafeBufferUsage(settings, argtok, offset, 2);
}
/** @brief Parse current TU and extract file info */
Check::FileInfo *CheckBufferOverrun::getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const
{
const std::list<CTU::FileInfo::UnsafeUsage> &unsafeArrayIndex = CTU::getUnsafeUsage(tokenizer, settings, isCtuUnsafeArrayIndex);
const std::list<CTU::FileInfo::UnsafeUsage> &unsafePointerArith = CTU::getUnsafeUsage(tokenizer, settings, isCtuUnsafePointerArith);
if (unsafeArrayIndex.empty() && unsafePointerArith.empty()) {
return nullptr;
}
auto *fileInfo = new MyFileInfo;
fileInfo->unsafeArrayIndex = unsafeArrayIndex;
fileInfo->unsafePointerArith = unsafePointerArith;
return fileInfo;
}
Check::FileInfo * CheckBufferOverrun::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const
{
// cppcheck-suppress shadowFunction - TODO: fix this
const std::string arrayIndex("array-index");
const std::string pointerArith("pointer-arith");
auto *fileInfo = new MyFileInfo;
for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char* name = e->Name();
if (name == arrayIndex)
fileInfo->unsafeArrayIndex = CTU::loadUnsafeUsageListFromXml(e);
else if (name == pointerArith)
fileInfo->unsafePointerArith = CTU::loadUnsafeUsageListFromXml(e);
}
if (fileInfo->unsafeArrayIndex.empty() && fileInfo->unsafePointerArith.empty()) {
delete fileInfo;
return nullptr;
}
return fileInfo;
}
/** @brief Analyse all file infos for all TU */
bool CheckBufferOverrun::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger)
{
if (!ctu)
return false;
bool foundErrors = false;
CheckBufferOverrun dummy(nullptr, &settings, &errorLogger);
dummy.
logChecker("CheckBufferOverrun::analyseWholeProgram");
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap();
for (const Check::FileInfo* fi1 : fileInfo) {
const auto *fi = dynamic_cast<const MyFileInfo*>(fi1);
if (!fi)
continue;
for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeArrayIndex)
foundErrors |= analyseWholeProgram1(callsMap, unsafeUsage, 1, errorLogger, settings.maxCtuDepth);
for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafePointerArith)
foundErrors |= analyseWholeProgram1(callsMap, unsafeUsage, 2, errorLogger, settings.maxCtuDepth);
}
return foundErrors;
}
bool CheckBufferOverrun::analyseWholeProgram1(const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap, const CTU::FileInfo::UnsafeUsage &unsafeUsage, int type, ErrorLogger &errorLogger, int maxCtuDepth)
{
const CTU::FileInfo::FunctionCall *functionCall = nullptr;
const std::list<ErrorMessage::FileLocation> &locationList =
CTU::FileInfo::getErrorPath(CTU::FileInfo::InvalidValueType::bufferOverflow,
unsafeUsage,
callsMap,
"Using argument ARG",
&functionCall,
false,
maxCtuDepth);
if (locationList.empty())
return false;
const char *errorId = nullptr;
std::string errmsg;
CWE cwe(0);
if (type == 1) {
errorId = "ctuArrayIndex";
if (unsafeUsage.value > 0)
errmsg = "Array index out of bounds; '" + unsafeUsage.myArgumentName + "' buffer size is " + std::to_string(functionCall->callArgValue) + " and it is accessed at offset " + std::to_string(unsafeUsage.value) + ".";
else
errmsg = "Array index out of bounds; buffer '" + unsafeUsage.myArgumentName + "' is accessed at offset " + std::to_string(unsafeUsage.value) + ".";
cwe = (unsafeUsage.value > 0) ? CWE_BUFFER_OVERRUN : CWE_BUFFER_UNDERRUN;
} else {
errorId = "ctuPointerArith";
errmsg = "Pointer arithmetic overflow; '" + unsafeUsage.myArgumentName + "' buffer size is " + std::to_string(functionCall->callArgValue);
cwe = CWE_POINTER_ARITHMETIC_OVERFLOW;
}
const ErrorMessage errorMessage(locationList,
emptyString,
Severity::error,
errmsg,
errorId,
cwe, Certainty::normal);
errorLogger.reportErr(errorMessage);
return true;
}
void CheckBufferOverrun::objectIndex()
{
logChecker("CheckBufferOverrun::objectIndex");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *functionScope : symbolDatabase->functionScopes) {
for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "["))
continue;
const Token *obj = tok->astOperand1();
const Token *idx = tok->astOperand2();
if (!idx || !obj)
continue;
if (idx->hasKnownIntValue()) {
if (idx->getKnownIntValue() == 0)
continue;
}
if (idx->hasKnownIntValue() && idx->getKnownIntValue() == 0)
continue;
std::vector<ValueFlow::Value> values = ValueFlow::getLifetimeObjValues(obj, false, -1);
for (const ValueFlow::Value& v:values) {
if (v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
continue;
const Variable *var = v.tokvalue->variable();
if (!var)
continue;
if (var->isReference())
continue;
if (var->isRValueReference())
continue;
if (var->isArray())
continue;
if (var->isPointer()) {
if (!var->valueType())
continue;
if (!obj->valueType())
continue;
if (var->valueType()->pointer > obj->valueType()->pointer)
continue;
}
if (obj->valueType() && var->valueType() && (obj->isCast() || (obj->isCpp() && isCPPCast(obj)) || obj->valueType()->pointer)) { // allow cast to a different type
const auto varSize = var->valueType()->typeSize(mSettings->platform);
if (varSize == 0)
continue;
if (obj->valueType()->type != var->valueType()->type) {
if (ValueFlow::isOutOfBounds(makeSizeValue(varSize, v.path), idx).empty())
continue;
}
}
if (v.path != 0) {
std::vector<ValueFlow::Value> idxValues;
std::copy_if(idx->values().cbegin(),
idx->values().cend(),
std::back_inserter(idxValues),
[&](const ValueFlow::Value& vidx) {
if (!vidx.isIntValue())
return false;
return vidx.path == v.path || vidx.path == 0;
});
if (std::any_of(idxValues.cbegin(), idxValues.cend(), [&](const ValueFlow::Value& vidx) {
if (vidx.isImpossible())
return (vidx.intvalue == 0);
return (vidx.intvalue != 0);
})) {
objectIndexError(tok, &v, idx->hasKnownIntValue());
}
} else {
objectIndexError(tok, &v, idx->hasKnownIntValue());
}
}
}
}
}
void CheckBufferOverrun::objectIndexError(const Token *tok, const ValueFlow::Value *v, bool known)
{
ErrorPath errorPath;
std::string name;
if (v) {
const Token* expr = v->tokvalue;
while (Token::simpleMatch(expr->astParent(), "."))
expr = expr->astParent();
name = expr->expressionString();
errorPath = v->errorPath;
}
errorPath.emplace_back(tok, "");
std::string verb = known ? "is" : "might be";
reportError(errorPath,
known ? Severity::error : Severity::warning,
"objectIndex",
"The address of variable '" + name + "' " + verb + " accessed at non-zero index.",
CWE758,
Certainty::normal);
}
static bool isVLAIndex(const Token* tok)
{
if (!tok)
return false;
if (tok->varId() != 0U)
return true;
if (tok->str() == "?") {
// this is a VLA index if both expressions around the ":" is VLA index
return tok->astOperand2() &&
tok->astOperand2()->str() == ":" &&
isVLAIndex(tok->astOperand2()->astOperand1()) &&
isVLAIndex(tok->astOperand2()->astOperand2());
}
return isVLAIndex(tok->astOperand1()) || isVLAIndex(tok->astOperand2());
}
void CheckBufferOverrun::negativeArraySize()
{
logChecker("CheckBufferOverrun::negativeArraySize");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isArray())
continue;
const Token* const nameToken = var->nameToken();
if (!Token::Match(nameToken, "%var% [") || !nameToken->next()->astOperand2())
continue;
const ValueFlow::Value* sz = nameToken->next()->astOperand2()->getValueLE(-1, *mSettings);
// don't warn about constant negative index because that is a compiler error
if (sz && isVLAIndex(nameToken->next()->astOperand2()))
negativeArraySizeError(nameToken);
}
for (const Scope* functionScope : symbolDatabase->functionScopes) {
for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!tok->isKeyword() || tok->str() != "new" || !tok->astOperand1() || tok->astOperand1()->str() != "[")
continue;
const Token* valOperand = tok->astOperand1()->astOperand2();
if (!valOperand)
continue;
const ValueFlow::Value* sz = valOperand->getValueLE(-1, *mSettings);
if (sz)
negativeMemoryAllocationSizeError(tok, sz);
}
}
}
void CheckBufferOverrun::negativeArraySizeError(const Token* tok)
{
const std::string arrayName = tok ? tok->expressionString() : std::string();
const std::string line1 = arrayName.empty() ? std::string() : ("$symbol:" + arrayName + '\n');
reportError(tok, Severity::error, "negativeArraySize",
line1 +
"Declaration of array '" + arrayName + "' with negative size is undefined behaviour", CWE758, Certainty::normal);
}
void CheckBufferOverrun::negativeMemoryAllocationSizeError(const Token* tok, const ValueFlow::Value* value)
{
const std::string msg = "Memory allocation size is negative.";
const ErrorPath errorPath = getErrorPath(tok, value, msg);
const bool inconclusive = value != nullptr && !value->isKnown();
reportError(errorPath, inconclusive ? Severity::warning : Severity::error, "negativeMemoryAllocationSize",
msg, CWE131, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
| null |
824 | cpp | cppcheck | checkmemoryleak.h | lib/checkmemoryleak.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkmemoryleakH
#define checkmemoryleakH
//---------------------------------------------------------------------------
/**
* @file
*
* %Check for memory leaks
*
* The checking is split up into three specialized classes.
* - CheckMemoryLeakInFunction can detect when a function variable is allocated but not deallocated properly.
* - CheckMemoryLeakInClass can detect when a class variable is allocated but not deallocated properly.
* - CheckMemoryLeakStructMember checks allocation/deallocation of structs and struct members
*/
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <cstdint>
#include <list>
#include <string>
class Function;
class Scope;
class Settings;
class Token;
class Variable;
class ErrorLogger;
struct CWE;
enum class Severity : std::uint8_t;
/// @addtogroup Core
/// @{
/** @brief Base class for memory leaks checking */
class CPPCHECKLIB CheckMemoryLeak {
private:
/** For access to the tokens */
const Tokenizer * const mTokenizer_;
/** ErrorLogger used to report errors */
ErrorLogger * const mErrorLogger_;
/** Enabled standards */
const Settings * const mSettings_;
/**
* Report error. Similar with the function Check::reportError
* @param tok the token where the error occurs
* @param severity the severity of the bug
* @param id type of message
* @param msg text
* @param cwe cwe number
*/
void reportErr(const Token *tok, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const;
/**
* Report error. Similar with the function Check::reportError
* @param callstack callstack of error
* @param severity the severity of the bug
* @param id type of message
* @param msg text
* @param cwe cwe number
*/
void reportErr(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe) const;
public:
CheckMemoryLeak() = delete;
CheckMemoryLeak(const CheckMemoryLeak &) = delete;
CheckMemoryLeak& operator=(const CheckMemoryLeak &) = delete;
CheckMemoryLeak(const Tokenizer *t, ErrorLogger *e, const Settings *s)
: mTokenizer_(t), mErrorLogger_(e), mSettings_(s) {}
/** @brief What type of allocation are used.. the "Many" means that several types of allocation and deallocation are used */
enum AllocType : std::uint8_t { No, Malloc, New, NewArray, File, Fd, Pipe, OtherMem, OtherRes, Many };
void memoryLeak(const Token *tok, const std::string &varname, AllocType alloctype) const;
/**
* @brief Get type of deallocation at given position
* @param tok position
* @param varid variable id
* @return type of deallocation
*/
AllocType getDeallocationType(const Token *tok, nonneg int varid) const;
/**
* @brief Get type of allocation at given position
*/
AllocType getAllocationType(const Token *tok2, nonneg int varid, std::list<const Function*> *callstack = nullptr) const;
/**
* @brief Get type of reallocation at given position
*/
AllocType getReallocationType(const Token *tok2, nonneg int varid) const;
/**
* Check if token reopens a standard stream
* @param tok token to check
*/
bool isReopenStandardStream(const Token *tok) const;
/**
* Check if token opens /dev/null
* @param tok token to check
*/
bool isOpenDevNull(const Token *tok) const;
/**
* Report that there is a memory leak (new/malloc/etc)
* @param tok token where memory is leaked
* @param varname name of variable
*/
void memleakError(const Token *tok, const std::string &varname) const;
/**
* Report that there is a resource leak (fopen/popen/etc)
* @param tok token where resource is leaked
* @param varname name of variable
*/
void resourceLeakError(const Token *tok, const std::string &varname) const;
void deallocuseError(const Token *tok, const std::string &varname) const;
void mismatchAllocDealloc(const std::list<const Token *> &callstack, const std::string &varname) const;
void memleakUponReallocFailureError(const Token *tok, const std::string &reallocfunction, const std::string &varname) const;
/** What type of allocated memory does the given function return? */
AllocType functionReturnType(const Function* func, std::list<const Function*> *callstack = nullptr) const;
};
/// @}
/// @addtogroup Checks
/// @{
/**
* @brief %CheckMemoryLeakInFunction detects when a function variable is allocated but not deallocated properly.
*
* The checking is done by looking at each function variable separately. By repeating these 4 steps over and over:
* -# locate a function variable
* -# create a simple token list that describes the usage of the function variable.
* -# simplify the token list.
* -# finally, check if the simplified token list contain any leaks.
*/
class CPPCHECKLIB CheckMemoryLeakInFunction : public Check, public CheckMemoryLeak {
friend class TestMemleakInFunction;
public:
/** @brief This constructor is used when registering this class */
CheckMemoryLeakInFunction() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {}
private:
/** @brief This constructor is used when running checks */
CheckMemoryLeakInFunction(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckMemoryLeakInFunction checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkMemoryLeak.checkReallocUsage();
}
/**
* Checking for a memory leak caused by improper realloc usage.
*/
void checkReallocUsage();
/** Report all possible errors (for the --errorlist) */
void getErrorMessages(ErrorLogger *e, const Settings *settings) const override {
CheckMemoryLeakInFunction c(nullptr, settings, e);
c.memleakError(nullptr, "varname");
c.resourceLeakError(nullptr, "varname");
c.deallocuseError(nullptr, "varname");
const std::list<const Token *> callstack;
c.mismatchAllocDealloc(callstack, "varname");
c.memleakUponReallocFailureError(nullptr, "realloc", "varname");
}
/**
* Get name of class (--doc)
* @return name of class
*/
static std::string myName() {
return "Memory leaks (function variables)";
}
/**
* Get class information (--doc)
* @return Wiki formatted information about this class
*/
std::string classInfo() const override {
return "Is there any allocated memory when a function goes out of scope\n";
}
};
/**
* @brief %Check class variables, variables that are allocated in the constructor should be deallocated in the destructor
*/
class CPPCHECKLIB CheckMemoryLeakInClass : public Check, private CheckMemoryLeak {
friend class TestMemleakInClass;
public:
CheckMemoryLeakInClass() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {}
private:
CheckMemoryLeakInClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (!tokenizer.isCPP())
return;
CheckMemoryLeakInClass checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkMemoryLeak.check();
}
void check();
void variable(const Scope *scope, const Token *tokVarname);
/** Public functions: possible double-allocation */
void checkPublicFunctions(const Scope *scope, const Token *classtok);
void publicAllocationError(const Token *tok, const std::string &varname);
void unsafeClassError(const Token *tok, const std::string &classname, const std::string &varname);
void getErrorMessages(ErrorLogger *e, const Settings *settings) const override {
CheckMemoryLeakInClass c(nullptr, settings, e);
c.publicAllocationError(nullptr, "varname");
c.unsafeClassError(nullptr, "class", "class::varname");
}
static std::string myName() {
return "Memory leaks (class variables)";
}
std::string classInfo() const override {
return "If the constructor allocate memory then the destructor must deallocate it.\n";
}
};
/** @brief detect simple memory leaks for struct members */
class CPPCHECKLIB CheckMemoryLeakStructMember : public Check, private CheckMemoryLeak {
friend class TestMemleakStructMember;
public:
CheckMemoryLeakStructMember() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {}
private:
CheckMemoryLeakStructMember(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckMemoryLeakStructMember checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkMemoryLeak.check();
}
void check();
/** Is local variable allocated with malloc? */
bool isMalloc(const Variable *variable) const;
void checkStructVariable(const Variable* variable) const;
void getErrorMessages(ErrorLogger * /*errorLogger*/, const Settings * /*settings*/) const override {}
static std::string myName() {
return "Memory leaks (struct members)";
}
std::string classInfo() const override {
return "Don't forget to deallocate struct members\n";
}
};
/** @brief detect simple memory leaks (address not taken) */
class CPPCHECKLIB CheckMemoryLeakNoVar : public Check, private CheckMemoryLeak {
friend class TestMemleakNoVar;
public:
CheckMemoryLeakNoVar() : Check(myName()), CheckMemoryLeak(nullptr, nullptr, nullptr) {}
private:
CheckMemoryLeakNoVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger), CheckMemoryLeak(tokenizer, errorLogger, settings) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckMemoryLeakNoVar checkMemoryLeak(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkMemoryLeak.check();
}
void check();
/**
* @brief %Check if an input argument to a function is the return value of an allocation function
* like malloc(), and the function does not release it.
* @param scope The scope of the function to check.
*/
void checkForUnreleasedInputArgument(const Scope *scope);
/**
* @brief %Check if a call to an allocation function like malloc() is made and its return value is not assigned.
* @param scope The scope of the function to check.
*/
void checkForUnusedReturnValue(const Scope *scope);
/**
* @brief %Check if an exception could cause a leak in an argument constructed with shared_ptr/unique_ptr.
* @param scope The scope of the function to check.
*/
void checkForUnsafeArgAlloc(const Scope *scope);
void functionCallLeak(const Token *loc, const std::string &alloc, const std::string &functionCall);
void returnValueNotUsedError(const Token* tok, const std::string &alloc);
void unsafeArgAllocError(const Token *tok, const std::string &funcName, const std::string &ptrType, const std::string &objType);
void getErrorMessages(ErrorLogger *e, const Settings *settings) const override {
CheckMemoryLeakNoVar c(nullptr, settings, e);
c.functionCallLeak(nullptr, "funcName", "funcName");
c.returnValueNotUsedError(nullptr, "funcName");
c.unsafeArgAllocError(nullptr, "funcName", "shared_ptr", "int");
}
static std::string myName() {
return "Memory leaks (address not taken)";
}
std::string classInfo() const override {
return "Not taking the address to allocated memory\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkmemoryleakH
| null |
825 | cpp | cppcheck | checkpostfixoperator.cpp | lib/checkpostfixoperator.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// You should use ++ and -- as prefix whenever possible as these are more
// efficient than postfix operators
//---------------------------------------------------------------------------
#include "checkpostfixoperator.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckPostfixOperator instance;
}
// CWE ids used
static const CWE CWE398(398U); // Indicator of Poor Code Quality
void CheckPostfixOperator::postfixOperator()
{
if (!mSettings->severity.isEnabled(Severity::performance))
return;
logChecker("CheckPostfixOperator::postfixOperator"); // performance
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Variable *var = tok->variable();
if (!var || !Token::Match(tok, "%var% ++|--"))
continue;
const Token* parent = tok->next()->astParent();
if (!parent || parent->str() == ";" || (parent->str() == "," && (!parent->astParent() || parent->astParent()->str() != "("))) {
if (var->isPointer() || var->isArray())
continue;
if (Token::Match(var->nameToken()->previous(), "iterator|const_iterator|reverse_iterator|const_reverse_iterator")) {
// the variable is an iterator
postfixOperatorError(tok);
} else if (var->type()) {
// the variable is an instance of class
postfixOperatorError(tok);
}
}
}
}
}
//---------------------------------------------------------------------------
void CheckPostfixOperator::postfixOperatorError(const Token *tok)
{
reportError(tok, Severity::performance, "postfixOperator",
"Prefer prefix ++/-- operators for non-primitive types.\n"
"Prefix ++/-- operators should be preferred for non-primitive types. "
"Pre-increment/decrement can be more efficient than "
"post-increment/decrement. Post-increment/decrement usually "
"involves keeping a copy of the previous value around and "
"adds a little extra code.", CWE398, Certainty::normal);
}
| null |
826 | cpp | cppcheck | reverseanalyzer.cpp | lib/reverseanalyzer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "reverseanalyzer.h"
#include "analyzer.h"
#include "astutils.h"
#include "errortypes.h"
#include "forwardanalyzer.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "valueptr.h"
#include <algorithm>
#include <cstddef>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
namespace {
struct ReverseTraversal {
ReverseTraversal(const ValuePtr<Analyzer>& analyzer, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
: analyzer(analyzer), tokenlist(tokenlist), errorLogger(errorLogger), settings(settings)
{}
ValuePtr<Analyzer> analyzer;
const TokenList& tokenlist;
ErrorLogger& errorLogger;
const Settings& settings;
std::pair<bool, bool> evalCond(const Token* tok) const {
std::vector<MathLib::bigint> result = analyzer->evaluate(tok);
// TODO: We should convert to bool
const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x == 1;
});
const bool checkElse = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x == 0;
});
return std::make_pair(checkThen, checkElse);
}
bool update(Token* tok) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Reverse);
if (action.isInconclusive() && !analyzer->lowerToInconclusive())
return false;
if (action.isInvalid())
return false;
if (!action.isNone())
analyzer->update(tok, action, Analyzer::Direction::Reverse);
return true;
}
static Token* getParentFunction(Token* tok)
{
if (!tok)
return nullptr;
if (!tok->astParent())
return nullptr;
int argn = -1;
if (Token* ftok = getTokenArgumentFunction(tok, argn)) {
while (!Token::Match(ftok, "(|{")) {
if (!ftok)
return nullptr;
if (ftok->index() >= tok->index())
return nullptr;
if (!ftok->link() || ftok->str() == ")")
ftok = ftok->next();
else
ftok = ftok->link()->next();
}
if (ftok == tok)
return nullptr;
return ftok;
}
return nullptr;
}
static Token* getTopFunction(Token* tok)
{
if (!tok)
return nullptr;
if (!tok->astParent())
return tok;
Token* parent = tok;
Token* top = tok;
while ((parent = getParentFunction(parent)))
top = parent;
return top;
}
static Token* jumpToStart(Token* tok)
{
if (Token::simpleMatch(tok->tokAt(-2), "} else {"))
tok = tok->linkAt(-2);
if (Token::simpleMatch(tok->previous(), ") {"))
return tok->linkAt(-1);
if (Token::simpleMatch(tok->previous(), "do {"))
return tok->previous();
return tok;
}
bool updateRecursive(Token* start) {
bool continueB = true;
visitAstNodes(start, [&](Token* tok) {
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent, ":"))
parent = parent->astParent();
if (isUnevaluated(tok) || isDeadCode(tok, parent))
return ChildrenToVisit::none;
continueB &= update(tok);
if (continueB)
return ChildrenToVisit::op1_and_op2;
return ChildrenToVisit::done;
});
return continueB;
}
Analyzer::Action analyzeRecursive(const Token* start) const {
Analyzer::Action result = Analyzer::Action::None;
visitAstNodes(start, [&](const Token* tok) {
result |= analyzer->analyze(tok, Analyzer::Direction::Reverse);
if (result.isModified())
return ChildrenToVisit::done;
return ChildrenToVisit::op1_and_op2;
});
return result;
}
Analyzer::Action analyzeRange(const Token* start, const Token* end) const {
Analyzer::Action result = Analyzer::Action::None;
for (const Token* tok = start; tok && tok != end; tok = tok->next()) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Reverse);
if (action.isModified())
return action;
result |= action;
}
return result;
}
Token* isDeadCode(Token* tok, const Token* end = nullptr) const {
int opSide = 0;
for (; tok && tok->astParent(); tok = tok->astParent()) {
if (tok == end)
break;
Token* parent = tok->astParent();
if (Token::simpleMatch(parent, ":")) {
if (astIsLHS(tok))
opSide = 1;
else if (astIsRHS(tok))
opSide = 2;
else
opSide = 0;
}
if (tok != parent->astOperand2())
continue;
if (Token::simpleMatch(parent, ":"))
parent = parent->astParent();
if (!Token::Match(parent, "%oror%|&&|?"))
continue;
const Token* condTok = parent->astOperand1();
if (!condTok)
continue;
bool checkThen, checkElse;
std::tie(checkThen, checkElse) = evalCond(condTok);
if (parent->str() == "?") {
if (checkElse && opSide == 1)
return parent;
if (checkThen && opSide == 2)
return parent;
}
if (!checkThen && parent->str() == "&&")
return parent;
if (!checkElse && parent->str() == "||")
return parent;
}
return nullptr;
}
void traverse(Token* start, const Token* end = nullptr) {
if (start == end)
return;
std::size_t i = start->index();
for (Token* tok = start->previous(); succeeds(tok, end); tok = tok->previous()) {
if (tok->index() >= i)
throw InternalError(tok, "Cyclic reverse analysis.");
i = tok->index();
if (tok == start || (tok->str() == "{" && (tok->scope()->type == Scope::ScopeType::eFunction ||
tok->scope()->type == Scope::ScopeType::eLambda))) {
const Function* f = tok->scope()->function;
if (f && f->isConstructor()) {
if (const Token* initList = f->constructorMemberInitialization())
traverse(tok->previous(), tok->tokAt(initList->index() - tok->index()));
}
break;
}
if (Token::Match(tok, "return|break|continue"))
break;
if (Token::Match(tok, "%name% :"))
break;
if (Token::simpleMatch(tok, ":"))
continue;
// Evaluate LHS of assignment before RHS
if (Token* assignTok = assignExpr(tok)) {
// If assignTok has broken ast then stop
if (!assignTok->astOperand1() || !assignTok->astOperand2())
break;
Token* assignTop = assignTok;
bool continueB = true;
while (assignTop->isAssignmentOp()) {
if (!Token::Match(assignTop->astOperand1(), "%assign%")) {
continueB &= updateRecursive(assignTop->astOperand1());
}
if (!assignTop->astParent())
break;
assignTop = assignTop->astParent();
}
// Is assignment in dead code
if (Token* parent = isDeadCode(assignTok)) {
tok = parent;
continue;
}
// Simple assign
if (assignTok->str() == "=" && (assignTok->astParent() == assignTop || assignTok == assignTop)) {
Analyzer::Action rhsAction =
analyzer->analyze(assignTok->astOperand2(), Analyzer::Direction::Reverse);
Analyzer::Action lhsAction =
analyzer->analyze(assignTok->astOperand1(), Analyzer::Direction::Reverse);
// Assignment from
if (rhsAction.isRead() && !lhsAction.isInvalid() && assignTok->astOperand1()->exprId() > 0) {
const std::string info = "Assignment from '" + assignTok->expressionString() + "'";
ValuePtr<Analyzer> a = analyzer->reanalyze(assignTok->astOperand1(), info);
if (a) {
valueFlowGenericForward(nextAfterAstRightmostLeaf(assignTok->astOperand2()),
assignTok->astOperand2()->scope()->bodyEnd,
a,
tokenlist,
errorLogger,
settings);
}
// Assignment to
} else if (lhsAction.matches() && !assignTok->astOperand2()->hasKnownIntValue() &&
assignTok->astOperand2()->exprId() > 0 &&
isConstExpression(assignTok->astOperand2(), settings.library)) {
const std::string info = "Assignment to '" + assignTok->expressionString() + "'";
ValuePtr<Analyzer> a = analyzer->reanalyze(assignTok->astOperand2(), info);
if (a) {
valueFlowGenericForward(nextAfterAstRightmostLeaf(assignTok->astOperand2()),
assignTok->astOperand2()->scope()->bodyEnd,
a,
tokenlist,
errorLogger,
settings);
valueFlowGenericReverse(assignTok->astOperand1()->previous(), end, a, tokenlist, errorLogger, settings);
}
}
}
if (!continueB)
break;
if (!updateRecursive(assignTop->astOperand2()))
break;
tok = previousBeforeAstLeftmostLeaf(assignTop)->next();
continue;
}
if (tok->str() == ")" && !isUnevaluated(tok)) {
if (Token* top = getTopFunction(tok->link())) {
if (!updateRecursive(top))
break;
Token* next = previousBeforeAstLeftmostLeaf(top);
if (next && precedes(next, tok))
tok = next->next();
}
continue;
}
if (tok->str() == "}") {
Token* condTok = getCondTokFromEnd(tok);
if (!condTok)
break;
Analyzer::Action condAction = analyzeRecursive(condTok);
const bool inLoop = Token::Match(condTok->astTop()->previous(), "for|while (");
// Evaluate condition of for and while loops first
if (inLoop) {
if (Token::findmatch(tok->link(), "goto|break", tok))
break;
if (condAction.isModified())
break;
valueFlowGenericForward(condTok, analyzer, tokenlist, errorLogger, settings);
}
Token* thenEnd;
const bool hasElse = Token::simpleMatch(tok->link()->tokAt(-2), "} else {");
if (hasElse) {
thenEnd = tok->link()->tokAt(-2);
} else {
thenEnd = tok;
}
Analyzer::Action thenAction = analyzeRange(thenEnd->link(), thenEnd);
Analyzer::Action elseAction = Analyzer::Action::None;
if (hasElse) {
elseAction = analyzeRange(tok->link(), tok);
}
if (thenAction.isModified() && inLoop)
break;
if (thenAction.isModified() && !elseAction.isModified())
analyzer->assume(condTok, hasElse);
else if (elseAction.isModified() && !thenAction.isModified())
analyzer->assume(condTok, !hasElse);
// Bail if one of the branches are read to avoid FPs due to over constraints
else if (thenAction.isIdempotent() || elseAction.isIdempotent() || thenAction.isRead() ||
elseAction.isRead())
break;
if (thenAction.isInvalid() || elseAction.isInvalid())
break;
if (!thenAction.isModified() && !elseAction.isModified())
valueFlowGenericForward(condTok, analyzer, tokenlist, errorLogger, settings);
else if (condAction.isRead())
break;
// If the condition modifies the variable then bail
if (condAction.isModified())
break;
tok = jumpToStart(tok->link());
continue;
}
if (tok->str() == "{") {
if (tok->previous() &&
(Token::simpleMatch(tok->previous(), "do") ||
(tok->strAt(-1) == ")" && Token::Match(tok->linkAt(-1)->previous(), "for|while (")))) {
Analyzer::Action action = analyzeRange(tok, tok->link());
if (action.isModified())
break;
}
Token* condTok = getCondTokFromEnd(tok->link());
if (condTok) {
Analyzer::Result r = valueFlowGenericForward(condTok, analyzer, tokenlist, errorLogger, settings);
if (r.action.isModified())
break;
}
tok = jumpToStart(tok);
continue;
}
if (Token* next = isUnevaluated(tok)) {
tok = next;
continue;
}
if (Token* parent = isDeadCode(tok)) {
tok = parent;
continue;
}
if (tok->str() == "case") {
const Scope* scope = tok->scope();
while (scope && scope->type != Scope::eSwitch)
scope = scope->nestedIn;
if (!scope || scope->type != Scope::eSwitch)
break;
tok = tok->tokAt(scope->bodyStart->index() - tok->index() - 1);
continue;
}
if (!update(tok))
break;
}
}
static Token* assignExpr(Token* tok) {
if (Token::Match(tok, ")|}"))
tok = tok->link();
while (tok->astParent() && (astIsRHS(tok) || !tok->astParent()->isBinaryOp())) {
if (tok->astParent()->isAssignmentOp())
return tok->astParent();
tok = tok->astParent();
}
return nullptr;
}
static Token* isUnevaluated(Token* tok) {
if (Token::Match(tok, ")|>") && tok->link()) {
Token* start = tok->link();
if (::isUnevaluated(start->previous()))
return start->previous();
if (Token::simpleMatch(start, "<"))
return start;
}
return nullptr;
}
};
}
void valueFlowGenericReverse(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings)
{
if (a->invalid())
return;
ReverseTraversal rt{a, tokenlist, errorLogger, settings};
rt.traverse(start, end);
}
| null |
827 | cpp | cppcheck | checkunusedfunctions.cpp | lib/checkunusedfunctions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkunusedfunctions.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <tuple>
#include <utility>
#include <vector>
#include "xml.h"
//---------------------------------------------------------------------------
static const CWE CWE561(561U); // Dead Code
static std::string stripTemplateParameters(const std::string& funcName) {
std::string name = funcName;
const auto pos = name.find('<');
if (pos > 0 && pos != std::string::npos)
name.erase(pos - 1);
return name;
}
//---------------------------------------------------------------------------
// FUNCTION USAGE - Check for unused functions etc
//---------------------------------------------------------------------------
static bool isRecursiveCall(const Token* ftok)
{
return ftok->function() && ftok->function() == Scope::nestedInFunction(ftok->scope());
}
void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer, const Settings &settings)
{
const char * const FileName = tokenizer.list.getFiles().front().c_str();
const bool doMarkup = settings.library.markupFile(FileName);
// Function declarations..
if (!doMarkup) {
const SymbolDatabase* symbolDatabase = tokenizer.getSymbolDatabase();
for (const Scope* scope : symbolDatabase->functionScopes) {
const Function* func = scope->function;
if (!func || !func->token)
continue;
// Don't warn about functions that are marked by __attribute__((constructor)) or __attribute__((destructor))
if (func->isAttributeConstructor() || func->isAttributeDestructor() || func->type != Function::eFunction || func->isOperator())
continue;
if (func->isExtern())
continue;
bool foundAllBaseClasses{};
if (const Function* ofunc = func->getOverriddenFunction(&foundAllBaseClasses)) {
if (!foundAllBaseClasses || ofunc->isPure())
continue;
}
else if (func->isImplicitlyVirtual()) {
continue;
}
mFunctionDecl.emplace_back(func);
FunctionUsage &usage = mFunctions[stripTemplateParameters(func->name())];
if (func->retDef && (func->retDef->isAttributeUnused() || func->retDef->isAttributeMaybeUnused())) {
usage.usedOtherFile = true;
}
if (!usage.lineNumber)
usage.lineNumber = func->token->linenr();
// TODO: why always overwrite this but not the filename and line?
usage.fileIndex = func->token->fileIndex();
const std::string& fileName = tokenizer.list.file(func->token);
// No filename set yet..
if (usage.filename.empty()) {
usage.filename = fileName;
}
// Multiple files => filename = "+"
else if (usage.filename != fileName) {
//func.filename = "+";
usage.usedOtherFile |= usage.usedSameFile;
}
}
}
// Function usage..
const Token *lambdaEndToken = nullptr;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (tok == lambdaEndToken)
lambdaEndToken = nullptr;
else if (!lambdaEndToken && tok->str() == "[")
lambdaEndToken = findLambdaEndToken(tok);
// parsing of library code to find called functions
if (settings.library.isexecutableblock(FileName, tok->str())) {
const Token * markupVarToken = tok->tokAt(settings.library.blockstartoffset(FileName));
// not found
if (!markupVarToken)
continue;
int scope = 0;
bool start = true;
// find all function calls in library code (starts with '(', not if or while etc)
while ((scope || start) && markupVarToken) {
if (markupVarToken->str() == settings.library.blockstart(FileName)) {
scope++;
start = false;
} else if (markupVarToken->str() == settings.library.blockend(FileName))
scope--;
else if (!settings.library.iskeyword(FileName, markupVarToken->str())) {
mFunctionCalls.insert(markupVarToken->str());
if (mFunctions.find(markupVarToken->str()) != mFunctions.end())
mFunctions[markupVarToken->str()].usedOtherFile = true;
else if (markupVarToken->strAt(1) == "(") {
FunctionUsage &func = mFunctions[markupVarToken->str()];
func.filename = tokenizer.list.getFiles()[markupVarToken->fileIndex()];
if (func.filename.empty() || func.filename == "+")
func.usedOtherFile = true;
else
func.usedSameFile = true;
}
}
markupVarToken = markupVarToken->next();
}
}
if (!doMarkup // only check source files
&& settings.library.isexporter(tok->str()) && tok->next() != nullptr) {
const Token * propToken = tok->next();
while (propToken && propToken->str() != ")") {
if (settings.library.isexportedprefix(tok->str(), propToken->str())) {
const Token* nextPropToken = propToken->next();
const std::string& value = nextPropToken->str();
if (mFunctions.find(value) != mFunctions.end()) {
mFunctions[value].usedOtherFile = true;
}
mFunctionCalls.insert(value);
}
if (settings.library.isexportedsuffix(tok->str(), propToken->str())) {
const Token* prevPropToken = propToken->previous();
const std::string& value = prevPropToken->str();
if (value != ")" && mFunctions.find(value) != mFunctions.end()) {
mFunctions[value].usedOtherFile = true;
}
mFunctionCalls.insert(value);
}
propToken = propToken->next();
}
}
if (doMarkup && settings.library.isimporter(FileName, tok->str()) && tok->next()) {
const Token * propToken = tok->next();
if (propToken->next()) {
propToken = propToken->next();
while (propToken && propToken->str() != ")") {
const std::string& value = propToken->str();
if (!value.empty()) {
mFunctions[value].usedOtherFile = true;
mFunctionCalls.insert(value);
break;
}
propToken = propToken->next();
}
}
}
if (settings.library.isreflection(tok->str())) {
const int argIndex = settings.library.reflectionArgument(tok->str());
if (argIndex >= 0) {
const Token * funcToken = tok->next();
int index = 0;
std::string value;
while (funcToken) {
if (funcToken->str()==",") {
if (++index == argIndex)
break;
value.clear();
} else
value += funcToken->str();
funcToken = funcToken->next();
}
if (index == argIndex) {
value = value.substr(1, value.length() - 2);
mFunctions[value].usedOtherFile = true;
mFunctionCalls.insert(std::move(value));
}
}
}
if (tok->hasAttributeCleanup()) {
const std::string& funcname = tok->getAttributeCleanup();
mFunctions[funcname].usedOtherFile = true;
mFunctionCalls.insert(funcname);
continue;
}
const Token *funcname = nullptr;
if (doMarkup)
funcname = Token::Match(tok, "%name% (") ? tok : nullptr;
else if ((lambdaEndToken || tok->scope()->isExecutable()) && Token::Match(tok, "%name% (")) {
funcname = tok;
} else if ((lambdaEndToken || tok->scope()->isExecutable()) && Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> (")) {
funcname = tok;
} else if (Token::Match(tok, "< %name%") && tok->link()) {
funcname = tok->next();
while (Token::Match(funcname, "%name% :: %name%"))
funcname = funcname->tokAt(2);
} else if (tok->scope()->type != Scope::ScopeType::eEnum && (Token::Match(tok, "[;{}.,()[=+-/|!?:]") || Token::Match(tok, "return|throw"))) {
funcname = tok->next();
if (funcname && funcname->str() == "&")
funcname = funcname->next();
if (funcname && funcname->str() == "::")
funcname = funcname->next();
while (Token::Match(funcname, "%name% :: %name%"))
funcname = funcname->tokAt(2);
if (!Token::Match(funcname, "%name% [(),;]:}<>]"))
continue;
}
if (!funcname || funcname->isKeyword() || funcname->isStandardType() || funcname->varId() || funcname->enumerator() || funcname->type())
continue;
// funcname ( => Assert that the end parentheses isn't followed by {
if (Token::Match(funcname, "%name% (|<") && funcname->linkAt(1)) {
const Token *ftok = funcname->next();
if (ftok->str() == "<")
ftok = ftok->link();
if (Token::Match(ftok->linkAt(1), ") const|throw|{"))
funcname = nullptr;
}
if (funcname) {
if (isRecursiveCall(funcname))
continue;
const auto baseName = stripTemplateParameters(funcname->str());
FunctionUsage &func = mFunctions[baseName];
const std::string& called_from_file = tokenizer.list.getFiles()[funcname->fileIndex()];
if (func.filename.empty() || func.filename == "+" || func.filename != called_from_file)
func.usedOtherFile = true;
else
func.usedSameFile = true;
mFunctionCalls.insert(baseName);
}
}
}
static bool isOperatorFunction(const std::string & funcName)
{
/* Operator functions are invalid function names for C, so no need to check
* this in here. As result the returned error function might be incorrect.
*
* List of valid operators can be found at:
* http://en.cppreference.com/w/cpp/language/operators
*
* Conversion functions must be a member function (at least for gcc), so no
* need to cover them for unused functions.
*
* To speed up the comparison, not the whole list of operators is used.
* Instead only the character after the operator prefix is checked to be a
* none alpa numeric value, but the '_', to cover function names like
* "operator_unused". In addition the following valid operators are checked:
* - new
* - new[]
* - delete
* - delete[]
*/
const std::string operatorPrefix = "operator";
if (funcName.compare(0, operatorPrefix.length(), operatorPrefix) != 0) {
return false;
}
// Taking care of funcName == "operator", which is no valid operator
if (funcName.length() == operatorPrefix.length()) {
return false;
}
const char firstOperatorChar = funcName[operatorPrefix.length()];
if (firstOperatorChar == '_') {
return false;
}
if (!std::isalnum(firstOperatorChar)) {
return true;
}
const std::vector<std::string> additionalOperators = {
"new", "new[]", "delete", "delete[]"
};
return std::find(additionalOperators.cbegin(), additionalOperators.cend(), funcName.substr(operatorPrefix.length())) != additionalOperators.cend();
}
#define logChecker(id) \
do { \
const ErrorMessage errmsg({}, nullptr, Severity::internal, "logChecker", (id), CWE(0U), Certainty::normal); \
errorLogger.reportErr(errmsg); \
} while (false)
bool CheckUnusedFunctions::check(const Settings& settings, ErrorLogger& errorLogger) const
{
logChecker("CheckUnusedFunctions::check"); // unusedFunction
using ErrorParams = std::tuple<std::string, unsigned int, unsigned int, std::string>;
std::vector<ErrorParams> errors; // ensure well-defined order
for (std::unordered_map<std::string, FunctionUsage>::const_iterator it = mFunctions.cbegin(); it != mFunctions.cend(); ++it) {
const FunctionUsage &func = it->second;
if (func.usedOtherFile || func.filename.empty())
continue;
if (settings.library.isentrypoint(it->first))
continue;
if (!func.usedSameFile) {
if (isOperatorFunction(it->first))
continue;
std::string filename;
if (func.filename != "+")
filename = func.filename;
errors.emplace_back(filename, func.fileIndex, func.lineNumber, it->first);
} else if (!func.usedOtherFile) {
/** @todo add error message "function is only used in <file> it can be static" */
/*
std::ostringstream errmsg;
errmsg << "The function '" << it->first << "' is only used in the file it was declared in so it should have local linkage.";
mErrorLogger->reportErr( errmsg.str() );
errors = true;
*/
}
}
std::sort(errors.begin(), errors.end());
for (const auto& e : errors)
unusedFunctionError(errorLogger, std::get<0>(e), std::get<1>(e), std::get<2>(e), std::get<3>(e));
return !errors.empty();
}
void CheckUnusedFunctions::unusedFunctionError(ErrorLogger& errorLogger,
const std::string &filename, unsigned int fileIndex, unsigned int lineNumber,
const std::string &funcname)
{
std::list<ErrorMessage::FileLocation> locationList;
if (!filename.empty()) {
locationList.emplace_back(filename, lineNumber, 0);
locationList.back().fileIndex = fileIndex;
}
const ErrorMessage errmsg(std::move(locationList), emptyString, Severity::style, "$symbol:" + funcname + "\nThe function '$symbol' is never used.", "unusedFunction", CWE561, Certainty::normal);
errorLogger.reportErr(errmsg);
}
CheckUnusedFunctions::FunctionDecl::FunctionDecl(const Function *f)
: functionName(f->name()), fileName(f->token->fileName()), lineNumber(f->token->linenr())
{}
std::string CheckUnusedFunctions::analyzerInfo() const
{
std::ostringstream ret;
for (const FunctionDecl &functionDecl : mFunctionDecl) {
ret << " <functiondecl"
<< " file=\"" << ErrorLogger::toxml(functionDecl.fileName) << '\"'
<< " functionName=\"" << ErrorLogger::toxml(functionDecl.functionName) << '\"'
<< " lineNumber=\"" << functionDecl.lineNumber << "\"/>\n";
}
for (const std::string &fc : mFunctionCalls) {
ret << " <functioncall functionName=\"" << ErrorLogger::toxml(fc) << "\"/>\n";
}
return ret.str();
}
namespace {
struct Location {
Location() : lineNumber(0) {}
Location(std::string f, const int l) : fileName(std::move(f)), lineNumber(l) {}
std::string fileName;
int lineNumber;
};
}
void CheckUnusedFunctions::analyseWholeProgram(const Settings &settings, ErrorLogger &errorLogger, const std::string &buildDir)
{
std::map<std::string, Location> decls;
std::set<std::string> calls;
const std::string filesTxt(buildDir + "/files.txt");
std::ifstream fin(filesTxt.c_str());
std::string filesTxtLine;
while (std::getline(fin, filesTxtLine)) {
const std::string::size_type firstColon = filesTxtLine.find(':');
if (firstColon == std::string::npos)
continue;
const std::string::size_type secondColon = filesTxtLine.find(':', firstColon+1);
if (secondColon == std::string::npos)
continue;
const std::string xmlfile = buildDir + '/' + filesTxtLine.substr(0,firstColon);
const std::string sourcefile = filesTxtLine.substr(secondColon+1);
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str());
if (error != tinyxml2::XML_SUCCESS)
continue;
const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement();
if (rootNode == nullptr)
continue;
for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "FileInfo") != 0)
continue;
const char *checkattr = e->Attribute("check");
if (checkattr == nullptr || std::strcmp(checkattr,"CheckUnusedFunctions") != 0)
continue;
for (const tinyxml2::XMLElement *e2 = e->FirstChildElement(); e2; e2 = e2->NextSiblingElement()) {
const char* functionName = e2->Attribute("functionName");
if (functionName == nullptr)
continue;
const char* name = e2->Name();
if (std::strcmp(name,"functioncall") == 0) {
calls.insert(functionName);
continue;
}
if (std::strcmp(name,"functiondecl") == 0) {
const char* lineNumber = e2->Attribute("lineNumber");
if (lineNumber) {
const char* file = e2->Attribute("file");
// cppcheck-suppress templateInstantiation - TODO: fix this - see #11631
decls[functionName] = Location(file ? file : sourcefile, strToInt<int>(lineNumber));
}
}
}
}
}
for (std::map<std::string, Location>::const_iterator decl = decls.cbegin(); decl != decls.cend(); ++decl) {
const std::string &functionName = stripTemplateParameters(decl->first);
if (settings.library.isentrypoint(functionName))
continue;
if (calls.find(functionName) == calls.end() && !isOperatorFunction(functionName)) {
const Location &loc = decl->second;
unusedFunctionError(errorLogger, loc.fileName, /*fileIndex*/ 0, loc.lineNumber, functionName);
}
}
}
void CheckUnusedFunctions::updateFunctionData(const CheckUnusedFunctions& check)
{
for (const auto& entry : check.mFunctions)
{
FunctionUsage &usage = mFunctions[entry.first];
if (!usage.lineNumber)
usage.lineNumber = entry.second.lineNumber;
// TODO: why always overwrite this but not the filename and line?
usage.fileIndex = entry.second.fileIndex;
if (usage.filename.empty())
usage.filename = entry.second.filename;
// cppcheck-suppress bitwiseOnBoolean - TODO: FP
usage.usedOtherFile |= entry.second.usedOtherFile;
// cppcheck-suppress bitwiseOnBoolean - TODO: FP
usage.usedSameFile |= entry.second.usedSameFile;
}
mFunctionDecl.insert(mFunctionDecl.cend(), check.mFunctionDecl.cbegin(), check.mFunctionDecl.cend());
mFunctionCalls.insert(check.mFunctionCalls.cbegin(), check.mFunctionCalls.cend());
}
| null |
828 | cpp | cppcheck | tokenrange.h | lib/tokenrange.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef tokenrangeH
#define tokenrangeH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstddef>
#include <iterator>
#include <type_traits>
class Token;
template<typename T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
class TokenRangeBase {
T* mFront;
T* mBack;
public:
TokenRangeBase(T* front, T* back) : mFront(front), mBack(back) {}
struct TokenIterator {
using iterator_category = std::forward_iterator_tag;
using value_type = T*;
using difference_type = std::ptrdiff_t;
using pointer = void;
using reference = T*;
T* mt;
TokenIterator() : mt(nullptr) {}
explicit TokenIterator(T* t) : mt(t) {}
TokenIterator& operator++() {
mt = mt->next();
return *this;
}
bool operator==(const TokenIterator& b) const {
return mt == b.mt;
}
bool operator!=(const TokenIterator& b) const {
return mt != b.mt;
}
T* operator*() const {
return mt;
}
};
TokenIterator begin() const {
return TokenIterator(mFront);
}
TokenIterator end() const {
return TokenIterator(mBack);
}
};
class TokenRange : public TokenRangeBase<Token> {
public:
TokenRange(Token* front, Token* back) : TokenRangeBase<Token>(front, back) {}
};
class ConstTokenRange : public TokenRangeBase<const Token> {
public:
ConstTokenRange(const Token* front, const Token* back) : TokenRangeBase<const Token>(front, back) {}
};
#endif // tokenrangeH
| null |
829 | cpp | cppcheck | color.cpp | lib/color.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "color.h"
#include <cstdlib>
#include <sstream>
#include <iostream>
#ifndef _WIN32
#include <unistd.h>
#endif
bool gDisableColors = false;
#ifndef _WIN32
static bool isStreamATty(const std::ostream & os)
{
static const bool stdout_tty = isatty(STDOUT_FILENO);
static const bool stderr_tty = isatty(STDERR_FILENO);
if (&os == &std::cout)
return stdout_tty;
if (&os == &std::cerr)
return stderr_tty;
return (stdout_tty && stderr_tty);
}
#endif
static bool isColorEnabled(const std::ostream & os)
{
// See https://bixense.com/clicolors/
static const bool color_forced_off = (nullptr != std::getenv("NO_COLOR"));
if (color_forced_off)
{
return false;
}
static const bool color_forced_on = (nullptr != std::getenv("CLICOLOR_FORCE"));
if (color_forced_on)
{
return true;
}
#ifdef _WIN32
(void)os;
return false;
#else
return isStreamATty(os);
#endif
}
std::ostream& operator<<(std::ostream & os, Color c)
{
if (!gDisableColors && isColorEnabled(os))
return os << "\033[" << static_cast<std::size_t>(c) << "m";
return os;
}
std::string toString(Color c)
{
std::ostringstream ss;
ss << c;
return ss.str();
}
| null |
830 | cpp | cppcheck | errorlogger.cpp | lib/errorlogger.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errorlogger.h"
#include "color.h"
#include "cppcheck.h"
#include "path.h"
#include "settings.h"
#include "suppressions.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <array>
#include <cassert>
#include <cctype>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <unordered_map>
#include <utility>
#include "xml.h"
const std::set<std::string> ErrorLogger::mCriticalErrorIds{
"cppcheckError",
"cppcheckLimit",
"internalAstError",
"instantiationError",
"internalError",
"premium-internalError",
"premium-invalidArgument",
"premium-invalidLicense",
"preprocessorErrorDirective",
"syntaxError",
"unknownMacro"
};
ErrorMessage::ErrorMessage()
: severity(Severity::none), cwe(0U), certainty(Certainty::normal), hash(0)
{}
// TODO: id and msg are swapped compared to other calls
ErrorMessage::ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, Certainty certainty) :
callStack(std::move(callStack)), // locations for this error message
id(std::move(id)), // set the message id
file0(std::move(file1)),
severity(severity), // severity for this error message
cwe(0U),
certainty(certainty),
hash(0)
{
// set the summary and verbose messages
setmsg(msg);
}
// TODO: id and msg are swapped compared to other calls
ErrorMessage::ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, const CWE &cwe, Certainty certainty) :
callStack(std::move(callStack)), // locations for this error message
id(std::move(id)), // set the message id
file0(std::move(file1)),
severity(severity), // severity for this error message
cwe(cwe.id),
certainty(certainty),
hash(0)
{
// set the summary and verbose messages
setmsg(msg);
}
ErrorMessage::ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, Certainty certainty)
: id(std::move(id)), severity(severity), cwe(0U), certainty(certainty), hash(0)
{
// Format callstack
for (std::list<const Token *>::const_iterator it = callstack.cbegin(); it != callstack.cend(); ++it) {
// --errorlist can provide null values here
if (!(*it))
continue;
callStack.emplace_back(*it, list);
}
if (list && !list->getFiles().empty())
file0 = list->getFiles()[0];
setmsg(msg);
}
ErrorMessage::ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, const CWE &cwe, Certainty certainty)
: id(std::move(id)), severity(severity), cwe(cwe.id), certainty(certainty)
{
// Format callstack
for (const Token *tok: callstack) {
// --errorlist can provide null values here
if (!tok)
continue;
callStack.emplace_back(tok, list);
}
if (list && !list->getFiles().empty())
file0 = list->getFiles()[0];
setmsg(msg);
hash = 0; // calculateWarningHash(list, hashWarning.str());
}
ErrorMessage::ErrorMessage(const ErrorPath &errorPath, const TokenList *tokenList, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty)
: id(id), severity(severity), cwe(cwe.id), certainty(certainty)
{
// Format callstack
for (const ErrorPathItem& e: errorPath) {
const Token *tok = e.first;
// --errorlist can provide null values here
if (!tok)
continue;
const std::string& path_info = e.second;
std::string info;
if (startsWith(path_info,"$symbol:") && path_info.find('\n') < path_info.size()) {
const std::string::size_type pos = path_info.find('\n');
const std::string symbolName = path_info.substr(8, pos - 8);
info = replaceStr(path_info.substr(pos+1), "$symbol", symbolName);
}
else {
info = path_info;
}
callStack.emplace_back(tok, std::move(info), tokenList);
}
if (tokenList && !tokenList->getFiles().empty())
file0 = tokenList->getFiles()[0];
setmsg(msg);
hash = 0; // calculateWarningHash(tokenList, hashWarning.str());
}
ErrorMessage::ErrorMessage(const tinyxml2::XMLElement * const errmsg)
: severity(Severity::none),
cwe(0U),
certainty(Certainty::normal)
{
const char * const unknown = "<UNKNOWN>";
const char *attr = errmsg->Attribute("id");
id = attr ? attr : unknown;
attr = errmsg->Attribute("severity");
severity = attr ? severityFromString(attr) : Severity::none;
attr = errmsg->Attribute("cwe");
// cppcheck-suppress templateInstantiation - TODO: fix this - see #11631
cwe.id = attr ? strToInt<unsigned short>(attr) : 0;
attr = errmsg->Attribute("inconclusive");
certainty = (attr && (std::strcmp(attr, "true") == 0)) ? Certainty::inconclusive : Certainty::normal;
attr = errmsg->Attribute("msg");
mShortMessage = attr ? attr : "";
attr = errmsg->Attribute("verbose");
mVerboseMessage = attr ? attr : "";
attr = errmsg->Attribute("hash");
hash = attr ? strToInt<std::size_t>(attr) : 0;
for (const tinyxml2::XMLElement *e = errmsg->FirstChildElement(); e; e = e->NextSiblingElement()) {
const char* name = e->Name();
if (std::strcmp(name,"location")==0) {
const char *strfile = e->Attribute("file");
const char *strinfo = e->Attribute("info");
const char *strline = e->Attribute("line");
const char *strcolumn = e->Attribute("column");
const char *file = strfile ? strfile : unknown;
const char *info = strinfo ? strinfo : "";
const int line = strline ? strToInt<int>(strline) : 0;
const int column = strcolumn ? strToInt<int>(strcolumn) : 0;
callStack.emplace_front(file, info, line, column);
} else if (std::strcmp(name,"symbol")==0) {
mSymbolNames += e->GetText();
}
}
}
void ErrorMessage::setmsg(const std::string &msg)
{
// If a message ends to a '\n' and contains only a one '\n'
// it will cause the mVerboseMessage to be empty which will show
// as an empty message to the user if --verbose is used.
// Even this doesn't cause problems with messages that have multiple
// lines, none of the error messages should end into it.
assert(!endsWith(msg,'\n'));
// The summary and verbose message are separated by a newline
// If there is no newline then both the summary and verbose messages
// are the given message
const std::string::size_type pos = msg.find('\n');
const std::string symbolName = mSymbolNames.empty() ? std::string() : mSymbolNames.substr(0, mSymbolNames.find('\n'));
if (pos == std::string::npos) {
mShortMessage = replaceStr(msg, "$symbol", symbolName);
mVerboseMessage = replaceStr(msg, "$symbol", symbolName);
} else if (startsWith(msg,"$symbol:")) {
mSymbolNames += msg.substr(8, pos-7);
setmsg(msg.substr(pos + 1));
} else {
mShortMessage = replaceStr(msg.substr(0, pos), "$symbol", symbolName);
mVerboseMessage = replaceStr(msg.substr(pos + 1), "$symbol", symbolName);
}
}
static void serializeString(std::string &oss, const std::string & str)
{
oss += std::to_string(str.length());
oss += " ";
oss += str;
}
ErrorMessage ErrorMessage::fromInternalError(const InternalError &internalError, const TokenList *tokenList, const std::string &filename, const std::string& msg)
{
if (internalError.token)
assert(tokenList != nullptr); // we need to make sure we can look up the provided token
std::list<ErrorMessage::FileLocation> locationList;
if (tokenList && internalError.token) {
locationList.emplace_back(internalError.token, tokenList);
} else {
locationList.emplace_back(filename, 0, 0);
if (tokenList && (filename != tokenList->getSourceFilePath())) {
locationList.emplace_back(tokenList->getSourceFilePath(), 0, 0);
}
}
ErrorMessage errmsg(std::move(locationList),
tokenList ? tokenList->getSourceFilePath() : filename,
Severity::error,
(msg.empty() ? "" : (msg + ": ")) + internalError.errorMessage,
internalError.id,
Certainty::normal);
// TODO: find a better way
if (!internalError.details.empty())
errmsg.mVerboseMessage = errmsg.mVerboseMessage + ": " + internalError.details;
return errmsg;
}
std::string ErrorMessage::serialize() const
{
// Serialize this message into a simple string
std::string oss;
serializeString(oss, id);
serializeString(oss, severityToString(severity));
serializeString(oss, std::to_string(cwe.id));
serializeString(oss, std::to_string(hash));
serializeString(oss, fixInvalidChars(remark));
serializeString(oss, file0);
serializeString(oss, (certainty == Certainty::inconclusive) ? "1" : "0");
const std::string saneShortMessage = fixInvalidChars(mShortMessage);
const std::string saneVerboseMessage = fixInvalidChars(mVerboseMessage);
serializeString(oss, saneShortMessage);
serializeString(oss, saneVerboseMessage);
oss += std::to_string(callStack.size());
oss += " ";
for (std::list<ErrorMessage::FileLocation>::const_iterator loc = callStack.cbegin(); loc != callStack.cend(); ++loc) {
std::string frame;
frame += std::to_string(loc->line);
frame += '\t';
frame += std::to_string(loc->column);
frame += '\t';
frame += loc->getfile(false);
frame += '\t';
frame += loc->getOrigFile(false);
frame += '\t';
frame += loc->getinfo();
serializeString(oss, frame);
}
return oss;
}
void ErrorMessage::deserialize(const std::string &data)
{
// TODO: clear all fields
certainty = Certainty::normal;
callStack.clear();
std::istringstream iss(data);
std::array<std::string, 9> results;
std::size_t elem = 0;
while (iss.good() && elem < 9) {
unsigned int len = 0;
if (!(iss >> len))
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid length");
if (iss.get() != ' ')
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator");
if (!iss.good())
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data");
std::string temp;
if (len > 0) {
temp.resize(len);
iss.read(&temp[0], len);
if (!iss.good())
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data");
}
results[elem++] = std::move(temp);
}
if (!iss.good())
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data");
if (elem != 9)
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - insufficient elements");
id = std::move(results[0]);
severity = severityFromString(results[1]);
cwe.id = 0;
if (!results[2].empty()) {
std::string err;
if (!strToInt(results[2], cwe.id, &err))
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid CWE ID - " + err);
}
hash = 0;
if (!results[3].empty()) {
std::string err;
if (!strToInt(results[3], hash, &err))
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid hash - " + err);
}
remark = std::move(results[4]);
file0 = std::move(results[5]);
if (results[6] == "1")
certainty = Certainty::inconclusive;
mShortMessage = std::move(results[7]);
mVerboseMessage = std::move(results[8]);
unsigned int stackSize = 0;
if (!(iss >> stackSize))
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid stack size");
if (iss.get() != ' ')
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator");
if (stackSize == 0)
return;
while (iss.good()) {
unsigned int len = 0;
if (!(iss >> len))
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid length (stack)");
if (iss.get() != ' ')
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator (stack)");
std::string temp;
if (len > 0) {
temp.resize(len);
iss.read(&temp[0], len);
if (!iss.good())
throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data (stack)");
}
std::vector<std::string> substrings;
substrings.reserve(5);
for (std::string::size_type pos = 0; pos < temp.size() && substrings.size() < 5; ++pos) {
if (substrings.size() == 4) {
substrings.push_back(temp.substr(pos));
break;
}
const std::string::size_type start = pos;
pos = temp.find('\t', pos);
if (pos == std::string::npos) {
substrings.push_back(temp.substr(start));
break;
}
substrings.push_back(temp.substr(start, pos - start));
}
if (substrings.size() < 4)
throw InternalError(nullptr, "Internal Error: Deserializing of error message failed");
// (*loc).line << '\t' << (*loc).column << '\t' << (*loc).getfile(false) << '\t' << loc->getOrigFile(false) << '\t' << loc->getinfo();
std::string info;
if (substrings.size() == 5)
info = std::move(substrings[4]);
ErrorMessage::FileLocation loc(substrings[3], std::move(info), strToInt<int>(substrings[0]), strToInt<unsigned int>(substrings[1]));
loc.setfile(std::move(substrings[2]));
callStack.push_back(std::move(loc));
if (callStack.size() >= stackSize)
break;
}
}
std::string ErrorMessage::getXMLHeader(std::string productName, int xmlVersion)
{
const auto nameAndVersion = Settings::getNameAndVersion(productName);
productName = nameAndVersion.first;
const std::string version = nameAndVersion.first.empty() ? CppCheck::version() : nameAndVersion.second;
tinyxml2::XMLPrinter printer;
// standard xml header
printer.PushDeclaration("xml version=\"1.0\" encoding=\"UTF-8\"");
// header
printer.OpenElement("results", false);
printer.PushAttribute("version", xmlVersion);
printer.OpenElement("cppcheck", false);
if (!productName.empty())
printer.PushAttribute("product-name", productName.c_str());
printer.PushAttribute("version", version.c_str());
printer.CloseElement(false);
printer.OpenElement("errors", false);
return std::string(printer.CStr()) + '>';
}
std::string ErrorMessage::getXMLFooter(int xmlVersion)
{
return xmlVersion == 3 ? "</results>" : " </errors>\n</results>";
}
// There is no utf-8 support around but the strings should at least be safe for to tinyxml2.
// See #5300 "Invalid encoding in XML output" and #6431 "Invalid XML created - Invalid encoding of string literal "
std::string ErrorMessage::fixInvalidChars(const std::string& raw)
{
std::string result;
result.reserve(raw.length());
std::string::const_iterator from=raw.cbegin();
while (from!=raw.cend()) {
if (std::isprint(static_cast<unsigned char>(*from))) {
result.push_back(*from);
} else {
std::ostringstream es;
// straight cast to (unsigned) doesn't work out.
const unsigned uFrom = (unsigned char)*from;
es << '\\' << std::setbase(8) << std::setw(3) << std::setfill('0') << uFrom;
result += es.str();
}
++from;
}
return result;
}
std::string ErrorMessage::toXML() const
{
tinyxml2::XMLPrinter printer(nullptr, false, 2);
printer.OpenElement("error", false);
printer.PushAttribute("id", id.c_str());
printer.PushAttribute("severity", severityToString(severity).c_str());
printer.PushAttribute("msg", fixInvalidChars(mShortMessage).c_str());
printer.PushAttribute("verbose", fixInvalidChars(mVerboseMessage).c_str());
if (cwe.id)
printer.PushAttribute("cwe", cwe.id);
if (hash)
printer.PushAttribute("hash", std::to_string(hash).c_str());
if (certainty == Certainty::inconclusive)
printer.PushAttribute("inconclusive", "true");
if (!file0.empty())
printer.PushAttribute("file0", file0.c_str());
if (!remark.empty())
printer.PushAttribute("remark", fixInvalidChars(remark).c_str());
for (std::list<FileLocation>::const_reverse_iterator it = callStack.crbegin(); it != callStack.crend(); ++it) {
printer.OpenElement("location", false);
printer.PushAttribute("file", it->getfile().c_str());
printer.PushAttribute("line", std::max(it->line,0));
printer.PushAttribute("column", it->column);
if (!it->getinfo().empty())
printer.PushAttribute("info", fixInvalidChars(it->getinfo()).c_str());
printer.CloseElement(false);
}
for (std::string::size_type pos = 0; pos < mSymbolNames.size();) {
const std::string::size_type pos2 = mSymbolNames.find('\n', pos);
std::string symbolName;
if (pos2 == std::string::npos) {
symbolName = mSymbolNames.substr(pos);
pos = pos2;
} else {
symbolName = mSymbolNames.substr(pos, pos2-pos);
pos = pos2 + 1;
}
printer.OpenElement("symbol", false);
printer.PushText(symbolName.c_str());
printer.CloseElement(false);
}
printer.CloseElement(false);
return printer.CStr();
}
// TODO: read info from some shared resource instead?
static std::string readCode(const std::string &file, int linenr, int column, const char endl[])
{
std::ifstream fin(file);
std::string line;
while (linenr > 0 && std::getline(fin,line)) {
linenr--;
}
const std::string::size_type endPos = line.find_last_not_of("\r\n\t ");
if (endPos + 1 < line.size())
line.erase(endPos + 1);
std::string::size_type pos = 0;
while ((pos = line.find('\t', pos)) != std::string::npos)
line[pos] = ' ';
return line + endl + std::string((column>0 ? column-1 : 0), ' ') + '^';
}
static void replaceSpecialChars(std::string& source)
{
// Support a few special characters to allow to specific formatting, see http://sourceforge.net/apps/phpbb/cppcheck/viewtopic.php?f=4&t=494&sid=21715d362c0dbafd3791da4d9522f814
// Substitution should be done first so messages from cppcheck never get translated.
static const std::unordered_map<char, std::string> substitutionMap = {
{'b', "\b"},
{'n', "\n"},
{'r', "\r"},
{'t', "\t"}
};
std::string::size_type index = 0;
while ((index = source.find('\\', index)) != std::string::npos) {
const char searchFor = source[index+1];
const auto it = substitutionMap.find(searchFor);
if (it == substitutionMap.end()) {
index += 1;
continue;
}
const std::string& replaceWith = it->second;
source.replace(index, 2, replaceWith);
index += replaceWith.length();
}
}
static void replace(std::string& source, const std::unordered_map<std::string, std::string> &substitutionMap)
{
std::string::size_type index = 0;
while ((index = source.find('{', index)) != std::string::npos) {
const std::string::size_type end = source.find('}', index);
if (end == std::string::npos)
break;
const std::string searchFor = source.substr(index, end-index+1);
const auto it = substitutionMap.find(searchFor);
if (it == substitutionMap.end()) {
index += 1;
continue;
}
const std::string& replaceWith = it->second;
source.replace(index, searchFor.length(), replaceWith);
index += replaceWith.length();
}
}
static void replaceColors(std::string& source) {
// TODO: colors are not applied when either stdout or stderr is not a TTY because we resolve them before the stream usage
static const std::unordered_map<std::string, std::string> substitutionMap =
{
{"{reset}", ::toString(Color::Reset)},
{"{bold}", ::toString(Color::Bold)},
{"{dim}", ::toString(Color::Dim)},
{"{red}", ::toString(Color::FgRed)},
{"{green}", ::toString(Color::FgGreen)},
{"{blue}", ::toString(Color::FgBlue)},
{"{magenta}", ::toString(Color::FgMagenta)},
{"{default}", ::toString(Color::FgDefault)},
};
replace(source, substitutionMap);
}
// TODO: remove default parameters
std::string ErrorMessage::toString(bool verbose, const std::string &templateFormat, const std::string &templateLocation) const
{
// Save this ErrorMessage in plain text.
// TODO: should never happen - remove this
// No template is given
// (not 100%) equivalent templateFormat: {callstack} ({severity}{inconclusive:, inconclusive}) {message}
if (templateFormat.empty()) {
std::string text;
if (!callStack.empty()) {
text += ErrorLogger::callStackToString(callStack);
text += ": ";
}
if (severity != Severity::none) {
text += '(';
text += severityToString(severity);
if (certainty == Certainty::inconclusive)
text += ", inconclusive";
text += ") ";
}
text += (verbose ? mVerboseMessage : mShortMessage);
return text;
}
// template is given. Reformat the output according to it
std::string result = templateFormat;
findAndReplace(result, "{id}", id);
std::string::size_type pos1 = result.find("{inconclusive:");
while (pos1 != std::string::npos) {
const std::string::size_type pos2 = result.find('}', pos1+1);
const std::string replaceFrom = result.substr(pos1,pos2-pos1+1);
const std::string replaceWith = (certainty == Certainty::inconclusive) ? result.substr(pos1+14, pos2-pos1-14) : std::string();
findAndReplace(result, replaceFrom, replaceWith);
pos1 = result.find("{inconclusive:", pos1);
}
findAndReplace(result, "{severity}", severityToString(severity));
findAndReplace(result, "{cwe}", std::to_string(cwe.id));
findAndReplace(result, "{message}", verbose ? mVerboseMessage : mShortMessage);
findAndReplace(result, "{remark}", remark);
if (!callStack.empty()) {
if (result.find("{callstack}") != std::string::npos)
findAndReplace(result, "{callstack}", ErrorLogger::callStackToString(callStack));
findAndReplace(result, "{file}", callStack.back().getfile());
findAndReplace(result, "{line}", std::to_string(callStack.back().line));
findAndReplace(result, "{column}", std::to_string(callStack.back().column));
if (result.find("{code}") != std::string::npos) {
const std::string::size_type pos = result.find('\r');
const char *endl;
if (pos == std::string::npos)
endl = "\n";
else if (pos+1 < result.size() && result[pos+1] == '\n')
endl = "\r\n";
else
endl = "\r";
findAndReplace(result, "{code}", readCode(callStack.back().getOrigFile(), callStack.back().line, callStack.back().column, endl));
}
} else {
static const std::unordered_map<std::string, std::string> callStackSubstitutionMap =
{
{"{callstack}", ""},
{"{file}", "nofile"},
{"{line}", "0"},
{"{column}", "0"},
{"{code}", ""}
};
replace(result, callStackSubstitutionMap);
}
if (!templateLocation.empty() && callStack.size() >= 2U) {
for (const FileLocation &fileLocation : callStack) {
std::string text = templateLocation;
findAndReplace(text, "{file}", fileLocation.getfile());
findAndReplace(text, "{line}", std::to_string(fileLocation.line));
findAndReplace(text, "{column}", std::to_string(fileLocation.column));
findAndReplace(text, "{info}", fileLocation.getinfo().empty() ? mShortMessage : fileLocation.getinfo());
if (text.find("{code}") != std::string::npos) {
const std::string::size_type pos = text.find('\r');
const char *endl;
if (pos == std::string::npos)
endl = "\n";
else if (pos+1 < text.size() && text[pos+1] == '\n')
endl = "\r\n";
else
endl = "\r";
findAndReplace(text, "{code}", readCode(fileLocation.getOrigFile(), fileLocation.line, fileLocation.column, endl));
}
result += '\n' + text;
}
}
return result;
}
std::string ErrorLogger::callStackToString(const std::list<ErrorMessage::FileLocation> &callStack)
{
std::string str;
for (std::list<ErrorMessage::FileLocation>::const_iterator tok = callStack.cbegin(); tok != callStack.cend(); ++tok) {
str += (tok == callStack.cbegin() ? "" : " -> ");
str += tok->stringify();
}
return str;
}
ErrorMessage::FileLocation::FileLocation(const Token* tok, const TokenList* tokenList)
: fileIndex(tok->fileIndex()), line(tok->linenr()), column(tok->column()), mOrigFileName(tokenList->getOrigFile(tok)), mFileName(tokenList->file(tok))
{}
ErrorMessage::FileLocation::FileLocation(const Token* tok, std::string info, const TokenList* tokenList)
: fileIndex(tok->fileIndex()), line(tok->linenr()), column(tok->column()), mOrigFileName(tokenList->getOrigFile(tok)), mFileName(tokenList->file(tok)), mInfo(std::move(info))
{}
std::string ErrorMessage::FileLocation::getfile(bool convert) const
{
if (convert)
return Path::toNativeSeparators(mFileName);
return mFileName;
}
std::string ErrorMessage::FileLocation::getOrigFile(bool convert) const
{
if (convert)
return Path::toNativeSeparators(mOrigFileName);
return mOrigFileName;
}
void ErrorMessage::FileLocation::setfile(std::string file)
{
mFileName = Path::simplifyPath(std::move(file));
}
std::string ErrorMessage::FileLocation::stringify() const
{
std::string str;
str += '[';
str += Path::toNativeSeparators(mFileName);
if (line != SuppressionList::Suppression::NO_LINE) {
str += ':';
str += std::to_string(line);
}
str += ']';
return str;
}
std::string ErrorLogger::toxml(const std::string &str)
{
std::string xml;
for (const unsigned char c : str) {
switch (c) {
case '<':
xml += "<";
break;
case '>':
xml += ">";
break;
case '&':
xml += "&";
break;
case '\"':
xml += """;
break;
case '\'':
xml += "'";
break;
case '\0':
xml += "\\0";
break;
default:
if (c >= ' ' && c <= 0x7f)
xml += c;
else
xml += 'x';
break;
}
}
return xml;
}
std::string ErrorLogger::plistHeader(const std::string &version, const std::vector<std::string> &files)
{
std::ostringstream ostr;
ostr << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
<< "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\r\n"
<< "<plist version=\"1.0\">\r\n"
<< "<dict>\r\n"
<< " <key>clang_version</key>\r\n"
<< "<string>cppcheck version " << version << "</string>\r\n"
<< " <key>files</key>\r\n"
<< " <array>\r\n";
for (const std::string & file : files)
ostr << " <string>" << ErrorLogger::toxml(file) << "</string>\r\n";
ostr << " </array>\r\n"
<< " <key>diagnostics</key>\r\n"
<< " <array>\r\n";
return ostr.str();
}
static std::string plistLoc(const char indent[], const ErrorMessage::FileLocation &loc)
{
std::ostringstream ostr;
ostr << indent << "<dict>\r\n"
<< indent << ' ' << "<key>line</key><integer>" << loc.line << "</integer>\r\n"
<< indent << ' ' << "<key>col</key><integer>" << loc.column << "</integer>\r\n"
<< indent << ' ' << "<key>file</key><integer>" << loc.fileIndex << "</integer>\r\n"
<< indent << "</dict>\r\n";
return ostr.str();
}
std::string ErrorLogger::plistData(const ErrorMessage &msg)
{
std::ostringstream plist;
plist << " <dict>\r\n"
<< " <key>path</key>\r\n"
<< " <array>\r\n";
std::list<ErrorMessage::FileLocation>::const_iterator prev = msg.callStack.cbegin();
for (std::list<ErrorMessage::FileLocation>::const_iterator it = msg.callStack.cbegin(); it != msg.callStack.cend(); ++it) {
if (prev != it) {
plist << " <dict>\r\n"
<< " <key>kind</key><string>control</string>\r\n"
<< " <key>edges</key>\r\n"
<< " <array>\r\n"
<< " <dict>\r\n"
<< " <key>start</key>\r\n"
<< " <array>\r\n"
<< plistLoc(" ", *prev)
<< plistLoc(" ", *prev)
<< " </array>\r\n"
<< " <key>end</key>\r\n"
<< " <array>\r\n"
<< plistLoc(" ", *it)
<< plistLoc(" ", *it)
<< " </array>\r\n"
<< " </dict>\r\n"
<< " </array>\r\n"
<< " </dict>\r\n";
prev = it;
}
std::list<ErrorMessage::FileLocation>::const_iterator next = it;
++next;
const std::string message = (it->getinfo().empty() && next == msg.callStack.cend() ? msg.shortMessage() : it->getinfo());
plist << " <dict>\r\n"
<< " <key>kind</key><string>event</string>\r\n"
<< " <key>location</key>\r\n"
<< plistLoc(" ", *it)
<< " <key>ranges</key>\r\n"
<< " <array>\r\n"
<< " <array>\r\n"
<< plistLoc(" ", *it)
<< plistLoc(" ", *it)
<< " </array>\r\n"
<< " </array>\r\n"
<< " <key>depth</key><integer>0</integer>\r\n"
<< " <key>extended_message</key>\r\n"
<< " <string>" << ErrorLogger::toxml(message) << "</string>\r\n"
<< " <key>message</key>\r\n"
<< " <string>" << ErrorLogger::toxml(message) << "</string>\r\n"
<< " </dict>\r\n";
}
plist << " </array>\r\n"
<< " <key>description</key><string>" << ErrorLogger::toxml(msg.shortMessage()) << "</string>\r\n"
<< " <key>category</key><string>" << severityToString(msg.severity) << "</string>\r\n"
<< " <key>type</key><string>" << ErrorLogger::toxml(msg.shortMessage()) << "</string>\r\n"
<< " <key>check_name</key><string>" << msg.id << "</string>\r\n"
<< " <!-- This hash is experimental and going to change! -->\r\n"
<< " <key>issue_hash_content_of_line_in_context</key><string>" << 0 << "</string>\r\n"
<< " <key>issue_context_kind</key><string></string>\r\n"
<< " <key>issue_context</key><string></string>\r\n"
<< " <key>issue_hash_function_offset</key><string></string>\r\n"
<< " <key>location</key>\r\n"
<< plistLoc(" ", msg.callStack.back())
<< " </dict>\r\n";
return plist.str();
}
std::string replaceStr(std::string s, const std::string &from, const std::string &to)
{
std::string::size_type pos1 = 0;
while (pos1 < s.size()) {
pos1 = s.find(from, pos1);
if (pos1 == std::string::npos)
return s;
if (pos1 > 0 && (s[pos1-1] == '_' || std::isalnum(s[pos1-1]))) {
pos1++;
continue;
}
const std::string::size_type pos2 = pos1 + from.size();
if (pos2 >= s.size())
return s.substr(0,pos1) + to;
if (s[pos2] == '_' || std::isalnum(s[pos2])) {
pos1++;
continue;
}
s.replace(pos1, from.size(), to);
pos1 += to.size();
}
return s;
}
void substituteTemplateFormatStatic(std::string& templateFormat)
{
replaceSpecialChars(templateFormat);
replaceColors(templateFormat);
}
void substituteTemplateLocationStatic(std::string& templateLocation)
{
replaceSpecialChars(templateLocation);
replaceColors(templateLocation);
}
| null |
831 | cpp | cppcheck | timer.h | lib/timer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef timerH
#define timerH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <ctime>
#include <functional>
#include <map>
#include <mutex>
#include <string>
#include <utility>
enum class SHOWTIME_MODES : std::uint8_t {
SHOWTIME_NONE,
SHOWTIME_FILE,
SHOWTIME_FILE_TOTAL,
SHOWTIME_SUMMARY,
SHOWTIME_TOP5_SUMMARY,
SHOWTIME_TOP5_FILE
};
class CPPCHECKLIB TimerResultsIntf {
public:
virtual ~TimerResultsIntf() = default;
virtual void addResults(const std::string& str, std::clock_t clocks) = 0;
};
struct TimerResultsData {
std::clock_t mClocks{};
long mNumberOfResults{};
double seconds() const {
const double ret = (double)((unsigned long)mClocks) / (double)CLOCKS_PER_SEC;
return ret;
}
};
class CPPCHECKLIB TimerResults : public TimerResultsIntf {
public:
TimerResults() = default;
void showResults(SHOWTIME_MODES mode) const;
void addResults(const std::string& str, std::clock_t clocks) override;
void reset();
private:
std::map<std::string, TimerResultsData> mResults;
mutable std::mutex mResultsSync;
};
class CPPCHECKLIB Timer {
public:
Timer(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults = nullptr);
Timer(bool fileTotal, std::string filename);
~Timer();
Timer(const Timer&) = delete;
Timer& operator=(const Timer&) = delete;
void stop();
static void run(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults, const std::function<void()>& f) {
Timer t(std::move(str), showtimeMode, timerResults);
f();
}
private:
const std::string mStr;
TimerResultsIntf* mTimerResults{};
std::clock_t mStart = std::clock();
const SHOWTIME_MODES mShowTimeMode = SHOWTIME_MODES::SHOWTIME_FILE_TOTAL;
bool mStopped{};
};
//---------------------------------------------------------------------------
#endif // timerH
| null |
832 | cpp | cppcheck | filesettings.h | lib/filesettings.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef fileSettingsH
#define fileSettingsH
#include "config.h"
#include "path.h"
#include "platform.h"
#include <list>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
class FileWithDetails
{
public:
explicit FileWithDetails(std::string path)
: FileWithDetails(std::move(path), 0)
{}
FileWithDetails(std::string path, std::size_t size)
: mPath(std::move(path))
, mPathSimplified(Path::simplifyPath(mPath))
, mSize(size)
{
if (mPath.empty())
throw std::runtime_error("empty path specified");
}
const std::string& path() const
{
return mPath;
}
const std::string& spath() const
{
return mPathSimplified;
}
std::size_t size() const
{
return mSize;
}
private:
std::string mPath;
std::string mPathSimplified;
std::size_t mSize;
};
/** File settings. Multiple configurations for a file is allowed. */
struct CPPCHECKLIB FileSettings {
explicit FileSettings(std::string path)
: file(std::move(path))
{}
FileSettings(std::string path, std::size_t size)
: file(std::move(path), size)
{}
std::string cfg;
FileWithDetails file;
const std::string& filename() const
{
return file.path();
}
// cppcheck-suppress unusedFunction
const std::string& sfilename() const
{
return file.spath();
}
std::string defines;
// TODO: handle differently
std::string cppcheckDefines() const {
return defines + (msc ? ";_MSC_VER=1900" : "") + (useMfc ? ";__AFXWIN_H__=1" : "");
}
std::set<std::string> undefs;
std::list<std::string> includePaths;
// only used by clang mode
std::list<std::string> systemIncludePaths;
std::string standard;
Platform::Type platformType = Platform::Type::Unspecified;
// TODO: get rid of these
bool msc{};
bool useMfc{};
};
#endif // fileSettingsH
| null |
833 | cpp | cppcheck | tokenlist.cpp | lib/tokenlist.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "tokenlist.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "keywords.h"
#include "library.h"
#include "path.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include <cctype>
#include <cstdint>
#include <exception>
#include <functional>
#include <iostream>
#include <utility>
#include <set>
#include <stack>
#include <unordered_set>
#include <simplecpp.h>
//#define N_ASSERT_LANG
#ifndef N_ASSERT_LANG
#include <cassert>
#define ASSERT_LANG(x) assert(x)
#else
#define ASSERT_LANG(x)
#endif
// How many compileExpression recursions are allowed?
// For practical code this could be endless. But in some special torture test
// there needs to be a limit.
static constexpr int AST_MAX_DEPTH = 150;
TokenList::TokenList(const Settings* settings)
: mTokensFrontBack(*this)
, mSettings(settings)
{
if (mSettings && (mSettings->enforcedLang != Standards::Language::None)) {
mLang = mSettings->enforcedLang;
}
}
TokenList::~TokenList()
{
deallocateTokens();
}
//---------------------------------------------------------------------------
const std::string& TokenList::getSourceFilePath() const
{
if (getFiles().empty()) {
return emptyString;
}
return getFiles()[0];
}
//---------------------------------------------------------------------------
// Deallocate lists..
void TokenList::deallocateTokens()
{
deleteTokens(mTokensFrontBack.front);
mTokensFrontBack.front = nullptr;
mTokensFrontBack.back = nullptr;
mFiles.clear();
}
void TokenList::determineCppC()
{
// only try to determine if it wasn't enforced
if (mLang == Standards::Language::None) {
ASSERT_LANG(!getSourceFilePath().empty());
mLang = Path::identify(getSourceFilePath(), mSettings ? mSettings->cppHeaderProbe : false);
// TODO: cannot enable assert as this might occur for unknown extensions
//ASSERT_LANG(mLang != Standards::Language::None);
if (mLang == Standards::Language::None) {
// TODO: should default to C instead like we do for headers
// default to C++
mLang = Standards::Language::CPP;
}
}
}
int TokenList::appendFileIfNew(std::string fileName)
{
// Has this file been tokenized already?
for (int i = 0; i < mFiles.size(); ++i)
if (Path::sameFileName(mFiles[i], fileName))
return i;
// The "mFiles" vector remembers what files have been tokenized..
mFiles.push_back(std::move(fileName));
// Update mIsC and mIsCpp properties
if (mFiles.size() == 1) { // Update only useful if first file added to _files
determineCppC();
}
return mFiles.size() - 1;
}
void TokenList::clangSetOrigFiles()
{
mOrigFiles = mFiles;
}
void TokenList::deleteTokens(Token *tok)
{
while (tok) {
Token *next = tok->next();
delete tok;
tok = next;
}
}
//---------------------------------------------------------------------------
// add a token.
//---------------------------------------------------------------------------
void TokenList::addtoken(const std::string& str, const nonneg int lineno, const nonneg int column, const nonneg int fileno, bool split)
{
if (str.empty())
return;
// If token contains # characters, split it up
if (split) {
size_t begin = 0;
size_t end = 0;
while ((end = str.find("##", begin)) != std::string::npos) {
addtoken(str.substr(begin, end - begin), lineno, fileno, false);
addtoken("##", lineno, column, fileno, false);
begin = end+2;
}
if (begin != 0) {
addtoken(str.substr(begin), lineno, column, fileno, false);
return;
}
}
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
}
void TokenList::addtoken(const std::string& str, const Token *locationTok)
{
if (str.empty())
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token * tok, const nonneg int lineno, const nonneg int column, const nonneg int fileno)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->linenr(lineno);
mTokensFrontBack.back->column(column);
mTokensFrontBack.back->fileIndex(fileno);
mTokensFrontBack.back->flags(tok->flags());
}
void TokenList::addtoken(const Token *tok, const Token *locationTok)
{
if (tok == nullptr || locationTok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
if (!tok->originalName().empty())
mTokensFrontBack.back->originalName(tok->originalName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(locationTok->linenr());
mTokensFrontBack.back->column(locationTok->column());
mTokensFrontBack.back->fileIndex(locationTok->fileIndex());
}
void TokenList::addtoken(const Token *tok)
{
if (tok == nullptr)
return;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(tok->str(), tok->originalName(), tok->getMacroName());
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(tok->str());
mTokensFrontBack.back->originalName(tok->originalName());
mTokensFrontBack.back->setMacroName(tok->getMacroName());
}
mTokensFrontBack.back->flags(tok->flags());
mTokensFrontBack.back->linenr(tok->linenr());
mTokensFrontBack.back->column(tok->column());
mTokensFrontBack.back->fileIndex(tok->fileIndex());
}
//---------------------------------------------------------------------------
// copyTokens - Copy and insert tokens
//---------------------------------------------------------------------------
Token *TokenList::copyTokens(Token *dest, const Token *first, const Token *last, bool one_line)
{
std::stack<Token *> links;
Token *tok2 = dest;
int linenr = dest->linenr();
const int commonFileIndex = dest->fileIndex();
for (const Token *tok = first; tok != last->next(); tok = tok->next()) {
tok2->insertToken(tok->str());
tok2 = tok2->next();
tok2->fileIndex(commonFileIndex);
tok2->linenr(linenr);
tok2->tokType(tok->tokType());
tok2->flags(tok->flags());
tok2->varId(tok->varId());
tok2->setTokenDebug(tok->getTokenDebug());
// Check for links and fix them up
if (Token::Match(tok2, "(|[|{"))
links.push(tok2);
else if (Token::Match(tok2, ")|]|}")) {
if (links.empty())
return tok2;
Token * link = links.top();
tok2->link(link);
link->link(tok2);
links.pop();
}
if (!one_line && tok->next())
linenr += tok->next()->linenr() - tok->linenr();
}
return tok2;
}
//---------------------------------------------------------------------------
// InsertTokens - Copy and insert tokens
//---------------------------------------------------------------------------
void TokenList::insertTokens(Token *dest, const Token *src, nonneg int n)
{
// TODO: put the linking in a helper?
std::stack<Token *> link;
while (n > 0) {
dest->insertToken(src->str(), src->originalName());
dest = dest->next();
// Set links
if (Token::Match(dest, "(|[|{"))
link.push(dest);
else if (!link.empty() && Token::Match(dest, ")|]|}")) {
Token::createMutualLinks(dest, link.top());
link.pop();
}
dest->fileIndex(src->fileIndex());
dest->linenr(src->linenr());
dest->column(src->column());
dest->varId(src->varId());
dest->tokType(src->tokType());
dest->flags(src->flags());
dest->setMacroName(src->getMacroName());
src = src->next();
--n;
}
}
//---------------------------------------------------------------------------
// Tokenize - tokenizes a given file.
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, const std::string& file0)
{
ASSERT_LANG(!file0.empty());
appendFileIfNew(file0);
return createTokensInternal(code, file0);
}
//---------------------------------------------------------------------------
bool TokenList::createTokens(std::istream &code, Standards::Language lang)
{
ASSERT_LANG(lang != Standards::Language::None);
if (mLang == Standards::Language::None) {
mLang = lang;
} else {
ASSERT_LANG(lang == mLang);
}
return createTokensInternal(code, "");
}
//---------------------------------------------------------------------------
bool TokenList::createTokensInternal(std::istream &code, const std::string& file0)
{
simplecpp::OutputList outputList;
simplecpp::TokenList tokens(code, mFiles, file0, &outputList);
createTokens(std::move(tokens));
return outputList.empty();
}
//---------------------------------------------------------------------------
// NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved)
void TokenList::createTokens(simplecpp::TokenList&& tokenList)
{
// TODO: what to do if the list has been filled already? clear mTokensFrontBack?
// tokenList.cfront() might be NULL if the file contained nothing to tokenize so we need to check the files instead
if (!tokenList.getFiles().empty()) {
// this is a copy
// TODO: this points to mFiles when called from createTokens(std::istream &, const std::string&)
mOrigFiles = mFiles = tokenList.getFiles();
}
else
mFiles.clear();
determineCppC();
for (const simplecpp::Token *tok = tokenList.cfront(); tok;) {
// TODO: move from TokenList
std::string str = tok->str();
// Float literal
if (str.size() > 1 && str[0] == '.' && std::isdigit(str[1]))
str = '0' + str;
if (mTokensFrontBack.back) {
mTokensFrontBack.back->insertToken(str);
} else {
mTokensFrontBack.front = new Token(mTokensFrontBack);
mTokensFrontBack.back = mTokensFrontBack.front;
mTokensFrontBack.back->str(str);
}
mTokensFrontBack.back->fileIndex(tok->location.fileIndex);
mTokensFrontBack.back->linenr(tok->location.line);
mTokensFrontBack.back->column(tok->location.col);
mTokensFrontBack.back->setMacroName(tok->macro);
tok = tok->next;
if (tok)
tokenList.deleteToken(tok->previous);
}
if (mSettings && mSettings->relativePaths) {
for (std::string & mFile : mFiles)
mFile = Path::getRelativePath(mFile, mSettings->basePaths);
}
Token::assignProgressValues(mTokensFrontBack.front);
}
//---------------------------------------------------------------------------
std::size_t TokenList::calculateHash() const
{
std::string hashData;
for (const Token* tok = front(); tok; tok = tok->next()) {
hashData += std::to_string(tok->flags());
hashData += std::to_string(tok->varId());
hashData += std::to_string(tok->tokType());
hashData += tok->str();
hashData += tok->originalName();
}
return (std::hash<std::string>{})(hashData);
}
//---------------------------------------------------------------------------
namespace {
struct AST_state {
std::stack<Token*> op;
int depth{};
int inArrayAssignment{};
bool cpp;
int assign{};
bool inCase{}; // true from case to :
bool stopAtColon{}; // help to properly parse ternary operators
const Token* functionCallEndPar{};
explicit AST_state(bool cpp) : cpp(cpp) {}
};
}
static Token* skipDecl(Token* tok, std::vector<Token*>* inner = nullptr)
{
auto isDecltypeFuncParam = [](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, ")"))
return false;
tok = tok->next();
while (Token::Match(tok, "*|&|&&|const"))
tok = tok->next();
if (Token::simpleMatch(tok, "("))
tok = tok->link()->next();
return Token::Match(tok, "%name%| ,|)");
};
if (!Token::Match(tok->previous(), "( %name%"))
return tok;
Token *vartok = tok;
while (Token::Match(vartok, "%name%|*|&|::|<")) {
if (vartok->str() == "<") {
if (vartok->link())
vartok = vartok->link();
else
return tok;
} else if (Token::Match(vartok, "%var% [:=({]")) {
return vartok;
} else if (Token::Match(vartok, "decltype|typeof (") && !isDecltypeFuncParam(tok->linkAt(1))) {
if (inner)
inner->push_back(vartok->tokAt(2));
return vartok->linkAt(1)->next();
}
vartok = vartok->next();
}
return tok;
}
static bool iscast(const Token *tok, bool cpp)
{
if (!Token::Match(tok, "( ::| %name%"))
return false;
if (Token::simpleMatch(tok->link(), ") ( )"))
return false;
if (Token::Match(tok->link(), ") %assign%|,|..."))
return false;
if (tok->previous() && tok->previous()->isName() && tok->strAt(-1) != "return" &&
(!cpp || !Token::Match(tok->previous(), "delete|throw")))
return false;
if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1))
return false;
if (Token::Match(tok, "( (| typeof (") && Token::Match(tok->link(), ") %num%"))
return true;
if (Token::Match(tok->link(), ") }|)|]|;"))
return false;
if (Token::Match(tok->link(), ") ++|-- [;)]"))
return false;
if (Token::Match(tok->link(), ") %cop%") && !Token::Match(tok->link(), ") [&*+-~!]"))
return false;
if (Token::Match(tok->previous(), "= ( %name% ) {") && tok->next()->varId() == 0)
return true;
bool type = false;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->varId() != 0)
return false;
if (cpp && !type && tok2->str() == "new")
return false;
while (tok2->link() && Token::Match(tok2, "(|[|<"))
tok2 = tok2->link()->next();
if (tok2->str() == ")") {
if (Token::simpleMatch(tok2, ") (") && Token::simpleMatch(tok2->linkAt(1), ") ."))
return true;
if (Token::simpleMatch(tok2, ") {") && !type) {
const Token *tok3 = tok2->linkAt(1);
while (tok3 != tok2 && Token::Match(tok3, "[{}]"))
tok3 = tok3->previous();
return tok3->str() != ";";
}
const bool res = type || tok2->strAt(-1) == "*" || Token::simpleMatch(tok2, ") ~") ||
(Token::Match(tok2, ") %any%") &&
(!tok2->next()->isOp() || Token::Match(tok2->next(), "!|~|++|--")) &&
!Token::Match(tok2->next(), "[[]);,?:.]"));
return res;
}
if (Token::Match(tok2, "&|&& )"))
return true;
if (!Token::Match(tok2, "%name%|*|::"))
return false;
if (tok2->isStandardType() && (tok2->strAt(1) != "(" || Token::Match(tok2->next(), "( * *| )")))
type = true;
}
return false;
}
// int(1), int*(2), ..
static Token * findCppTypeInitPar(Token *tok)
{
if (!tok || !Token::Match(tok->previous(), "[,()] %name%"))
return nullptr;
bool istype = false;
while (Token::Match(tok, "%name%|::|<")) {
if (tok->str() == "<") {
tok = tok->link();
if (!tok)
return nullptr;
}
istype |= tok->isStandardType();
tok = tok->next();
}
if (!istype)
return nullptr;
if (!Token::Match(tok, "[*&]"))
return nullptr;
while (Token::Match(tok, "[*&]"))
tok = tok->next();
return (tok && tok->str() == "(") ? tok : nullptr;
}
// X{} X<Y>{} etc
static bool iscpp11init_impl(const Token * tok);
static bool iscpp11init(const Token * const tok)
{
if (tok->isCpp11init() == TokenImpl::Cpp11init::UNKNOWN)
tok->setCpp11init(iscpp11init_impl(tok));
return tok->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
}
static bool iscpp11init_impl(const Token * const tok)
{
if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->link()->previous(), "; }"))
return false;
const Token *nameToken = tok;
while (nameToken && nameToken->str() == "{") {
if (nameToken->isCpp11init() != TokenImpl::Cpp11init::UNKNOWN)
return nameToken->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT;
nameToken = nameToken->previous();
if (nameToken && nameToken->str() == "," && Token::simpleMatch(nameToken->previous(), "} ,"))
nameToken = nameToken->linkAt(-1);
}
if (!nameToken)
return false;
if (nameToken->str() == ")" && Token::simpleMatch(nameToken->link()->previous(), "decltype (") &&
!Token::simpleMatch(nameToken->link()->tokAt(-2), "."))
nameToken = nameToken->link()->previous();
if (Token::simpleMatch(nameToken, ", {"))
return true;
if (nameToken->str() == ">" && nameToken->link())
nameToken = nameToken->link()->previous();
if (Token::Match(nameToken, "]|*")) {
const Token* newTok = nameToken->link() ? nameToken->link()->previous() : nameToken->previous();
while (Token::Match(newTok, "%type%|::|*") && !newTok->isKeyword())
newTok = newTok->previous();
if (Token::simpleMatch(newTok, "new"))
return true;
}
auto isCaseStmt = [](const Token* colonTok) {
if (!Token::Match(colonTok->tokAt(-1), "%name%|%num%|%char%|) :"))
return false;
if (const Token* castTok = colonTok->linkAt(-1)) {
if (Token::simpleMatch(castTok->astParent(), "case"))
return true;
}
const Token* caseTok = colonTok->tokAt(-2);
while (caseTok && Token::Match(caseTok->tokAt(-1), "::|%name%"))
caseTok = caseTok->tokAt(-1);
return Token::simpleMatch(caseTok, "case");
};
const Token *endtok = nullptr;
if (Token::Match(nameToken, "%name%|return|: {") && !isCaseStmt(nameToken) &&
(!Token::simpleMatch(nameToken->tokAt(2), "[") || findLambdaEndScope(nameToken->tokAt(2))))
endtok = nameToken->linkAt(1);
else if (Token::Match(nameToken,"%name% <") && Token::simpleMatch(nameToken->linkAt(1),"> {"))
endtok = nameToken->linkAt(1)->linkAt(1);
else if (Token::Match(nameToken->previous(), "%name%|> ( {"))
endtok = nameToken->linkAt(1);
else if (Token::simpleMatch(nameToken, "decltype") && nameToken->linkAt(1))
endtok = nameToken->linkAt(1)->linkAt(1);
else
return false;
if (Token::Match(nameToken, "else|try|do|const|constexpr|override|volatile|&|&&"))
return false;
if (Token::simpleMatch(nameToken->previous(), ". void {") && nameToken->previous()->originalName() == "->")
return false; // trailing return type. The only function body that can contain no semicolon is a void function.
if (Token::simpleMatch(nameToken->previous(), "namespace") || Token::simpleMatch(nameToken, "namespace") /*anonymous namespace*/)
return false;
if (precedes(nameToken->next(), endtok) && !Token::Match(nameToken, "return|:")) {
// If there is semicolon between {..} this is not a initlist
for (const Token *tok2 = nameToken->next(); tok2 != endtok; tok2 = tok2->next()) {
if (tok2->str() == ";")
return false;
const Token * lambdaEnd = findLambdaEndScope(tok2);
if (lambdaEnd)
tok2 = lambdaEnd;
}
}
// There is no initialisation for example here: 'class Fred {};'
if (!Token::simpleMatch(endtok, "} ;"))
return true;
const Token *prev = nameToken;
while (Token::Match(prev, "%name%|::|:|<|>|(|)|,|%num%|%cop%|...")) {
if (Token::Match(prev, "class|struct|union|enum"))
return false;
prev = prev->previous();
}
return true;
}
static bool isQualifier(const Token* tok)
{
while (Token::Match(tok, "&|&&|*"))
tok = tok->next();
return Token::Match(tok, "{|;");
}
static void compileUnaryOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state))
{
Token *unaryop = tok;
if (f) {
tok = tok->next();
state.depth++;
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
if (tok)
f(tok, state);
state.depth--;
}
if (!state.op.empty() && (!precedes(state.op.top(), unaryop) || unaryop->isIncDecOp() || Token::Match(unaryop, "[({[]"))) { // nullary functions, empty lists/arrays
unaryop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(unaryop);
}
static void compileBinOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state))
{
Token *binop = tok;
if (f) {
tok = tok->next();
if (Token::Match(binop, "::|. ~"))
tok = tok->next();
state.depth++;
if (tok && state.depth <= AST_MAX_DEPTH)
f(tok, state);
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST);
state.depth--;
}
// TODO: Should we check if op is empty.
// * Is it better to add assertion that it isn't?
// * Write debug warning if it's empty?
if (!state.op.empty()) {
binop->astOperand2(state.op.top());
state.op.pop();
}
if (!state.op.empty()) {
binop->astOperand1(state.op.top());
state.op.pop();
}
state.op.push(binop);
}
static void compileExpression(Token *&tok, AST_state& state);
static void compileTerm(Token *&tok, AST_state& state)
{
if (!tok)
return;
if (Token::Match(tok, "L %str%|%char%"))
tok = tok->next();
if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] . %name%")) { // Jump over . in C style struct initialization
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(2);
}
if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] [ %num%|%name% ]")) {
state.op.push(tok);
tok->astOperand1(tok->next());
tok = tok->tokAt(3);
}
if (tok->isLiteral()) {
state.op.push(tok);
do {
tok = tok->next();
} while (Token::Match(tok, "%name%|%str%"));
} else if (tok->isName()) {
if (Token::Match(tok, "return|case") || (state.cpp && (tok->str() == "throw"))) {
if (tok->str() == "case")
state.inCase = true;
const bool tokIsReturn = tok->str() == "return";
const bool stopAtColon = state.stopAtColon;
state.stopAtColon=true;
compileUnaryOp(tok, state, compileExpression);
state.stopAtColon=stopAtColon;
if (tokIsReturn)
state.op.pop();
if (state.inCase && Token::simpleMatch(tok, ": ;")) {
state.inCase = false;
tok = tok->next();
}
} else if (Token::Match(tok, "sizeof !!(")) {
compileUnaryOp(tok, state, compileExpression);
state.op.pop();
} else if (state.cpp && findCppTypeInitPar(tok)) { // int(0), int*(123), ..
tok = findCppTypeInitPar(tok);
state.op.push(tok);
tok = tok->tokAt(2);
} else if (state.cpp && iscpp11init(tok)) { // X{} X<Y>{} etc
state.op.push(tok);
tok = tok->next();
if (tok->str() == "<")
tok = tok->link()->next();
if (Token::Match(tok, "{ . %name% =|{")) {
const Token* end = tok->link();
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
if (tok == end)
tok = tok->next();
else
throw InternalError(tok, "Syntax error. Unexpected tokens in designated initializer.", InternalError::AST);
}
} else if (!state.cpp || !Token::Match(tok, "new|delete %name%|*|&|::|(|[")) {
std::vector<Token*> inner;
tok = skipDecl(tok, &inner);
for (Token* tok3 : inner) {
AST_state state1(state.cpp);
compileExpression(tok3, state1);
}
bool repeat = true;
while (repeat) {
repeat = false;
if (Token::Match(tok->next(), "%name%")) {
tok = tok->next();
repeat = true;
}
if (Token::simpleMatch(tok->next(), "<") && Token::Match(tok->linkAt(1), "> %name%")) {
tok = tok->linkAt(1)->next();
repeat = true;
}
}
state.op.push(tok);
if (Token::Match(tok, "%name% <") && tok->linkAt(1))
tok = tok->linkAt(1);
else if (Token::Match(tok, "%name% ...") || (state.op.size() == 1 && state.depth == 0 && Token::Match(tok->tokAt(-3), "!!& ) ( %name% ) =")))
tok = tok->next();
tok = tok->next();
if (Token::Match(tok, "%str%")) {
while (Token::Match(tok, "%name%|%str%"))
tok = tok->next();
}
if (Token::Match(tok, "%name% %assign%"))
tok = tok->next();
}
} else if (tok->str() == "{") {
const Token *prev = tok->previous();
if (Token::simpleMatch(prev, ") {") && iscast(prev->link(), state.cpp))
prev = prev->link()->previous();
if (Token::simpleMatch(tok->link(),"} [")) {
tok = tok->next();
} else if ((state.cpp && iscpp11init(tok)) || Token::simpleMatch(tok->previous(), "] {")) {
Token *const end = tok->link();
if (state.op.empty() || Token::Match(tok->previous(), "[{,]") || Token::Match(tok->tokAt(-2), "%name% (")) {
if (Token::Match(tok->tokAt(-1), "!!, { . %name% =|{")) {
const int inArrayAssignment = state.inArrayAssignment;
state.inArrayAssignment = 1;
compileBinOp(tok, state, compileExpression);
state.inArrayAssignment = inArrayAssignment;
} else if (Token::simpleMatch(tok, "{ }")) {
state.op.push(tok);
tok = tok->next();
} else {
compileUnaryOp(tok, state, compileExpression);
if (precedes(tok,end)) // typically for something like `MACRO(x, { if (c) { ... } })`, where end is the last curly, and tok is the open curly for the if
tok = end;
}
} else
compileBinOp(tok, state, compileExpression);
if (tok != end)
throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST);
if (tok->next())
tok = tok->next();
} else if (state.cpp && Token::Match(tok->tokAt(-2), "%name% ( {") && !Token::findsimplematch(tok, ";", tok->link())) {
if (Token::simpleMatch(tok, "{ }"))
tok = tok->tokAt(2);
else {
Token *tok1 = tok;
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
state.inArrayAssignment--;
tok = tok1->link()->next();
}
} else if (!state.inArrayAssignment && !Token::simpleMatch(prev, "=")) {
state.op.push(tok);
tok = tok->link()->next();
} else {
if (tok->link() != tok->next()) {
state.inArrayAssignment++;
compileUnaryOp(tok, state, compileExpression);
if (Token::Match(tok, "} [,};]") && state.inArrayAssignment > 0) {
tok = tok->next();
state.inArrayAssignment--;
}
} else {
state.op.push(tok);
tok = tok->tokAt(2);
}
}
}
}
static void compileScope(Token *&tok, AST_state& state)
{
compileTerm(tok, state);
while (tok) {
if (tok->str() == "::") {
const Token *lastOp = state.op.empty() ? nullptr : state.op.top();
if (Token::Match(lastOp, ":: %name%"))
lastOp = lastOp->next();
if (Token::Match(lastOp, "%name%") &&
(lastOp->next() == tok || (Token::Match(lastOp, "%name% <") && lastOp->linkAt(1) && tok == lastOp->linkAt(1)->next())))
compileBinOp(tok, state, compileTerm);
else
compileUnaryOp(tok, state, compileTerm);
} else break;
}
}
static bool isPrefixUnary(const Token* tok, bool cpp)
{
if (cpp && Token::simpleMatch(tok->previous(), "* [") && Token::simpleMatch(tok->link(), "] {")) {
for (const Token* prev = tok->previous(); Token::Match(prev, "%name%|::|*|&|>|>>"); prev = prev->previous()) {
if (Token::Match(prev, ">|>>")) {
if (!prev->link())
break;
prev = prev->link();
}
if (prev->str() == "new")
return false;
}
}
if (!tok->previous()
|| ((Token::Match(tok->previous(), "(|[|{|%op%|;|?|:|,|.|case|return|::") || (cpp && tok->strAt(-1) == "throw"))
&& (tok->previous()->tokType() != Token::eIncDecOp || tok->tokType() == Token::eIncDecOp)))
return true;
if (tok->strAt(-1) == "}") {
const Token* parent = tok->linkAt(-1)->tokAt(-1);
return !Token::Match(parent, "%type%") || parent->isKeyword();
}
if (tok->str() == "*" && tok->previous()->tokType() == Token::eIncDecOp && isPrefixUnary(tok->previous(), cpp))
return true;
return tok->strAt(-1) == ")" && iscast(tok->linkAt(-1), cpp);
}
static void compilePrecedence2(Token *&tok, AST_state& state)
{
auto doCompileScope = [&](const Token* tok) -> bool {
const bool isStartOfCpp11Init = state.cpp && tok && tok->str() == "{" && iscpp11init(tok);
if (isStartOfCpp11Init || Token::simpleMatch(tok, "(")) {
tok = tok->previous();
while (Token::simpleMatch(tok, "*"))
tok = tok->previous();
while (tok && Token::Match(tok->previous(), ":: %type%"))
tok = tok->tokAt(-2);
if (tok && !tok->isKeyword())
tok = tok->previous();
return !Token::Match(tok, "new ::| %type%");
}
return !findLambdaEndTokenWithoutAST(tok);
};
bool isNew = true;
if (doCompileScope(tok)) {
compileScope(tok, state);
isNew = false;
}
while (tok) {
if (tok->tokType() == Token::eIncDecOp && !isPrefixUnary(tok, state.cpp)) {
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "...") {
if (!Token::simpleMatch(tok->previous(), ")"))
state.op.push(tok);
tok = tok->next();
break;
} else if (tok->str() == "." && tok->strAt(1) != "*") {
if (tok->strAt(1) == ".") {
state.op.push(tok);
tok = tok->tokAt(3);
break;
}
if (!Token::Match(tok->tokAt(-1), "[{,]"))
compileBinOp(tok, state, compileScope);
else
compileUnaryOp(tok, state, compileScope);
} else if (tok->str() == "[") {
if (state.cpp && isPrefixUnary(tok, /*cpp*/ true) && Token::Match(tok->link(), "] (|{|<")) { // Lambda
// What we do here:
// - Nest the round bracket under the square bracket.
// - Nest what follows the lambda (if anything) with the lambda opening [
// - Compile the content of the lambda function as separate tree (this is done later)
// this must be consistent with isLambdaCaptureList
Token* const squareBracket = tok;
// Parse arguments in the capture list
if (tok->strAt(1) != "]") {
Token* tok2 = tok->next();
AST_state state2(state.cpp);
compileExpression(tok2, state2);
if (!state2.op.empty()) {
squareBracket->astOperand2(state2.op.top());
}
}
const bool hasTemplateArg = Token::simpleMatch(squareBracket->link(), "] <") &&
Token::simpleMatch(squareBracket->link()->linkAt(1), "> (");
if (Token::simpleMatch(squareBracket->link(), "] (") || hasTemplateArg) {
Token* const roundBracket = hasTemplateArg ? squareBracket->link()->linkAt(1)->next() : squareBracket->link()->next();
Token* curlyBracket = roundBracket->link()->next();
while (Token::Match(curlyBracket, "mutable|const|constexpr|consteval"))
curlyBracket = curlyBracket->next();
if (Token::simpleMatch(curlyBracket, "noexcept")) {
if (Token::simpleMatch(curlyBracket->next(), "("))
curlyBracket = curlyBracket->linkAt(1)->next();
else
curlyBracket = curlyBracket->next();
}
if (curlyBracket && curlyBracket->originalName() == "->")
curlyBracket = findTypeEnd(curlyBracket->next());
if (curlyBracket && curlyBracket->str() == "{") {
squareBracket->astOperand1(roundBracket);
roundBracket->astOperand1(curlyBracket);
state.op.push(squareBracket);
tok = curlyBracket->link()->next();
continue;
}
} else {
Token* const curlyBracket = squareBracket->link()->next();
squareBracket->astOperand1(curlyBracket);
state.op.push(squareBracket);
tok = curlyBracket->link() ? curlyBracket->link()->next() : nullptr;
continue;
}
}
Token* const tok2 = tok;
if (tok->strAt(1) != "]") {
compileBinOp(tok, state, compileExpression);
if (Token::Match(tok2->previous(), "%type%|* [") && Token::Match(tok, "] { !!}")) {
tok = tok->next();
Token* const tok3 = tok;
compileBinOp(tok, state, compileExpression);
if (tok != tok3->link())
throw InternalError(tok, "Syntax error in {..}", InternalError::AST);
tok = tok->next();
continue;
}
}
else
compileUnaryOp(tok, state, compileExpression);
tok = tok2->link()->next();
} else if (Token::simpleMatch(tok->previous(), "requires {")) {
state.op.push(tok);
tok = tok->link()->next();
continue;
} else if (Token::simpleMatch(tok, "( {") && Token::simpleMatch(tok->linkAt(1)->previous(), "; } )") &&
!Token::Match(tok->previous(), "%name% (")) {
state.op.push(tok->next());
tok = tok->link()->next();
continue;
} else if (tok->str() == "(" &&
(!iscast(tok, state.cpp) || Token::Match(tok->previous(), "if|while|for|switch|catch"))) {
Token* tok2 = tok;
tok = tok->next();
const bool opPrevTopSquare = !state.op.empty() && state.op.top() && state.op.top()->str() == "[";
const std::size_t oldOpSize = state.op.size();
compileExpression(tok, state);
tok = tok2;
if ((oldOpSize > 0 && (isNew || Token::simpleMatch(tok->previous(), "} (")))
|| (tok->previous() && tok->previous()->isName() && !Token::Match(tok->previous(), "return|case") && (!state.cpp || !Token::Match(tok->previous(), "throw|delete")))
|| (tok->strAt(-1) == "]" && (!state.cpp || !Token::Match(tok->linkAt(-1)->previous(), "new|delete")))
|| (tok->strAt(-1) == ">" && tok->linkAt(-1))
|| (tok->strAt(-1) == ")" && !iscast(tok->linkAt(-1), state.cpp)) // Don't treat brackets to clarify precedence as function calls
|| (tok->strAt(-1) == "}" && opPrevTopSquare)) {
const bool operandInside = oldOpSize < state.op.size();
if (operandInside)
compileBinOp(tok, state, nullptr);
else
compileUnaryOp(tok, state, nullptr);
}
tok = tok->link()->next();
if (Token::simpleMatch(tok, "::"))
compileBinOp(tok, state, compileTerm);
} else if (iscast(tok, state.cpp) && Token::simpleMatch(tok->link(), ") {") &&
Token::simpleMatch(tok->link()->linkAt(1), "} [")) {
Token *cast = tok;
tok = tok->link()->next();
Token *tok1 = tok;
compileUnaryOp(tok, state, compileExpression);
cast->astOperand1(tok1);
tok = tok1->link()->next();
} else if (state.cpp && tok->str() == "{" && iscpp11init(tok)) {
Token* end = tok->link();
if (Token::simpleMatch(tok, "{ }"))
{
compileUnaryOp(tok, state, nullptr);
tok = tok->next();
}
else
{
compileBinOp(tok, state, compileExpression);
}
if (tok == end)
tok = end->next();
else
throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST);
} else
break;
}
}
static void compilePrecedence3(Token *&tok, AST_state& state)
{
compilePrecedence2(tok, state);
while (tok) {
if ((Token::Match(tok, "[+-!~*&]") || tok->tokType() == Token::eIncDecOp) &&
isPrefixUnary(tok, state.cpp)) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
continue;
}
}
compileUnaryOp(tok, state, compilePrecedence3);
} else if (tok->str() == "(" && iscast(tok, state.cpp)) {
Token* castTok = tok;
castTok->isCast(true);
tok = tok->link()->next();
const int inArrayAssignment = state.inArrayAssignment;
if (tok && tok->str() == "{")
state.inArrayAssignment = 1;
compilePrecedence3(tok, state);
state.inArrayAssignment = inArrayAssignment;
compileUnaryOp(castTok, state, nullptr);
} else if (state.cpp && Token::Match(tok, "new %name%|::|(")) {
Token* newtok = tok;
tok = tok->next();
bool innertype = false;
if (tok->str() == "(") {
if (Token::Match(tok, "( &| %name%") && Token::Match(tok->link(), ") ( %type%") && Token::simpleMatch(tok->link()->linkAt(1), ") ("))
tok = tok->link()->next();
if (Token::Match(tok->link(), ") ::| %type%")) {
if (Token::Match(tok, "( !!)")) {
Token *innerTok = tok->next();
AST_state innerState(true);
compileExpression(innerTok, innerState);
}
tok = tok->link()->next();
} else if (Token::Match(tok, "( %type%") && Token::Match(tok->link(), ") [();,[]")) {
tok = tok->next();
innertype = true;
} else if (Token::Match(tok, "( &| %name%") && Token::simpleMatch(tok->link(), ") (")) {
tok = tok->next();
innertype = true;
} else {
/* bad code */
continue;
}
}
Token* leftToken = tok;
if (Token::simpleMatch(tok, "::")) {
tok->astOperand1(tok->next());
tok = tok->next();
}
else {
while (Token::Match(tok->next(), ":: %name%")) {
Token* scopeToken = tok->next(); //The ::
scopeToken->astOperand1(leftToken);
scopeToken->astOperand2(scopeToken->next());
leftToken = scopeToken;
tok = scopeToken->next();
}
}
state.op.push(tok);
while (Token::Match(tok, "%name%|*|&|<|::")) {
if (tok->link())
tok = tok->link();
tok = tok->next();
}
if (Token::Match(tok, "( const| %type% ) (")) {
state.op.push(tok->next());
tok = tok->link()->next();
compileBinOp(tok, state, compilePrecedence2);
} else if (Token::Match(tok, "(|{|["))
compilePrecedence2(tok, state);
else if (innertype && Token::simpleMatch(tok, ") [")) {
tok = tok->next();
compilePrecedence2(tok, state);
}
compileUnaryOp(newtok, state, nullptr);
if (Token::simpleMatch(newtok->previous(), ":: new")) {
newtok->previous()->astOperand1(newtok);
state.op.pop();
}
if (innertype && Token::simpleMatch(tok, ") ,"))
tok = tok->next();
} else if (state.cpp && Token::Match(tok, "delete %name%|*|&|::|(|[")) {
Token* tok2 = tok;
tok = tok->next();
if (tok && tok->str() == "[")
tok = tok->link()->next();
compilePrecedence3(tok, state);
compileUnaryOp(tok2, state, nullptr);
if (Token::simpleMatch(tok2->previous(), ":: delete")) {
tok2->previous()->astOperand1(tok2);
state.op.pop();
}
}
// TODO: Handle sizeof
else break;
}
}
static void compilePointerToElem(Token *&tok, AST_state& state)
{
compilePrecedence3(tok, state);
while (tok) {
if (Token::simpleMatch(tok, ". *")) {
compileBinOp(tok, state, compilePrecedence3);
} else break;
}
}
static void compileMulDiv(Token *&tok, AST_state& state)
{
compilePointerToElem(tok, state);
while (tok) {
if (Token::Match(tok, "[/%]") || (tok->str() == "*" && !tok->astOperand1() && !isQualifier(tok))) {
if (Token::Match(tok, "* [*,)]")) {
Token* tok2 = tok->next();
while (tok2->next() && tok2->str() == "*")
tok2 = tok2->next();
if (Token::Match(tok2, "[>),]")) {
tok = tok2;
break;
}
}
compileBinOp(tok, state, compilePointerToElem);
} else break;
}
}
static void compileAddSub(Token *&tok, AST_state& state)
{
compileMulDiv(tok, state);
while (tok) {
if (Token::Match(tok, "+|-") && !tok->astOperand1()) {
compileBinOp(tok, state, compileMulDiv);
} else break;
}
}
static void compileShift(Token *&tok, AST_state& state)
{
compileAddSub(tok, state);
while (tok) {
if (Token::Match(tok, "<<|>>")) {
compileBinOp(tok, state, compileAddSub);
} else break;
}
}
static void compileThreewayComp(Token *&tok, AST_state& state)
{
compileShift(tok, state);
while (tok) {
if (tok->str() == "<=>") {
compileBinOp(tok, state, compileShift);
} else break;
}
}
static void compileRelComp(Token *&tok, AST_state& state)
{
compileThreewayComp(tok, state);
while (tok) {
if (Token::Match(tok, "<|<=|>=|>") && !tok->link()) {
compileBinOp(tok, state, compileThreewayComp);
} else break;
}
}
static void compileEqComp(Token *&tok, AST_state& state)
{
compileRelComp(tok, state);
while (tok) {
if (Token::Match(tok, "==|!=")) {
compileBinOp(tok, state, compileRelComp);
} else break;
}
}
static void compileAnd(Token *&tok, AST_state& state)
{
compileEqComp(tok, state);
while (tok) {
if (tok->str() == "&" && !tok->astOperand1() && !isQualifier(tok)) {
Token* tok2 = tok->next();
if (!tok2)
break;
if (tok2->str() == "&")
tok2 = tok2->next();
if (state.cpp && Token::Match(tok2, ",|)")) {
tok = tok2;
break; // rValue reference
}
compileBinOp(tok, state, compileEqComp);
} else break;
}
}
static void compileXor(Token *&tok, AST_state& state)
{
compileAnd(tok, state);
while (tok) {
if (tok->str() == "^") {
compileBinOp(tok, state, compileAnd);
} else break;
}
}
static void compileOr(Token *&tok, AST_state& state)
{
compileXor(tok, state);
while (tok) {
if (tok->str() == "|") {
compileBinOp(tok, state, compileXor);
} else break;
}
}
static void compileLogicAnd(Token *&tok, AST_state& state)
{
compileOr(tok, state);
while (tok) {
if (tok->str() == "&&" && !isQualifier(tok)) {
if (!tok->astOperand1()) {
Token* tok2 = tok->next();
if (!tok2)
break;
if (state.cpp && Token::Match(tok2, ",|)")) {
tok = tok2;
break; // rValue reference
}
}
compileBinOp(tok, state, compileOr);
} else break;
}
}
static void compileLogicOr(Token *&tok, AST_state& state)
{
compileLogicAnd(tok, state);
while (tok) {
if (tok->str() == "||") {
compileBinOp(tok, state, compileLogicAnd);
} else break;
}
}
static void compileAssignTernary(Token *&tok, AST_state& state)
{
compileLogicOr(tok, state);
while (tok) {
if (tok->isAssignmentOp()) {
state.assign++;
const Token *tok1 = tok->next();
compileBinOp(tok, state, compileAssignTernary);
if (Token::simpleMatch(tok1, "{") && tok == tok1->link() && tok->next())
tok = tok->next();
if (state.assign > 0)
state.assign--;
} else if (tok->str() == "?") {
// http://en.cppreference.com/w/cpp/language/operator_precedence says about ternary operator:
// "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored."
// Hence, we rely on Tokenizer::prepareTernaryOpForAST() to add such parentheses where necessary.
const bool stopAtColon = state.stopAtColon;
state.stopAtColon = false;
if (tok->strAt(1) == ":") {
state.op.push(nullptr);
}
const int assign = state.assign;
state.assign = 0;
compileBinOp(tok, state, compileAssignTernary);
state.assign = assign;
state.stopAtColon = stopAtColon;
} else if (tok->str() == ":") {
if (state.depth == 1U && state.inCase) {
state.inCase = false;
tok = tok->next();
break;
}
if (state.stopAtColon)
break;
if (state.assign > 0)
break;
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileComma(Token *&tok, AST_state& state)
{
compileAssignTernary(tok, state);
while (tok) {
if (tok->str() == ",") {
if (Token::simpleMatch(tok, ", }"))
tok = tok->next();
else
compileBinOp(tok, state, compileAssignTernary);
} else if (tok->str() == ";" && state.functionCallEndPar && tok->index() < state.functionCallEndPar->index()) {
compileBinOp(tok, state, compileAssignTernary);
} else break;
}
}
static void compileExpression(Token *&tok, AST_state& state)
{
if (state.depth > AST_MAX_DEPTH)
throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST); // ticket #5592
if (tok)
compileComma(tok, state);
}
const Token* isLambdaCaptureList(const Token * tok)
{
// a lambda expression '[x](y){}' is compiled as:
// [
// `-( <<-- optional
// `-{
// see compilePrecedence2
if (!Token::simpleMatch(tok, "["))
return nullptr;
if (!Token::Match(tok->link(), "] (|{"))
return nullptr;
if (Token::simpleMatch(tok->astOperand1(), "{") && tok->astOperand1() == tok->link()->next())
return tok->astOperand1();
if (!tok->astOperand1() || tok->astOperand1()->str() != "(")
return nullptr;
const Token * params = tok->astOperand1();
if (!Token::simpleMatch(params->astOperand1(), "{"))
return nullptr;
return params->astOperand1();
}
const Token* findLambdaEndTokenWithoutAST(const Token* tok) {
if (!(Token::simpleMatch(tok, "[") && tok->link()))
return nullptr;
tok = tok->link()->next();
if (Token::simpleMatch(tok, "(") && tok->link())
tok = tok->link()->next();
if (Token::simpleMatch(tok, ".")) { // trailing return type
tok = tok->next();
while (Token::Match(tok, "%type%|%name%|::|&|&&|*|<|(")) {
if (tok->link())
tok = tok->link()->next();
else
tok = tok->next();
}
}
if (!(Token::simpleMatch(tok, "{") && tok->link()))
return nullptr;
return tok->link()->next();
}
static Token * createAstAtToken(Token *tok);
// Compile inner expressions inside inner ({..}) and lambda bodies
static void createAstAtTokenInner(Token * const tok1, const Token *endToken, bool cpp)
{
for (Token* tok = tok1; precedes(tok, endToken); tok = tok ? tok->next() : nullptr) {
if (tok->str() == "{" && !iscpp11init(tok)) {
const Token * const endToken2 = tok->link();
bool hasAst = false;
for (const Token *inner = tok->next(); inner != endToken2; inner = inner->next()) {
if (inner->astOperand1()) {
hasAst = true;
break;
}
if (tok->isConstOp())
break;
if (inner->str() == "{")
inner = inner->link();
}
if (!hasAst) {
for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr)
tok = createAstAtToken(tok);
}
} else if (cpp && tok->str() == "[") {
if (isLambdaCaptureList(tok)) {
tok = tok->astOperand1();
if (tok->str() == "(")
tok = tok->astOperand1();
const Token * const endToken2 = tok->link();
tok = tok->next();
for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr)
tok = createAstAtToken(tok);
}
}
else if (Token::simpleMatch(tok, "( * ) [")) {
bool hasAst = false;
for (const Token* tok2 = tok->linkAt(3); tok2 != tok; tok2 = tok2->previous()) {
if (tok2->astParent() || tok2->astOperand1() || tok2->astOperand2()) {
hasAst = true;
break;
}
}
if (!hasAst) {
Token *const startTok = tok = tok->tokAt(4);
const Token* const endtok = startTok->linkAt(-1);
AST_state state(cpp);
compileExpression(tok, state);
createAstAtTokenInner(startTok, endtok, cpp);
}
}
}
}
static Token * findAstTop(Token *tok1, const Token *tok2)
{
for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) {
if (tok->astParent() || tok->astOperand1() || tok->astOperand2()) {
while (tok->astParent() && tok->astParent()->index() >= tok1->index() && tok->astParent()->index() <= tok2->index())
tok = tok->astParent();
return tok;
}
if (Token::simpleMatch(tok, "( {"))
tok = tok->link();
}
for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) {
if (tok->isName() || tok->isNumber())
return tok;
if (Token::simpleMatch(tok, "( {"))
tok = tok->link();
}
return nullptr;
}
static Token * createAstAtToken(Token *tok)
{
const bool cpp = tok->isCpp();
// skip function pointer declaration
if (Token::Match(tok, "%type% %type%") && !Token::Match(tok, "return|throw|new|delete")) {
Token* tok2 = tok->tokAt(2);
// skip type tokens and qualifiers etc
while (Token::Match(tok2, "%type%|*|&"))
tok2 = tok2->next();
if (Token::Match(tok2, "%var% [;,)]"))
return tok2;
}
if (Token::Match(tok, "%type%") && !Token::Match(tok, "return|throw|if|while|new|delete")) {
bool isStandardTypeOrQualifier = false;
Token* type = tok;
while (Token::Match(type, "%type%|*|&|<")) {
if (type->isName() && (type->isStandardType() || Token::Match(type, "const|mutable|static|volatile")))
isStandardTypeOrQualifier = true;
if (type->str() == "<") {
if (type->link())
type = type->link();
else
break;
}
type = type->next();
}
if (isStandardTypeOrQualifier && Token::Match(type, "%var% [;,)]"))
return type;
if (Token::Match(type, "( * *| %var%") &&
Token::Match(type->link()->previous(), "%var%|] ) (") &&
Token::Match(type->link()->linkAt(1), ") [;,)]"))
return type->link()->linkAt(1)->next();
}
if (Token::simpleMatch(tok, "for (")) {
if (cpp && Token::Match(tok, "for ( const| auto &|&&| [")) {
Token *decl = Token::findsimplematch(tok, "[");
if (Token::simpleMatch(decl->link(), "] :")) {
AST_state state1(cpp);
while (decl->str() != "]") {
if (Token::Match(decl, "%name% ,|]")) {
state1.op.push(decl);
} else if (decl->str() == ",") {
if (!state1.op.empty()) {
decl->astOperand1(state1.op.top());
state1.op.pop();
}
if (!state1.op.empty()) {
state1.op.top()->astOperand2(decl);
state1.op.pop();
}
state1.op.push(decl);
}
decl = decl->next();
}
if (state1.op.size() > 1) {
Token *lastName = state1.op.top();
state1.op.pop();
state1.op.top()->astOperand2(lastName);
}
decl = decl->next();
Token *colon = decl;
compileExpression(decl, state1);
tok->next()->astOperand1(tok);
tok->next()->astOperand2(colon);
return decl;
}
}
std::vector<Token*> inner;
Token* tok2 = skipDecl(tok->tokAt(2), &inner);
for (Token* tok3 : inner) {
AST_state state1(cpp);
compileExpression(tok3, state1);
}
Token *init1 = nullptr;
Token * const endPar = tok->linkAt(1);
if (tok2 == tok->tokAt(2) && Token::Match(tok2, "%op%|(")) {
init1 = tok2;
AST_state state1(cpp);
compileExpression(tok2, state1);
if (Token::Match(init1, "( !!{")) {
for (Token *tok3 = init1; tok3 && tok3 != tok3->link(); tok3 = tok3->next()) {
if (tok3->astParent()) {
while (tok3->astParent())
tok3 = tok3->astParent();
init1 = tok3;
break;
}
if (!Token::Match(tok3, "%op%|(|["))
init1 = tok3;
}
}
} else {
while (tok2 && tok2 != endPar && tok2->str() != ";") {
if (tok2->str() == "<" && tok2->link()) {
tok2 = tok2->link();
} else if (Token::Match(tok2, "%name% )| %op%|(|[|{|.|:|::") || Token::Match(tok2->previous(), "[(;{}] %cop%|(")) {
init1 = tok2;
AST_state state1(cpp);
compileExpression(tok2, state1);
if (Token::Match(tok2, ";|)"))
break;
init1 = nullptr;
}
if (!tok2) // #7109 invalid code
return nullptr;
tok2 = tok2->next();
}
}
if (!tok2 || tok2->str() != ";") {
if (tok2 == endPar && init1) {
createAstAtTokenInner(init1->next(), endPar, cpp);
tok->next()->astOperand2(init1);
tok->next()->astOperand1(tok);
}
return tok2;
}
Token * const init = init1 ? init1 : tok2;
Token * const semicolon1 = tok2;
tok2 = tok2->next();
AST_state state2(cpp);
compileExpression(tok2, state2);
Token * const semicolon2 = tok2;
if (!semicolon2)
return nullptr; // invalid code #7235
if (semicolon2->str() == ";") {
tok2 = tok2->next();
AST_state state3(cpp);
if (Token::simpleMatch(tok2, "( {")) {
state3.op.push(tok2->next());
tok2 = tok2->link()->next();
}
compileExpression(tok2, state3);
tok2 = findAstTop(semicolon1->next(), semicolon2);
if (tok2)
semicolon2->astOperand1(tok2);
tok2 = findAstTop(semicolon2->next(), endPar);
if (tok2)
semicolon2->astOperand2(tok2);
else if (!state3.op.empty())
semicolon2->astOperand2(state3.op.top());
semicolon1->astOperand2(semicolon2);
} else {
if (!cpp || state2.op.empty() || !Token::simpleMatch(state2.op.top(), ":"))
throw InternalError(tok, "syntax error", InternalError::SYNTAX);
semicolon1->astOperand2(state2.op.top());
}
if (init != semicolon1)
semicolon1->astOperand1(init->astTop());
tok->next()->astOperand1(tok);
tok->next()->astOperand2(semicolon1);
createAstAtTokenInner(endPar->link(), endPar, cpp);
return endPar;
}
if (Token::simpleMatch(tok, "( {"))
return tok;
if (Token::Match(tok, "%type% <") && tok->linkAt(1) && !Token::Match(tok->linkAt(1), "> [({]"))
return tok->linkAt(1);
if (cpp && !tok->isKeyword() && Token::Match(tok, "%type% ::|<|%name%")) {
Token *tok2 = tok;
while (true) {
if (Token::Match(tok2, "%name%|> :: %name%"))
tok2 = tok2->tokAt(2);
else if (Token::Match(tok2, "%name% <") && tok2->linkAt(1))
tok2 = tok2->linkAt(1);
else
break;
}
if (Token::Match(tok2, "%name%|> %name% {") && tok2->next()->varId() && iscpp11init(tok2->tokAt(2))) {
Token *const tok1 = tok = tok2->next();
AST_state state(cpp);
compileExpression(tok, state);
createAstAtTokenInner(tok1->next(), tok1->linkAt(1), cpp);
return tok;
}
}
if (Token::Match(tok, "%type% %name%|*|&|::") && !Token::Match(tok, "return|new|delete")) {
int typecount = 0;
Token *typetok = tok;
while (Token::Match(typetok, "%type%|::|*|&")) {
if (typetok->isName() && !Token::simpleMatch(typetok->previous(), "::"))
typecount++;
typetok = typetok->next();
}
if (Token::Match(typetok, "%var% =") && typetok->varId())
tok = typetok;
// Do not create AST for function declaration
if (typetok &&
typecount >= 2 &&
!Token::Match(tok, "return|throw") &&
Token::Match(typetok->previous(), "%name% ( !!*") &&
typetok->previous()->varId() == 0 &&
!typetok->previous()->isKeyword() &&
(Token::Match(typetok->link(), ") const|;|{") || Token::Match(typetok->link(), ") const| = delete ;")))
return typetok;
}
if (Token::Match(tok, "return|case") ||
(cpp && tok->str() == "throw") ||
!tok->previous() ||
Token::Match(tok, "%name% %op%|(|[|.|::|<|?|;") ||
(cpp && Token::Match(tok, "%name% {") && iscpp11init(tok->next())) ||
Token::Match(tok->previous(), "[;{}] %cop%|++|--|( !!{") ||
Token::Match(tok->previous(), "[;{}] %num%|%str%|%char%") ||
Token::Match(tok->previous(), "[;{}] delete new")) {
if (cpp && (Token::Match(tok->tokAt(-2), "[;{}] new|delete %name%") || Token::Match(tok->tokAt(-3), "[;{}] :: new|delete %name%")))
tok = tok->previous();
Token * const tok1 = tok;
AST_state state(cpp);
if (Token::Match(tok, "%name% ("))
state.functionCallEndPar = tok->linkAt(1);
if (Token::simpleMatch(tok->tokAt(-1), "::") && (!tok->tokAt(-2) || !tok->tokAt(-2)->isName()))
tok = tok->tokAt(-1);
compileExpression(tok, state);
Token * const endToken = tok;
if (endToken == tok1 || !endToken)
return tok1;
createAstAtTokenInner(tok1->next(), endToken, cpp);
return endToken->previous();
}
if (cpp && tok->str() == "{" && iscpp11init(tok)) {
Token * const tok1 = tok;
AST_state state(cpp);
compileExpression(tok, state);
Token* const endToken = tok;
if (endToken == tok1 || !endToken)
return tok1;
createAstAtTokenInner(tok1->next(), endToken, cpp);
return endToken->previous();
}
return tok;
}
void TokenList::createAst() const
{
for (Token *tok = mTokensFrontBack.front; tok; tok = tok ? tok->next() : nullptr) {
Token* const nextTok = createAstAtToken(tok);
if (precedes(nextTok, tok))
throw InternalError(tok, "Syntax Error: Infinite loop when creating AST.", InternalError::AST);
tok = nextTok;
}
}
namespace {
struct OnException {
std::function<void()> f;
~OnException() {
#ifndef _MSC_VER
if (std::uncaught_exception())
f();
#endif
}
};
}
void TokenList::validateAst(bool print) const
{
OnException oe{[&] {
if (print)
mTokensFrontBack.front->printOut(std::cout);
}};
// Check for some known issues in AST to avoid crash/hang later on
std::set<const Token*> safeAstTokens; // list of "safe" AST tokens without endless recursion
for (const Token *tok = mTokensFrontBack.front; tok; tok = tok->next()) {
// Syntax error if binary operator only has 1 operand
if ((tok->isAssignmentOp() || tok->isComparisonOp() || Token::Match(tok,"[|^/%]")) && tok->astOperand1() && !tok->astOperand2())
throw InternalError(tok, "Syntax Error: AST broken, binary operator has only one operand.", InternalError::AST);
// Syntax error if we encounter "?" with operand2 that is not ":"
if (tok->str() == "?") {
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok, "AST broken, ternary operator missing operand(s)", InternalError::AST);
if (tok->astOperand2()->str() != ":")
throw InternalError(tok, "Syntax Error: AST broken, ternary operator lacks ':'.", InternalError::AST);
}
// Check for endless recursion
const Token* parent = tok->astParent();
if (parent) {
std::set<const Token*> astTokens; // list of ancestors
astTokens.insert(tok);
do {
if (safeAstTokens.find(parent) != safeAstTokens.end())
break;
if (astTokens.find(parent) != astTokens.end())
throw InternalError(tok, "AST broken: endless recursion from '" + tok->str() + "'", InternalError::AST);
astTokens.insert(parent);
} while ((parent = parent->astParent()) != nullptr);
safeAstTokens.insert(astTokens.cbegin(), astTokens.cend());
} else if (tok->str() == ";") {
safeAstTokens.clear();
} else {
safeAstTokens.insert(tok);
}
// Don't check templates
if (tok->str() == "<" && tok->link()) {
tok = tok->link();
continue;
}
if (tok->isCast()) {
if (!tok->astOperand2() && precedes(tok->astOperand1(), tok))
throw InternalError(tok, "AST broken: '" + tok->str() + "' has improper operand.", InternalError::AST);
if (tok->astOperand1() && tok->link()) { // skip casts (not part of the AST)
tok = tok->link();
continue;
}
}
if (findLambdaEndToken(tok)) { // skip lambda captures
tok = tok->link();
continue;
}
// Check binary operators
if (Token::Match(tok, "%or%|%oror%|%assign%|%comp%")) {
// Skip pure virtual functions
if (Token::simpleMatch(tok->previous(), ") = 0"))
continue;
// Skip operator definitions
if (Token::simpleMatch(tok->previous(), "operator"))
continue;
// Skip incomplete code
if (!tok->astOperand1() && !tok->astOperand2() && !tok->astParent())
continue;
// Skip lambda assignment and/or initializer
if (Token::Match(tok, "= {|^|["))
continue;
// FIXME: Workaround broken AST assignment in type aliases
if (Token::Match(tok->previous(), "%name% = %name%"))
continue;
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok, "Syntax Error: AST broken, binary operator '" + tok->str() + "' doesn't have two operands.", InternalError::AST);
}
if (Token::Match(tok, "++|--") && !tok->astOperand1()) {
throw InternalError(tok, "Syntax Error: AST broken, operator '" + tok->str() + "' doesn't have an operand.", InternalError::AST);
}
// Check control blocks and asserts
if (Token::Match(tok->previous(), "if|while|for|switch|assert|ASSERT (")) {
if (!tok->astOperand1() || !tok->astOperand2())
throw InternalError(tok,
"Syntax Error: AST broken, '" + tok->strAt(-1) +
"' doesn't have two operands.",
InternalError::AST);
}
if (tok->str() == "case" && !tok->astOperand1()) {
throw InternalError(tok,
"Syntax Error: AST broken, 'case' doesn't have an operand.",
InternalError::AST);
}
// Check member access
if (Token::Match(tok, "%var% .")) {
if (!tok->astParent()) {
throw InternalError(
tok, "Syntax Error: AST broken, '" + tok->str() + "' doesn't have a parent.", InternalError::AST);
}
if (!tok->next()->astOperand1() || !tok->next()->astOperand2()) {
const std::string& op =
tok->next()->originalName().empty() ? tok->strAt(1) : tok->next()->originalName();
throw InternalError(
tok, "Syntax Error: AST broken, '" + op + "' doesn't have two operands.", InternalError::AST);
}
}
}
}
std::string TokenList::getOrigFile(const Token *tok) const
{
return mOrigFiles.at(tok->fileIndex());
}
const std::string& TokenList::file(const Token *tok) const
{
return mFiles.at(tok->fileIndex());
}
std::string TokenList::fileLine(const Token *tok) const
{
return ErrorMessage::FileLocation(tok, this).stringify();
}
bool TokenList::validateToken(const Token* tok) const
{
if (!tok)
return true;
for (const Token *t = mTokensFrontBack.front; t; t = t->next()) {
if (tok==t)
return true;
}
return false;
}
void TokenList::simplifyPlatformTypes()
{
if (!mSettings)
return;
const bool isCPP11 = isCPP() && (mSettings->standards.cpp >= Standards::CPP11);
enum : std::uint8_t { isLongLong, isLong, isInt } type;
/** @todo This assumes a flat address space. Not true for segmented address space (FAR *). */
if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long)
type = isLong;
else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long_long)
type = isLongLong;
else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_int)
type = isInt;
else
return;
for (Token *tok = front(); tok; tok = tok->next()) {
// pre-check to reduce unneeded match calls
if (!Token::Match(tok, "std| ::| %type%"))
continue;
bool isUnsigned;
if (Token::Match(tok, "std| ::| size_t|uintptr_t|uintmax_t")) {
if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=")
continue;
isUnsigned = true;
} else if (Token::Match(tok, "std| ::| ssize_t|ptrdiff_t|intptr_t|intmax_t")) {
if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=")
continue;
isUnsigned = false;
} else
continue;
bool inStd = false;
if (tok->str() == "::") {
tok->deleteThis();
} else if (tok->str() == "std") {
if (tok->strAt(1) != "::")
continue;
inStd = true;
tok->deleteNext();
tok->deleteThis();
}
if (inStd)
tok->originalName("std::" + tok->str());
else
tok->originalName(tok->str());
if (isUnsigned)
tok->isUnsigned(true);
switch (type) {
case isLongLong:
tok->isLong(true);
tok->str("long");
break;
case isLong:
tok->str("long");
break;
case isInt:
tok->str("int");
break;
}
}
const std::string platform_type(mSettings->platform.toString());
for (Token *tok = front(); tok; tok = tok->next()) {
if (tok->tokType() != Token::eType && tok->tokType() != Token::eName)
continue;
const Library::PlatformType * const platformtype = mSettings->library.platform_type(tok->str(), platform_type);
if (platformtype) {
// check for namespace
if (tok->strAt(-1) == "::") {
const Token * tok1 = tok->tokAt(-2);
// skip when non-global namespace defined
if (tok1 && tok1->tokType() == Token::eName)
continue;
tok = tok->previous();
tok->deleteThis();
}
tok->originalName(tok->str());
const bool isFunctionalPtrCast = (platformtype->mConstPtr || platformtype->mPointer || platformtype->mPtrPtr) &&
Token::Match(tok, "%name% [({]") && !Token::simpleMatch(tok->linkAt(1), ") (");
Token* start = isFunctionalPtrCast ? tok->tokAt(1) : nullptr;
Token* end = isFunctionalPtrCast ? tok->linkAt(1) : nullptr;
Token *typeToken;
if (platformtype->mConstPtr) {
tok->str("const");
tok->isSimplifiedTypedef(true);
tok->insertToken("*")->isSimplifiedTypedef(true);
tok->insertToken(platformtype->mType)->isSimplifiedTypedef(true);
typeToken = tok;
} else if (platformtype->mPointer) {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
tok->insertToken("*")->isSimplifiedTypedef(true);
} else if (platformtype->mPtrPtr) {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
tok->insertToken("*")->isSimplifiedTypedef(true);
tok->insertToken("*")->isSimplifiedTypedef(true);
} else {
tok->str(platformtype->mType);
tok->isSimplifiedTypedef(true);
typeToken = tok;
}
if (platformtype->mSigned)
typeToken->isSigned(true);
if (platformtype->mUnsigned)
typeToken->isUnsigned(true);
if (platformtype->mLong)
typeToken->isLong(true);
if (isFunctionalPtrCast) {
start->str("(");
end->str(")");
if (end == start->tokAt(1))
end->insertTokenBefore("0");
end = start->insertTokenBefore(")");
start = tok->insertTokenBefore("(");
start->isSimplifiedTypedef(true);
Token::createMutualLinks(start, end);
}
}
}
}
void TokenList::simplifyStdType()
{
auto isVarDeclC = [](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, "}"))
return false;
tok = tok->link()->previous();
while (Token::Match(tok, "%name%")) {
if (Token::Match(tok, "struct|union|enum"))
return true;
tok = tok->previous();
}
return false;
};
for (Token *tok = front(); tok; tok = tok->next()) {
if (isC() && Token::Match(tok, "const|extern *|&|%name%") && (!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) {
if (Token::Match(tok->next(), "%name% !!;"))
continue;
if (isVarDeclC(tok->previous()))
continue;
tok->insertToken("int");
tok->next()->isImplicitInt(true);
continue;
}
if (Token::Match(tok, "char|short|int|long|unsigned|signed|double|float") || (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok, "complex|_Complex"))) {
bool isFloat= false;
bool isSigned = false;
bool isUnsigned = false;
bool isComplex = false;
int countLong = 0;
Token* typeSpec = nullptr;
Token* tok2 = tok;
for (; tok2->next(); tok2 = tok2->next()) {
if (tok2->str() == "long") {
countLong++;
if (!isFloat)
typeSpec = tok2;
} else if (tok2->str() == "short") {
typeSpec = tok2;
} else if (tok2->str() == "unsigned")
isUnsigned = true;
else if (tok2->str() == "signed")
isSigned = true;
else if (Token::Match(tok2, "float|double")) {
isFloat = true;
typeSpec = tok2;
} else if (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok2, "complex|_Complex"))
isComplex = !isFloat || tok2->str() == "_Complex" || Token::Match(tok2->next(), "*|&|%name%"); // Ensure that "complex" is not the variables name
else if (Token::Match(tok2, "char|int")) {
if (!typeSpec)
typeSpec = tok2;
} else
break;
}
if (!typeSpec) { // unsigned i; or similar declaration
if (!isComplex) { // Ensure that "complex" is not the variables name
tok->str("int");
tok->isSigned(isSigned);
tok->isUnsigned(isUnsigned);
tok->isImplicitInt(true);
}
} else {
typeSpec->isLong(typeSpec->isLong() || (isFloat && countLong == 1) || countLong > 1);
typeSpec->isComplex(typeSpec->isComplex() || (isFloat && isComplex));
typeSpec->isSigned(typeSpec->isSigned() || isSigned);
typeSpec->isUnsigned(typeSpec->isUnsigned() || isUnsigned);
// Remove specifiers
const Token* tok3 = tok->previous();
tok2 = tok2->previous();
while (tok3 != tok2) {
if (tok2 != typeSpec &&
(isComplex || !Token::Match(tok2, "complex|_Complex"))) // Ensure that "complex" is not the variables name
tok2->deleteThis();
tok2 = tok2->previous();
}
}
}
}
}
bool TokenList::isKeyword(const std::string &str) const
{
if (isCPP()) {
// TODO: integrate into keywords?
// types and literals are not handled as keywords
static const std::unordered_set<std::string> cpp_types = {"bool", "false", "true"};
if (cpp_types.find(str) != cpp_types.end())
return false;
if (mSettings) {
const auto &cpp_keywords = Keywords::getAll(mSettings->standards.cpp);
return cpp_keywords.find(str) != cpp_keywords.end();
}
static const auto& latest_cpp_keywords = Keywords::getAll(Standards::cppstd_t::CPPLatest);
return latest_cpp_keywords.find(str) != latest_cpp_keywords.end();
}
// TODO: integrate into Keywords?
// types are not handled as keywords
static const std::unordered_set<std::string> c_types = {"char", "double", "float", "int", "long", "short"};
if (c_types.find(str) != c_types.end())
return false;
if (mSettings) {
const auto &c_keywords = Keywords::getAll(mSettings->standards.c);
return c_keywords.find(str) != c_keywords.end();
}
static const auto& latest_c_keywords = Keywords::getAll(Standards::cstd_t::CLatest);
return latest_c_keywords.find(str) != latest_c_keywords.end();
}
bool TokenList::isC() const
{
ASSERT_LANG(mLang != Standards::Language::None);
// TODO: remove the fallback
if (mLang == Standards::Language::None)
return false; // treat as C++ by default
return mLang == Standards::Language::C;
}
bool TokenList::isCPP() const
{
ASSERT_LANG(mLang != Standards::Language::None);
// TODO: remove the fallback
if (mLang == Standards::Language::None)
return true; // treat as C++ by default
return mLang == Standards::Language::CPP;
}
void TokenList::setLang(Standards::Language lang, bool force)
{
ASSERT_LANG(lang != Standards::Language::None);
if (!force)
{
ASSERT_LANG(mLang == Standards::Language::None);
}
mLang = lang;
}
| null |
834 | cpp | cppcheck | checkvaarg.h | lib/checkvaarg.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkvaargtH
#define checkvaargtH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Checking for misusage of variable argument lists
*/
class CPPCHECKLIB CheckVaarg : public Check {
public:
CheckVaarg() : Check(myName()) {}
private:
CheckVaarg(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckVaarg check(&tokenizer, &tokenizer.getSettings(), errorLogger);
check.va_start_argument();
check.va_list_usage();
}
void va_start_argument();
void va_list_usage();
void wrongParameterTo_va_start_error(const Token *tok, const std::string& paramIsName, const std::string& paramShouldName);
void referenceAs_va_start_error(const Token *tok, const std::string& paramName);
void va_end_missingError(const Token *tok, const std::string& varname);
void va_list_usedBeforeStartedError(const Token *tok, const std::string& varname);
void va_start_subsequentCallsError(const Token *tok, const std::string& varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckVaarg c(nullptr, settings, errorLogger);
c.wrongParameterTo_va_start_error(nullptr, "arg1", "arg2");
c.referenceAs_va_start_error(nullptr, "arg1");
c.va_end_missingError(nullptr, "vl");
c.va_list_usedBeforeStartedError(nullptr, "vl");
c.va_start_subsequentCallsError(nullptr, "vl");
}
static std::string myName() {
return "Vaarg";
}
std::string classInfo() const override {
return "Check for misusage of variable argument lists:\n"
"- Wrong parameter passed to va_start()\n"
"- Reference passed to va_start()\n"
"- Missing va_end()\n"
"- Using va_list before it is opened\n"
"- Subsequent calls to va_start/va_copy()\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkvaargtH
| null |
835 | cpp | cppcheck | checkersreport.cpp | lib/checkersreport.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkersreport.h"
#include "addoninfo.h"
#include "checkers.h"
#include "errortypes.h"
#include "settings.h"
#include <algorithm>
#include <cstddef>
#include <map>
#include <sstream>
#include <unordered_set>
#include <vector>
static bool isCppcheckPremium(const Settings& settings) {
return (settings.cppcheckCfgProductName.compare(0, 16, "Cppcheck Premium") == 0);
}
static int getMisraCVersion(const Settings& settings) {
if (settings.premiumArgs.find("misra-c-2012") != std::string::npos)
return 2012;
if (settings.premiumArgs.find("misra-c-2023") != std::string::npos)
return 2023;
if (settings.addons.count("misra"))
return 2012;
const bool misraAddonInfo = std::any_of(settings.addonInfos.cbegin(), settings.addonInfos.cend(), [](const AddonInfo& addonInfo) {
return addonInfo.name == "misra";
});
if (misraAddonInfo)
return 2012;
return 0;
}
static bool isMisraRuleActive(const std::set<std::string>& activeCheckers, const std::string& rule) {
if (activeCheckers.count("Misra C: " + rule))
return true;
if (rule == "1.1")
return true; // syntax error
if (rule == "1.3")
return true; // undefined behavior
if (rule == "2.1")
return activeCheckers.count("CheckCondition::alwaysTrueFalse") != 0;
if (rule == "2.6")
return activeCheckers.count("CheckOther::checkUnusedLabel") != 0;
if (rule == "2.8")
return activeCheckers.count("CheckUnusedVar::checkFunctionVariableUsage") != 0;
if (rule == "5.3")
return activeCheckers.count("CheckOther::checkShadowVariables") != 0;
if (rule == "8.13")
return activeCheckers.count("CheckOther::checkConstPointer") != 0;
if (rule == "9.1")
return true; // uninitvar
if (rule == "12.5")
return activeCheckers.count("CheckOther::checkConstPointer") != 0;
if (rule == "14.3")
return activeCheckers.count("CheckCondition::alwaysTrueFalse") != 0;
if (rule == "17.5")
return activeCheckers.count("CheckBufferOverrun::argumentSize") != 0;
if (rule == "18.1")
return activeCheckers.count("CheckBufferOverrun::pointerArithmetic") != 0;
if (rule == "18.2")
return activeCheckers.count("CheckOther::checkComparePointers") != 0;
if (rule == "18.3")
return activeCheckers.count("CheckOther::checkComparePointers") != 0;
if (rule == "18.6")
return true; // danlingLifetime => error
if (rule == "19.1")
return activeCheckers.count("CheckOther::checkOverlappingWrite") != 0;
if (rule == "20.6")
return true; // preprocessorErrorDirective
if (rule == "21.13")
return activeCheckers.count("CheckFunctions::invalidFunctionUsage") != 0;
if (rule == "21.17")
return activeCheckers.count("CheckBufferOverrun::bufferOverflow") != 0;
if (rule == "21.18")
return activeCheckers.count("CheckBufferOverrun::bufferOverflow") != 0;
if (rule == "22.1")
return true; // memleak => error
if (rule == "22.2")
return activeCheckers.count("CheckAutoVariables::autoVariables") != 0;
if (rule == "22.3")
return activeCheckers.count("CheckIO::checkFileUsage") != 0;
if (rule == "22.4")
return activeCheckers.count("CheckIO::checkFileUsage") != 0;
if (rule == "22.6")
return activeCheckers.count("CheckIO::checkFileUsage") != 0;
return false;
}
CheckersReport::CheckersReport(const Settings& settings, const std::set<std::string>& activeCheckers)
: mSettings(settings), mActiveCheckers(activeCheckers)
{}
int CheckersReport::getActiveCheckersCount()
{
if (mAllCheckersCount == 0) {
countCheckers();
}
return mActiveCheckersCount;
}
int CheckersReport::getAllCheckersCount()
{
if (mAllCheckersCount == 0) {
countCheckers();
}
return mAllCheckersCount;
}
void CheckersReport::countCheckers()
{
mActiveCheckersCount = mAllCheckersCount = 0;
for (const auto& checkReq: checkers::allCheckers) {
if (mActiveCheckers.count(checkReq.first) > 0)
++mActiveCheckersCount;
++mAllCheckersCount;
}
for (const auto& checkReq: checkers::premiumCheckers) {
if (mActiveCheckers.count(checkReq.first) > 0)
++mActiveCheckersCount;
++mAllCheckersCount;
}
if (mSettings.premiumArgs.find("misra-c-") != std::string::npos || mSettings.addons.count("misra")) {
for (const checkers::MisraInfo& info: checkers::misraC2012Rules) {
const std::string rule = std::to_string(info.a) + "." + std::to_string(info.b);
const bool active = isMisraRuleActive(mActiveCheckers, rule);
if (active)
++mActiveCheckersCount;
++mAllCheckersCount;
}
}
}
std::string CheckersReport::getReport(const std::string& criticalErrors) const
{
std::ostringstream fout;
fout << "Critical errors" << std::endl;
fout << "---------------" << std::endl;
if (!criticalErrors.empty()) {
fout << "There were critical errors (" << criticalErrors << ")." << std::endl;
fout << "These cause the analysis of the file to end prematurely." << std::endl;
} else {
fout << "No critical errors encountered." << std::endl;
// TODO: mention "information" and "debug" as source for indications of bailouts
// TODO: still rephrase this - this message does not provides confidence in the results
// TODO: document what a bailout is and why it is done - mention it in the upcoming security/tuning guide
// TODO: make bailouts a seperate group - need to differentiate between user bailouts (missing data like configuration/includes) and internal bailouts (e.g. limitations of ValueFlow)
fout << "Note: There might still have been non-critical bailouts which might lead to false negatives." << std::endl;
}
fout << std::endl << std::endl;
fout << "Open source checkers" << std::endl;
fout << "--------------------" << std::endl;
std::size_t maxCheckerSize = 0;
for (const auto& checkReq: checkers::allCheckers) {
const std::string& checker = checkReq.first;
maxCheckerSize = std::max(checker.size(), maxCheckerSize);
}
for (const auto& checkReq: checkers::allCheckers) {
const std::string& checker = checkReq.first;
const bool active = mActiveCheckers.count(checkReq.first) > 0;
const std::string& req = checkReq.second;
fout << (active ? "Yes " : "No ") << checker;
if (!active && !req.empty())
fout << std::string(maxCheckerSize + 4 - checker.size(), ' ') << "require:" + req;
fout << std::endl;
}
const bool cppcheckPremium = isCppcheckPremium(mSettings);
auto reportSection = [&fout, cppcheckPremium]
(const std::string& title,
const Settings& settings,
const std::set<std::string>& activeCheckers,
const std::map<std::string, std::string>& premiumCheckers,
const std::string& substring) {
fout << std::endl << std::endl;
fout << title << std::endl;
fout << std::string(title.size(), '-') << std::endl;
if (!cppcheckPremium) {
fout << "Not available, Cppcheck Premium is not used" << std::endl;
return;
}
int maxCheckerSize = 0;
for (const auto& checkReq: premiumCheckers) {
const std::string& checker = checkReq.first;
if (checker.find(substring) != std::string::npos && checker.size() > maxCheckerSize)
maxCheckerSize = checker.size();
}
for (const auto& checkReq: premiumCheckers) {
const std::string& checker = checkReq.first;
if (checker.find(substring) == std::string::npos)
continue;
std::string req = checkReq.second;
bool active = cppcheckPremium && activeCheckers.count(checker) > 0;
if (substring == "::") {
if (req == "warning")
active &= settings.severity.isEnabled(Severity::warning);
else if (req == "style")
active &= settings.severity.isEnabled(Severity::style);
else if (req == "portability")
active &= settings.severity.isEnabled(Severity::portability);
else if (!req.empty())
active = false; // FIXME: handle req
}
fout << (active ? "Yes " : "No ") << checker;
if (!cppcheckPremium) {
if (!req.empty())
req = "premium," + req;
else
req = "premium";
}
if (!req.empty())
req = "require:" + req;
if (!active)
fout << std::string(maxCheckerSize + 4 - checker.size(), ' ') << req;
fout << std::endl;
}
};
reportSection("Premium checkers", mSettings, mActiveCheckers, checkers::premiumCheckers, "::");
reportSection("Autosar", mSettings, mActiveCheckers, checkers::premiumCheckers, "Autosar: ");
reportSection("Cert C", mSettings, mActiveCheckers, checkers::premiumCheckers, "Cert C: ");
reportSection("Cert C++", mSettings, mActiveCheckers, checkers::premiumCheckers, "Cert C++: ");
const int misraCVersion = getMisraCVersion(mSettings);
if (misraCVersion == 0) {
fout << std::endl << std::endl;
fout << "Misra C" << std::endl;
fout << "-------" << std::endl;
fout << "Misra is not enabled" << std::endl;
} else {
fout << std::endl << std::endl;
fout << "Misra C " << misraCVersion << std::endl;
fout << "------------" << std::endl;
for (const checkers::MisraInfo& info: checkers::misraC2012Directives) {
const std::string directive = "Dir " + std::to_string(info.a) + "." + std::to_string(info.b);
const bool active = isMisraRuleActive(mActiveCheckers, directive);
fout << (active ? "Yes " : "No ") << "Misra C " << misraCVersion << ": " << directive;
std::string extra;
if (misraCVersion == 2012 && info.amendment >= 1)
extra = " amendment:" + std::to_string(info.amendment);
if (!extra.empty())
fout << std::string(10 - directive.size(), ' ') << extra;
fout << '\n';
}
for (const checkers::MisraInfo& info: checkers::misraC2012Rules) {
const std::string rule = std::to_string(info.a) + "." + std::to_string(info.b);
const bool active = isMisraRuleActive(mActiveCheckers, rule);
fout << (active ? "Yes " : "No ") << "Misra C " << misraCVersion << ": " << rule;
std::string extra;
if (misraCVersion == 2012 && info.amendment >= 1)
extra = " amendment:" + std::to_string(info.amendment);
std::string reqs;
if (info.amendment >= 3)
reqs += ",premium";
if (!active && !reqs.empty())
extra += " require:" + reqs.substr(1);
if (!extra.empty())
fout << std::string(10 - rule.size(), ' ') << extra;
fout << '\n';
}
}
reportSection("Misra C++ 2008", mSettings, mActiveCheckers, checkers::premiumCheckers, "Misra C++ 2008: ");
reportSection("Misra C++ 2023", mSettings, mActiveCheckers, checkers::premiumCheckers, "Misra C++ 2023: ");
return fout.str();
}
std::string CheckersReport::getXmlReport(const std::string& criticalErrors) const
{
std::string ret;
if (!criticalErrors.empty())
ret += " <critical-errors>" + criticalErrors + "</critical-errors>\n";
else
ret += " <critical-errors/>\n";
ret += " <checkers-report>\n";
const int misraCVersion = getMisraCVersion(mSettings);
for (std::string checker: mActiveCheckers) {
if (checker.compare(0,8,"Misra C:") == 0)
checker = "Misra C " + std::to_string(misraCVersion) + ":" + checker.substr(8);
ret += " <checker id=\"" + checker + "\"/>\n";
}
ret += " </checkers-report>";
return ret;
}
| null |
836 | cpp | cppcheck | library.h | lib/library.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef libraryH
#define libraryH
//---------------------------------------------------------------------------
#include "config.h"
#include "mathlib.h"
#include "standards.h"
#include <array>
#include <cstdint>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
class Token;
enum class Severity : std::uint8_t;
namespace tinyxml2 {
class XMLDocument;
class XMLElement;
}
/// @addtogroup Core
/// @{
/**
* @brief Library definitions handling
*/
class CPPCHECKLIB Library {
friend struct LibraryHelper; // for testing
public:
Library();
~Library();
Library(const Library& other);
Library& operator=(const Library& other) &;
enum class ErrorCode : std::uint8_t {
OK,
FILE_NOT_FOUND, BAD_XML, UNKNOWN_ELEMENT, MISSING_ATTRIBUTE, BAD_ATTRIBUTE_VALUE,
UNSUPPORTED_FORMAT, DUPLICATE_PLATFORM_TYPE, PLATFORM_TYPE_REDEFINED, DUPLICATE_DEFINE
};
class Error {
public:
Error() : errorcode(ErrorCode::OK) {}
explicit Error(ErrorCode e) : errorcode(e) {}
template<typename T>
Error(ErrorCode e, T&& r) : errorcode(e), reason(r) {}
ErrorCode errorcode;
std::string reason;
};
Error load(const char exename[], const char path[], bool debug = false);
struct AllocFunc {
int groupId{};
int arg{};
enum class BufferSize : std::uint8_t {none,malloc,calloc,strdup};
BufferSize bufferSize{BufferSize::none};
int bufferSizeArg1{};
int bufferSizeArg2{};
int reallocArg{};
bool initData{};
};
/** get allocation info for function */
const AllocFunc* getAllocFuncInfo(const Token *tok) const;
/** get deallocation info for function */
const AllocFunc* getDeallocFuncInfo(const Token *tok) const;
/** get reallocation info for function */
const AllocFunc* getReallocFuncInfo(const Token *tok) const;
/** get allocation id for function */
int getAllocId(const Token *tok, int arg) const;
/** get deallocation id for function */
int getDeallocId(const Token *tok, int arg) const;
/** get reallocation id for function */
int getReallocId(const Token *tok, int arg) const;
// TODO: get rid of this
/** get allocation info for function by name (deprecated, use other alloc) */
const AllocFunc* getAllocFuncInfo(const char name[]) const;
// TODO: get rid of this
/** get deallocation info for function by name (deprecated, use other alloc) */
const AllocFunc* getDeallocFuncInfo(const char name[]) const;
// TODO: get rid of this
/** get allocation id for function by name (deprecated, use other alloc) */
int allocId(const char name[]) const;
// TODO: get rid of this
/** get deallocation id for function by name (deprecated, use other alloc) */
int deallocId(const char name[]) const;
static bool isCompliantValidationExpression(const char* p);
/** is allocation type memory? */
static bool ismemory(const int id) {
return ((id > 0) && ((id & 1) == 0));
}
static bool ismemory(const AllocFunc* const func) {
return func && (func->groupId > 0) && ((func->groupId & 1) == 0);
}
/** is allocation type resource? */
static bool isresource(const int id) {
return ((id > 0) && ((id & 1) == 1));
}
static bool isresource(const AllocFunc* const func) {
return func && (func->groupId > 0) && ((func->groupId & 1) == 1);
}
bool formatstr_function(const Token* ftok) const;
int formatstr_argno(const Token* ftok) const;
bool formatstr_scan(const Token* ftok) const;
bool formatstr_secure(const Token* ftok) const;
struct NonOverlappingData {
int ptr1Arg;
int ptr2Arg;
int sizeArg;
int strlenArg;
int countArg;
};
const NonOverlappingData* getNonOverlappingData(const Token *ftok) const;
struct WarnInfo {
std::string message;
Standards standards;
Severity severity;
};
const std::map<std::string, WarnInfo>& functionwarn() const;
const WarnInfo* getWarnInfo(const Token* ftok) const;
struct Function;
// returns true if ftok is not a library function
bool isNotLibraryFunction(const Token *ftok, const Function **func = nullptr) const;
bool matchArguments(const Token *ftok, const std::string &functionName, const Function **func = nullptr) const;
enum class UseRetValType : std::uint8_t { NONE, DEFAULT, ERROR_CODE };
UseRetValType getUseRetValType(const Token* ftok) const;
const std::string& returnValue(const Token *ftok) const;
const std::string& returnValueType(const Token *ftok) const;
int returnValueContainer(const Token *ftok) const;
std::vector<MathLib::bigint> unknownReturnValues(const Token *ftok) const;
bool isnoreturn(const Token *ftok) const;
bool isnotnoreturn(const Token *ftok) const;
bool isScopeNoReturn(const Token *end, std::string *unknownFunc) const;
class Container {
public:
Container() = default;
enum class Action : std::uint8_t {
RESIZE,
CLEAR,
PUSH,
POP,
FIND,
FIND_CONST,
INSERT,
ERASE,
APPEND,
CHANGE_CONTENT,
CHANGE,
CHANGE_INTERNAL,
NO_ACTION
};
enum class Yield : std::uint8_t {
AT_INDEX,
ITEM,
BUFFER,
BUFFER_NT,
START_ITERATOR,
END_ITERATOR,
ITERATOR,
SIZE,
EMPTY,
NO_YIELD
};
struct Function {
Action action;
Yield yield;
std::string returnType;
};
struct RangeItemRecordTypeItem {
std::string name;
int templateParameter; // TODO: use this
};
std::string startPattern, startPattern2, endPattern, itEndPattern;
std::map<std::string, Function> functions;
int type_templateArgNo = -1;
std::vector<RangeItemRecordTypeItem> rangeItemRecordType;
int size_templateArgNo = -1;
bool arrayLike_indexOp{};
bool stdStringLike{};
bool stdAssociativeLike{};
bool opLessAllowed = true;
bool hasInitializerListConstructor{};
bool unstableErase{};
bool unstableInsert{};
bool view{};
Action getAction(const std::string& function) const {
const std::map<std::string, Function>::const_iterator i = functions.find(function);
if (i != functions.end())
return i->second.action;
return Action::NO_ACTION;
}
Yield getYield(const std::string& function) const {
const std::map<std::string, Function>::const_iterator i = functions.find(function);
if (i != functions.end())
return i->second.yield;
return Yield::NO_YIELD;
}
const std::string& getReturnType(const std::string& function) const {
auto i = functions.find(function);
return (i != functions.end()) ? i->second.returnType : emptyString;
}
static Yield yieldFrom(const std::string& yieldName);
static Action actionFrom(const std::string& actionName);
};
const std::unordered_map<std::string, Container>& containers() const;
const Container* detectContainer(const Token* typeStart) const;
const Container* detectIterator(const Token* typeStart) const;
const Container* detectContainerOrIterator(const Token* typeStart, bool* isIterator = nullptr, bool withoutStd = false) const;
struct ArgumentChecks {
bool notbool{};
bool notnull{};
int notuninit = -1;
bool formatstr{};
bool strz{};
bool optional{};
bool variadic{};
std::string valid;
struct IteratorInfo {
int container{};
bool it{};
bool first{};
bool last{};
};
IteratorInfo iteratorInfo;
struct MinSize {
enum class Type : std::uint8_t { NONE, STRLEN, ARGVALUE, SIZEOF, MUL, VALUE };
MinSize(Type t, int a) : type(t), arg(a) {}
Type type;
int arg;
int arg2 = 0;
long long value = 0;
std::string baseType;
};
std::vector<MinSize> minsizes;
enum class Direction : std::uint8_t {
DIR_IN, ///< Input to called function. Data is treated as read-only.
DIR_OUT, ///< Output to caller. Data is passed by reference or address and is potentially written.
DIR_INOUT, ///< Input to called function, and output to caller. Data is passed by reference or address and is potentially modified.
DIR_UNKNOWN ///< direction not known / specified
};
// argument directions up to ** indirect level (only one can be configured explicitly at the moment)
std::array<Direction, 3> direction = { { Direction::DIR_UNKNOWN, Direction::DIR_UNKNOWN, Direction::DIR_UNKNOWN } };
};
struct Function {
std::map<int, ArgumentChecks> argumentChecks; // argument nr => argument data
bool use{};
bool leakignore{};
bool isconst{};
bool ispure{};
UseRetValType useretval = UseRetValType::NONE;
bool ignore{}; // ignore functions/macros from a library (gtk, qt etc)
bool formatstr{};
bool formatstr_scan{};
bool formatstr_secure{};
Container::Action containerAction = Container::Action::NO_ACTION;
Container::Yield containerYield = Container::Yield::NO_YIELD;
std::string returnType;
};
const Function *getFunction(const Token *ftok) const;
const std::unordered_map<std::string, Function>& functions() const;
bool isUse(const std::string& functionName) const;
bool isLeakIgnore(const std::string& functionName) const;
bool isFunctionConst(const std::string& functionName, bool pure) const;
bool isFunctionConst(const Token *ftok) const;
bool isboolargbad(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg && arg->notbool;
}
bool isnullargbad(const Token *ftok, int argnr) const;
bool isuninitargbad(const Token *ftok, int argnr, int indirect = 0, bool *hasIndirect=nullptr) const;
bool isargformatstr(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg && arg->formatstr;
}
bool isargstrz(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg && arg->strz;
}
bool isIntArgValid(const Token *ftok, int argnr, MathLib::bigint argvalue) const;
bool isFloatArgValid(const Token *ftok, int argnr, double argvalue) const;
const std::string& validarg(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg ? arg->valid : emptyString;
}
const ArgumentChecks::IteratorInfo *getArgIteratorInfo(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg && arg->iteratorInfo.it ? &arg->iteratorInfo : nullptr;
}
bool hasminsize(const Token *ftok) const;
const std::vector<ArgumentChecks::MinSize> *argminsizes(const Token *ftok, int argnr) const {
const ArgumentChecks *arg = getarg(ftok, argnr);
return arg ? &arg->minsizes : nullptr;
}
ArgumentChecks::Direction getArgDirection(const Token* ftok, int argnr, int indirect = 0) const;
bool markupFile(const std::string &path) const;
bool processMarkupAfterCode(const std::string &path) const;
const std::set<std::string> &markupExtensions() const;
bool reportErrors(const std::string &path) const;
bool ignorefunction(const std::string &functionName) const;
bool isexecutableblock(const std::string &file, const std::string &token) const;
int blockstartoffset(const std::string &file) const;
const std::string& blockstart(const std::string &file) const;
const std::string& blockend(const std::string &file) const;
bool iskeyword(const std::string &file, const std::string &keyword) const;
bool isexporter(const std::string &prefix) const;
bool isexportedprefix(const std::string &prefix, const std::string &token) const;
bool isexportedsuffix(const std::string &prefix, const std::string &token) const;
bool isimporter(const std::string& file, const std::string &importer) const;
const Token* getContainerFromYield(const Token* tok, Container::Yield yield) const;
const Token* getContainerFromAction(const Token* tok, Container::Action action) const;
static bool isContainerYield(const Token* cond, Library::Container::Yield y, const std::string& fallback = emptyString);
static Library::Container::Yield getContainerYield(const Token* cond);
bool isreflection(const std::string &token) const;
int reflectionArgument(const std::string &token) const;
bool isentrypoint(const std::string &func) const;
const std::set<std::string>& defines() const; // to provide some library defines
struct SmartPointer {
std::string name;
bool unique = false;
};
const std::unordered_map<std::string, SmartPointer>& smartPointers() const;
bool isSmartPointer(const Token *tok) const;
const SmartPointer* detectSmartPointer(const Token* tok, bool withoutStd = false) const;
struct PodType {
unsigned int size{};
char sign{};
enum class Type : std::uint8_t { NO, BOOL, CHAR, SHORT, INT, LONG, LONGLONG } stdtype = Type::NO;
};
const PodType *podtype(const std::string &name) const;
struct PlatformType {
bool operator == (const PlatformType & type) const {
return (mSigned == type.mSigned &&
mUnsigned == type.mUnsigned &&
mLong == type.mLong &&
mPointer == type.mPointer &&
mPtrPtr == type.mPtrPtr &&
mConstPtr == type.mConstPtr &&
mType == type.mType);
}
bool operator != (const PlatformType & type) const {
return !(*this == type);
}
std::string mType;
bool mSigned{};
bool mUnsigned{};
bool mLong{};
bool mPointer{};
bool mPtrPtr{};
bool mConstPtr{};
};
const PlatformType *platform_type(const std::string &name, const std::string & platform) const;
/**
* Get function name for function call
*/
std::string getFunctionName(const Token *ftok) const;
/** Suppress/check a type */
enum class TypeCheck : std::uint8_t {
def,
check,
suppress,
checkFiniteLifetime, // (unusedvar) object has side effects, but immediate destruction is wrong
};
TypeCheck getTypeCheck(std::string check, std::string typeName) const;
bool hasAnyTypeCheck(const std::string& typeName) const;
private:
Error load(const tinyxml2::XMLDocument &doc);
// load a <function> xml node
Error loadFunction(const tinyxml2::XMLElement * node, const std::string &name, std::set<std::string> &unknown_elements);
struct LibraryData;
std::unique_ptr<LibraryData> mData;
const ArgumentChecks * getarg(const Token *ftok, int argnr) const;
std::string getFunctionName(const Token *ftok, bool &error) const;
static const AllocFunc* getAllocDealloc(const std::map<std::string, AllocFunc> &data, const std::string &name) {
const std::map<std::string, AllocFunc>::const_iterator it = data.find(name);
return (it == data.end()) ? nullptr : &it->second;
}
enum DetectContainer : std::uint8_t { ContainerOnly, IteratorOnly, Both };
const Library::Container* detectContainerInternal(const Token* typeStart, DetectContainer detect, bool* isIterator = nullptr, bool withoutStd = false) const;
};
CPPCHECKLIB const Library::Container * getLibraryContainer(const Token * tok);
/// @}
//---------------------------------------------------------------------------
#endif // libraryH
| null |
837 | cpp | cppcheck | checkersidmapping.cpp | lib/checkersidmapping.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This file is auto generated by script, do not edit
// Mappings of Cppcheck warning IDs to guidelines
#include "checkers.h"
std::vector<checkers::IdMapping> checkers::idMappingAutosar{
{"m0-1-1", "unreachableCode,duplicateBreak"},
{"m0-1-2", "unsignedLessThanZero"},
{"m0-1-3", "unusedVariable,unusedStructMember"},
{"a0-1-1", "unreadVariable,unusedValue,redundantAssignment"},
{"m0-1-9", "redundantAssignment,redundantInitialization"},
{"m0-1-10", "unusedFunction"},
{"m0-2-1", "overlappingWriteUnion,overlappingWriteFunction"},
{"a1-1-1", "g++ .."},
{"a2-3-1", "The code contains unhandled character(s) (character code=195). Neither unicode nor extended ascii is supported. [syntaxError]"},
{"a2-7-3", "doxygen,clang -Wdocumentation"},
{"a2-10-1", "shadowVariable,shadowFunction,shadowArgument"},
{"a2-13-2", "compile error"},
{"a2-13-4", "compiler error"},
{"m3-2-2", "ctuOneDefinitionRuleViolation"},
{"m3-4-1", "variableScope"},
{"a5-0-1", "-Wsequence-point"},
{"m5-0-16", "pointerOutOfBounds"},
{"m5-0-17", "comparePointers"},
{"m5-0-18", "comparePointers"},
{"a5-1-4", "returnDanglingLifetime"},
{"a5-2-2", "cstyleCast"},
{"a5-2-5", "arrayIndexOutOfBounds,arrayIndexOutOfBoundsCond,pointerOutOfBounds,pointerOutOfBoundsCond,negativeIndex,arrayIndexThenCheck,bufferAccessOutOfBounds,objectIndex,argumentSize"},
{"m5-3-4", "sizeofFunctionCall"},
{"a5-3-2", "nullPointer,nullPointerRedundantCheck,nullPointerArithmetic,nullPointerArithmeticRedundantCheck,nullPointerDefaultArg"},
{"a5-6-1", "zerodiv,zerodivcond"},
{"m5-8-1", "shiftTooManyBits"},
{"m7-1-2", "constParameter"},
{"a7-5-1", "returnDanglingLifetime"},
{"m8-4-2", "funcArgNamesDifferent"},
{"a8-4-2", "missingReturn"},
{"a8-5-0", "uninitdata"},
{"m9-3-3", "functionConst,functionStatic"},
{"a12-1-1", "uninitMemberVar"},
{"m12-1-1", "virtualCallInConstructor"},
{"a12-1-4", "noExplicitConstructor"},
{"a12-6-1", "useInitializationList"},
{"a12-8-3", "accessMoved"},
{"a15-1-4", "memleak"},
{"m15-3-1", "exceptThrowInDestructor"},
{"a15-4-2", "throwInNoexceptFunction"},
{"m16-0-5", "preprocessorErrorDirective"},
{"a16-2-2", "iwyu,check headers"},
{"a18-5-3", "mismatchAllocDealloc"},
{"a20-8-1", "doubleFree"},
{"a23-0-2", "invalidContainer"},
};
std::vector<checkers::IdMapping> checkers::idMappingCertC{
{"PRE30", "preprocessorErrorDirective"},
{"PRE32", "preprocessorErrorDirective"},
{"DCL30", "danglingLifetime,autoVariables,invalidLifetime,returnDanglingLifetime"},
{"EXP30", "unknownEvaluationOrder"},
{"EXP33", "uninitvar,uninitdata,uninitStructMember"},
{"EXP34", "nullPointer,nullPointerDefaultArg,nullPointerRedundantCheck,nullPointerArithmetic,nullPointerArithmeticRedundantCheck"},
{"EXP44", "sizeofCalculation"},
{"EXP46", "bitwiseOnBoolean"},
{"FLP32", "invalidFunctionArg"},
{"FLP34", "floatConversionOverflow"},
{"ARR36", "comparePointers"},
{"STR30", "stringLiteralWrite"},
{"STR37", "invalidFunctionArg"},
{"MEM30", "doubleFree,deallocret,deallocuse"},
{"MEM31", "memleak,leakReturnValNotUsed,leakUnsafeArgAlloc,memleakOnRealloc"},
{"MEM34", "autovarInvalidDeallocation,mismatchAllocDealloc"},
{"FIO39", "IOWithoutPositioning"},
{"FIO42", "resourceLeak"},
{"FIO46", "deallocuse,useClosedFile"},
{"FIO47", "invalidscanf,wrongPrintfScanfArgNum,invalidLengthModifierError,invalidScanfFormatWidth,wrongPrintfScanfParameterPositionError"},
{"MSC37", "missingReturn"},
};
std::vector<checkers::IdMapping> checkers::idMappingCertCpp{
{"DCL57", "deallocThrow,exceptThrowInDestructor"},
{"DCL60", "ctuOneDefinitionRuleViolation"},
{"EXP52", "sizeofCalculation"},
{"EXP53", "uninitvar"},
{"EXP54", "uninitvar,danglingLifetime,danglingReference,danglingTemporaryLifetime,danglingTempReference,returnDanglingLifetime"},
{"EXP61", "danglingLifetime,danglingReference,danglingTemporaryLifetime,danglingTempReference,returnDanglingLifetime"},
{"EXP63", "accessMoved"},
{"CTR51", "eraseDereference"},
{"CTR54", "comparePointers"},
{"CTR55", "containerOutOfBounds"},
{"STR51", "nullPointer"},
{"STR52", "invalidContainer"},
{"MEM50", "deallocuse"},
{"MEM51", "mismatchAllocDealloc"},
{"MEM56", "doubleFree"},
{"FIO50", "IOWithoutPositioning"},
{"ERR57", "memleak"},
{"OOP50", "virtualCallInConstructor"},
{"OOP52", "virtualDestructor"},
{"OOP53", "initializerList"},
{"OOP54", "operatorEqToSelf"},
{"MSC52", "missingReturn"},
};
std::vector<checkers::IdMapping> checkers::idMappingMisraC{
{"1.1", "syntaxError"},
{"1.3", "error"},
{"2.1", "duplicateBreak,unreachableCode"},
{"2.2", "redundantCondition,redundantAssignment,redundantAssignInSwitch,unreadVariable"},
{"2.6", "unusedLabel"},
{"2.8", "unusedVariable"},
{"5.3", "shadowVariable"},
{"8.3", "funcArgNamesDifferent"},
{"8.13", "constParameterPointer"},
{"9.1", "uninitvar"},
{"12.5", "sizeofwithsilentarraypointer"},
{"13.2", "unknownEvaluationOrder"},
{"13.6", "sizeofCalculation"},
{"14.3", "compareValueOutOfTypeRangeError,knownConditionTrueFalse"},
{"17.4", "missingReturn"},
{"17.5", "argumentSize"},
{"18.1", "pointerOutOfBounds"},
{"18.2", "comparePointers"},
{"18.3", "comparePointers"},
{"18.6", "danglingLifetime,danglingTemporaryLifetime,returnDanglingLifetime"},
{"19.1", "overlappingWriteUnion,overlappingWriteFunction"},
{"20.6", "preprocessorErrorDirective"},
{"21.13", "invalidFunctionArg"},
{"21.17", "bufferAccessOutOfBounds"},
{"21.18", "bufferAccessOutOfBounds"},
{"22.1", "memleak,resourceLeak,memleakOnRealloc,leakReturnValNotUsed,leakNoVarFunctionCall"},
{"22.2", "autovarInvalidDeallocation"},
{"22.3", "incompatibleFileOpen"},
{"22.4", "writeReadOnlyFile"},
{"22.6", "useClosedFile"},
};
std::vector<checkers::IdMapping> checkers::idMappingMisraCpp2008{
{"0-1-1", "unreachableCode,duplicateBreak"},
{"0-1-2", "unsignedLessThanZero"},
{"0-1-3", "unusedVariable,unusedStructMember"},
{"0-1-6", "redundantAssignment,unreadVariable,variableScope"},
{"0-1-9", "redundantAssignment,redundantInitialization"},
{"0-1-10", "unusedFunction"},
{"0-2-1", "overlappingWriteUnion,overlappingWriteFunction"},
{"2-10-2", "shadowVariable"},
{"3-2-2", "ctuOneDefinitionRuleViolation"},
{"3-4-1", "variableScope"},
{"5-0-1", "unknownEvaluationOrder"},
{"5-0-16", "pointerOutOfBounds"},
{"5-0-17", "comparePointers"},
{"5-0-18", "comparePointers"},
{"5-2-4", "cstyleCast"},
{"5-3-4", "sizeofFunctionCall"},
{"5-8-1", "shiftTooManyBits"},
{"7-1-1", "constVariable,constParameter"},
{"7-1-2", "constParameter"},
{"7-5-1", "autoVariables,returnReference,returnTempReference"},
{"7-5-2", "danglingLifetime"},
{"8-4-2", "funcArgNamesDifferent"},
{"8-4-3", "missingReturn"},
{"8-5-1", "uninitvar,uninitdata,uninitStructMember,uninitMemberVar,uninitMemberVarPrivate,uninitDerivedMemberVar,uninitDerivedMemberVarPrivate"},
{"9-3-3", "functionConst,functionStatic"},
{"12-1-1", "virtualCallInConstructor"},
{"12-1-3", "noExplicitConstructor"},
{"15-3-1", "exceptThrowInDestructor"},
{"15-5-1", "exceptThrowInDestructor"},
{"15-5-3", "exceptThrowInDestructor"},
{"16-0-5", "preprocessorErrorDirective"},
};
std::vector<checkers::IdMapping> checkers::idMappingMisraCpp2023{
{"0.0.1", "unreachableCode"},
{"0.0.2", "compareBoolExpressionWithInt,compareValueOutOfTypeRangeError,identicalConditionAfterEarlyExit,identicalInnerCondition,knownConditionTrueFalse"},
{"0.1.1", "redundantAssignInSwitch,redundantAssignment,redundantCopy,redundantInitialization,unreadVariable"},
{"Dir 0.3.2", "invalidFunctionArg,invalidFunctionArgBool,invalidFunctionArgStr"},
{"4.1.3", "error"},
{"4.6.1", "unknownEvaluationOrder"},
{"6.2.1", "ctuOneDefinitionRuleViolation"},
{"6.4.1", "shadowVariable"},
{"6.8.1", "danglingLifetime"},
{"6.8.2", "autoVariables"},
{"8.7.1", "pointerOutOfBounds,pointerOutOfBoundsCond"},
{"8.7.2", "subtractPointers"},
{"8.9.1", "comparePointers"},
{"8.18.1", "overlappingWriteUnion"},
{"9.6.5", "missingReturn"},
{"10.1.1", "constParameter,constParameterReference"},
{"11.6.2", "uninitvar"},
{"15.1.1", "virtualCallInConstructor"},
{"15.1.4", "uninitMemberVar"},
{"Dir 15.8.1", "operatorEqToSelf"},
{"19.3.5", "preprocessorErrorDirective"},
{"28.6.3", "accessForwarded,accessMoved"},
{"28.6.4", "ignoredReturnValue"},
};
| null |
838 | cpp | cppcheck | ctu.h | lib/ctu.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef ctuH
#define ctuH
//---------------------------------------------------------------------------
#include "config.h"
#include "check.h"
#include "errorlogger.h"
#include "mathlib.h"
#include "vfvalue.h"
#include <cstdint>
#include <list>
#include <map>
#include <string>
#include <utility>
#include <vector>
class Function;
class Settings;
class Token;
class Tokenizer;
namespace tinyxml2 {
class XMLElement;
}
/// @addtogroup Core
/// @{
/** @brief Whole program analysis (ctu=Cross Translation Unit) */
namespace CTU {
class CPPCHECKLIB FileInfo : public Check::FileInfo {
public:
enum class InvalidValueType : std::uint8_t { null, uninit, bufferOverflow };
std::string toString() const override;
struct Location {
Location() = default;
Location(const Tokenizer &tokenizer, const Token *tok);
Location(std::string fileName, nonneg int lineNumber, nonneg int column) : fileName(std::move(fileName)), lineNumber(lineNumber), column(column) {}
std::string fileName;
nonneg int lineNumber{};
nonneg int column{};
};
struct UnsafeUsage {
UnsafeUsage() = default;
UnsafeUsage(std::string myId, nonneg int myArgNr, std::string myArgumentName, Location location, MathLib::bigint value) : myId(std::move(myId)), myArgNr(myArgNr), myArgumentName(std::move(myArgumentName)), location(std::move(location)), value(value) {}
std::string myId;
nonneg int myArgNr{};
std::string myArgumentName;
Location location;
MathLib::bigint value{};
std::string toString() const;
};
class CallBase {
public:
CallBase() = default;
CallBase(std::string callId, int callArgNr, std::string callFunctionName, Location loc)
: callId(std::move(callId)), callArgNr(callArgNr), callFunctionName(std::move(callFunctionName)), location(std::move(loc))
{}
CallBase(const Tokenizer &tokenizer, const Token *callToken);
virtual ~CallBase() = default;
CallBase(const CallBase&) = default;
std::string callId;
int callArgNr{};
std::string callFunctionName;
Location location;
protected:
std::string toBaseXmlString() const;
bool loadBaseFromXml(const tinyxml2::XMLElement *xmlElement);
};
class FunctionCall : public CallBase {
public:
std::string callArgumentExpression;
MathLib::bigint callArgValue;
ValueFlow::Value::ValueType callValueType;
std::vector<ErrorMessage::FileLocation> callValuePath;
bool warning;
std::string toXmlString() const;
bool loadFromXml(const tinyxml2::XMLElement *xmlElement);
};
class NestedCall : public CallBase {
public:
NestedCall() = default;
NestedCall(std::string myId, nonneg int myArgNr, const std::string &callId, nonneg int callArgnr, const std::string &callFunctionName, const Location &location)
: CallBase(callId, callArgnr, callFunctionName, location),
myId(std::move(myId)),
myArgNr(myArgNr) {}
NestedCall(const Tokenizer &tokenizer, const Function *myFunction, const Token *callToken);
std::string toXmlString() const;
bool loadFromXml(const tinyxml2::XMLElement *xmlElement);
std::string myId;
nonneg int myArgNr{};
};
std::list<FunctionCall> functionCalls;
std::list<NestedCall> nestedCalls;
void loadFromXml(const tinyxml2::XMLElement *xmlElement);
std::map<std::string, std::list<const CallBase *>> getCallsMap() const;
static std::list<ErrorMessage::FileLocation> getErrorPath(InvalidValueType invalidValue,
const UnsafeUsage &unsafeUsage,
const std::map<std::string, std::list<const CallBase *>> &callsMap,
const char info[],
const FunctionCall ** functionCallPtr,
bool warning,
int maxCtuDepth);
};
CPPCHECKLIB std::string toString(const std::list<FileInfo::UnsafeUsage> &unsafeUsage);
CPPCHECKLIB std::string getFunctionId(const Tokenizer &tokenizer, const Function *function);
/** @brief Parse current TU and extract file info */
CPPCHECKLIB RET_NONNULL FileInfo *getFileInfo(const Tokenizer &tokenizer);
CPPCHECKLIB std::list<FileInfo::UnsafeUsage> getUnsafeUsage(const Tokenizer &tokenizer, const Settings &settings, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value));
CPPCHECKLIB std::list<FileInfo::UnsafeUsage> loadUnsafeUsageListFromXml(const tinyxml2::XMLElement *xmlElement);
}
/// @}
//---------------------------------------------------------------------------
#endif // ctuH
| null |
839 | cpp | cppcheck | tokenize.h | lib/tokenize.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef tokenizeH
#define tokenizeH
//---------------------------------------------------------------------------
#include "config.h"
#include "tokenlist.h"
#include <cstdint>
#include <iosfwd>
#include <list>
#include <map>
#include <string>
#include <vector>
class Settings;
class SymbolDatabase;
class TimerResults;
class Token;
class TemplateSimplifier;
class ErrorLogger;
struct Directive;
enum class Severity : std::uint8_t;
/// @addtogroup Core
/// @{
/** @brief The main purpose is to tokenize the source code. It also has functions that simplify the token list */
class CPPCHECKLIB Tokenizer {
friend class SymbolDatabase;
friend class TemplateSimplifier;
friend class TestSimplifyTemplate;
friend class TestSimplifyTypedef;
friend class TestTokenizer;
public:
explicit Tokenizer(const Settings & settings, ErrorLogger &errorLogger);
~Tokenizer();
void setTimerResults(TimerResults *tr) {
mTimerResults = tr;
}
/** Is the code C. Used for bailouts */
bool isC() const {
return list.isC();
}
/** Is the code CPP. Used for bailouts */
bool isCPP() const {
return list.isCPP();
}
/**
* Check if inner scope ends with a call to a noreturn function
* \param endScopeToken The '}' token
* \param unknown set to true if it's unknown if the scope is noreturn
* \return true if scope ends with a function call that might be 'noreturn'
*/
bool isScopeNoReturn(const Token *endScopeToken, bool *unknown = nullptr) const;
bool simplifyTokens1(const std::string &configuration);
private:
/** Set variable id */
void setVarId();
void setVarIdPass1();
void setVarIdPass2();
/**
* Basic simplification of tokenlist
*
* @param FileName The filename to run; used to do
* markup checks.
*
* @return false if there is an error that requires aborting
* the checking of this file.
*/
bool simplifyTokenList1(const char FileName[]);
/**
* If --check-headers=no has been given; then remove unneeded code in headers.
* - All executable code.
* - Unused types/variables/etc
*/
void simplifyHeadersAndUnusedTemplates();
/**
* Remove extra "template" keywords that are not used by Cppcheck
*/
void removeExtraTemplateKeywords();
/** Split up template right angle brackets.
* foo < bar < >> => foo < bar < > >
*/
void splitTemplateRightAngleBrackets(bool check);
public:
/**
* Calculates sizeof value for given type.
* @param type Token which will contain e.g. "int", "*", or string.
* @return sizeof for given type, or 0 if it can't be calculated.
*/
nonneg int sizeOfType(const Token* type) const;
nonneg int sizeOfType(const std::string& type) const;
private:
void simplifyDebug();
/** Simplify assignment where rhs is a block : "x=({123;});" => "{x=123;}" */
void simplifyAssignmentBlock();
/** Insert array size where it isn't given */
void arraySize();
void arraySizeAfterValueFlow(); // cppcheck-suppress functionConst
/** Simplify labels and 'case|default' syntaxes.
*/
void simplifyLabelsCaseDefault();
/** simplify case ranges (gcc extension)
*/
void simplifyCaseRange();
/** Remove macros in global scope */
void removeMacrosInGlobalScope();
void addSemicolonAfterUnknownMacro();
// Remove C99 and CPP11 _Pragma(str)
void removePragma();
/** Remove undefined macro in class definition:
* class DLLEXPORT Fred { };
* class Fred FINAL : Base { };
*/
void removeMacroInClassDef();
/** Add parentheses for sizeof: sizeof x => sizeof(x) */
void sizeofAddParentheses();
/**
* Simplify variable declarations (split up)
* \param only_k_r_fpar Only simplify K&R function parameters
*/
void simplifyVarDecl( bool only_k_r_fpar);
void simplifyVarDecl(Token * tokBegin, const Token * tokEnd, bool only_k_r_fpar); // cppcheck-suppress functionConst // has side effects
/**
* Simplify variable initialization
* '; int *p(0);' => '; int *p = 0;'
*/
void simplifyInitVar();
RET_NONNULL static Token* initVar(Token* tok);
/**
* Simplify the location of "static" and "const" qualifiers in
* a variable declaration or definition.
* Example: "int static const a;" => "static const a;"
* Example: "long long const static b;" => "static const long long b;"
*/
void simplifyStaticConst();
/**
* Simplify multiple assignments.
* Example: "a = b = c = 0;" => "a = 0; b = 0; c = 0;"
*/
void simplifyVariableMultipleAssign();
/**
* Simplify the 'C Alternative Tokens'
* Examples:
* "if(s and t)" => "if(s && t)"
* "while((r bitand s) and not t)" => while((r & s) && !t)"
* "a and_eq b;" => "a &= b;"
*/
bool simplifyCAlternativeTokens();
/** Add braces to an if-block, for-block, etc.
* @return true if no syntax errors
*/
bool simplifyAddBraces();
/** Add braces to an if-block, for-block, etc.
* for command starting at token including else-block
* @return last token of command
* or input token in case of an error where no braces are added
* or NULL when syntaxError is called
*/
Token * simplifyAddBracesToCommand(Token * tok);
/** Add pair of braces to an single if-block, else-block, for-block, etc.
* for command starting at token
* @return last token of command
* or input token in case of an error where no braces are added
* or NULL when syntaxError is called
*/
Token * simplifyAddBracesPair(Token *tok, bool commandWithCondition);
// Convert "using ...;" to corresponding typedef
void simplifyUsingToTypedef();
/**
* typedef A mytype;
* mytype c;
*
* Becomes:
* typedef A mytype;
* A c;
*/
void simplifyTypedef();
void simplifyTypedefCpp();
/**
* Move typedef token to the left og the expression
*/
void simplifyTypedefLHS();
/**
*/
static bool isMemberFunction(const Token *openParen);
/**
*/
bool simplifyUsing();
void simplifyUsingError(const Token* usingStart, const Token* usingEnd);
/** Simplify useless C++ empty namespaces, like: 'namespace %name% { }'*/
void simplifyEmptyNamespaces();
/** Simplify "if else" */
void elseif();
/** Simplify C++17/C++20 if/switch/for initialization expression */
void simplifyIfSwitchForInit();
/**
* Reduces "; ;" to ";", except in "( ; ; )"
*/
void removeRedundantSemicolons();
/** Struct simplification
* "struct S { } s;" => "struct S { }; S s;"
*/
void simplifyStructDecl();
/**
* Remove redundant parentheses:
* - "((x))" => "(x)"
* - "(function())" => "function()"
* - "(delete x)" => "delete x"
* - "(delete [] x)" => "delete [] x"
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
bool simplifyRedundantParentheses();
/**
* Simplify functions like "void f(x) int x; {"
* into "void f(int x) {"
*/
void simplifyFunctionParameters();
/** Simplify function level try blocks:
* Convert "void f() try {} catch (int) {}"
* to "void f() { try {} catch (int) {} }"
*/
void simplifyFunctionTryCatch();
/**
* Simplify templates
*/
void simplifyTemplates();
void simplifyDoublePlusAndDoubleMinus();
void simplifyRedundantConsecutiveBraces();
void simplifyArrayAccessSyntax();
void simplifyParameterVoid();
void fillTypeSizes();
void combineOperators();
void combineStringAndCharLiterals();
void concatenateNegativeNumberAndAnyPositive();
void simplifyExternC();
void simplifyCompoundStatements();
void simplifyTypeIntrinsics();
void simplifySQL();
void checkForEnumsWithTypedef();
void findComplicatedSyntaxErrorsInTemplates();
/**
* Modify strings in the token list by replacing hex and oct
* values. E.g. "\x61" -> "a" and "\000" -> "\0"
* @param source The string to be modified, e.g. "\x61"
* @return Modified string, e.g. "a"
*/
static std::string simplifyString(const std::string &source);
public:
/**
* is token pointing at function head?
* @param tok A '(' or ')' token in a possible function head
* @param endsWith string after function head
* @return token matching with endsWith if syntax seems to be a function head else nullptr
*/
static const Token * isFunctionHead(const Token *tok, const std::string &endsWith);
bool hasIfdef(const Token *start, const Token *end) const;
bool isPacked(const Token * bodyStart) const;
private:
/** Simplify pointer to standard type (C only) */
void simplifyPointerToStandardType();
/** Simplify function pointers */
void simplifyFunctionPointers();
/**
* Send error message to error logger about internal bug.
* @param tok the token that this bug concerns.
*/
NORETURN void cppcheckError(const Token *tok) const;
/**
* Setup links for tokens so that one can call Token::link().
*/
void createLinks();
/**
* Setup links between < and >.
*/
void createLinks2();
/**
* Set isCast() for C++ casts
*/
void markCppCasts();
public:
/** Syntax error */
NORETURN void syntaxError(const Token *tok, const std::string &code = emptyString) const;
/** Syntax error. Unmatched character. */
NORETURN void unmatchedToken(const Token *tok) const;
/** Syntax error. C++ code in C file. */
NORETURN void syntaxErrorC(const Token *tok, const std::string &what) const;
/** Warn about unknown macro(s), configuration is recommended */
NORETURN void unknownMacroError(const Token *tok1) const;
void unhandledCharLiteral(const Token *tok, const std::string& msg) const;
private:
/** Report that there is an unhandled "class x y {" code */
void unhandled_macro_class_x_y(const Token *tok) const;
/** Check configuration (unknown macros etc) */
void checkConfiguration() const;
void macroWithSemicolonError(const Token *tok, const std::string ¯oName) const;
/**
* Is there C++ code in C file?
*/
void validateC() const;
/**
* assert that tokens are ok - used during debugging for example
* to catch problems in simplifyTokenList1/2.
*/
void validate() const;
/** Detect unknown macros and throw unknownMacro */
void reportUnknownMacros() const;
/** Detect garbage code and call syntaxError() if found. */
void findGarbageCode() const;
/** Detect garbage expression */
static bool isGarbageExpr(const Token *start, const Token *end, bool allowSemicolon);
/**
* Remove __declspec()
*/
void simplifyDeclspec();
/**
* Remove calling convention
*/
void simplifyCallingConvention();
/**
* Remove \__attribute\__ ((?))
*/
void simplifyAttribute();
/** Get function token for a attribute */
Token* getAttributeFuncTok(Token* tok, bool gccattr) const;
/**
* Remove \__cppcheck\__ ((?))
*/
void simplifyCppcheckAttribute();
/** Simplify c++20 spaceship operator */
void simplifySpaceshipOperator();
/**
* Remove keywords "volatile", "inline", "register", and "restrict"
*/
void simplifyKeyword();
/**
* Remove __asm
*/
void simplifyAsm();
/**
* asm heuristics, Put ^{} statements in asm()
*/
void simplifyAsm2();
/**
* Simplify \@… (compiler extension)
*/
void simplifyAt();
/**
* Simplify bitfields - the field width is removed as we don't use it.
*/
void simplifyBitfields();
/**
* Remove unnecessary member qualification
*/
void removeUnnecessaryQualification();
/**
* Add std:: in front of std classes, when using namespace std; was given
*/
void simplifyNamespaceStd();
/**
* Convert Microsoft memory functions
* CopyMemory(dst, src, len) -> memcpy(dst, src, len)
* FillMemory(dst, len, val) -> memset(dst, val, len)
* MoveMemory(dst, src, len) -> memmove(dst, src, len)
* ZeroMemory(dst, len) -> memset(dst, 0, len)
*/
void simplifyMicrosoftMemoryFunctions();
/**
* Convert Microsoft string functions
* _tcscpy -> strcpy
*/
void simplifyMicrosoftStringFunctions();
/**
* Remove Borland code
*/
void simplifyBorland();
/**
* Collapse operator name tokens into single token
* operator = => operator=
*/
void simplifyOperatorName();
/** simplify overloaded operators: 'obj(123)' => 'obj . operator() ( 123 )' */
void simplifyOverloadedOperators();
/**
* Remove [[attribute]] (C++11, C23) from TokenList
*/
void simplifyCPPAttribute();
/**
* Convert namespace aliases
*/
void simplifyNamespaceAliases();
/**
* Convert C++17 style nested namespace to older style
*/
void simplifyNestedNamespace();
/**
* Simplify coroutines - just put parentheses around arguments for
* co_* keywords so they can be handled like function calls in data
* flow.
*/
void simplifyCoroutines();
/**
* Prepare ternary operators with parentheses so that the AST can be created
* */
void prepareTernaryOpForAST();
/**
* report error message
*/
void reportError(const Token* tok, Severity severity, const std::string& id, const std::string& msg, bool inconclusive = false) const;
void reportError(const std::list<const Token*>& callstack, Severity severity, const std::string& id, const std::string& msg, bool inconclusive = false) const;
bool duplicateTypedef(Token *&tokPtr, const Token *name, const Token *typeDef) const;
void unsupportedTypedef(const Token *tok) const;
static void setVarIdClassFunction(const std::string &classname,
Token * startToken,
const Token * endToken,
const std::map<std::string, nonneg int> &varlist,
std::map<nonneg int, std::map<std::string, nonneg int>>& structMembers,
nonneg int &varId_);
/**
* Output list of unknown types.
*/
void printUnknownTypes() const;
/** Find end of SQL (or PL/SQL) block */
static const Token *findSQLBlockEnd(const Token *tokSQLStart);
static bool operatorEnd(const Token * tok);
public:
const SymbolDatabase *getSymbolDatabase() const {
return mSymbolDatabase;
}
void createSymbolDatabase();
/** print --debug output if debug flags match the simplification:
* 0=unknown/both simplifications
* 1=1st simplifications
* 2=2nd simplifications
*/
void printDebugOutput(int simplification, std::ostream &out) const;
void dump(std::ostream &out) const;
Token *deleteInvalidTypedef(Token *typeDef);
/**
* Get variable count.
* @return number of variables
*/
nonneg int varIdCount() const {
return mVarId;
}
/**
* Token list: stores all tokens.
*/
TokenList list;
// Implement tokens() as a wrapper for convenience when using the TokenList
const Token* tokens() const {
return list.front();
}
Token* tokens() {
return list.front();
}
/**
* Helper function to check whether number is one (1 or 0.1E+1 or 1E+0) or not?
* @param s the string to check
* @return true in case is is one and false otherwise.
*/
static bool isOneNumber(const std::string &s);
/**
* Helper function to check for start of function execution scope.
* Do not use this in checks. Use the symbol database.
* @param tok pointer to end parentheses of parameter list
* @return pointer to start brace of function scope or nullptr if not start.
*/
static const Token * startOfExecutableScope(const Token * tok);
const Settings &getSettings() const {
return mSettings;
}
void calculateScopes();
/** Disable copy constructor */
Tokenizer(const Tokenizer &) = delete;
/** Disable assignment operator */
Tokenizer &operator=(const Tokenizer &) = delete;
void setDirectives(std::list<Directive> directives);
std::string dumpTypedefInfo() const;
private:
const Token *processFunc(const Token *tok2, bool inOperator) const;
Token *processFunc(Token *tok2, bool inOperator);
/**
* Get new variable id.
* @return new variable id
*/
nonneg int newVarId() {
return ++mVarId;
}
/** Set pod types */
void setPodTypes();
/** settings */
const Settings & mSettings;
/** errorlogger */
ErrorLogger& mErrorLogger;
/** Symbol database that all checks etc can use */
SymbolDatabase* mSymbolDatabase{};
TemplateSimplifier * const mTemplateSimplifier;
/** E.g. "A" for code where "#ifdef A" is true. This is used to
print additional information in error situations. */
std::string mConfiguration;
/** sizeof information for known types */
std::map<std::string, int> mTypeSize;
struct TypedefInfo {
std::string name;
std::string filename;
int lineNumber;
int column;
bool used;
bool isFunctionPointer;
};
std::vector<TypedefInfo> mTypedefInfo;
std::list<Directive> mDirectives;
/** variable count */
nonneg int mVarId{};
/** unnamed count "Unnamed0", "Unnamed1", "Unnamed2", ... */
nonneg int mUnnamedCount{};
/**
* TimerResults
*/
TimerResults* mTimerResults{};
};
/// @}
//---------------------------------------------------------------------------
#endif // tokenizeH
| null |
840 | cpp | cppcheck | checkers.h | lib/checkers.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef checkersH
#define checkersH
#include <map>
#include <string>
#include <vector>
#include "config.h"
namespace checkers {
extern CPPCHECKLIB const std::map<std::string, std::string> allCheckers;
extern CPPCHECKLIB const std::map<std::string, std::string> premiumCheckers;
struct CPPCHECKLIB MisraInfo {
int a;
int b;
const char* str;
int amendment;
};
struct CPPCHECKLIB MisraCppInfo {
int a;
int b;
int c;
const char* classification;
};
extern CPPCHECKLIB const char Req[]; // = "Required";
extern CPPCHECKLIB const char Adv[]; // = "Advisory";
extern CPPCHECKLIB const char Man[]; // = "Mandatory";
extern CPPCHECKLIB const char Doc[]; // = "Document";
extern CPPCHECKLIB const std::vector<MisraInfo> misraC2012Directives;
extern CPPCHECKLIB const std::vector<MisraInfo> misraC2012Rules;
extern CPPCHECKLIB const std::vector<MisraCppInfo> misraCpp2008Rules;
extern CPPCHECKLIB const std::vector<MisraCppInfo> misraCpp2023Rules;
extern CPPCHECKLIB const std::map<std::string, std::string> misraRuleSeverity;
struct CPPCHECKLIB IdMapping {
const char* guideline;
const char* cppcheckId;
};
extern std::vector<IdMapping> idMappingMisraC;
extern std::vector<IdMapping> idMappingMisraCpp2008;
extern std::vector<IdMapping> idMappingMisraCpp2023;
extern std::vector<IdMapping> idMappingAutosar;
extern std::vector<IdMapping> idMappingCertC;
extern std::vector<IdMapping> idMappingCertCpp;
struct CPPCHECKLIB Info {
const char* guideline;
const char* classification;
};
extern std::vector<Info> autosarInfo;
extern std::vector<Info> certCInfo;
extern std::vector<Info> certCppInfo;
}
#endif
| null |
841 | cpp | cppcheck | checkclass.h | lib/checkclass.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkclassH
#define checkclassH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include "symboldatabase.h"
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief %Check classes. Uninitialized member variables, non-conforming operators, missing virtual destructor, etc */
class CPPCHECKLIB CheckClass : public Check {
friend class TestClass;
friend class TestConstructors;
friend class TestUnusedPrivateFunction;
public:
/** @brief This constructor is used when registering the CheckClass */
CheckClass() : Check(myName()) {}
/** @brief Set of the STL types whose operator[] is not const */
static const std::set<std::string> stl_containers_not_const;
private:
/** @brief This constructor is used when running checks. */
CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger);
/** @brief Run checks on the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckClass checkClass(&tokenizer, &tokenizer.getSettings(), errorLogger);
// can't be a simplified check .. the 'sizeof' is used.
checkClass.checkMemset();
checkClass.constructors();
checkClass.privateFunctions();
checkClass.operatorEqRetRefThis();
checkClass.thisSubtraction();
checkClass.operatorEqToSelf();
checkClass.initializerListOrder();
checkClass.initializationListUsage();
checkClass.checkSelfInitialization();
checkClass.virtualDestructor();
checkClass.checkConst();
checkClass.copyconstructors();
checkClass.checkVirtualFunctionCallInConstructor();
checkClass.checkDuplInheritedMembers();
checkClass.checkExplicitConstructors();
checkClass.checkCopyCtorAndEqOperator();
checkClass.checkOverride();
checkClass.checkUselessOverride();
checkClass.checkReturnByReference();
checkClass.checkThisUseAfterFree();
checkClass.checkUnsafeClassRefMember();
}
/** @brief %Check that all class constructors are ok */
void constructors();
/** @brief %Check that constructors with single parameter are explicit,
* if they has to be.*/
void checkExplicitConstructors();
/** @brief %Check that all private functions are called */
void privateFunctions();
/**
* @brief %Check that the memsets are valid.
* The 'memset' function can do dangerous things if used wrong. If it
* is used on STL containers for instance it will clear all its data
* and then the STL container may leak memory or worse have an invalid state.
* It can also overwrite the virtual table.
* Important: The checking doesn't work on simplified tokens list.
*/
void checkMemset();
void checkMemsetType(const Scope *start, const Token *tok, const Scope *type, bool allocation, std::set<const Scope *> parsedTypes);
/** @brief 'operator=' should return reference to *this */
void operatorEqRetRefThis(); // Warning upon no "return *this;"
/** @brief 'operator=' should check for assignment to self */
void operatorEqToSelf(); // Warning upon no check for assignment to self
/** @brief The destructor in a base class should be virtual */
void virtualDestructor();
/** @brief warn for "this-x". The indented code may be "this->x" */
void thisSubtraction();
/** @brief can member function be const? */
void checkConst();
/** @brief Check initializer list order */
void initializerListOrder();
/** @brief Suggest using initialization list */
void initializationListUsage();
/** @brief Check for initialization of a member with itself */
void checkSelfInitialization();
void copyconstructors();
/** @brief call of virtual function in constructor/destructor */
void checkVirtualFunctionCallInConstructor();
/** @brief Check duplicated inherited members */
void checkDuplInheritedMembers();
/** @brief Check that copy constructor and operator defined together */
void checkCopyCtorAndEqOperator();
/** @brief Check that the override keyword is used when overriding virtual functions */
void checkOverride();
/** @brief Check that the overriden function is not identical to the base function */
void checkUselessOverride();
/** @brief Check that large members are returned by reference from getter function */
void checkReturnByReference();
/** @brief When "self pointer" is destroyed, 'this' might become invalid. */
void checkThisUseAfterFree();
/** @brief Unsafe class check - const reference member */
void checkUnsafeClassRefMember();
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
const SymbolDatabase* mSymbolDatabase{};
// Reporting errors..
void noConstructorError(const Token *tok, const std::string &classname, bool isStruct);
void noExplicitConstructorError(const Token *tok, const std::string &classname, bool isStruct);
//void copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& var_name);
void copyConstructorShallowCopyError(const Token *tok, const std::string& varname);
void noCopyConstructorError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive);
void noOperatorEqError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive);
void noDestructorError(const Scope *scope, bool isdefault, const Token *alloc);
void uninitVarError(const Token *tok, bool isprivate, Function::Type functionType, const std::string &classname, const std::string &varname, bool derived, bool inconclusive);
void uninitVarError(const Token *tok, const std::string &classname, const std::string &varname);
void missingMemberCopyError(const Token *tok, Function::Type functionType, const std::string& classname, const std::string& varname);
void operatorEqVarError(const Token *tok, const std::string &classname, const std::string &varname, bool inconclusive);
void unusedPrivateFunctionError(const Token *tok, const std::string &classname, const std::string &funcname);
void memsetError(const Token *tok, const std::string &memfunc, const std::string &classname, const std::string &type, bool isContainer = false);
void memsetErrorReference(const Token *tok, const std::string &memfunc, const std::string &type);
void memsetErrorFloat(const Token *tok, const std::string &type);
void mallocOnClassError(const Token* tok, const std::string &memfunc, const Token* classTok, const std::string &classname);
void mallocOnClassWarning(const Token* tok, const std::string &memfunc, const Token* classTok);
void virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived, bool inconclusive);
void thisSubtractionError(const Token *tok);
void operatorEqRetRefThisError(const Token *tok);
void operatorEqShouldBeLeftUnimplementedError(const Token *tok);
void operatorEqMissingReturnStatementError(const Token *tok, bool error);
void operatorEqToSelfError(const Token *tok);
void checkConstError(const Token *tok, const std::string &classname, const std::string &funcname, bool suggestStatic, bool foundAllBaseClasses = true);
void checkConstError2(const Token *tok1, const Token *tok2, const std::string &classname, const std::string &funcname, bool suggestStatic, bool foundAllBaseClasses = true);
void initializerListError(const Token *tok1,const Token *tok2, const std::string & classname, const std::string &varname, const std::string& argname = {});
void suggestInitializationList(const Token *tok, const std::string& varname);
void selfInitializationError(const Token* tok, const std::string& varname);
void pureVirtualFunctionCallInConstructorError(const Function * scopeFunction, const std::list<const Token *> & tokStack, const std::string &purefuncname);
void virtualFunctionCallInConstructorError(const Function * scopeFunction, const std::list<const Token *> & tokStack, const std::string &funcname);
void duplInheritedMembersError(const Token* tok1, const Token* tok2, const std::string &derivedName, const std::string &baseName, const std::string &memberName, bool derivedIsStruct, bool baseIsStruct, bool isFunction = false);
void copyCtorAndEqOperatorError(const Token *tok, const std::string &classname, bool isStruct, bool hasCopyCtor);
void overrideError(const Function *funcInBase, const Function *funcInDerived);
void uselessOverrideError(const Function *funcInBase, const Function *funcInDerived, bool isSameCode = false);
void returnByReferenceError(const Function *func, const Variable* var);
void thisUseAfterFree(const Token *self, const Token *free, const Token *use);
void unsafeClassRefMemberError(const Token *tok, const std::string &varname);
void checkDuplInheritedMembersRecursive(const Type* typeCurrent, const Type* typeBase);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckClass c(nullptr, settings, errorLogger);
c.noConstructorError(nullptr, "classname", false);
c.noExplicitConstructorError(nullptr, "classname", false);
//c.copyConstructorMallocError(nullptr, 0, "var");
c.copyConstructorShallowCopyError(nullptr, "var");
c.noCopyConstructorError(nullptr, false, nullptr, false);
c.noOperatorEqError(nullptr, false, nullptr, false);
c.noDestructorError(nullptr, false, nullptr);
c.uninitVarError(nullptr, false, Function::eConstructor, "classname", "varname", false, false);
c.uninitVarError(nullptr, true, Function::eConstructor, "classname", "varnamepriv", false, false);
c.uninitVarError(nullptr, false, Function::eConstructor, "classname", "varname", true, false);
c.uninitVarError(nullptr, true, Function::eConstructor, "classname", "varnamepriv", true, false);
c.missingMemberCopyError(nullptr, Function::eConstructor, "classname", "varnamepriv");
c.operatorEqVarError(nullptr, "classname", emptyString, false);
c.unusedPrivateFunctionError(nullptr, "classname", "funcname");
c.memsetError(nullptr, "memfunc", "classname", "class");
c.memsetErrorReference(nullptr, "memfunc", "class");
c.memsetErrorFloat(nullptr, "class");
c.mallocOnClassWarning(nullptr, "malloc", nullptr);
c.mallocOnClassError(nullptr, "malloc", nullptr, "std::string");
c.virtualDestructorError(nullptr, "Base", "Derived", false);
c.thisSubtractionError(nullptr);
c.operatorEqRetRefThisError(nullptr);
c.operatorEqMissingReturnStatementError(nullptr, true);
c.operatorEqShouldBeLeftUnimplementedError(nullptr);
c.operatorEqToSelfError(nullptr);
c.checkConstError(nullptr, "class", "function", false);
c.checkConstError(nullptr, "class", "function", true);
c.initializerListError(nullptr, nullptr, "class", "variable");
c.suggestInitializationList(nullptr, "variable");
c.selfInitializationError(nullptr, "var");
c.duplInheritedMembersError(nullptr, nullptr, "class", "class", "variable", false, false);
c.copyCtorAndEqOperatorError(nullptr, "class", false, false);
c.overrideError(nullptr, nullptr);
c.uselessOverrideError(nullptr, nullptr);
c.returnByReferenceError(nullptr, nullptr);
c.pureVirtualFunctionCallInConstructorError(nullptr, std::list<const Token *>(), "f");
c.virtualFunctionCallInConstructorError(nullptr, std::list<const Token *>(), "f");
c.thisUseAfterFree(nullptr, nullptr, nullptr);
c.unsafeClassRefMemberError(nullptr, "UnsafeClass::var");
}
static std::string myName() {
return "Class";
}
std::string classInfo() const override {
return "Check the code for each class.\n"
"- Missing constructors and copy constructors\n"
//"- Missing allocation of memory in copy constructor\n"
"- Constructors which should be explicit\n"
"- Are all variables initialized by the constructors?\n"
"- Are all variables assigned by 'operator='?\n"
"- Warn if memset, memcpy etc are used on a class\n"
"- Warn if memory for classes is allocated with malloc()\n"
"- If it's a base class, check that the destructor is virtual\n"
"- Are there unused private functions?\n"
"- 'operator=' should check for assignment to self\n"
"- Constness for member functions\n"
"- Order of initializations\n"
"- Suggest usage of initialization list\n"
"- Initialization of a member with itself\n"
"- Suspicious subtraction from 'this'\n"
"- Call of pure virtual function in constructor/destructor\n"
"- Duplicated inherited data members\n"
// disabled for now "- If 'copy constructor' defined, 'operator=' also should be defined and vice versa\n"
"- Check that arbitrary usage of public interface does not result in division by zero\n"
"- Delete \"self pointer\" and then access 'this'\n"
"- Check that the 'override' keyword is used when overriding virtual functions\n"
"- Check that the 'one definition rule' is not violated\n";
}
// operatorEqRetRefThis helper functions
void checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last);
void checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last, std::set<const Function*>& analyzedFunctions);
// operatorEqToSelf helper functions
bool hasAllocation(const Function *func, const Scope* scope) const;
bool hasAllocation(const Function *func, const Scope* scope, const Token *start, const Token *end) const;
bool hasAllocationInIfScope(const Function *func, const Scope* scope, const Token *ifStatementScopeStart) const;
static bool hasAssignSelf(const Function *func, const Token *rhs, const Token *&out_ifStatementScopeStart);
enum class Bool : std::uint8_t { TRUE, FALSE, BAILOUT };
static Bool isInverted(const Token *tok, const Token *rhs);
static const Token * getIfStmtBodyStart(const Token *tok, const Token *rhs);
// checkConst helper functions
bool isMemberVar(const Scope *scope, const Token *tok) const;
static bool isMemberFunc(const Scope *scope, const Token *tok);
static bool isConstMemberFunc(const Scope *scope, const Token *tok);
enum class MemberAccess : std::uint8_t { NONE, SELF, MEMBER };
bool checkConstFunc(const Scope *scope, const Function *func, MemberAccess& memberAccessed) const;
// constructors helper function
/** @brief Information about a member variable. Used when checking for uninitialized variables */
struct Usage {
explicit Usage(const Variable *var) : var(var) {}
/** Variable that this usage is for */
const Variable *var;
/** @brief has this variable been assigned? */
bool assign{};
/** @brief has this variable been initialized? */
bool init{};
};
static bool isBaseClassMutableMemberFunc(const Token *tok, const Scope *scope);
/**
* @brief Create usage list that contains all scope members and also members
* of base classes without constructors.
* @param scope current class scope
*/
static std::vector<Usage> createUsageList(const Scope *scope);
/**
* @brief assign a variable in the varlist
* @param usageList reference to usage vector
* @param varid id of variable to mark assigned
*/
static void assignVar(std::vector<Usage> &usageList, nonneg int varid);
/**
* @brief assign a variable in the varlist
* @param usageList reference to usage vector
* @param vartok variable token
*/
static void assignVar(std::vector<Usage> &usageList, const Token *vartok);
/**
* @brief initialize a variable in the varlist
* @param usageList reference to usage vector
* @param varid id of variable to mark initialized
*/
static void initVar(std::vector<Usage> &usageList, nonneg int varid);
/**
* @brief set all variables in list assigned
* @param usageList reference to usage vector
*/
static void assignAllVar(std::vector<Usage> &usageList);
/**
* @brief set all variable in list assigned, if visible from given scope
* @param usageList reference to usage vector
* @param scope scope from which usages must be visible
*/
static void assignAllVarsVisibleFromScope(std::vector<Usage> &usageList, const Scope *scope);
/**
* @brief set all variables in list not assigned and not initialized
* @param usageList reference to usage vector
*/
static void clearAllVar(std::vector<Usage> &usageList);
/**
* @brief parse a scope for a constructor or member function and set the "init" flags in the provided varlist
* @param func reference to the function that should be checked
* @param callstack the function doesn't look into recursive function calls.
* @param scope pointer to variable Scope
* @param usage reference to usage vector
*/
void initializeVarList(const Function &func, std::list<const Function *> &callstack, const Scope *scope, std::vector<Usage> &usage) const;
/**
* @brief gives a list of tokens where virtual functions are called directly or indirectly
* @param function function to be checked
* @param virtualFunctionCallsMap map of results for already checked functions
* @return list of tokens where pure virtual functions are called
*/
const std::list<const Token *> & getVirtualFunctionCalls(
const Function & function,
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap);
/**
* @brief looks for the first virtual function call stack
* @param virtualFunctionCallsMap map of results obtained from getVirtualFunctionCalls
* @param callToken token where pure virtual function is called directly or indirectly
* @param[in,out] pureFuncStack list to append the stack
*/
static void getFirstVirtualFunctionCallStack(
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap,
const Token *callToken,
std::list<const Token *> & pureFuncStack);
static bool canNotCopy(const Scope *scope);
static bool canNotMove(const Scope *scope);
/**
* @brief Helper for checkThisUseAfterFree
*/
bool checkThisUseAfterFreeRecursive(const Scope *classScope, const Function *func, const Variable *selfPointer, std::set<const Function *> callstack, const Token *&freeToken);
};
/// @}
//---------------------------------------------------------------------------
#endif // checkclassH
| null |
842 | cpp | cppcheck | summaries.cpp | lib/summaries.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "summaries.h"
#include "analyzerinfo.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <algorithm>
#include <fstream>
#include <map>
#include <sstream>
#include <utility>
#include <vector>
std::string Summaries::create(const Tokenizer &tokenizer, const std::string &cfg)
{
const SymbolDatabase *symbolDatabase = tokenizer.getSymbolDatabase();
const Settings &settings = tokenizer.getSettings();
std::ostringstream ostr;
for (const Scope *scope : symbolDatabase->functionScopes) {
const Function *f = scope->function;
if (!f)
continue;
// Summarize function
std::set<std::string> noreturn;
std::set<std::string> globalVars;
std::set<std::string> calledFunctions;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->variable() && tok->variable()->isGlobal())
globalVars.insert(tok->variable()->name());
if (Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) {
calledFunctions.insert(tok->str());
if (Token::simpleMatch(tok->linkAt(1), ") ; }"))
noreturn.insert(tok->str());
}
}
// Write summary for function
auto join = [](const std::set<std::string> &data) -> std::string {
std::string ret;
const char *sep = "";
for (const std::string &d: data)
{
ret += sep + d;
sep = ",";
}
return ret;
};
ostr << f->name();
if (!globalVars.empty())
ostr << " global:[" << join(globalVars) << "]";
if (!calledFunctions.empty())
ostr << " call:[" << join(calledFunctions) << "]";
if (!noreturn.empty())
ostr << " noreturn:[" << join(noreturn) << "]";
ostr << std::endl;
}
if (!settings.buildDir.empty()) {
std::string filename = AnalyzerInformation::getAnalyzerInfoFile(settings.buildDir, tokenizer.list.getSourceFilePath(), cfg);
const std::string::size_type pos = filename.rfind(".a");
if (pos != std::string::npos) {
filename[pos+1] = 's';
std::ofstream fout(filename);
fout << ostr.str();
}
}
return ostr.str();
}
static std::vector<std::string> getSummaryFiles(const std::string &filename)
{
std::vector<std::string> ret;
std::ifstream fin(filename);
if (!fin.is_open())
return ret;
std::string line;
while (std::getline(fin, line)) {
const std::string::size_type dotA = line.find(".a");
const std::string::size_type colon = line.find(':');
if (colon > line.size() || dotA > colon)
continue;
std::string f = line.substr(0,colon);
f[dotA + 1] = 's';
ret.push_back(std::move(f));
}
return ret;
}
static std::vector<std::string> getSummaryData(const std::string &line, const std::string &data)
{
std::vector<std::string> ret;
const std::string::size_type start = line.find(" " + data + ":[");
if (start == std::string::npos)
return ret;
const std::string::size_type end = line.find(']', start);
if (end >= line.size())
return ret;
std::string::size_type pos1 = start + 3 + data.size();
while (pos1 < end) {
const std::string::size_type pos2 = line.find_first_of(",]",pos1);
ret.push_back(line.substr(pos1, pos2-pos1-1));
pos1 = pos2 + 1;
}
return ret;
}
static void removeFunctionCalls(const std::string& calledFunction,
std::map<std::string, std::vector<std::string>> &functionCalledBy,
std::map<std::string, std::vector<std::string>> &functionCalls,
std::vector<std::string> &add)
{
std::vector<std::string> calledBy = functionCalledBy[calledFunction];
functionCalledBy.erase(calledFunction);
for (const std::string &c: calledBy) {
std::vector<std::string> &calls = functionCalls[c];
calls.erase(std::remove(calls.begin(), calls.end(), calledFunction), calls.end());
if (calls.empty()) {
add.push_back(calledFunction);
removeFunctionCalls(c, functionCalledBy, functionCalls, add);
}
}
}
void Summaries::loadReturn(const std::string &buildDir, std::set<std::string> &summaryReturn)
{
if (buildDir.empty())
return;
std::vector<std::string> return1;
std::map<std::string, std::vector<std::string>> functionCalls;
std::map<std::string, std::vector<std::string>> functionCalledBy;
// extract "functionNoreturn" and "functionCalledBy" from summaries
std::vector<std::string> summaryFiles = getSummaryFiles(buildDir + "/files.txt");
for (const std::string &filename: summaryFiles) {
std::ifstream fin(buildDir + '/' + filename);
if (!fin.is_open())
continue;
std::string line;
while (std::getline(fin, line)) {
// Get function name
constexpr std::string::size_type pos1 = 0;
const std::string::size_type pos2 = line.find(' ', pos1);
const std::string functionName = (pos2 == std::string::npos) ? line : line.substr(0, pos2);
std::vector<std::string> call = getSummaryData(line, "call");
functionCalls[functionName] = call;
if (call.empty())
return1.push_back(functionName);
else {
for (const std::string &c: call) {
functionCalledBy[c].push_back(functionName);
}
}
}
}
summaryReturn.insert(return1.cbegin(), return1.cend());
// recursively set "summaryNoreturn"
for (const std::string &f: return1) {
std::vector<std::string> return2;
removeFunctionCalls(f, functionCalledBy, functionCalls, return2);
summaryReturn.insert(return2.cbegin(), return2.cend());
}
}
| null |
843 | cpp | cppcheck | valueptr.h | lib/valueptr.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef valueptrH
#define valueptrH
//---------------------------------------------------------------------------
#include "config.h"
#include <memory>
template<class T>
class CPPCHECKLIB ValuePtr {
template<class U>
struct cloner {
static T* apply(const T* x) {
return new U(*static_cast<const U*>(x));
}
};
public:
using pointer = T*;
using element_type = T;
using cloner_type = decltype(&cloner<T>::apply);
ValuePtr() : mPtr(nullptr), mClone() {}
template<class U>
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
ValuePtr(const U& value) : mPtr(cloner<U>::apply(&value)), mClone(&cloner<U>::apply)
{}
ValuePtr(const ValuePtr& rhs) : mPtr(nullptr), mClone(rhs.mClone) {
if (rhs) {
mPtr.reset(mClone(rhs.get()));
}
}
ValuePtr(ValuePtr&& rhs) NOEXCEPT : mPtr(std::move(rhs.mPtr)), mClone(std::move(rhs.mClone)) {}
T* get() NOEXCEPT {
return mPtr.get();
}
const T* get() const NOEXCEPT {
return mPtr.get();
}
T& operator*() {
return *get();
}
const T& operator*() const {
return *get();
}
T* operator->() NOEXCEPT {
return get();
}
const T* operator->() const NOEXCEPT {
return get();
}
void swap(ValuePtr& rhs) NOEXCEPT {
using std::swap;
swap(mPtr, rhs.mPtr);
swap(mClone, rhs.mClone);
}
ValuePtr<T>& operator=(ValuePtr rhs) & {
swap(rhs);
return *this;
}
// NOLINTNEXTLINE(google-explicit-constructor)
operator bool() const NOEXCEPT {
return !!mPtr;
}
private:
std::shared_ptr<T> mPtr;
cloner_type mClone;
};
#endif
| null |
844 | cpp | cppcheck | checkassert.h | lib/checkassert.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkassertH
#define checkassertH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Scope;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Checking for side effects in assert statements
*/
class CPPCHECKLIB CheckAssert : public Check {
public:
CheckAssert() : Check(myName()) {}
private:
CheckAssert(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** run checks, the token list is not simplified */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckAssert checkAssert(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkAssert.assertWithSideEffects();
}
void assertWithSideEffects();
void checkVariableAssignment(const Token* assignTok, const Scope *assertionScope);
static bool inSameScope(const Token* returnTok, const Token* assignTok);
void sideEffectInAssertError(const Token *tok, const std::string& functionName);
void assignmentInAssertError(const Token *tok, const std::string &varname);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckAssert c(nullptr, settings, errorLogger);
c.sideEffectInAssertError(nullptr, "function");
c.assignmentInAssertError(nullptr, "var");
}
static std::string myName() {
return "Assert";
}
std::string classInfo() const override {
return "Warn if there are side effects in assert statements (since this cause different behaviour in debug/release builds).\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkassertH
| null |
845 | cpp | cppcheck | checkother.cpp | lib/checkother.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkother.h"
#include "astutils.h"
#include "fwdanalysis.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include "vfvalue.h"
#include <algorithm> // find_if()
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <utility>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckOther instance;
}
static const CWE CWE128(128U); // Wrap-around Error
static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size
static const CWE CWE197(197U); // Numeric Truncation Error
static const CWE CWE362(362U); // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
static const CWE CWE369(369U); // Divide By Zero
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE475(475U); // Undefined Behavior for Input to API
static const CWE CWE561(561U); // Dead Code
static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable')
static const CWE CWE570(570U); // Expression is Always False
static const CWE CWE571(571U); // Expression is Always True
static const CWE CWE672(672U); // Operation on a Resource after Expiration or Release
static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments
static const CWE CWE683(683U); // Function Call With Incorrect Order of Arguments
static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation
static const CWE CWE783(783U); // Operator Precedence Logic Error
//----------------------------------------------------------------------------------
// The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value.
// If this return value is stored in a character variable and then compared
// to EOF, which is an integer, the comparison maybe be false.
//
// Reference:
// - Ticket #160
// - http://www.cplusplus.com/reference/cstdio/fgetc/
// - http://www.cplusplus.com/reference/cstdio/getc/
// - http://www.cplusplus.com/reference/cstdio/getchar/
// - http://www.cplusplus.com/reference/cstdio/ungetc/ ...
//----------------------------------------------------------------------------------
void CheckOther::checkCastIntToCharAndBack()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkCastIntToCharAndBack"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
std::map<int, std::string> vars;
for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
// Quick check to see if any of the matches below have any chances
if (!Token::Match(tok, "%var%|EOF %comp%|="))
continue;
if (Token::Match(tok, "%var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) {
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
vars[tok->varId()] = tok->strAt(2);
}
} else if (Token::Match(tok, "EOF %comp% ( %var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) {
tok = tok->tokAt(3);
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, tok->strAt(2));
}
} else if (tok->isCpp() && (Token::Match(tok, "EOF %comp% ( %var% = std :: cin . get (") || Token::Match(tok, "EOF %comp% ( %var% = cin . get ("))) {
tok = tok->tokAt(3);
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
checkCastIntToCharAndBackError(tok, "cin.get");
}
} else if (tok->isCpp() && (Token::Match(tok, "%var% = std :: cin . get (") || Token::Match(tok, "%var% = cin . get ("))) {
const Variable *var = tok->variable();
if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) {
vars[tok->varId()] = "cin.get";
}
} else if (Token::Match(tok, "%var% %comp% EOF")) {
if (vars.find(tok->varId()) != vars.end()) {
checkCastIntToCharAndBackError(tok, vars[tok->varId()]);
}
} else if (Token::Match(tok, "EOF %comp% %var%")) {
tok = tok->tokAt(2);
if (vars.find(tok->varId()) != vars.end()) {
checkCastIntToCharAndBackError(tok, vars[tok->varId()]);
}
}
}
}
}
void CheckOther::checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName)
{
reportError(
tok,
Severity::warning,
"checkCastIntToCharAndBack",
"$symbol:" + strFunctionName + "\n"
"Storing $symbol() return value in char variable and then comparing with EOF.\n"
"When saving $symbol() return value in char variable there is loss of precision. "
" When $symbol() returns EOF this value is truncated. Comparing the char "
"variable with EOF can have unexpected results. For instance a loop \"while (EOF != (c = $symbol());\" "
"loops forever on some compilers/platforms and on other compilers/platforms it will stop "
"when the file contains a matching character.", CWE197, Certainty::normal
);
}
//---------------------------------------------------------------------------
// Clarify calculation precedence for ternary operators.
//---------------------------------------------------------------------------
void CheckOther::clarifyCalculation()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("clarifyCalculation"))
return;
logChecker("CheckOther::clarifyCalculation"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// ? operator where lhs is arithmetical expression
if (tok->str() != "?" || !tok->astOperand1() || !tok->astOperand1()->isCalculation())
continue;
if (!tok->astOperand1()->isArithmeticalOp() && tok->astOperand1()->tokType() != Token::eBitOp)
continue;
// non-pointer calculation in lhs and pointer in rhs => no clarification is needed
if (tok->astOperand1()->isBinaryOp() && Token::Match(tok->astOperand1(), "%or%|&|%|*|/") && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->pointer > 0)
continue;
// bit operation in lhs and char literals in rhs => probably no mistake
if (tok->astOperand1()->tokType() == Token::eBitOp && Token::Match(tok->astOperand2()->astOperand1(), "%char%") && Token::Match(tok->astOperand2()->astOperand2(), "%char%"))
continue;
// 2nd operand in lhs has known integer value => probably no mistake
if (tok->astOperand1()->isBinaryOp() && tok->astOperand1()->astOperand2()->hasKnownIntValue()) {
const Token *op = tok->astOperand1()->astOperand2();
if (op->isNumber())
continue;
if (op->valueType() && op->valueType()->isEnum())
continue;
}
// Is code clarified by parentheses already?
const Token *tok2 = tok->astOperand1();
for (; tok2; tok2 = tok2->next()) {
if (tok2->str() == "(")
tok2 = tok2->link();
else if (tok2->str() == ")")
break;
else if (tok2->str() == "?") {
clarifyCalculationError(tok, tok->astOperand1()->str());
break;
}
}
}
}
}
void CheckOther::clarifyCalculationError(const Token *tok, const std::string &op)
{
// suspicious calculation
const std::string calc("'a" + op + "b?c:d'");
// recommended calculation #1
const std::string s1("'(a" + op + "b)?c:d'");
// recommended calculation #2
const std::string s2("'a" + op + "(b?c:d)'");
reportError(tok,
Severity::style,
"clarifyCalculation",
"Clarify calculation precedence for '" + op + "' and '?'.\n"
"Suspicious calculation. Please use parentheses to clarify the code. "
"The code '" + calc + "' should be written as either '" + s1 + "' or '" + s2 + "'.", CWE783, Certainty::normal);
}
//---------------------------------------------------------------------------
// Clarify (meaningless) statements like *foo++; with parentheses.
//---------------------------------------------------------------------------
void CheckOther::clarifyStatement()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::clarifyStatement"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->astOperand1() && Token::Match(tok, "* %name%")) {
const Token *tok2 = tok->previous();
while (tok2 && tok2->str() == "*")
tok2 = tok2->previous();
if (tok2 && !tok2->astParent() && Token::Match(tok2, "[{};]")) {
tok2 = tok->astOperand1();
if (Token::Match(tok2, "++|-- [;,]"))
clarifyStatementError(tok2);
}
}
}
}
}
void CheckOther::clarifyStatementError(const Token *tok)
{
reportError(tok, Severity::warning, "clarifyStatement", "In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n"
"A statement like '*A++;' might not do what you intended. Postfix 'operator++' is executed before 'operator*'. "
"Thus, the dereference is meaningless. Did you intend to write '(*A)++;'?", CWE783, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for suspicious occurrences of 'if(); {}'.
//---------------------------------------------------------------------------
void CheckOther::checkSuspiciousSemicolon()
{
if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning))
return;
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
logChecker("CheckOther::checkSuspiciousSemicolon"); // warning,inconclusive
// Look for "if(); {}", "for(); {}" or "while(); {}"
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type == Scope::eIf || scope.type == Scope::eElse || scope.type == Scope::eWhile || scope.type == Scope::eFor) {
// Ensure the semicolon is at the same line number as the if/for/while statement
// and the {..} block follows it without an extra empty line.
if (Token::simpleMatch(scope.bodyStart, "{ ; } {") &&
scope.bodyStart->previous()->linenr() == scope.bodyStart->tokAt(2)->linenr() &&
scope.bodyStart->linenr()+1 >= scope.bodyStart->tokAt(3)->linenr() &&
!scope.bodyStart->tokAt(3)->isExpandedMacro()) {
suspiciousSemicolonError(scope.classDef);
}
}
}
}
void CheckOther::suspiciousSemicolonError(const Token* tok)
{
reportError(tok, Severity::warning, "suspiciousSemicolon",
"Suspicious use of ; at the end of '" + (tok ? tok->str() : std::string()) + "' statement.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// For C++ code, warn if C-style casts are used on pointer types
//---------------------------------------------------------------------------
void CheckOther::warningOldStylePointerCast()
{
// Only valid on C++ code
if (!mTokenizer->isCPP())
return;
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("cstyleCast"))
return;
logChecker("CheckOther::warningOldStylePointerCast"); // style,c++
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok;
if (scope->function && scope->function->isConstructor())
tok = scope->classDef;
else
tok = scope->bodyStart;
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
// Old style pointer casting..
if (tok->str() != "(")
continue;
const Token* castTok = tok->next();
while (Token::Match(castTok, "const|volatile|class|struct|union|%type%|::")) {
castTok = castTok->next();
if (Token::simpleMatch(castTok, "<") && castTok->link())
castTok = castTok->link()->next();
}
if (castTok == tok->next())
continue;
bool isPtr = false, isRef = false;
while (Token::Match(castTok, "*|const|&")) {
if (castTok->str() == "*")
isPtr = true;
else if (castTok->str() == "&")
isRef = true;
castTok = castTok->next();
}
if ((!isPtr && !isRef) || !Token::Match(castTok, ") (| %name%|%num%|%bool%|%char%|%str%|&"))
continue;
if (Token::Match(tok->previous(), "%type%"))
continue;
// skip first "const" in "const Type* const"
while (Token::Match(tok->next(), "const|volatile|class|struct|union"))
tok = tok->next();
const Token* typeTok = tok->next();
// skip second "const" in "const Type* const"
if (tok->strAt(3) == "const")
tok = tok->next();
const Token *p = tok->tokAt(4);
if (p->hasKnownIntValue() && p->values().front().intvalue==0) // Casting nullpointers is safe
continue;
if (typeTok->tokType() == Token::eType || typeTok->tokType() == Token::eName)
cstyleCastError(tok, isPtr);
}
}
}
void CheckOther::cstyleCastError(const Token *tok, bool isPtr)
{
const std::string type = isPtr ? "pointer" : "reference";
reportError(tok, Severity::style, "cstyleCast",
"C-style " + type + " casting\n"
"C-style " + type + " casting detected. C++ offers four different kinds of casts as replacements: "
"static_cast, const_cast, dynamic_cast and reinterpret_cast. A C-style cast could evaluate to "
"any of those automatically, thus it is considered safer if the programmer explicitly states "
"which kind of cast is expected.", CWE398, Certainty::normal);
}
void CheckOther::suspiciousFloatingPointCast()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("suspiciousFloatingPointCast"))
return;
logChecker("CheckOther::suspiciousFloatingPointCast"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token* tok = scope->bodyStart;
if (scope->function && scope->function->isConstructor())
tok = scope->classDef;
for (; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isCast())
continue;
const ValueType* vt = tok->valueType();
if (!vt || vt->pointer || vt->reference != Reference::None || (vt->type != ValueType::FLOAT && vt->type != ValueType::DOUBLE))
continue;
using VTT = std::vector<ValueType::Type>;
const VTT sourceTypes = vt->type == ValueType::FLOAT ? VTT{ ValueType::DOUBLE, ValueType::LONGDOUBLE } : VTT{ ValueType::LONGDOUBLE };
const Token* source = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!source || !source->valueType() || std::find(sourceTypes.begin(), sourceTypes.end(), source->valueType()->type) == sourceTypes.end())
continue;
const Token* parent = tok->astParent();
if (!parent)
continue;
const ValueType* parentVt = parent->valueType();
if (!parentVt || parent->str() == "(") {
int argn{};
if (const Token* ftok = getTokenArgumentFunction(tok, argn)) {
if (ftok->function()) {
if (const Variable* argVar = ftok->function()->getArgumentVar(argn))
parentVt = argVar->valueType();
}
}
}
if (!parentVt || std::find(sourceTypes.begin(), sourceTypes.end(), parentVt->type) == sourceTypes.end())
continue;
suspiciousFloatingPointCastError(tok);
}
}
}
void CheckOther::suspiciousFloatingPointCastError(const Token* tok)
{
reportError(tok, Severity::style, "suspiciousFloatingPointCast",
"Floating-point cast causes loss of precision.\n"
"If this cast is not intentional, remove it to avoid loss of precision", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// float* f; double* d = (double*)f; <-- Pointer cast to a type with an incompatible binary data representation
//---------------------------------------------------------------------------
void CheckOther::invalidPointerCast()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("CheckOther::invalidPointerCast"); // portability
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const Token* toTok = nullptr;
const Token* fromTok = nullptr;
// Find cast
if (Token::Match(tok, "( const|volatile| const|volatile| %type% %type%| const| * )")) {
toTok = tok;
fromTok = tok->astOperand1();
} else if (Token::simpleMatch(tok, "reinterpret_cast <") && tok->linkAt(1)) {
toTok = tok->linkAt(1)->next();
fromTok = toTok->astOperand2();
}
if (!fromTok)
continue;
const ValueType* fromType = fromTok->valueType();
const ValueType* toType = toTok->valueType();
if (!fromType || !toType || !fromType->pointer || !toType->pointer)
continue;
if (fromType->type != toType->type && fromType->type >= ValueType::Type::BOOL && toType->type >= ValueType::Type::BOOL && (toType->type != ValueType::Type::CHAR || printInconclusive)) {
if (toType->isIntegral() && fromType->isIntegral())
continue;
invalidPointerCastError(tok, fromType->str(), toType->str(), toType->type == ValueType::Type::CHAR, toType->isIntegral());
}
}
}
}
void CheckOther::invalidPointerCastError(const Token* tok, const std::string& from, const std::string& to, bool inconclusive, bool toIsInt)
{
if (toIsInt) { // If we cast something to int*, this can be useful to play with its binary data representation
reportError(tok, Severity::portability, "invalidPointerCast", "Casting from " + from + " to " + to + " is not portable due to different binary data representations on different platforms.", CWE704, inconclusive ? Certainty::inconclusive : Certainty::normal);
} else
reportError(tok, Severity::portability, "invalidPointerCast", "Casting between " + from + " and " + to + " which have an incompatible binary data representation.", CWE704, Certainty::normal);
}
//---------------------------------------------------------------------------
// Detect redundant assignments: x = 0; x = 4;
//---------------------------------------------------------------------------
void CheckOther::checkRedundantAssignment()
{
if (!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("redundantAssignment") &&
!mSettings->isPremiumEnabled("redundantAssignInSwitch"))
return;
logChecker("CheckOther::checkRedundantAssignment"); // style
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
if (!scope->bodyStart)
continue;
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::simpleMatch(tok, "] ("))
// todo: handle lambdas
break;
if (Token::simpleMatch(tok, "try {"))
// todo: check try blocks
tok = tok->linkAt(1);
if ((tok->isAssignmentOp() || tok->tokType() == Token::eIncDecOp) && tok->astOperand1()) {
if (tok->astParent())
continue;
// Do not warn about redundant initialization when rhs is trivial
// TODO : do not simplify the variable declarations
bool isInitialization = false;
if (Token::Match(tok->tokAt(-2), "; %var% =") && tok->tokAt(-2)->isSplittedVarDeclEq()) {
isInitialization = true;
bool trivial = true;
visitAstNodes(tok->astOperand2(),
[&](const Token *rhs) {
if (Token::simpleMatch(rhs, "{ 0 }"))
return ChildrenToVisit::none;
if (Token::Match(rhs, "%str%|%num%|%name%") && !rhs->varId())
return ChildrenToVisit::none;
if (Token::Match(rhs, ":: %name%") && rhs->hasKnownIntValue())
return ChildrenToVisit::none;
if (rhs->isCast())
return ChildrenToVisit::op2;
trivial = false;
return ChildrenToVisit::done;
});
if (trivial)
continue;
}
const Token* rhs = tok->astOperand2();
// Do not warn about assignment with 0 / NULL
if ((rhs && MathLib::isNullValue(rhs->str())) || isNullOperand(rhs))
continue;
if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isReference())
// todo: check references
continue;
if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isStatic())
// todo: check static variables
continue;
bool inconclusive = false;
if (tok->isCpp() && tok->astOperand1()->valueType()) {
// If there is a custom assignment operator => this is inconclusive
if (tok->astOperand1()->valueType()->typeScope) {
const std::string op = "operator" + tok->str();
const std::list<Function>& fList = tok->astOperand1()->valueType()->typeScope->functionList;
inconclusive = std::any_of(fList.cbegin(), fList.cend(), [&](const Function& f) {
return f.name() == op;
});
}
// assigning a smart pointer has side effects
if (tok->astOperand1()->valueType()->type == ValueType::SMART_POINTER)
break;
}
if (inconclusive && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
FwdAnalysis fwdAnalysis(*mSettings);
if (fwdAnalysis.hasOperand(tok->astOperand2(), tok->astOperand1()))
continue;
// Is there a redundant assignment?
const Token *start;
if (tok->isAssignmentOp())
start = tok->next();
else
start = tok->findExpressionStartEndTokens().second->next();
const Token * tokenToCheck = tok->astOperand1();
// Check if we are working with union
for (const Token* tempToken = tokenToCheck; Token::simpleMatch(tempToken, ".");) {
tempToken = tempToken->astOperand1();
if (tempToken && tempToken->variable() && tempToken->variable()->type() && tempToken->variable()->type()->isUnionType())
tokenToCheck = tempToken;
}
if (start->hasKnownSymbolicValue(tokenToCheck) && Token::simpleMatch(start->astParent(), "=") && !diag(tok)) {
const ValueFlow::Value* val = start->getKnownValue(ValueFlow::Value::ValueType::SYMBOLIC);
if (val->intvalue == 0) // no offset
redundantAssignmentSameValueError(tokenToCheck, val, tok->astOperand1()->expressionString());
}
// Get next assignment..
const Token *nextAssign = fwdAnalysis.reassign(tokenToCheck, start, scope->bodyEnd);
// extra check for union
if (nextAssign && tokenToCheck != tok->astOperand1())
nextAssign = fwdAnalysis.reassign(tok->astOperand1(), start, scope->bodyEnd);
if (!nextAssign)
continue;
// there is redundant assignment. Is there a case between the assignments?
bool hasCase = false;
for (const Token *tok2 = tok; tok2 != nextAssign; tok2 = tok2->next()) {
if (tok2->str() == "break" || tok2->str() == "return")
break;
if (tok2->str() == "case") {
hasCase = true;
break;
}
}
// warn
if (hasCase)
redundantAssignmentInSwitchError(tok, nextAssign, tok->astOperand1()->expressionString());
else if (isInitialization)
redundantInitializationError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive);
else {
diag(nextAssign);
redundantAssignmentError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive);
}
}
}
}
}
void CheckOther::redundantCopyError(const Token *tok1, const Token* tok2, const std::string& var)
{
const std::list<const Token *> callstack = { tok1, tok2 };
reportError(callstack, Severity::performance, "redundantCopy",
"$symbol:" + var + "\n"
"Buffer '$symbol' is being written before its old content has been used.", CWE563, Certainty::normal);
}
void CheckOther::redundantAssignmentError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive)
{
const ErrorPath errorPath = { ErrorPathItem(tok1, var + " is assigned"), ErrorPathItem(tok2, var + " is overwritten") };
if (inconclusive)
reportError(errorPath, Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used if variable is no semaphore variable.\n"
"Variable '$symbol' is reassigned a value before the old one has been used. Make sure that this variable is not used like a semaphore in a threading environment before simplifying this code.", CWE563, Certainty::inconclusive);
else
reportError(errorPath, Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used.", CWE563, Certainty::normal);
}
void CheckOther::redundantInitializationError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive)
{
const ErrorPath errorPath = { ErrorPathItem(tok1, var + " is initialized"), ErrorPathItem(tok2, var + " is overwritten") };
reportError(errorPath, Severity::style, "redundantInitialization",
"$symbol:" + var + "\nRedundant initialization for '$symbol'. The initialized value is overwritten before it is read.",
CWE563,
inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::redundantAssignmentInSwitchError(const Token *tok1, const Token* tok2, const std::string &var)
{
const ErrorPath errorPath = { ErrorPathItem(tok1, "$symbol is assigned"), ErrorPathItem(tok2, "$symbol is overwritten") };
reportError(errorPath, Severity::style, "redundantAssignInSwitch",
"$symbol:" + var + "\n"
"Variable '$symbol' is reassigned a value before the old one has been used. 'break;' missing?", CWE563, Certainty::normal);
}
void CheckOther::redundantAssignmentSameValueError(const Token *tok, const ValueFlow::Value* val, const std::string &var)
{
auto errorPath = val->errorPath;
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::style, "redundantAssignment",
"$symbol:" + var + "\n"
"Variable '$symbol' is assigned an expression that holds the same value.", CWE563, Certainty::normal);
}
//---------------------------------------------------------------------------
// switch (x)
// {
// case 2:
// y = a; // <- this assignment is redundant
// case 3:
// y = b; // <- case 2 falls through and sets y twice
// }
//---------------------------------------------------------------------------
static inline bool isFunctionOrBreakPattern(const Token *tok)
{
return Token::Match(tok, "%name% (") || Token::Match(tok, "break|continue|return|exit|goto|throw");
}
void CheckOther::redundantBitwiseOperationInSwitchError()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::redundantBitwiseOperationInSwitch"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Find the beginning of a switch. E.g.:
// switch (var) { ...
for (const Scope &switchScope : symbolDatabase->scopeList) {
if (switchScope.type != Scope::eSwitch || !switchScope.bodyStart)
continue;
// Check the contents of the switch statement
std::map<int, const Token*> varsWithBitsSet;
std::map<int, std::string> bitOperations;
for (const Token *tok2 = switchScope.bodyStart->next(); tok2 != switchScope.bodyEnd; tok2 = tok2->next()) {
if (tok2->str() == "{") {
// Inside a conditional or loop. Don't mark variable accesses as being redundant. E.g.:
// case 3: b = 1;
// case 4: if (a) { b = 2; } // Doesn't make the b=1 redundant because it's conditional
if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) {
const Token* endOfConditional = tok2->link();
for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) {
if (tok3->varId() != 0) {
varsWithBitsSet.erase(tok3->varId());
bitOperations.erase(tok3->varId());
} else if (isFunctionOrBreakPattern(tok3)) {
varsWithBitsSet.clear();
bitOperations.clear();
}
}
tok2 = endOfConditional;
}
}
// Variable assignment. Report an error if it's assigned to twice before a break. E.g.:
// case 3: b = 1; // <== redundant
// case 4: b = 2;
if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;")) {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
// Bitwise operation. Report an error if it's performed twice before a break. E.g.:
// case 3: b |= 1; // <== redundant
// case 4: b |= 1;
else if (Token::Match(tok2->previous(), ";|{|}|: %var% %assign% %num% ;") &&
(tok2->strAt(1) == "|=" || tok2->strAt(1) == "&=") &&
Token::Match(tok2->next()->astOperand2(), "%num%")) {
const std::string bitOp = tok2->strAt(1)[0] + tok2->strAt(2);
const std::map<int, const Token*>::const_iterator i2 = varsWithBitsSet.find(tok2->varId());
// This variable has not had a bit operation performed on it yet, so just make a note of it
if (i2 == varsWithBitsSet.end()) {
varsWithBitsSet[tok2->varId()] = tok2;
bitOperations[tok2->varId()] = bitOp;
}
// The same bit operation has been performed on the same variable twice, so report an error
else if (bitOperations[tok2->varId()] == bitOp)
redundantBitwiseOperationInSwitchError(i2->second, i2->second->str());
// A different bit operation was performed on the variable, so clear it
else {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
}
// Bitwise operation. Report an error if it's performed twice before a break. E.g.:
// case 3: b = b | 1; // <== redundant
// case 4: b = b | 1;
else if (Token::Match(tok2->previous(), ";|{|}|: %var% = %name% %or%|& %num% ;") &&
tok2->varId() == tok2->tokAt(2)->varId()) {
const std::string bitOp = tok2->strAt(3) + tok2->strAt(4);
const std::map<int, const Token*>::const_iterator i2 = varsWithBitsSet.find(tok2->varId());
// This variable has not had a bit operation performed on it yet, so just make a note of it
if (i2 == varsWithBitsSet.end()) {
varsWithBitsSet[tok2->varId()] = tok2;
bitOperations[tok2->varId()] = bitOp;
}
// The same bit operation has been performed on the same variable twice, so report an error
else if (bitOperations[tok2->varId()] == bitOp)
redundantBitwiseOperationInSwitchError(i2->second, i2->second->str());
// A different bit operation was performed on the variable, so clear it
else {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
}
// Not a simple assignment so there may be good reason if this variable is assigned to twice. E.g.:
// case 3: b = 1;
// case 4: b++;
else if (tok2->varId() != 0 && tok2->strAt(1) != "|" && tok2->strAt(1) != "&") {
varsWithBitsSet.erase(tok2->varId());
bitOperations.erase(tok2->varId());
}
// Reset our record of assignments if there is a break or function call. E.g.:
// case 3: b = 1; break;
if (isFunctionOrBreakPattern(tok2)) {
varsWithBitsSet.clear();
bitOperations.clear();
}
}
}
}
void CheckOther::redundantBitwiseOperationInSwitchError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::style,
"redundantBitwiseOperationInSwitch",
"$symbol:" + varname + "\n"
"Redundant bitwise operation on '$symbol' in 'switch' statement. 'break;' missing?");
}
//---------------------------------------------------------------------------
// Check for statements like case A||B: in switch()
//---------------------------------------------------------------------------
void CheckOther::checkSuspiciousCaseInSwitch()
{
if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkSuspiciousCaseInSwitch"); // warning,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eSwitch)
continue;
for (const Token* tok = scope.bodyStart->next(); tok != scope.bodyEnd; tok = tok->next()) {
if (tok->str() == "case") {
const Token* finding = nullptr;
for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == ":")
break;
if (Token::Match(tok2, "[;}{]"))
break;
if (tok2->str() == "?")
finding = nullptr;
else if (Token::Match(tok2, "&&|%oror%"))
finding = tok2;
}
if (finding)
suspiciousCaseInSwitchError(finding, finding->str());
}
}
}
}
void CheckOther::suspiciousCaseInSwitchError(const Token* tok, const std::string& operatorString)
{
reportError(tok, Severity::warning, "suspiciousCase",
"Found suspicious case label in switch(). Operator '" + operatorString + "' probably doesn't work as intended.\n"
"Using an operator like '" + operatorString + "' in a case label is suspicious. Did you intend to use a bitwise operator, multiple case labels or if/else instead?", CWE398, Certainty::inconclusive);
}
//---------------------------------------------------------------------------
// Find consecutive return, break, continue, goto or throw statements. e.g.:
// break; break;
// Detect dead code, that follows such a statement. e.g.:
// return(0); foo();
//---------------------------------------------------------------------------
void CheckOther::checkUnreachableCode()
{
// misra-c-2012-2.1
// misra-c-2023-2.1
// misra-cpp-2008-0-1-1
// autosar
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateBreak") && !mSettings->isPremiumEnabled("unreachableCode"))
return;
logChecker("CheckOther::checkUnreachableCode"); // style
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
const Token* secondBreak = nullptr;
const Token* labelName = nullptr;
if (tok->link() && Token::Match(tok, "(|[|<"))
tok = tok->link();
else if (Token::Match(tok, "break|continue ;"))
secondBreak = tok->tokAt(2);
else if (Token::Match(tok, "[;{}:] return|throw") && tok->next()->isKeyword()) {
if (Token::simpleMatch(tok->astParent(), "?"))
continue;
tok = tok->next(); // tok should point to return or throw
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(" || tok2->str() == "{")
tok2 = tok2->link();
if (tok2->str() == ";") {
secondBreak = tok2->next();
break;
}
}
} else if (Token::Match(tok, "goto %any% ;")) {
secondBreak = tok->tokAt(3);
labelName = tok->next();
} else if (Token::Match(tok, "%name% (") && mSettings->library.isnoreturn(tok) && !Token::Match(tok->next()->astParent(), "?|:")) {
if ((!tok->function() || (tok->function()->token != tok && tok->function()->tokenDef != tok)) && tok->linkAt(1)->strAt(1) != "{")
secondBreak = tok->linkAt(1)->tokAt(2);
if (Token::simpleMatch(secondBreak, "return")) {
// clarification for tools that function returns
continue;
}
}
while (Token::simpleMatch(secondBreak, "}") && secondBreak->scope()->type == Scope::ScopeType::eUnconditional)
secondBreak = secondBreak->next();
if (secondBreak && secondBreak->scope()->nestedIn && secondBreak->scope()->nestedIn->type == Scope::ScopeType::eSwitch &&
tok->str() == "break") {
while (Token::simpleMatch(secondBreak, "{") && secondBreak->scope()->type == Scope::ScopeType::eUnconditional)
secondBreak = secondBreak->next();
if (Token::Match(secondBreak, "%name% :"))
continue;
}
if (Token::simpleMatch(secondBreak, "; }"))
continue;
// Statements follow directly, no line between them. (#3383)
// TODO: Try to find a better way to avoid false positives due to preprocessor configurations.
const bool inconclusive = secondBreak && (secondBreak->linenr() - 1 > secondBreak->previous()->linenr());
if (secondBreak && (printInconclusive || !inconclusive)) {
if (Token::Match(secondBreak, "continue|goto|throw|return") && secondBreak->isKeyword()) {
duplicateBreakError(secondBreak, inconclusive);
tok = Token::findmatch(secondBreak, "[}:]");
} else if (secondBreak->str() == "break") { // break inside switch as second break statement should not issue a warning
if (tok->str() == "break") // If the previous was a break, too: Issue warning
duplicateBreakError(secondBreak, inconclusive);
else {
if (tok->scope()->type != Scope::eSwitch) // Check, if the enclosing scope is a switch
duplicateBreakError(secondBreak, inconclusive);
}
tok = Token::findmatch(secondBreak, "[}:]");
} else if (!Token::Match(secondBreak, "return|}|case|default") && secondBreak->strAt(1) != ":") { // TODO: No bailout for unconditional scopes
// If the goto label is followed by a loop construct in which the label is defined it's quite likely
// that the goto jump was intended to skip some code on the first loop iteration.
bool labelInFollowingLoop = false;
if (labelName && Token::Match(secondBreak, "while|do|for")) {
const Token *scope2 = Token::findsimplematch(secondBreak, "{");
if (scope2) {
for (const Token *tokIter = scope2; tokIter != scope2->link() && tokIter; tokIter = tokIter->next()) {
if (Token::Match(tokIter, "[;{}] %any% :") && labelName->str() == tokIter->strAt(1)) {
labelInFollowingLoop = true;
break;
}
}
}
}
// hide FP for statements that just hide compiler warnings about unused function arguments
bool silencedCompilerWarningOnly = false;
const Token *silencedWarning = secondBreak;
for (;;) {
if (Token::Match(silencedWarning, "( void ) %name% ;")) {
silencedWarning = silencedWarning->tokAt(5);
continue;
}
if (silencedWarning && silencedWarning == scope->bodyEnd)
silencedCompilerWarningOnly = true;
break;
}
if (silencedWarning)
secondBreak = silencedWarning;
if (!labelInFollowingLoop && !silencedCompilerWarningOnly)
unreachableCodeError(secondBreak, tok, inconclusive);
tok = Token::findmatch(secondBreak, "[}:]");
} else if (secondBreak->scope() && secondBreak->scope()->isLoopScope() && secondBreak->str() == "}" && tok->str() == "continue") {
redundantContinueError(tok);
tok = secondBreak;
} else
tok = secondBreak;
if (!tok)
break;
tok = tok->previous(); // Will be advanced again by for loop
}
}
}
}
void CheckOther::duplicateBreakError(const Token *tok, bool inconclusive)
{
reportError(tok, Severity::style, "duplicateBreak",
"Consecutive return, break, continue, goto or throw statements are unnecessary.\n"
"Consecutive return, break, continue, goto or throw statements are unnecessary. "
"The second statement can never be executed, and so should be removed.", CWE561, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::unreachableCodeError(const Token *tok, const Token* noreturn, bool inconclusive)
{
std::string msg = "Statements following ";
if (noreturn && (noreturn->function() || mSettings->library.isnoreturn(noreturn)))
msg += "noreturn function '" + noreturn->str() + "()'";
else if (noreturn && noreturn->isKeyword())
msg += "'" + noreturn->str() + "'";
else
msg += "return, break, continue, goto or throw";
msg += " will never be executed.";
reportError(tok, Severity::style, "unreachableCode",
msg, CWE561, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::redundantContinueError(const Token *tok)
{
reportError(tok, Severity::style, "redundantContinue",
"'continue' is redundant since it is the last statement in a loop.", CWE561, Certainty::normal);
}
static bool isSimpleExpr(const Token* tok, const Variable* var, const Settings& settings) {
if (!tok)
return false;
if (tok->isNumber() || tok->tokType() == Token::eString || tok->tokType() == Token::eChar || tok->isBoolean())
return true;
bool needsCheck = tok->varId() > 0;
if (!needsCheck) {
if (tok->isArithmeticalOp())
return isSimpleExpr(tok->astOperand1(), var, settings) && (!tok->astOperand2() || isSimpleExpr(tok->astOperand2(), var, settings));
const Token* ftok = tok->previous();
if (Token::Match(ftok, "%name% (") &&
((ftok->function() && ftok->function()->isConst()) || settings.library.isFunctionConst(ftok->str(), /*pure*/ true)))
needsCheck = true;
else if (tok->str() == "[") {
needsCheck = tok->astOperand1() && tok->astOperand1()->varId() > 0;
tok = tok->astOperand1();
}
else if (isLeafDot(tok->astOperand2())) {
needsCheck = tok->astOperand2()->varId() > 0;
tok = tok->astOperand2();
}
}
return (needsCheck && !findExpressionChanged(tok, tok->astParent(), var->scope()->bodyEnd, settings));
}
//---------------------------------------------------------------------------
// Check scope of variables..
//---------------------------------------------------------------------------
void CheckOther::checkVariableScope()
{
if (mSettings->clang)
return;
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("variableScope"))
return;
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// In C it is common practice to declare local variables at the
// start of functions.
if (mSettings->daca && mTokenizer->isC())
return;
logChecker("CheckOther::checkVariableScope"); // style,notclang
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isLocal() || var->isConst())
continue;
if (var->nameToken()->isExpandedMacro())
continue;
const bool isPtrOrRef = var->isPointer() || var->isReference();
const bool isSimpleType = var->typeStartToken()->isStandardType() || var->typeStartToken()->isEnumType() || (var->typeStartToken()->isC() && var->type() && var->type()->isStructType());
if (!isPtrOrRef && !isSimpleType && !astIsContainer(var->nameToken()))
continue;
if (mTokenizer->hasIfdef(var->nameToken(), var->scope()->bodyEnd))
continue;
// reference of range for loop variable..
if (Token::Match(var->nameToken()->previous(), "& %var% = %var% .")) {
const Token *otherVarToken = var->nameToken()->tokAt(2);
const Variable *otherVar = otherVarToken->variable();
if (otherVar && Token::Match(otherVar->nameToken(), "%var% :") &&
otherVar->nameToken()->next()->astParent() &&
Token::simpleMatch(otherVar->nameToken()->next()->astParent()->previous(), "for ("))
continue;
}
bool forHead = false; // Don't check variables declared in header of a for loop
for (const Token* tok = var->typeStartToken(); tok; tok = tok->previous()) {
if (tok->str() == "(") {
forHead = true;
break;
}
if (Token::Match(tok, "[;{}]"))
break;
}
if (forHead)
continue;
const Token* tok = var->nameToken()->next();
bool isConstructor = false;
if (Token::Match(tok, "; %varid% =", var->declarationId())) { // bailout for assignment
tok = tok->tokAt(2)->astOperand2();
if (!isSimpleExpr(tok, var, *mSettings))
continue;
}
else if (Token::Match(tok, "{|(")) { // bailout for constructor
isConstructor = true;
const Token* argTok = tok->astOperand2();
bool bail = false;
while (argTok) {
if (Token::simpleMatch(argTok, ",")) {
if (!isSimpleExpr(argTok->astOperand2(), var, *mSettings)) {
bail = true;
break;
}
} else if (argTok->str() != "." && !isSimpleExpr(argTok, var, *mSettings)) {
bail = true;
break;
}
argTok = argTok->astOperand1();
}
if (bail)
continue;
}
// bailout if initialized with function call that has possible side effects
if (!isConstructor && Token::Match(tok, "[(=]") && Token::simpleMatch(tok->astOperand2(), "("))
continue;
bool reduce = true;
bool used = false; // Don't warn about unused variables
for (; tok && tok != var->scope()->bodyEnd; tok = tok->next()) {
if (tok->str() == "{" && tok->scope() != tok->previous()->scope() && !tok->isExpandedMacro() && !isWithinScope(tok, var, Scope::ScopeType::eLambda)) {
if (used) {
bool used2 = false;
if (!checkInnerScope(tok, var, used2) || used2) {
reduce = false;
break;
}
} else if (!checkInnerScope(tok, var, used)) {
reduce = false;
break;
}
tok = tok->link();
// parse else if blocks..
} else if (Token::simpleMatch(tok, "else { if (") && Token::simpleMatch(tok->linkAt(3), ") {")) {
tok = tok->next();
} else if (tok->varId() == var->declarationId() || tok->str() == "goto") {
reduce = false;
break;
}
}
if (reduce && used)
variableScopeError(var->nameToken(), var->name());
}
}
// used to check if an argument to a function might depend on another argument
static bool mayDependOn(const ValueType *other, const ValueType *original)
{
if (!other || !original)
return false;
// other must be pointer
if (!other->pointer)
return false;
// must be same underlying type
if (other->type != original->type)
return false;
const int otherPtr = other->pointer + (other->reference == Reference::LValue ? 1 : 0);
const int originalPtr = original->pointer;
if (otherPtr == originalPtr) {
// if other is not const than original may be copied to other
return !other->isConst(otherPtr);
}
// other may be reassigned to original
return otherPtr > originalPtr;
}
bool CheckOther::checkInnerScope(const Token *tok, const Variable* var, bool& used) const
{
const Scope* scope = tok->next()->scope();
bool loopVariable = scope->isLoopScope();
bool noContinue = true;
const Token* forHeadEnd = nullptr;
const Token* end = tok->link();
if (scope->type == Scope::eUnconditional && (tok->strAt(-1) == ")" || tok->previous()->isName())) // Might be an unknown macro like BOOST_FOREACH
loopVariable = true;
if (scope->type == Scope::eDo) {
end = end->linkAt(2);
} else if (loopVariable && tok->strAt(-1) == ")") {
tok = tok->linkAt(-1); // Jump to opening ( of for/while statement
} else if (scope->type == Scope::eSwitch) {
for (const Scope* innerScope : scope->nestedList) {
if (used) {
bool used2 = false;
if (!checkInnerScope(innerScope->bodyStart, var, used2) || used2) {
return false;
}
} else if (!checkInnerScope(innerScope->bodyStart, var, used)) {
return false;
}
}
}
bool bFirstAssignment=false;
for (; tok && tok != end; tok = tok->next()) {
if (tok->str() == "goto")
return false;
if (tok->str() == "continue")
noContinue = false;
if (Token::simpleMatch(tok, "for ("))
forHeadEnd = tok->linkAt(1);
if (tok == forHeadEnd)
forHeadEnd = nullptr;
if (loopVariable && noContinue && tok->scope() == scope && !forHeadEnd && scope->type != Scope::eSwitch && Token::Match(tok, "%varid% =", var->declarationId())) { // Assigned in outer scope.
loopVariable = false;
std::pair<const Token*, const Token*> range = tok->next()->findExpressionStartEndTokens();
if (range.first)
range.first = range.first->next();
const Token* exprTok = findExpression(var->nameToken()->exprId(), range.first, range.second, [&](const Token* tok2) {
return tok2->varId() == var->declarationId();
});
if (exprTok) {
tok = exprTok;
loopVariable = true;
}
}
if (loopVariable && Token::Match(tok, "%varid% !!=", var->declarationId())) // Variable used in loop
return false;
if (Token::Match(tok, "& %varid%", var->declarationId())) // Taking address of variable
return false;
if (Token::Match(tok, "%varid% =", var->declarationId())) {
if (!bFirstAssignment && var->isInit() && Token::findmatch(tok->tokAt(2), "%varid%", Token::findsimplematch(tok->tokAt(3), ";"), var->declarationId()))
return false;
bFirstAssignment = true;
}
if (!bFirstAssignment && Token::Match(tok, "* %varid%", var->declarationId())) // dereferencing means access to previous content
return false;
if (Token::Match(tok, "= %varid%", var->declarationId()) && (var->isArray() || var->isPointer() || (var->valueType() && var->valueType()->container))) // Create a copy of array/pointer. Bailout, because the memory it points to might be necessary in outer scope
return false;
if (tok->varId() == var->declarationId()) {
used = true;
if (scope == tok->scope()) {
if (scope->type == Scope::eSwitch)
return false; // Used in outer switch scope - unsafe or impossible to reduce scope
if (scope->bodyStart && scope->bodyStart->isSimplifiedScope())
return false; // simplified if/for/switch init statement
}
if (var->isArrayOrPointer()) {
int argn{};
if (const Token* ftok = getTokenArgumentFunction(tok, argn)) { // var passed to function?
if (ftok->next()->astParent()) { // return value used?
if (ftok->function() && Function::returnsPointer(ftok->function()))
return false;
const std::string ret = mSettings->library.returnValueType(ftok); // assume that var is returned
if (!ret.empty() && ret.back() == '*')
return false;
}
if (ftok->function()) {
const std::list<Variable> &argvars = ftok->function()->argumentList;
if (const Variable* argvar = ftok->function()->getArgumentVar(argn)) {
if (!std::all_of(argvars.cbegin(), argvars.cend(), [&](const Variable& other) {
return &other == argvar || !mayDependOn(other.valueType(), argvar->valueType());
}))
return false;
}
}
}
}
const auto yield = astContainerYield(tok);
if (yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT)
return false;
}
}
return true;
}
void CheckOther::variableScopeError(const Token *tok, const std::string &varname)
{
reportError(tok,
Severity::style,
"variableScope",
"$symbol:" + varname + "\n"
"The scope of the variable '$symbol' can be reduced.\n"
"The scope of the variable '$symbol' can be reduced. Warning: Be careful "
"when fixing this message, especially when there are inner loops. Here is an "
"example where cppcheck will write that the scope for 'i' can be reduced:\n"
"void f(int x)\n"
"{\n"
" int i = 0;\n"
" if (x) {\n"
" // it's safe to move 'int i = 0;' here\n"
" for (int n = 0; n < 10; ++n) {\n"
" // it is possible but not safe to move 'int i = 0;' here\n"
" do_something(&i);\n"
" }\n"
" }\n"
"}\n"
"When you see this message it is always safe to reduce the variable scope 1 level.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// Comma in return statement: return a+1, b++;. (experimental)
//---------------------------------------------------------------------------
void CheckOther::checkCommaSeparatedReturn()
{
// This is experimental for now. See #5076
if ((true) || !mSettings->severity.isEnabled(Severity::style)) // NOLINT(readability-simplify-boolean-expr)
return;
// logChecker
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "return") {
tok = tok->next();
while (tok && tok->str() != ";") {
if (tok->link() && Token::Match(tok, "[([{<]"))
tok = tok->link();
if (!tok->isExpandedMacro() && tok->str() == "," && tok->linenr() != tok->next()->linenr())
commaSeparatedReturnError(tok);
tok = tok->next();
}
// bailout: missing semicolon (invalid code / bad tokenizer)
if (!tok)
break;
}
}
}
void CheckOther::commaSeparatedReturnError(const Token *tok)
{
reportError(tok,
Severity::style,
"commaSeparatedReturn",
"Comma is used in return statement. The comma can easily be misread as a ';'.\n"
"Comma is used in return statement. When comma is used in a return statement it can "
"easily be misread as a semicolon. For example in the code below the value "
"of 'b' is returned if the condition is true, but it is easy to think that 'a+1' is "
"returned:\n"
" if (x)\n"
" return a + 1,\n"
" b++;\n"
"However it can be useful to use comma in macros. Cppcheck does not warn when such a "
"macro is then used in a return statement, it is less likely such code is misunderstood.", CWE398, Certainty::normal);
}
static bool isLargeContainer(const Variable* var, const Settings* settings)
{
const ValueType* vt = var->valueType();
if (vt->container->size_templateArgNo < 0)
return true;
const std::size_t maxByValueSize = 2 * settings->platform.sizeof_pointer;
if (var->dimensions().empty()) {
if (vt->container->startPattern == "std :: bitset <") {
if (vt->containerTypeToken->hasKnownIntValue())
return vt->containerTypeToken->getKnownIntValue() / 8 > maxByValueSize;
}
return false;
}
const ValueType vtElem = ValueType::parseDecl(vt->containerTypeToken, *settings);
const auto elemSize = std::max<std::size_t>(ValueFlow::getSizeOf(vtElem, *settings), 1);
const auto arraySize = var->dimension(0) * elemSize;
return arraySize > maxByValueSize;
}
void CheckOther::checkPassByReference()
{
if (!mSettings->severity.isEnabled(Severity::performance) || mTokenizer->isC())
return;
logChecker("CheckOther::checkPassByReference"); // performance,c++
const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->isClass() || var->isPointer() || (var->isArray() && !var->isStlType()) || var->isReference() || var->isEnumType())
continue;
const bool isRangeBasedFor = astIsRangeBasedForDecl(var->nameToken());
if (!var->isArgument() && !isRangeBasedFor)
continue;
if (!isRangeBasedFor && var->scope() && var->scope()->function->arg->link()->strAt(-1) == "...")
continue; // references could not be used as va_start parameters (#5824)
const Token * const varDeclEndToken = var->declEndToken();
if ((varDeclEndToken && varDeclEndToken->isExternC()) ||
(var->scope() && var->scope()->function && var->scope()->function->tokenDef && var->scope()->function->tokenDef->isExternC()))
continue; // references cannot be used in functions in extern "C" blocks
bool inconclusive = false;
const bool isContainer = var->valueType() && var->valueType()->type == ValueType::Type::CONTAINER && var->valueType()->container && !var->valueType()->container->view;
if (isContainer && !isLargeContainer(var, mSettings))
continue;
if (!isContainer) {
if (var->type() && !var->type()->isEnumType()) { // Check if type is a struct or class.
// Ensure that it is a large object.
if (!var->type()->classScope)
inconclusive = true;
else if (!var->valueType() || ValueFlow::getSizeOf(*var->valueType(), *mSettings) <= 2 * mSettings->platform.sizeof_pointer)
continue;
}
else
continue;
}
if (inconclusive && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
if (var->isArray() && var->getTypeName() != "std::array")
continue;
const bool isConst = var->isConst();
if (isConst) {
passedByValueError(var, inconclusive, isRangeBasedFor);
continue;
}
// Check if variable could be const
if (!isRangeBasedFor && (!var->scope() || var->scope()->function->isImplicitlyVirtual()))
continue;
if (!isVariableChanged(var, *mSettings)) {
passedByValueError(var, inconclusive, isRangeBasedFor);
}
}
}
void CheckOther::passedByValueError(const Variable* var, bool inconclusive, bool isRangeBasedFor)
{
std::string id = isRangeBasedFor ? "iterateByValue" : "passedByValue";
const std::string action = isRangeBasedFor ? "declared as": "passed by";
const std::string type = isRangeBasedFor ? "Range variable" : "Function parameter";
std::string msg = "$symbol:" + (var ? var->name() : "") + "\n" +
type + " '$symbol' should be " + action + " const reference.";
ErrorPath errorPath;
if (var && var->scope() && var->scope()->function && var->scope()->function->functionPointerUsage) {
id += "Callback";
errorPath.emplace_front(var->scope()->function->functionPointerUsage, "Function pointer used here.");
msg += " However it seems that '" + var->scope()->function->name() + "' is a callback function.";
}
if (var)
errorPath.emplace_back(var->nameToken(), msg);
if (isRangeBasedFor)
msg += "\nVariable '$symbol' is used to iterate by value. It could be declared as a const reference which is usually faster and recommended in C++.";
else
msg += "\nParameter '$symbol' is passed by value. It could be passed as a const reference which is usually faster and recommended in C++.";
reportError(errorPath, Severity::performance, id.c_str(), msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
static bool isVariableMutableInInitializer(const Token* start, const Token * end, nonneg int varid)
{
if (!start)
return false;
if (!end)
return false;
for (const Token *tok = start; tok != end; tok = tok->next()) {
if (tok->varId() != varid)
continue;
if (tok->astParent()) {
const Token * memberTok = tok->astParent()->previous();
if (Token::Match(memberTok, "%var% (") && memberTok->variable()) {
const Variable * memberVar = memberTok->variable();
if (memberVar->isClass())
//TODO: check if the called constructor could live with a const variable
// pending that, assume the worst (that it can't)
return true;
if (!memberVar->isReference())
continue;
if (memberVar->isConst())
continue;
}
}
return true;
}
return false;
}
void CheckOther::checkConstVariable()
{
if ((!mSettings->severity.isEnabled(Severity::style) || mTokenizer->isC()) && !mSettings->isPremiumEnabled("constVariable"))
return;
logChecker("CheckOther::checkConstVariable"); // style,c++
const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable *var : symbolDatabase->variableList()) {
if (!var)
continue;
if (!var->isReference())
continue;
if (var->isRValueReference())
continue;
if (var->isPointer())
continue;
if (var->isConst())
continue;
const Scope* scope = var->scope();
if (!scope)
continue;
const Function* function = scope->function;
if (!function && !scope->isLocal())
continue;
if (function && var->isArgument()) {
if (function->isImplicitlyVirtual() || function->templateDef)
continue;
if (function->isConstructor() && isVariableMutableInInitializer(function->constructorMemberInitialization(), scope->bodyStart, var->declarationId()))
continue;
}
if (var->isGlobal())
continue;
if (var->isStatic())
continue;
if (var->isArray() && !var->isStlType())
continue;
if (var->isEnumType())
continue;
if (var->isVolatile())
continue;
if (var->isMaybeUnused())
continue;
if (var->nameToken()->isExpandedMacro())
continue;
if (isStructuredBindingVariable(var)) // TODO: check all bound variables
continue;
if (isVariableChanged(var, *mSettings))
continue;
const bool hasFunction = function != nullptr;
if (!hasFunction) {
const Scope* functionScope = scope;
do {
functionScope = functionScope->nestedIn;
} while (functionScope && !(function = functionScope->function));
}
if (function && (Function::returnsReference(function) || Function::returnsPointer(function)) && !Function::returnsConst(function)) {
std::vector<const Token*> returns = Function::findReturns(function);
if (std::any_of(returns.cbegin(), returns.cend(), [&](const Token* retTok) {
if (retTok->varId() == var->declarationId())
return true;
while (retTok && retTok->isCast())
retTok = retTok->astOperand2();
while (Token::simpleMatch(retTok, "."))
retTok = retTok->astOperand2();
if (Token::simpleMatch(retTok, "&"))
retTok = retTok->astOperand1();
return ValueFlow::hasLifetimeToken(getParentLifetime(retTok), var->nameToken(), *mSettings);
}))
continue;
}
// Skip if another non-const variable is initialized with this variable
{
//Is it the right side of an initialization of a non-const reference
bool usedInAssignment = false;
for (const Token* tok = var->nameToken(); tok != scope->bodyEnd && tok != nullptr; tok = tok->next()) {
if (Token::Match(tok, "& %var% = %varid%", var->declarationId())) {
const Variable* refvar = tok->next()->variable();
if (refvar && !refvar->isConst() && refvar->nameToken() == tok->next()) {
usedInAssignment = true;
break;
}
}
if (tok->isUnaryOp("&") && Token::Match(tok, "& %varid%", var->declarationId())) {
const Token* opTok = tok->astParent();
int argn = -1;
if (opTok && (opTok->isUnaryOp("!") || opTok->isComparisonOp()))
continue;
if (opTok && (opTok->isAssignmentOp() || opTok->isCalculation())) {
if (opTok->isCalculation()) {
if (opTok->astOperand1() != tok)
opTok = opTok->astOperand1();
else
opTok = opTok->astOperand2();
}
if (opTok && opTok->valueType() && var->valueType() && opTok->valueType()->isConst(var->valueType()->pointer))
continue;
} else if (const Token* ftok = getTokenArgumentFunction(tok, argn)) {
bool inconclusive{};
if (var->valueType() && !isVariableChangedByFunctionCall(ftok, var->valueType()->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive)
continue;
}
usedInAssignment = true;
break;
}
if (astIsRangeBasedForDecl(tok) && Token::Match(tok->astParent()->astOperand2(), "%varid%", var->declarationId())) {
const Variable* refvar = tok->astParent()->astOperand1()->variable();
if (refvar && refvar->isReference() && !refvar->isConst()) {
usedInAssignment = true;
break;
}
}
}
if (usedInAssignment)
continue;
}
constVariableError(var, hasFunction ? function : nullptr);
}
}
static const Token* getVariableChangedStart(const Variable* p)
{
if (p->isArgument())
return p->scope()->bodyStart;
const Token* start = p->nameToken()->next();
if (start->isSplittedVarDeclEq())
start = start->tokAt(3);
return start;
}
static bool isConstPointerVariable(const Variable* p, const Settings& settings)
{
const int indirect = p->isArray() ? p->dimensions().size() : 1;
const Token* start = getVariableChangedStart(p);
while (const Token* tok =
findVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, settings)) {
if (p->isReference())
return false;
// Assigning a pointer through another pointer may still be const
if (!Token::simpleMatch(tok->astParent(), "="))
return false;
if (!astIsLHS(tok))
return false;
start = tok->next();
}
return true;
}
namespace {
struct CompareVariables {
bool operator()(const Variable* a, const Variable* b) const {
const int fileA = a->nameToken()->fileIndex();
const int fileB = b->nameToken()->fileIndex();
if (fileA != fileB)
return fileA < fileB;
const int lineA = a->nameToken()->linenr();
const int lineB = b->nameToken()->linenr();
if (lineA != lineB)
return lineA < lineB;
const int columnA = a->nameToken()->column();
const int columnB = b->nameToken()->column();
return columnA < columnB;
}
};
}
void CheckOther::checkConstPointer()
{
if (!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("constParameter") &&
!mSettings->isPremiumEnabled("constParameterPointer") &&
!mSettings->isPremiumEnabled("constParameterReference") &&
!mSettings->isPremiumEnabled("constVariablePointer"))
return;
logChecker("CheckOther::checkConstPointer"); // style
std::set<const Variable*, CompareVariables> pointers, nonConstPointers;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
const Variable* const var = tok->variable();
if (!var)
continue;
if (!var->isLocal() && !var->isArgument())
continue;
const Token* const nameTok = var->nameToken();
if (tok == nameTok) {
// declarations of (static) pointers are (not) split up, array declarations are never split up
if (var->isLocal() && (!var->isStatic() || Token::simpleMatch(nameTok->next(), "[")) &&
!astIsRangeBasedForDecl(nameTok))
continue;
}
// Skip function pointers
if (Token::Match(nameTok, "%name% ) ("))
continue;
const ValueType* const vt = tok->valueType();
if (!vt)
continue;
if ((vt->pointer != 1 && !(vt->pointer == 2 && var->isArray())) || (vt->constness & 1))
continue;
if (var->typeStartToken()->isTemplateArg())
continue;
if (std::find(nonConstPointers.cbegin(), nonConstPointers.cend(), var) != nonConstPointers.cend())
continue;
pointers.emplace(var);
const Token* parent = tok->astParent();
enum Deref : std::uint8_t { NONE, DEREF, MEMBER } deref = NONE;
bool hasIncDecPlus = false;
if (parent && (parent->isUnaryOp("*") || (((hasIncDecPlus = parent->isIncDecOp()) || (hasIncDecPlus = (parent->str() == "+"))) &&
parent->astParent() && parent->astParent()->isUnaryOp("*"))))
deref = DEREF;
else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok && tok != nameTok)
deref = DEREF;
else if (Token::Match(parent, "%op%") && Token::simpleMatch(parent->astParent(), "."))
deref = MEMBER;
else if (Token::simpleMatch(parent, "."))
deref = MEMBER;
else if (astIsRangeBasedForDecl(tok))
continue;
if (deref != NONE) {
const Token* gparent = parent->astParent();
while (Token::simpleMatch(gparent, "[") && parent != gparent->astOperand2() && parent->str() == gparent->str())
gparent = gparent->astParent();
if (deref == MEMBER) {
if (!gparent)
continue;
if (parent->astOperand2()) {
if (parent->astOperand2()->function() && parent->astOperand2()->function()->isConst())
continue;
if (mSettings->library.isFunctionConst(parent->astOperand2()))
continue;
}
}
if (hasIncDecPlus) {
parent = gparent;
gparent = gparent ? gparent->astParent() : nullptr;
}
if (Token::Match(gparent, "%cop%") && !gparent->isUnaryOp("&") && !gparent->isUnaryOp("*"))
continue;
int argn = -1;
if (Token::simpleMatch(gparent, "return")) {
const Function* function = gparent->scope()->function;
if (function && (!Function::returnsReference(function) || Function::returnsConst(function)))
continue;
}
else if (Token::Match(gparent, "%assign%") && parent == gparent->astOperand2()) {
bool takingRef = false, nonConstPtrAssignment = false;
const Token *lhs = gparent->astOperand1();
if (lhs && lhs->variable() && lhs->variable()->isReference() && lhs->variable()->nameToken() == lhs && !lhs->variable()->isConst())
takingRef = true;
if (lhs && lhs->valueType() && lhs->valueType()->pointer && (lhs->valueType()->constness & 1) == 0 &&
parent->valueType() && parent->valueType()->pointer)
nonConstPtrAssignment = true;
if (!takingRef && !nonConstPtrAssignment)
continue;
} else if (Token::simpleMatch(gparent, "[") && gparent->astOperand2() == parent)
continue;
else if (gparent && gparent->isCast() && gparent->valueType() &&
((gparent->valueType()->pointer == 0 && gparent->valueType()->reference == Reference::None) ||
(var->valueType() && gparent->valueType()->isConst(var->valueType()->pointer))))
continue;
else if (const Token* ftok = getTokenArgumentFunction(parent, argn)) {
bool inconclusive{};
if (!isVariableChangedByFunctionCall(ftok->next(), vt->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive)
continue;
}
} else {
int argn = -1;
if (Token::Match(parent, "%oror%|%comp%|&&|?|!|-|<<"))
continue;
if (hasIncDecPlus && !parent->astParent())
continue;
if (Token::simpleMatch(parent, "(") && Token::Match(parent->astOperand1(), "if|while"))
continue;
if (Token::simpleMatch(parent, "=") && parent->astOperand1() == tok)
continue;
if (const Token* ftok = getTokenArgumentFunction(tok, argn)) {
if (ftok->function()) {
const bool isCastArg = parent->isCast() && !ftok->function()->getOverloadedFunctions().empty(); // assume that cast changes the called function
if (!isCastArg) {
const Variable* argVar = ftok->function()->getArgumentVar(argn);
if (argVar && argVar->valueType() && argVar->valueType()->isConst(vt->pointer)) {
bool inconclusive{};
if (!isVariableChangedByFunctionCall(ftok, vt->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive)
continue;
}
}
} else {
const auto dir = mSettings->library.getArgDirection(ftok, argn + 1);
if (dir == Library::ArgumentChecks::Direction::DIR_IN)
continue;
}
}
else if (Token::simpleMatch(parent, "(")) {
if (parent->isCast() && parent->valueType() && var->valueType() && parent->valueType()->isConst(var->valueType()->pointer))
continue;
}
}
if (tok != nameTok)
nonConstPointers.emplace(var);
}
for (const Variable *p: pointers) {
if (p->isArgument()) {
if (!p->scope() || !p->scope()->function || p->scope()->function->isImplicitlyVirtual(true) || p->scope()->function->hasVirtualSpecifier())
continue;
if (p->isMaybeUnused())
continue;
}
if (const Function* func = Scope::nestedInFunction(p->scope()))
if (func->templateDef)
continue;
if (std::find(nonConstPointers.cbegin(), nonConstPointers.cend(), p) == nonConstPointers.cend()) {
// const Token *start = getVariableChangedStart(p);
// const int indirect = p->isArray() ? p->dimensions().size() : 1;
// if (isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, *mSettings))
// continue;
if (!isConstPointerVariable(p, *mSettings))
continue;
if (p->typeStartToken() && p->typeStartToken()->isSimplifiedTypedef() && !(Token::simpleMatch(p->typeEndToken(), "*") && !p->typeEndToken()->isSimplifiedTypedef()))
continue;
constVariableError(p, p->isArgument() ? p->scope()->function : nullptr);
}
}
}
void CheckOther::constVariableError(const Variable *var, const Function *function)
{
if (!var) {
reportError(nullptr, Severity::style, "constParameter", "Parameter 'x' can be declared with const");
reportError(nullptr, Severity::style, "constVariable", "Variable 'x' can be declared with const");
reportError(nullptr, Severity::style, "constParameterReference", "Parameter 'x' can be declared with const");
reportError(nullptr, Severity::style, "constVariableReference", "Variable 'x' can be declared with const");
reportError(nullptr, Severity::style, "constParameterPointer", "Parameter 'x' can be declared with const");
reportError(nullptr, Severity::style, "constVariablePointer", "Variable 'x' can be declared with const");
reportError(nullptr, Severity::style, "constParameterCallback", "Parameter 'x' can be declared with const, however it seems that 'f' is a callback function.");
return;
}
const std::string vartype(var->isArgument() ? "Parameter" : "Variable");
const std::string& varname(var->name());
const std::string ptrRefArray = var->isArray() ? "const array" : (var->isPointer() ? "pointer to const" : "reference to const");
ErrorPath errorPath;
std::string id = "const" + vartype;
std::string message = "$symbol:" + varname + "\n" + vartype + " '$symbol' can be declared as " + ptrRefArray;
errorPath.emplace_back(var->nameToken(), message);
if (var->isArgument() && function && function->functionPointerUsage) {
errorPath.emplace_front(function->functionPointerUsage, "You might need to cast the function pointer here");
id += "Callback";
message += ". However it seems that '" + function->name() + "' is a callback function, if '$symbol' is declared with const you might also need to cast function pointer(s).";
} else if (var->isReference()) {
id += "Reference";
} else if (var->isPointer() && !var->isArray()) {
id += "Pointer";
}
reportError(errorPath, Severity::style, id.c_str(), message, CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check usage of char variables..
//---------------------------------------------------------------------------
void CheckOther::checkCharVariable()
{
const bool warning = mSettings->severity.isEnabled(Severity::warning);
const bool portability = mSettings->severity.isEnabled(Severity::portability);
if (!warning && !portability)
return;
logChecker("CheckOther::checkCharVariable"); // warning,portability
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% [")) {
if (!tok->variable())
continue;
if (!tok->variable()->isArray() && !tok->variable()->isPointer())
continue;
const Token *index = tok->next()->astOperand2();
if (warning && tok->variable()->isArray() && astIsSignedChar(index) && index->getValueGE(0x80, *mSettings))
signedCharArrayIndexError(tok);
if (portability && astIsUnknownSignChar(index) && index->getValueGE(0x80, *mSettings))
unknownSignCharArrayIndexError(tok);
} else if (warning && Token::Match(tok, "[&|^]") && tok->isBinaryOp()) {
bool warn = false;
if (astIsSignedChar(tok->astOperand1())) {
const ValueFlow::Value *v1 = tok->astOperand1()->getValueLE(-1, *mSettings);
const ValueFlow::Value *v2 = tok->astOperand2()->getMaxValue(false);
if (!v1)
v1 = tok->astOperand1()->getValueGE(0x80, *mSettings);
if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100))
warn = true;
} else if (astIsSignedChar(tok->astOperand2())) {
const ValueFlow::Value *v1 = tok->astOperand2()->getValueLE(-1, *mSettings);
const ValueFlow::Value *v2 = tok->astOperand1()->getMaxValue(false);
if (!v1)
v1 = tok->astOperand2()->getValueGE(0x80, *mSettings);
if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100))
warn = true;
}
// is the result stored in a short|int|long?
if (warn && Token::simpleMatch(tok->astParent(), "=")) {
const Token *lhs = tok->astParent()->astOperand1();
if (lhs && lhs->valueType() && lhs->valueType()->type >= ValueType::Type::SHORT)
charBitOpError(tok); // This is an error..
}
}
}
}
}
void CheckOther::signedCharArrayIndexError(const Token *tok)
{
reportError(tok,
Severity::warning,
"signedCharArrayIndex",
"Signed 'char' type used as array index.\n"
"Signed 'char' type used as array index. If the value "
"can be greater than 127 there will be a buffer underflow "
"because of sign extension.", CWE128, Certainty::normal);
}
void CheckOther::unknownSignCharArrayIndexError(const Token *tok)
{
reportError(tok,
Severity::portability,
"unknownSignCharArrayIndex",
"'char' type used as array index.\n"
"'char' type used as array index. Values greater than 127 will be "
"treated depending on whether 'char' is signed or unsigned on target platform.", CWE758, Certainty::normal);
}
void CheckOther::charBitOpError(const Token *tok)
{
reportError(tok,
Severity::warning,
"charBitOp",
"When using 'char' variables in bit operations, sign extension can generate unexpected results.\n"
"When using 'char' variables in bit operations, sign extension can generate unexpected results. For example:\n"
" char c = 0x80;\n"
" int i = 0 | c;\n"
" if (i & 0x8000)\n"
" printf(\"not expected\");\n"
"The \"not expected\" will be printed on the screen.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// Incomplete statement..
//---------------------------------------------------------------------------
static bool isType(const Token * tok, bool unknown)
{
if (tok && (tok->isStandardType() || (!tok->isKeyword() && Token::Match(tok, "%type%")) || tok->str() == "auto"))
return true;
if (tok && tok->varId())
return false;
if (Token::simpleMatch(tok, "::"))
return isType(tok->astOperand2(), unknown);
if (Token::simpleMatch(tok, "<") && tok->link())
return true;
if (unknown && Token::Match(tok, "%name% !!("))
return true;
return false;
}
static bool isVarDeclOp(const Token* tok)
{
if (!tok)
return false;
const Token * vartok = tok->astOperand2();
if (vartok && vartok->variable() && vartok->variable()->nameToken() == vartok)
return true;
const Token * typetok = tok->astOperand1();
return isType(typetok, vartok && vartok->varId() != 0);
}
static bool isBracketAccess(const Token* tok)
{
if (!Token::simpleMatch(tok, "[") || !tok->astOperand1())
return false;
tok = tok->astOperand1();
if (tok->str() == ".")
tok = tok->astOperand2();
while (Token::simpleMatch(tok, "["))
tok = tok->astOperand1();
if (!tok || !tok->variable())
return false;
return tok->variable()->nameToken() != tok;
}
static bool isConstant(const Token* tok) {
return tok && (tok->isEnumerator() || Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL"));
}
static bool isConstStatement(const Token *tok, bool isNestedBracket = false)
{
if (!tok)
return false;
if (tok->isExpandedMacro())
return false;
if (tok->varId() != 0)
return true;
if (isConstant(tok))
return true;
if (Token::Match(tok, "*|&|&&") &&
(Token::Match(tok->previous(), "::|.|const|volatile|restrict") || isVarDeclOp(tok)))
return false;
if (Token::Match(tok, "<<|>>") && !astIsIntegral(tok, false))
return false;
const Token* tok2 = tok;
while (tok2) {
if (Token::simpleMatch(tok2->astOperand1(), "delete"))
return false;
tok2 = tok2->astParent();
}
if (Token::Match(tok, "&&|%oror%"))
return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2());
if (Token::Match(tok, "!|~|%cop%") && (tok->astOperand1() || tok->astOperand2()))
return true;
if (Token::simpleMatch(tok->previous(), "sizeof ("))
return true;
if (isCPPCast(tok)) {
if (Token::simpleMatch(tok->astOperand1(), "dynamic_cast") && Token::simpleMatch(tok->astOperand1()->linkAt(1)->previous(), "& >"))
return false;
return isWithoutSideEffects(tok) && isConstStatement(tok->astOperand2());
}
if (tok->isCast() && tok->next() && tok->next()->isStandardType())
return isWithoutSideEffects(tok->astOperand1()) && isConstStatement(tok->astOperand1());
if (Token::simpleMatch(tok, "."))
return isConstStatement(tok->astOperand2());
if (Token::simpleMatch(tok, ",")) {
if (tok->astParent()) // warn about const statement on rhs at the top level
return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2());
const Token* lml = previousBeforeAstLeftmostLeaf(tok); // don't warn about matrix/vector assignment (e.g. Eigen)
if (lml)
lml = lml->next();
const Token* stream = lml;
while (stream && Token::Match(stream->astParent(), ".|[|(|*"))
stream = stream->astParent();
return (!stream || !isLikelyStream(stream)) && isConstStatement(tok->astOperand2());
}
if (Token::simpleMatch(tok, "?") && Token::simpleMatch(tok->astOperand2(), ":")) // ternary operator
return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2()->astOperand1()) && isConstStatement(tok->astOperand2()->astOperand2());
if (isBracketAccess(tok) && isWithoutSideEffects(tok->astOperand1(), /*checkArrayAccess*/ true, /*checkReference*/ false)) {
const bool isChained = succeeds(tok->astParent(), tok);
if (Token::simpleMatch(tok->astParent(), "[")) {
if (isChained)
return isConstStatement(tok->astOperand2()) && isConstStatement(tok->astParent());
return isNestedBracket && isConstStatement(tok->astOperand2());
}
return isConstStatement(tok->astOperand2(), /*isNestedBracket*/ !isChained);
}
return false;
}
static bool isVoidStmt(const Token *tok)
{
if (Token::simpleMatch(tok, "( void"))
return true;
if (isCPPCast(tok) && tok->astOperand1() && Token::Match(tok->astOperand1()->next(), "< void *| >"))
return true;
const Token *tok2 = tok;
while (tok2->astOperand1())
tok2 = tok2->astOperand1();
if (Token::simpleMatch(tok2->previous(), ")") && Token::simpleMatch(tok2->linkAt(-1), "( void"))
return true;
if (Token::simpleMatch(tok2, "( void"))
return true;
return Token::Match(tok2->previous(), "delete|throw|return");
}
static bool isConstTop(const Token *tok)
{
if (!tok)
return false;
if (!tok->astParent())
return true;
if (Token::simpleMatch(tok->astParent(), ";") &&
Token::Match(tok->astTop()->previous(), "for|if (") && Token::simpleMatch(tok->astTop()->astOperand2(), ";")) {
if (Token::simpleMatch(tok->astParent()->astParent(), ";"))
return tok->astParent()->astOperand2() == tok;
return tok->astParent()->astOperand1() == tok;
}
if (Token::simpleMatch(tok, "[")) {
const Token* bracTok = tok;
while (Token::simpleMatch(bracTok->astParent(), "["))
bracTok = bracTok->astParent();
if (!bracTok->astParent())
return true;
}
if (tok->str() == "," && tok->astParent()->isAssignmentOp())
return true;
return false;
}
void CheckOther::checkIncompleteStatement()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkIncompleteStatement"); // warning
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
const Scope *scope = tok->scope();
if (scope && !scope->isExecutable())
continue;
if (!isConstTop(tok))
continue;
if (tok->str() == "," && Token::simpleMatch(tok->astTop()->previous(), "for ("))
continue;
// Do not warn for statement when both lhs and rhs has side effects:
// dostuff() || x=213;
if (Token::Match(tok, "%oror%|&&")) {
bool warn = false;
visitAstNodes(tok, [&warn](const Token *child) {
if (Token::Match(child, "%oror%|&&"))
return ChildrenToVisit::op1_and_op2;
if (child->isAssignmentOp())
return ChildrenToVisit::none;
if (child->tokType() == Token::Type::eIncDecOp)
return ChildrenToVisit::none;
if (Token::Match(child->previous(), "%name% ("))
return ChildrenToVisit::none;
warn = true;
return ChildrenToVisit::done;
});
if (!warn)
continue;
}
const Token *rtok = nextAfterAstRightmostLeaf(tok);
if (!Token::simpleMatch(tok->astParent(), ";") && !Token::simpleMatch(rtok, ";") &&
!Token::Match(tok->previous(), ";|}|{ %any% ;") &&
!(tok->isCpp() && tok->isCast() && !tok->astParent()) &&
!Token::simpleMatch(tok->tokAt(-2), "for (") &&
!Token::Match(tok->tokAt(-1), "%var% [") &&
!(tok->str() == "," && tok->astParent() && tok->astParent()->isAssignmentOp()))
continue;
// Skip statement expressions
if (Token::simpleMatch(rtok, "; } )"))
continue;
if (!isConstStatement(tok))
continue;
if (isVoidStmt(tok))
continue;
if (tok->isCpp() && tok->str() == "&" && !(tok->astOperand1() && tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->isIntegral()))
// Possible archive
continue;
const bool inconclusive = tok->isConstOp();
if (mSettings->certainty.isEnabled(Certainty::inconclusive) || !inconclusive)
constStatementError(tok, tok->isNumber() ? "numeric" : "string", inconclusive);
}
}
void CheckOther::constStatementError(const Token *tok, const std::string &type, bool inconclusive)
{
const Token *valueTok = tok;
while (valueTok && valueTok->isCast())
valueTok = valueTok->astOperand2() ? valueTok->astOperand2() : valueTok->astOperand1();
std::string msg;
if (Token::simpleMatch(tok, "=="))
msg = "Found suspicious equality comparison. Did you intend to assign a value instead?";
else if (Token::Match(tok, ",|!|~|%cop%"))
msg = "Found suspicious operator '" + tok->str() + "', result is not used.";
else if (Token::Match(tok, "%var%"))
msg = "Unused variable value '" + tok->str() + "'";
else if (isConstant(valueTok)) {
std::string typeStr("string");
if (valueTok->isNumber())
typeStr = "numeric";
else if (valueTok->isBoolean())
typeStr = "bool";
else if (valueTok->tokType() == Token::eChar)
typeStr = "character";
else if (isNullOperand(valueTok))
typeStr = "NULL";
else if (valueTok->isEnumerator())
typeStr = "enumerator";
msg = "Redundant code: Found a statement that begins with " + typeStr + " constant.";
}
else if (!tok)
msg = "Redundant code: Found a statement that begins with " + type + " constant.";
else if (tok->isCast() && tok->tokType() == Token::Type::eExtendedOp) {
msg = "Redundant code: Found unused cast ";
msg += valueTok ? "of expression '" + valueTok->expressionString() + "'." : "expression.";
}
else if (tok->str() == "?" && tok->tokType() == Token::Type::eExtendedOp)
msg = "Redundant code: Found unused result of ternary operator.";
else if (tok->str() == "." && tok->tokType() == Token::Type::eOther)
msg = "Redundant code: Found unused member access.";
else if (tok->str() == "[" && tok->tokType() == Token::Type::eExtendedOp)
msg = "Redundant code: Found unused array access.";
else if (mSettings->debugwarnings) {
reportError(tok, Severity::debug, "debug", "constStatementError not handled.");
return;
}
reportError(tok, Severity::warning, "constStatement", msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// Detect division by zero.
//---------------------------------------------------------------------------
void CheckOther::checkZeroDivision()
{
logChecker("CheckOther::checkZeroDivision");
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->astOperand2() || !tok->astOperand1())
continue;
if (tok->str() != "%" && tok->str() != "/" && tok->str() != "%=" && tok->str() != "/=")
continue;
if (!tok->valueType() || !tok->valueType()->isIntegral())
continue;
if (tok->scope() && tok->scope()->type == Scope::eEnum) // don't warn for compile-time error
continue;
// Value flow..
const ValueFlow::Value *value = tok->astOperand2()->getValue(0LL);
if (value && mSettings->isEnabled(value, false))
zerodivError(tok, value);
}
}
void CheckOther::zerodivError(const Token *tok, const ValueFlow::Value *value)
{
if (!tok && !value) {
reportError(tok, Severity::error, "zerodiv", "Division by zero.", CWE369, Certainty::normal);
reportError(tok, Severity::warning, "zerodivcond", ValueFlow::eitherTheConditionIsRedundant(nullptr) + " or there is division by zero.", CWE369, Certainty::normal);
return;
}
const ErrorPath errorPath = getErrorPath(tok, value, "Division by zero");
std::ostringstream errmsg;
if (value->condition) {
const int line = tok ? tok->linenr() : 0;
errmsg << ValueFlow::eitherTheConditionIsRedundant(value->condition)
<< " or there is division by zero at line " << line << ".";
} else
errmsg << "Division by zero.";
reportError(errorPath,
value->errorSeverity() ? Severity::error : Severity::warning,
value->condition ? "zerodivcond" : "zerodiv",
errmsg.str(), CWE369, value->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for NaN (not-a-number) in an arithmetic expression, e.g.
// double d = 1.0 / 0.0 + 100.0;
//---------------------------------------------------------------------------
void CheckOther::checkNanInArithmeticExpression()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("nanInArithmeticExpression"))
return;
logChecker("CheckOther::checkNanInArithmeticExpression"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "/")
continue;
if (!Token::Match(tok->astParent(), "[+-]"))
continue;
if (Token::simpleMatch(tok->astOperand2(), "0.0"))
nanInArithmeticExpressionError(tok);
}
}
void CheckOther::nanInArithmeticExpressionError(const Token *tok)
{
reportError(tok, Severity::style, "nanInArithmeticExpression",
"Using NaN/Inf in a computation.\n"
"Using NaN/Inf in a computation. "
"Although nothing bad really happens, it is suspicious.", CWE369, Certainty::normal);
}
//---------------------------------------------------------------------------
// Creating instance of classes which are destroyed immediately
//---------------------------------------------------------------------------
void CheckOther::checkMisusedScopedObject()
{
// Skip this check for .c files
if (mTokenizer->isC())
return;
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedScopedObject"))
return;
logChecker("CheckOther::checkMisusedScopedObject"); // style,c++
auto getConstructorTok = [](const Token* tok, std::string& typeStr) -> const Token* {
if (!Token::Match(tok, "[;{}] %name%") || tok->next()->isKeyword())
return nullptr;
tok = tok->next();
typeStr.clear();
while (Token::Match(tok, "%name% ::")) {
typeStr += tok->str();
typeStr += "::";
tok = tok->tokAt(2);
}
typeStr += tok->str();
const Token* endTok = tok;
if (Token::Match(endTok, "%name% <"))
endTok = endTok->linkAt(1);
if (Token::Match(endTok, "%name%|> (|{") && Token::Match(endTok->linkAt(1), ")|} ;") &&
!Token::simpleMatch(endTok->next()->astParent(), ";")) { // for loop condition
return tok;
}
return nullptr;
};
auto isLibraryConstructor = [&](const Token* tok, const std::string& typeStr) -> bool {
const Library::TypeCheck typeCheck = mSettings->library.getTypeCheck("unusedvar", typeStr);
if (typeCheck == Library::TypeCheck::check || typeCheck == Library::TypeCheck::checkFiniteLifetime)
return true;
return mSettings->library.detectContainerOrIterator(tok);
};
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
std::string typeStr;
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
const Token* ctorTok = getConstructorTok(tok, typeStr);
if (ctorTok && (((ctorTok->type() || ctorTok->isStandardType() || (ctorTok->function() && ctorTok->function()->isConstructor())) // TODO: The rhs of || should be removed; It is a workaround for a symboldatabase bug
&& (!ctorTok->function() || ctorTok->function()->isConstructor()) // // is not a function on this scope or is function in this scope and it's a ctor
&& ctorTok->str() != "void") || isLibraryConstructor(tok->next(), typeStr))) {
const Token* parTok = ctorTok->next();
if (Token::simpleMatch(parTok, "<") && parTok->link())
parTok = parTok->link()->next();
if (const Token* arg = parTok->astOperand2()) {
if (!isConstStatement(arg))
continue;
if (parTok->str() == "(") {
if (arg->varId() && !(arg->variable() && arg->variable()->nameToken() != arg))
continue;
const Token* rml = nextAfterAstRightmostLeaf(arg);
if (rml && rml->previous() && rml->previous()->varId())
continue;
}
}
tok = tok->next();
misusedScopeObjectError(ctorTok, typeStr);
tok = tok->next();
}
if (tok->isAssignmentOp() && Token::simpleMatch(tok->astOperand1(), "(") && tok->astOperand1()->astOperand1()) {
if (const Function* ftok = tok->astOperand1()->astOperand1()->function()) {
if (ftok->retType && Token::Match(ftok->retType->classDef, "class|struct|union") && !Function::returnsReference(ftok, /*unknown*/ false, /*includeRValueRef*/ true))
misusedScopeObjectError(tok->next(), ftok->retType->name(), /*isAssignment*/ true);
}
}
}
}
}
void CheckOther::misusedScopeObjectError(const Token *tok, const std::string& varname, bool isAssignment)
{
std::string msg = "Instance of '$symbol' object is destroyed immediately";
msg += isAssignment ? ", assignment has no effect." : ".";
reportError(tok, Severity::style,
"unusedScopedObject",
"$symbol:" + varname + "\n" +
msg, CWE563, Certainty::normal);
}
static const Token * getSingleExpressionInBlock(const Token * tok)
{
if (!tok)
return nullptr;
const Token * top = tok->astTop();
const Token * nextExpression = nextAfterAstRightmostLeaf(top);
if (!Token::simpleMatch(nextExpression, "; }"))
return nullptr;
return top;
}
//-----------------------------------------------------------------------------
// check for duplicate code in if and else branches
// if (a) { b = true; } else { b = true; }
//-----------------------------------------------------------------------------
void CheckOther::checkDuplicateBranch()
{
// This is inconclusive since in practice most warnings are noise:
// * There can be unfixed low-priority todos. The code is fine as it
// is but it could be possible to enhance it. Writing a warning
// here is noise since the code is fine (see cppcheck, abiword, ..)
// * There can be overspecified code so some conditions can't be true
// and their conditional code is a duplicate of the condition that
// is always true just in case it would be false. See for instance
// abiword.
if (!mSettings->severity.isEnabled(Severity::style) || !mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckOther::checkDuplicateBranch"); // style,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
// check all the code in the function for if (..) else
if (Token::simpleMatch(scope.bodyEnd, "} else {")) {
// Make sure there are no macros (different macros might be expanded
// to the same code)
bool macro = false;
for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd->linkAt(2); tok = tok->next()) {
if (tok->isExpandedMacro()) {
macro = true;
break;
}
}
if (macro)
continue;
const Token * const tokIf = scope.bodyStart->next();
const Token * const tokElse = scope.bodyEnd->tokAt(3);
// compare first tok before stringifying the whole blocks
const std::string tokIfStr = tokIf->stringify(false, true, false);
if (tokIfStr.empty())
continue;
const std::string tokElseStr = tokElse->stringify(false, true, false);
if (tokIfStr == tokElseStr) {
// save if branch code
const std::string branch1 = tokIf->stringifyList(scope.bodyEnd);
if (branch1.empty())
continue;
// save else branch code
const std::string branch2 = tokElse->stringifyList(scope.bodyEnd->linkAt(2));
// check for duplicates
if (branch1 == branch2) {
duplicateBranchError(scope.classDef, scope.bodyEnd->next(), ErrorPath{});
continue;
}
}
// check for duplicates using isSameExpression
const Token * branchTop1 = getSingleExpressionInBlock(tokIf);
if (!branchTop1)
continue;
const Token * branchTop2 = getSingleExpressionInBlock(tokElse);
if (!branchTop2)
continue;
if (branchTop1->str() != branchTop2->str())
continue;
ErrorPath errorPath;
if (isSameExpression(false, branchTop1->astOperand1(), branchTop2->astOperand1(), *mSettings, true, true, &errorPath) &&
isSameExpression(false, branchTop1->astOperand2(), branchTop2->astOperand2(), *mSettings, true, true, &errorPath))
duplicateBranchError(scope.classDef, scope.bodyEnd->next(), std::move(errorPath));
}
}
}
void CheckOther::duplicateBranchError(const Token *tok1, const Token *tok2, ErrorPath errors)
{
errors.emplace_back(tok2, "");
errors.emplace_back(tok1, "");
reportError(errors, Severity::style, "duplicateBranch", "Found duplicate branches for 'if' and 'else'.\n"
"Finding the same code in an 'if' and related 'else' branch is suspicious and "
"might indicate a cut and paste or logic error. Please examine this code "
"carefully to determine if it is correct.", CWE398, Certainty::inconclusive);
}
//-----------------------------------------------------------------------------
// Check for a free() of an invalid address
// char* p = malloc(100);
// free(p + 10);
//-----------------------------------------------------------------------------
void CheckOther::checkInvalidFree()
{
std::map<int, bool> inconclusive;
std::map<int, std::string> allocation;
logChecker("CheckOther::checkInvalidFree");
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) {
// Keep track of which variables were assigned addresses to newly-allocated memory
if ((tok->isCpp() && Token::Match(tok, "%var% = new")) ||
(Token::Match(tok, "%var% = %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)))) {
allocation.emplace(tok->varId(), tok->strAt(2));
inconclusive.emplace(tok->varId(), false);
}
// If a previously-allocated pointer is incremented or decremented, any subsequent
// free involving pointer arithmetic may or may not be invalid, so we should only
// report an inconclusive result.
else if (Token::Match(tok, "%var% = %name% +|-") &&
tok->varId() == tok->tokAt(2)->varId() &&
allocation.find(tok->varId()) != allocation.end()) {
if (printInconclusive)
inconclusive[tok->varId()] = true;
else {
allocation.erase(tok->varId());
inconclusive.erase(tok->varId());
}
}
// If a previously-allocated pointer is assigned a completely new value,
// we can't know if any subsequent free() on that pointer is valid or not.
else if (Token::Match(tok, "%var% =")) {
allocation.erase(tok->varId());
inconclusive.erase(tok->varId());
}
// If a variable that was previously assigned a newly-allocated memory location is
// added or subtracted from when used to free the memory, report an error.
else if ((Token::Match(tok, "%name% ( %any% +|-") && mSettings->library.getDeallocFuncInfo(tok)) ||
Token::Match(tok, "delete [ ] ( %any% +|-") ||
Token::Match(tok, "delete %any% +|- %any%")) {
const int varIndex = tok->strAt(1) == "(" ? 2 :
tok->strAt(3) == "(" ? 4 : 1;
const int var1 = tok->tokAt(varIndex)->varId();
const int var2 = tok->tokAt(varIndex + 2)->varId();
const std::map<int, bool>::const_iterator alloc1 = inconclusive.find(var1);
const std::map<int, bool>::const_iterator alloc2 = inconclusive.find(var2);
if (alloc1 != inconclusive.end()) {
invalidFreeError(tok, allocation[var1], alloc1->second);
} else if (alloc2 != inconclusive.end()) {
invalidFreeError(tok, allocation[var2], alloc2->second);
}
}
// If the previously-allocated variable is passed in to another function
// as a parameter, it might be modified, so we shouldn't report an error
// if it is later used to free memory
else if (Token::Match(tok, "%name% (") && !mSettings->library.isFunctionConst(tok->str(), true)) {
const Token* tok2 = Token::findmatch(tok->next(), "%var%", tok->linkAt(1));
while (tok2 != nullptr) {
allocation.erase(tok->varId());
inconclusive.erase(tok2->varId());
tok2 = Token::findmatch(tok2->next(), "%var%", tok->linkAt(1));
}
}
}
}
}
void CheckOther::invalidFreeError(const Token *tok, const std::string &allocation, bool inconclusive)
{
std::string alloc = allocation;
if (alloc != "new")
alloc += "()";
std::string deallocated = (alloc == "new") ? "deleted" : "freed";
reportError(tok, Severity::error, "invalidFree", "Mismatching address is " + deallocated + ". The address you get from " + alloc + " must be " + deallocated + " without offset.", CWE(0U), inconclusive ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// check for the same expression on both sides of an operator
// (x == x), (x && x), (x || x)
// (x.y == x.y), (x.y && x.y), (x.y || x.y)
//---------------------------------------------------------------------------
namespace {
bool notconst(const Function* func)
{
return !func->isConst();
}
void getConstFunctions(const SymbolDatabase *symbolDatabase, std::list<const Function*> &constFunctions)
{
for (const Scope &scope : symbolDatabase->scopeList) {
// only add const functions that do not have a non-const overloaded version
// since it is pretty much impossible to tell which is being called.
using StringFunctionMap = std::map<std::string, std::list<const Function*>>;
StringFunctionMap functionsByName;
for (const Function &func : scope.functionList) {
functionsByName[func.tokenDef->str()].push_back(&func);
}
for (std::pair<const std::string, std::list<const Function*>>& it : functionsByName) {
const std::list<const Function*>::const_iterator nc = std::find_if(it.second.cbegin(), it.second.cend(), notconst);
if (nc == it.second.cend()) {
// ok to add all of them
constFunctions.splice(constFunctions.end(), it.second);
}
}
}
}
}
static bool
isStaticAssert(const Settings &settings, const Token *tok)
{
if (tok->isCpp() && settings.standards.cpp >= Standards::CPP11 &&
Token::simpleMatch(tok, "static_assert")) {
return true;
}
if (tok->isC() && settings.standards.c >= Standards::C11 &&
Token::simpleMatch(tok, "_Static_assert")) {
return true;
}
return false;
}
void CheckOther::checkDuplicateExpression()
{
{
const bool styleEnabled = mSettings->severity.isEnabled(Severity::style);
const bool premiumEnabled = mSettings->isPremiumEnabled("oppositeExpression") ||
mSettings->isPremiumEnabled("duplicateExpression") ||
mSettings->isPremiumEnabled("duplicateAssignExpression") ||
mSettings->isPremiumEnabled("duplicateExpressionTernary") ||
mSettings->isPremiumEnabled("duplicateValueTernary") ||
mSettings->isPremiumEnabled("selfAssignment") ||
mSettings->isPremiumEnabled("knownConditionTrueFalse");
if (!styleEnabled && !premiumEnabled)
return;
}
logChecker("CheckOther::checkDuplicateExpression"); // style,warning
// Parse all executing scopes..
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::list<const Function*> constFunctions;
getConstFunctions(symbolDatabase, constFunctions);
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "=" && Token::Match(tok->astOperand1(), "%var%")) {
const Token * endStatement = Token::findsimplematch(tok, ";");
if (Token::Match(endStatement, "; %type% %var% ;")) {
endStatement = endStatement->tokAt(4);
}
if (Token::Match(endStatement, "%var% %assign%")) {
const Token * nextAssign = endStatement->tokAt(1);
const Token * var1 = tok->astOperand1();
const Token * var2 = nextAssign->astOperand1();
if (var1 && var2 &&
Token::Match(var1->previous(), ";|{|} %var%") &&
Token::Match(var2->previous(), ";|{|} %var%") &&
var2->valueType() && var1->valueType() &&
var2->valueType()->originalTypeName == var1->valueType()->originalTypeName &&
var2->valueType()->pointer == var1->valueType()->pointer &&
var2->valueType()->constness == var1->valueType()->constness &&
var2->varId() != var1->varId() && (
tok->astOperand2()->isArithmeticalOp() ||
tok->astOperand2()->str() == "." ||
Token::Match(tok->astOperand2()->previous(), "%name% (")
) &&
tok->next()->tokType() != Token::eType &&
isSameExpression(true, tok->next(), nextAssign->next(), *mSettings, true, false) &&
isSameExpression(true, tok->astOperand2(), nextAssign->astOperand2(), *mSettings, true, false) &&
tok->astOperand2()->expressionString() == nextAssign->astOperand2()->expressionString()) {
bool differentDomain = false;
const Scope * varScope = var1->scope() ? var1->scope() : scope;
const Token* assignTok = Token::findsimplematch(var2, ";");
for (; assignTok && assignTok != varScope->bodyEnd; assignTok = assignTok->next()) {
if (!Token::Match(assignTok, "%assign%|%comp%"))
continue;
if (!assignTok->astOperand1())
continue;
if (!assignTok->astOperand2())
continue;
if (assignTok->astOperand1()->varId() != var1->varId() &&
assignTok->astOperand1()->varId() != var2->varId() &&
!isSameExpression(true,
tok->astOperand2(),
assignTok->astOperand1(),
*mSettings,
true,
true))
continue;
if (assignTok->astOperand2()->varId() != var1->varId() &&
assignTok->astOperand2()->varId() != var2->varId() &&
!isSameExpression(true,
tok->astOperand2(),
assignTok->astOperand2(),
*mSettings,
true,
true))
continue;
differentDomain = true;
break;
}
if (!differentDomain && !isUniqueExpression(tok->astOperand2()))
duplicateAssignExpressionError(var1, var2, false);
else if (mSettings->certainty.isEnabled(Certainty::inconclusive)) {
diag(assignTok);
duplicateAssignExpressionError(var1, var2, true);
}
}
}
}
auto isInsideLambdaCaptureList = [](const Token* tok) {
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent, ","))
parent = parent->astParent();
return isLambdaCaptureList(parent);
};
ErrorPath errorPath;
if (tok->isOp() && tok->astOperand1() && !Token::Match(tok, "+|*|<<|>>|+=|*=|<<=|>>=") && !isInsideLambdaCaptureList(tok)) {
if (Token::Match(tok, "==|!=|-") && astIsFloat(tok->astOperand1(), true))
continue;
const bool pointerDereference = (tok->astOperand1() && tok->astOperand1()->isUnaryOp("*")) ||
(tok->astOperand2() && tok->astOperand2()->isUnaryOp("*"));
const bool followVar = (!isConstVarExpression(tok) || Token::Match(tok, "%comp%|%oror%|&&")) && !pointerDereference;
if (isSameExpression(true,
tok->astOperand1(),
tok->astOperand2(),
*mSettings,
true,
followVar,
&errorPath)) {
if (isWithoutSideEffects(tok->astOperand1())) {
const Token* loopTok = isInLoopCondition(tok);
if (!loopTok ||
!findExpressionChanged(tok, tok, loopTok->link()->linkAt(1), *mSettings)) {
const bool isEnum = tok->scope()->type == Scope::eEnum;
const bool assignment = !isEnum && tok->str() == "=";
if (assignment)
selfAssignmentError(tok, tok->astOperand1()->expressionString());
else if (!isEnum) {
if (tok->str() == "==") {
const Token* parent = tok->astParent();
while (parent && parent->astParent()) {
parent = parent->astParent();
}
if (parent && parent->previous() && isStaticAssert(*mSettings, parent->previous())) {
continue;
}
}
duplicateExpressionError(tok->astOperand1(), tok->astOperand2(), tok, std::move(errorPath));
}
}
}
} else if (tok->str() == "=" && Token::simpleMatch(tok->astOperand2(), "=") &&
isSameExpression(false,
tok->astOperand1(),
tok->astOperand2()->astOperand1(),
*mSettings,
true,
false)) {
if (isWithoutSideEffects(tok->astOperand1())) {
selfAssignmentError(tok, tok->astOperand1()->expressionString());
}
} else if (isOppositeExpression(tok->astOperand1(),
tok->astOperand2(),
*mSettings,
false,
true,
&errorPath) &&
!Token::Match(tok, "=|-|-=|/|/=") &&
isWithoutSideEffects(tok->astOperand1())) {
oppositeExpressionError(tok, std::move(errorPath));
} else if (!Token::Match(tok, "[-/%]")) { // These operators are not associative
if (tok->astOperand2() && tok->str() == tok->astOperand1()->str() &&
isSameExpression(true,
tok->astOperand2(),
tok->astOperand1()->astOperand2(),
*mSettings,
true,
followVar,
&errorPath) &&
isWithoutSideEffects(tok->astOperand2()))
duplicateExpressionError(tok->astOperand2(), tok->astOperand1()->astOperand2(), tok, std::move(errorPath));
else if (tok->astOperand2() && isConstExpression(tok->astOperand1(), mSettings->library)) {
auto checkDuplicate = [&](const Token* exp1, const Token* exp2, const Token* ast1) {
if (isSameExpression(true, exp1, exp2, *mSettings, true, true, &errorPath) &&
isWithoutSideEffects(exp1) &&
isWithoutSideEffects(ast1->astOperand2()))
duplicateExpressionError(exp1, exp2, tok, errorPath, /*hasMultipleExpr*/ true);
};
const Token *ast1 = tok->astOperand1();
while (ast1 && tok->str() == ast1->str()) { // chain of identical operators
checkDuplicate(ast1->astOperand2(), tok->astOperand2(), ast1);
if (ast1->astOperand1() && ast1->astOperand1()->str() != tok->str()) // check first condition in the chain
checkDuplicate(ast1->astOperand1(), tok->astOperand2(), ast1);
ast1 = ast1->astOperand1();
}
}
}
} else if (tok->astOperand1() && tok->astOperand2() && tok->str() == ":" && tok->astParent() && tok->astParent()->str() == "?") {
if (!tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2()) &&
!isVariableChanged(tok->astParent(), /*indirect*/ 0, *mSettings) &&
isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2()))
duplicateValueTernaryError(tok);
else if (isSameExpression(true, tok->astOperand1(), tok->astOperand2(), *mSettings, false, true, &errorPath))
duplicateExpressionTernaryError(tok, std::move(errorPath));
}
}
}
}
void CheckOther::oppositeExpressionError(const Token *opTok, ErrorPath errors)
{
errors.emplace_back(opTok, "");
const std::string& op = opTok ? opTok->str() : "&&";
reportError(errors, Severity::style, "oppositeExpression", "Opposite expression on both sides of \'" + op + "\'.\n"
"Finding the opposite expression on both sides of an operator is suspicious and might "
"indicate a cut and paste or logic error. Please examine this code carefully to "
"determine if it is correct.", CWE398, Certainty::normal);
}
void CheckOther::duplicateExpressionError(const Token *tok1, const Token *tok2, const Token *opTok, ErrorPath errors, bool hasMultipleExpr)
{
errors.emplace_back(opTok, "");
const std::string& expr1 = tok1 ? tok1->expressionString() : "x";
const std::string& expr2 = tok2 ? tok2->expressionString() : "x";
const std::string& op = opTok ? opTok->str() : "&&";
std::string msg = "Same expression " + (hasMultipleExpr ? "\'" + expr1 + "\'" + " found multiple times in chain of \'" + op + "\' operators" : "on both sides of \'" + op + "\'");
const char *id = "duplicateExpression";
if (expr1 != expr2 && (!opTok || Token::Match(opTok, "%oror%|%comp%|&&|?|!"))) {
id = "knownConditionTrueFalse";
std::string exprMsg = "The comparison \'" + expr1 + " " + op + " " + expr2 + "\' is always ";
if (Token::Match(opTok, "==|>=|<="))
msg = exprMsg + "true";
else if (Token::Match(opTok, "!=|>|<"))
msg = exprMsg + "false";
}
if (expr1 != expr2 && !Token::Match(tok1, "%num%|NULL|nullptr") && !Token::Match(tok2, "%num%|NULL|nullptr"))
msg += " because '" + expr1 + "' and '" + expr2 + "' represent the same value";
reportError(errors, Severity::style, id, msg +
(std::string(".\nFinding the same expression ") + (hasMultipleExpr ? "more than once in a condition" : "on both sides of an operator")) +
" is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to "
"determine if it is correct.", CWE398, Certainty::normal);
}
void CheckOther::duplicateAssignExpressionError(const Token *tok1, const Token *tok2, bool inconclusive)
{
const std::list<const Token *> toks = { tok2, tok1 };
const std::string& var1 = tok1 ? tok1->str() : "x";
const std::string& var2 = tok2 ? tok2->str() : "x";
reportError(toks, Severity::style, "duplicateAssignExpression",
"Same expression used in consecutive assignments of '" + var1 + "' and '" + var2 + "'.\n"
"Finding variables '" + var1 + "' and '" + var2 + "' that are assigned the same expression "
"is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to "
"determine if it is correct.", CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::duplicateExpressionTernaryError(const Token *tok, ErrorPath errors)
{
errors.emplace_back(tok, "");
reportError(errors, Severity::style, "duplicateExpressionTernary", "Same expression in both branches of ternary operator.\n"
"Finding the same expression in both branches of ternary operator is suspicious as "
"the same code is executed regardless of the condition.", CWE398, Certainty::normal);
}
void CheckOther::duplicateValueTernaryError(const Token *tok)
{
reportError(tok, Severity::style, "duplicateValueTernary", "Same value in both branches of ternary operator.\n"
"Finding the same value in both branches of ternary operator is suspicious as "
"the same code is executed regardless of the condition.", CWE398, Certainty::normal);
}
void CheckOther::selfAssignmentError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::style,
"selfAssignment",
"$symbol:" + varname + "\n"
"Redundant assignment of '$symbol' to itself.", CWE398, Certainty::normal);
}
//-----------------------------------------------------------------------------
// Check is a comparison of two variables leads to condition, which is
// always true or false.
// For instance: int a = 1; if(isless(a,a)){...}
// In this case isless(a,a) always evaluates to false.
//
// Reference:
// - http://www.cplusplus.com/reference/cmath/
//-----------------------------------------------------------------------------
void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->isName() && Token::Match(tok, "isgreater|isless|islessgreater|isgreaterequal|islessequal ( %var% , %var% )")) {
const int varidLeft = tok->tokAt(2)->varId();// get the left varid
const int varidRight = tok->tokAt(4)->varId();// get the right varid
// compare varids: if they are not zero but equal
// --> the comparison function is called with the same variables
if (varidLeft == varidRight) {
const std::string& functionName = tok->str(); // store function name
const std::string& varNameLeft = tok->strAt(2); // get the left variable name
if (functionName == "isgreater" || functionName == "isless" || functionName == "islessgreater") {
// e.g.: isgreater(x,x) --> (x)>(x) --> false
checkComparisonFunctionIsAlwaysTrueOrFalseError(tok, functionName, varNameLeft, false);
} else { // functionName == "isgreaterequal" || functionName == "islessequal"
// e.g.: isgreaterequal(x,x) --> (x)>=(x) --> true
checkComparisonFunctionIsAlwaysTrueOrFalseError(tok, functionName, varNameLeft, true);
}
}
}
}
}
}
void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, const bool result)
{
const std::string strResult = bool_to_string(result);
const CWE cweResult = result ? CWE571 : CWE570;
reportError(tok, Severity::warning, "comparisonFunctionIsAlwaysTrueOrFalse",
"$symbol:" + functionName + "\n"
"Comparison of two identical variables with $symbol(" + varName + "," + varName + ") always evaluates to " + strResult + ".\n"
"The function $symbol is designed to compare two variables. Calling this function with one variable (" + varName + ") "
"for both parameters leads to a statement which is always " + strResult + ".", cweResult, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check testing sign of unsigned variables and pointers.
//---------------------------------------------------------------------------
void CheckOther::checkSignOfUnsignedVariable()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unsignedLessThanZero"))
return;
logChecker("CheckOther::checkSignOfUnsignedVariable"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
// check all the code in the function
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
const ValueFlow::Value *zeroValue = nullptr;
const Token *nonZeroExpr = nullptr;
if (comparisonNonZeroExpressionLessThanZero(tok, zeroValue, nonZeroExpr)) {
const ValueType* vt = nonZeroExpr->valueType();
if (vt->pointer)
pointerLessThanZeroError(tok, zeroValue);
else
unsignedLessThanZeroError(tok, zeroValue, nonZeroExpr->expressionString());
} else if (testIfNonZeroExpressionIsPositive(tok, zeroValue, nonZeroExpr)) {
const ValueType* vt = nonZeroExpr->valueType();
if (vt->pointer)
pointerPositiveError(tok, zeroValue);
else
unsignedPositiveError(tok, zeroValue, nonZeroExpr->expressionString());
}
}
}
}
bool CheckOther::comparisonNonZeroExpressionLessThanZero(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr, bool suppress)
{
if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2())
return false;
const ValueFlow::Value *v1 = tok->astOperand1()->getValue(0);
const ValueFlow::Value *v2 = tok->astOperand2()->getValue(0);
if (Token::Match(tok, "<|<=") && v2 && v2->isKnown()) {
zeroValue = v2;
nonZeroExpr = tok->astOperand1();
} else if (Token::Match(tok, ">|>=") && v1 && v1->isKnown()) {
zeroValue = v1;
nonZeroExpr = tok->astOperand2();
} else {
return false;
}
if (const Variable* var = nonZeroExpr->variable())
if (var->typeStartToken()->isTemplateArg())
return suppress;
const ValueType* vt = nonZeroExpr->valueType();
return vt && (vt->pointer || vt->sign == ValueType::UNSIGNED);
}
bool CheckOther::testIfNonZeroExpressionIsPositive(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr)
{
if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2())
return false;
const ValueFlow::Value *v1 = tok->astOperand1()->getValue(0);
const ValueFlow::Value *v2 = tok->astOperand2()->getValue(0);
if (Token::simpleMatch(tok, ">=") && v2 && v2->isKnown()) {
zeroValue = v2;
nonZeroExpr = tok->astOperand1();
} else if (Token::simpleMatch(tok, "<=") && v1 && v1->isKnown()) {
zeroValue = v1;
nonZeroExpr = tok->astOperand2();
} else {
return false;
}
const ValueType* vt = nonZeroExpr->valueType();
return vt && (vt->pointer || vt->sign == ValueType::UNSIGNED);
}
void CheckOther::unsignedLessThanZeroError(const Token *tok, const ValueFlow::Value * v, const std::string &varname)
{
reportError(getErrorPath(tok, v, "Unsigned less than zero"), Severity::style, "unsignedLessThanZero",
"$symbol:" + varname + "\n"
"Checking if unsigned expression '$symbol' is less than zero.\n"
"The unsigned expression '$symbol' will never be negative so it "
"is either pointless or an error to check if it is.", CWE570, Certainty::normal);
}
void CheckOther::pointerLessThanZeroError(const Token *tok, const ValueFlow::Value *v)
{
reportError(getErrorPath(tok, v, "Pointer less than zero"), Severity::style, "pointerLessThanZero",
"A pointer can not be negative so it is either pointless or an error to check if it is.", CWE570, Certainty::normal);
}
void CheckOther::unsignedPositiveError(const Token *tok, const ValueFlow::Value * v, const std::string &varname)
{
reportError(getErrorPath(tok, v, "Unsigned positive"), Severity::style, "unsignedPositive",
"$symbol:" + varname + "\n"
"Unsigned expression '$symbol' can't be negative so it is unnecessary to test it.", CWE570, Certainty::normal);
}
void CheckOther::pointerPositiveError(const Token *tok, const ValueFlow::Value * v)
{
reportError(getErrorPath(tok, v, "Pointer positive"), Severity::style, "pointerPositive",
"A pointer can not be negative so it is either pointless or an error to check if it is not.", CWE570, Certainty::normal);
}
/* check if a constructor in given class scope takes a reference */
static bool constructorTakesReference(const Scope * const classScope)
{
return std::any_of(classScope->functionList.begin(), classScope->functionList.end(), [&](const Function& constructor) {
if (constructor.isConstructor()) {
for (int argnr = 0U; argnr < constructor.argCount(); argnr++) {
const Variable * const argVar = constructor.getArgumentVar(argnr);
if (argVar && argVar->isReference()) {
return true;
}
}
}
return false;
});
}
//---------------------------------------------------------------------------
// This check rule works for checking the "const A a = getA()" usage when getA() returns "const A &" or "A &".
// In most scenarios, "const A & a = getA()" will be more efficient.
//---------------------------------------------------------------------------
void CheckOther::checkRedundantCopy()
{
if (!mSettings->severity.isEnabled(Severity::performance) || mTokenizer->isC() || !mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckOther::checkRedundantCopy"); // c++,performance,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || var->isReference() || var->isPointer() ||
(!var->type() && !var->isStlType() && !(var->valueType() && var->valueType()->container)) || // bailout if var is of standard type, if it is a pointer or non-const
(!var->isConst() && isVariableChanged(var, *mSettings)))
continue;
const Token* startTok = var->nameToken();
if (startTok->strAt(1) == "=") // %type% %name% = ... ;
;
else if (Token::Match(startTok->next(), "(|{") && var->isClass()) {
if (!var->typeScope() && !(var->valueType() && var->valueType()->container))
continue;
// Object is instantiated. Warn if constructor takes arguments by value.
if (var->typeScope() && constructorTakesReference(var->typeScope()))
continue;
} else if (Token::simpleMatch(startTok->next(), ";") && startTok->next()->isSplittedVarDeclEq()) {
startTok = startTok->tokAt(2);
} else
continue;
const Token* tok = startTok->next()->astOperand2();
if (!tok)
continue;
if (!Token::Match(tok->previous(), "%name% ("))
continue;
if (!Token::Match(tok->link(), ") )|}| ;")) // bailout for usage like "const A a = getA()+3"
continue;
const Token* dot = tok->astOperand1();
if (Token::simpleMatch(dot, ".")) {
const Token* varTok = dot->astOperand1();
const int indirect = varTok->valueType() ? varTok->valueType()->pointer : 0;
if (isVariableChanged(tok, tok->scope()->bodyEnd, indirect, varTok->varId(), /*globalvar*/ true, *mSettings))
continue;
if (isTemporary(dot, &mSettings->library, /*unknown*/ true))
continue;
}
if (exprDependsOnThis(tok->previous()))
continue;
const Function* func = tok->previous()->function();
if (func && func->tokenDef->strAt(-1) == "&") {
const Scope* fScope = func->functionScope;
if (fScope && fScope->bodyEnd && Token::Match(fScope->bodyEnd->tokAt(-3), "return %var% ;")) {
const Token* varTok = fScope->bodyEnd->tokAt(-2);
if (varTok->variable() && !varTok->variable()->isGlobal() &&
(!varTok->variable()->type() || !varTok->variable()->type()->classScope ||
(varTok->variable()->valueType() && ValueFlow::getSizeOf(*varTok->variable()->valueType(), *mSettings) > 2 * mSettings->platform.sizeof_pointer)))
redundantCopyError(startTok, startTok->str());
}
}
}
}
void CheckOther::redundantCopyError(const Token *tok,const std::string& varname)
{
reportError(tok, Severity::performance, "redundantCopyLocalConst",
"$symbol:" + varname + "\n"
"Use const reference for '$symbol' to avoid unnecessary data copying.\n"
"The const variable '$symbol' is assigned a copy of the data. You can avoid "
"the unnecessary data copying by converting '$symbol' to const reference.",
CWE398,
Certainty::inconclusive); // since #5618 that check became inconclusive
}
//---------------------------------------------------------------------------
// Checking for shift by negative values
//---------------------------------------------------------------------------
static bool isNegative(const Token *tok, const Settings &settings)
{
return tok->valueType() && tok->valueType()->sign == ValueType::SIGNED && tok->getValueLE(-1LL, settings);
}
void CheckOther::checkNegativeBitwiseShift()
{
const bool portability = mSettings->severity.isEnabled(Severity::portability);
logChecker("CheckOther::checkNegativeBitwiseShift");
for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) {
tok = skipUnreachableBranch(tok);
if (!tok->astOperand1() || !tok->astOperand2())
continue;
if (!Token::Match(tok, "<<|>>|<<=|>>="))
continue;
// don't warn if lhs is a class. this is an overloaded operator then
if (tok->isCpp()) {
const ValueType * lhsType = tok->astOperand1()->valueType();
if (!lhsType || !lhsType->isIntegral() || lhsType->pointer)
continue;
}
// bailout if operation is protected by ?:
bool ternary = false;
for (const Token *parent = tok; parent; parent = parent->astParent()) {
if (Token::Match(parent, "?|:")) {
ternary = true;
break;
}
}
if (ternary)
continue;
// Get negative rhs value. preferably a value which doesn't have 'condition'.
if (portability && isNegative(tok->astOperand1(), *mSettings))
negativeBitwiseShiftError(tok, 1);
else if (isNegative(tok->astOperand2(), *mSettings))
negativeBitwiseShiftError(tok, 2);
}
}
void CheckOther::negativeBitwiseShiftError(const Token *tok, int op)
{
if (op == 1)
// LHS - this is used by intention in various software, if it
// is used often in a project and works as expected then this is
// a portability issue
reportError(tok, Severity::portability, "shiftNegativeLHS", "Shifting a negative value is technically undefined behaviour", CWE758, Certainty::normal);
else // RHS
reportError(tok, Severity::error, "shiftNegative", "Shifting by a negative value is undefined behaviour", CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for incompletely filled buffers.
//---------------------------------------------------------------------------
void CheckOther::checkIncompleteArrayFill()
{
if (!mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
const bool printPortability = mSettings->severity.isEnabled(Severity::portability);
if (!printPortability && !printWarning)
return;
logChecker("CheckOther::checkIncompleteArrayFill"); // warning,portability,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "memset|memcpy|memmove (") && Token::Match(tok->linkAt(1)->tokAt(-2), ", %num% )")) {
const Token* tok2 = tok->tokAt(2);
if (tok2->str() == "::")
tok2 = tok2->next();
while (Token::Match(tok2, "%name% ::|."))
tok2 = tok2->tokAt(2);
if (!Token::Match(tok2, "%var% ,"))
continue;
const Variable *var = tok2->variable();
if (!var || !var->isArray() || var->dimensions().empty() || !var->dimension(0))
continue;
if (MathLib::toBigNumber(tok->linkAt(1)->strAt(-1)) == var->dimension(0)) {
int size = mTokenizer->sizeOfType(var->typeStartToken());
if (size == 0 && var->valueType()->pointer)
size = mSettings->platform.sizeof_pointer;
else if (size == 0 && var->valueType())
size = ValueFlow::getSizeOf(*var->valueType(), *mSettings);
const Token* tok3 = tok->next()->astOperand2()->astOperand1()->astOperand1();
if ((size != 1 && size != 100 && size != 0) || var->isPointer()) {
if (printWarning)
incompleteArrayFillError(tok, tok3->expressionString(), tok->str(), false);
} else if (var->valueType()->type == ValueType::Type::BOOL && printPortability) // sizeof(bool) is not 1 on all platforms
incompleteArrayFillError(tok, tok3->expressionString(), tok->str(), true);
}
}
}
}
}
void CheckOther::incompleteArrayFillError(const Token* tok, const std::string& buffer, const std::string& function, bool boolean)
{
if (boolean)
reportError(tok, Severity::portability, "incompleteArrayFill",
"$symbol:" + buffer + "\n"
"$symbol:" + function + "\n"
"Array '" + buffer + "' might be filled incompletely. Did you forget to multiply the size given to '" + function + "()' with 'sizeof(*" + buffer + ")'?\n"
"The array '" + buffer + "' is filled incompletely. The function '" + function + "()' needs the size given in bytes, but the type 'bool' is larger than 1 on some platforms. Did you forget to multiply the size with 'sizeof(*" + buffer + ")'?", CWE131, Certainty::inconclusive);
else
reportError(tok, Severity::warning, "incompleteArrayFill",
"$symbol:" + buffer + "\n"
"$symbol:" + function + "\n"
"Array '" + buffer + "' is filled incompletely. Did you forget to multiply the size given to '" + function + "()' with 'sizeof(*" + buffer + ")'?\n"
"The array '" + buffer + "' is filled incompletely. The function '" + function + "()' needs the size given in bytes, but an element of the given array is larger than one byte. Did you forget to multiply the size with 'sizeof(*" + buffer + ")'?", CWE131, Certainty::inconclusive);
}
//---------------------------------------------------------------------------
// Detect NULL being passed to variadic function.
//---------------------------------------------------------------------------
void CheckOther::checkVarFuncNullUB()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("CheckOther::checkVarFuncNullUB"); // portability
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
// Is NULL passed to a function?
if (Token::Match(tok,"[(,] NULL [,)]")) {
// Locate function name in this function call.
const Token *ftok = tok;
int argnr = 1;
while (ftok && ftok->str() != "(") {
if (ftok->str() == ")")
ftok = ftok->link();
else if (ftok->str() == ",")
++argnr;
ftok = ftok->previous();
}
ftok = ftok ? ftok->previous() : nullptr;
if (ftok && ftok->isName()) {
// If this is a variadic function then report error
const Function *f = ftok->function();
if (f && f->argCount() <= argnr) {
const Token *tok2 = f->argDef;
tok2 = tok2 ? tok2->link() : nullptr; // goto ')'
if (tok2 && Token::simpleMatch(tok2->tokAt(-1), "..."))
varFuncNullUBError(tok);
}
}
}
}
}
}
void CheckOther::varFuncNullUBError(const Token *tok)
{
reportError(tok,
Severity::portability,
"varFuncNullUB",
"Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.\n"
"Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.\n"
"The C99 standard, in section 7.15.1.1, states that if the type used by va_arg() is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined.\n"
"The value of the NULL macro is an implementation-defined null pointer constant (7.17), which can be any integer constant expression with the value 0, or such an expression casted to (void*) (6.3.2.3). This includes values like 0, 0L, or even 0LL.\n"
"In practice on common architectures, this will cause real crashes if sizeof(int) != sizeof(void*), and NULL is defined to 0 or any other null pointer constant that promotes to int.\n"
"To reproduce you might be able to use this little code example on 64bit platforms. If the output includes \"ERROR\", the sentinel had only 4 out of 8 bytes initialized to zero and was not detected as the final argument to stop argument processing via va_arg(). Changing the 0 to (void*)0 or 0L will make the \"ERROR\" output go away.\n"
"#include <stdarg.h>\n"
"#include <stdio.h>\n"
"\n"
"void f(char *s, ...) {\n"
" va_list ap;\n"
" va_start(ap,s);\n"
" for (;;) {\n"
" char *p = va_arg(ap,char*);\n"
" printf(\"%018p, %s\\n\", p, (long)p & 255 ? p : \"\");\n"
" if(!p) break;\n"
" }\n"
" va_end(ap);\n"
"}\n"
"\n"
"void g() {\n"
" char *s2 = \"x\";\n"
" char *s3 = \"ERROR\";\n"
"\n"
" // changing 0 to 0L for the 7th argument (which is intended to act as sentinel) makes the error go away on x86_64\n"
" f(\"first\", s2, s2, s2, s2, s2, 0, s3, (char*)0);\n"
"}\n"
"\n"
"void h() {\n"
" int i;\n"
" volatile unsigned char a[1000];\n"
" for (i = 0; i<sizeof(a); i++)\n"
" a[i] = -1;\n"
"}\n"
"\n"
"int main() {\n"
" h();\n"
" g();\n"
" return 0;\n"
"}", CWE475, Certainty::normal);
}
void CheckOther::checkRedundantPointerOp()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("redundantPointerOp"))
return;
logChecker("CheckOther::checkRedundantPointerOp"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->isExpandedMacro() && tok->str() == "(")
tok = tok->link();
bool addressOfDeref{};
if (tok->isUnaryOp("&") && tok->astOperand1()->isUnaryOp("*"))
addressOfDeref = true;
else if (tok->isUnaryOp("*") && tok->astOperand1()->isUnaryOp("&"))
addressOfDeref = false;
else
continue;
// variable
const Token *varTok = tok->astOperand1()->astOperand1();
if (!varTok || varTok->isExpandedMacro())
continue;
if (!addressOfDeref) { // dereference of address
if (tok->isExpandedMacro())
continue;
if (varTok->valueType() && varTok->valueType()->pointer && varTok->valueType()->reference == Reference::LValue)
continue;
}
const Variable *var = varTok->variable();
if (!var || (addressOfDeref && !var->isPointer()))
continue;
redundantPointerOpError(tok, var->name(), false, addressOfDeref);
}
}
void CheckOther::redundantPointerOpError(const Token* tok, const std::string &varname, bool inconclusive, bool addressOfDeref)
{
std::string msg = "$symbol:" + varname + "\nRedundant pointer operation on '$symbol' - it's already a ";
msg += addressOfDeref ? "pointer." : "variable.";
reportError(tok, Severity::style, "redundantPointerOp", msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::checkInterlockedDecrement()
{
if (!mSettings->platform.isWindows()) {
return;
}
logChecker("CheckOther::checkInterlockedDecrement"); // windows-platform
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->isName() && Token::Match(tok, "InterlockedDecrement ( & %name% ) ; if ( %name%|!|0")) {
const Token* interlockedVarTok = tok->tokAt(3);
const Token* checkStartTok = interlockedVarTok->tokAt(5);
if ((Token::Match(checkStartTok, "0 %comp% %name% )") && checkStartTok->strAt(2) == interlockedVarTok->str()) ||
(Token::Match(checkStartTok, "! %name% )") && checkStartTok->strAt(1) == interlockedVarTok->str()) ||
(Token::Match(checkStartTok, "%name% )") && checkStartTok->str() == interlockedVarTok->str()) ||
(Token::Match(checkStartTok, "%name% %comp% 0 )") && checkStartTok->str() == interlockedVarTok->str())) {
raceAfterInterlockedDecrementError(checkStartTok);
}
} else if (Token::Match(tok, "if ( ::| InterlockedDecrement ( & %name%")) {
const Token* condEnd = tok->linkAt(1);
const Token* funcTok = tok->tokAt(2);
const Token* firstAccessTok = funcTok->str() == "::" ? funcTok->tokAt(4) : funcTok->tokAt(3);
if (condEnd && condEnd->next() && condEnd->linkAt(1)) {
const Token* ifEndTok = condEnd->linkAt(1);
if (Token::Match(ifEndTok, "} return %name%")) {
const Token* secondAccessTok = ifEndTok->tokAt(2);
if (secondAccessTok->str() == firstAccessTok->str()) {
raceAfterInterlockedDecrementError(secondAccessTok);
}
} else if (Token::Match(ifEndTok, "} else { return %name%")) {
const Token* secondAccessTok = ifEndTok->tokAt(4);
if (secondAccessTok->str() == firstAccessTok->str()) {
raceAfterInterlockedDecrementError(secondAccessTok);
}
}
}
}
}
}
void CheckOther::raceAfterInterlockedDecrementError(const Token* tok)
{
reportError(tok, Severity::error, "raceAfterInterlockedDecrement",
"Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.", CWE362, Certainty::normal);
}
void CheckOther::checkUnusedLabel()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("unusedLabel"))
return;
logChecker("CheckOther::checkUnusedLabel"); // style,warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const bool hasIfdef = mTokenizer->hasIfdef(scope->bodyStart, scope->bodyEnd);
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->scope()->isExecutable())
tok = tok->scope()->bodyEnd;
if (Token::Match(tok, "{|}|; %name% :") && !tok->tokAt(1)->isKeyword()) {
const std::string tmp("goto " + tok->strAt(1));
if (!Token::findsimplematch(scope->bodyStart->next(), tmp.c_str(), tmp.size(), scope->bodyEnd->previous()) && !tok->next()->isExpandedMacro())
unusedLabelError(tok->next(), tok->next()->scope()->type == Scope::eSwitch, hasIfdef);
}
}
}
}
void CheckOther::unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef)
{
if (tok && !mSettings->severity.isEnabled(inSwitch ? Severity::warning : Severity::style))
return;
std::string id = "unusedLabel";
if (inSwitch)
id += "Switch";
if (hasIfdef)
id += "Configuration";
std::string msg = "$symbol:" + (tok ? tok->str() : emptyString) + "\nLabel '$symbol' is not used.";
if (hasIfdef)
msg += " There is #if in function body so the label might be used in code that is removed by the preprocessor.";
if (inSwitch)
msg += " Should this be a 'case' of the enclosing switch()?";
reportError(tok,
inSwitch ? Severity::warning : Severity::style,
id,
msg,
CWE398,
Certainty::normal);
}
static bool checkEvaluationOrderC(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings, bool & selfAssignmentError)
{
// self assignment..
if (tok2 == tok && tok->str() == "=" && parent->str() == "=" && isSameExpression(false, tok->astOperand1(), parent->astOperand1(), settings, true, false)) {
if (settings.severity.isEnabled(Severity::warning) && isSameExpression(true, tok->astOperand1(), parent->astOperand1(), settings, true, false))
selfAssignmentError = true;
return false;
}
// Is expression used?
bool foundError = false;
visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) {
if (tok3->str() == "&" && !tok3->astOperand2())
return ChildrenToVisit::none; // don't handle address-of for now
if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof"))
return ChildrenToVisit::none; // don't care about sizeof usage
if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false))
foundError = true;
return foundError ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
return foundError;
}
static bool checkEvaluationOrderCpp11(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings)
{
if (tok->isAssignmentOp()) // TODO check assignment
return false;
if (tok->previous() == tok->astOperand1() && parent->isArithmeticalOp() && parent->isBinaryOp()) {
if (parent->astParent() && parent->astParent()->isAssignmentOp() && isSameExpression(false, tok->astOperand1(), parent->astParent()->astOperand1(), settings, true, false))
return true;
}
bool foundUndefined{false};
visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) {
if (tok3->str() == "&" && !tok3->astOperand2())
return ChildrenToVisit::none; // don't handle address-of for now
if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof"))
return ChildrenToVisit::none; // don't care about sizeof usage
if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false))
foundUndefined = true;
return foundUndefined ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
return foundUndefined;
}
static bool checkEvaluationOrderCpp17(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings, bool & foundUnspecified)
{
if (tok->isAssignmentOp())
return false;
bool foundUndefined{false};
visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) {
if (tok3->str() == "&" && !tok3->astOperand2())
return ChildrenToVisit::none; // don't handle address-of for now
if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof"))
return ChildrenToVisit::none; // don't care about sizeof usage
if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false) && parent->isArithmeticalOp() && parent->isBinaryOp())
foundUndefined = true;
if (tok3->tokType() == Token::eIncDecOp && isSameExpression(false, tok->astOperand1(), tok3->astOperand1(), settings, true, false)) {
if (parent->isArithmeticalOp() && parent->isBinaryOp())
foundUndefined = true;
else
foundUnspecified = true;
}
return (foundUndefined || foundUnspecified) ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
return foundUndefined || foundUnspecified;
}
void CheckOther::checkEvaluationOrder()
{
logChecker("CheckOther::checkEvaluationOrder");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * functionScope : symbolDatabase->functionScopes) {
for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!tok->isIncDecOp() && !tok->isAssignmentOp())
continue;
if (!tok->astOperand1())
continue;
for (const Token *tok2 = tok;; tok2 = tok2->astParent()) {
// If ast parent is a sequence point then break
const Token * const parent = tok2->astParent();
if (!parent)
break;
if (Token::Match(parent, "%oror%|&&|?|:|;"))
break;
if (parent->str() == ",") {
const Token *par = parent;
while (Token::simpleMatch(par,","))
par = par->astParent();
// not function or in a while clause => break
if (!(par && par->str() == "(" && par->astOperand2() && par->strAt(-1) != "while"))
break;
// control flow (if|while|etc) => break
if (Token::simpleMatch(par->link(),") {"))
break;
// sequence point in function argument: dostuff((1,2),3) => break
par = par->next();
while (par && (par->previous() != parent))
par = par->nextArgument();
if (!par)
break;
}
if (parent->str() == "(" && parent->astOperand2())
break;
bool foundError{false}, foundUnspecified{false}, bSelfAssignmentError{false};
if (mTokenizer->isCPP() && mSettings->standards.cpp >= Standards::CPP11) {
if (mSettings->standards.cpp >= Standards::CPP17)
foundError = checkEvaluationOrderCpp17(tok, tok2, parent, *mSettings, foundUnspecified);
else
foundError = checkEvaluationOrderCpp11(tok, tok2, parent, *mSettings);
}
else
foundError = checkEvaluationOrderC(tok, tok2, parent, *mSettings, bSelfAssignmentError);
if (foundError) {
unknownEvaluationOrder(parent, foundUnspecified);
break;
}
if (bSelfAssignmentError) {
selfAssignmentError(parent, tok->astOperand1()->expressionString());
break;
}
}
}
}
}
void CheckOther::unknownEvaluationOrder(const Token* tok, bool isUnspecifiedBehavior)
{
isUnspecifiedBehavior ?
reportError(tok, Severity::portability, "unknownEvaluationOrder",
"Expression '" + (tok ? tok->expressionString() : std::string("x++, x++")) + "' depends on order of evaluation of side effects. Behavior is Unspecified according to c++17", CWE768, Certainty::normal)
: reportError(tok, Severity::error, "unknownEvaluationOrder",
"Expression '" + (tok ? tok->expressionString() : std::string("x = x++;")) + "' depends on order of evaluation of side effects", CWE768, Certainty::normal);
}
void CheckOther::checkAccessOfMovedVariable()
{
if (!mTokenizer->isCPP() || mSettings->standards.cpp < Standards::CPP11)
return;
if (!mSettings->isPremiumEnabled("accessMoved") && !mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckOther::checkAccessOfMovedVariable"); // c++11,warning
const bool reportInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
const Token * scopeStart = scope->bodyStart;
if (scope->function) {
const Token * memberInitializationStart = scope->function->constructorMemberInitialization();
if (memberInitializationStart)
scopeStart = memberInitializationStart;
}
for (const Token* tok = scopeStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->astParent())
continue;
const ValueFlow::Value * movedValue = tok->getMovedValue();
if (!movedValue || movedValue->moveKind == ValueFlow::Value::MoveKind::NonMovedVariable)
continue;
if (movedValue->isInconclusive() && !reportInconclusive)
continue;
bool inconclusive = false;
bool accessOfMoved = false;
if (tok->strAt(1) == ".") {
if (tok->next()->originalName() == "->")
accessOfMoved = true;
else
inconclusive = true;
} else {
const ExprUsage usage = getExprUsage(tok, 0, *mSettings);
if (usage == ExprUsage::Used)
accessOfMoved = true;
if (usage == ExprUsage::PassedByReference)
accessOfMoved = !isVariableChangedByFunctionCall(tok, 0, *mSettings, &inconclusive);
else if (usage == ExprUsage::Inconclusive)
inconclusive = true;
}
if (accessOfMoved || (inconclusive && reportInconclusive))
accessMovedError(tok, tok->str(), movedValue, inconclusive || movedValue->isInconclusive());
}
}
}
void CheckOther::accessMovedError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive)
{
if (!tok) {
reportError(tok, Severity::warning, "accessMoved", "Access of moved variable 'v'.", CWE672, Certainty::normal);
reportError(tok, Severity::warning, "accessForwarded", "Access of forwarded variable 'v'.", CWE672, Certainty::normal);
return;
}
const char * errorId = nullptr;
std::string kindString;
switch (value->moveKind) {
case ValueFlow::Value::MoveKind::MovedVariable:
errorId = "accessMoved";
kindString = "moved";
break;
case ValueFlow::Value::MoveKind::ForwardedVariable:
errorId = "accessForwarded";
kindString = "forwarded";
break;
default:
return;
}
const std::string errmsg("$symbol:" + varname + "\nAccess of " + kindString + " variable '$symbol'.");
const ErrorPath errorPath = getErrorPath(tok, value, errmsg);
reportError(errorPath, Severity::warning, errorId, errmsg, CWE672, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckOther::checkFuncArgNamesDifferent()
{
const bool style = mSettings->severity.isEnabled(Severity::style);
const bool inconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const bool warning = mSettings->severity.isEnabled(Severity::warning);
if (!(warning || (style && inconclusive)) && !mSettings->isPremiumEnabled("funcArgNamesDifferent"))
return;
logChecker("CheckOther::checkFuncArgNamesDifferent"); // style,warning,inconclusive
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// check every function
for (const Scope *scope : symbolDatabase->functionScopes) {
const Function * function = scope->function;
// only check functions with arguments
if (!function || function->argCount() == 0)
continue;
// only check functions with separate declarations and definitions
if (function->argDef == function->arg)
continue;
// get the function argument name tokens
std::vector<const Token *> declarations(function->argCount());
std::vector<const Token *> definitions(function->argCount());
const Token * decl = function->argDef->next();
for (int j = 0; j < function->argCount(); ++j) {
declarations[j] = nullptr;
definitions[j] = nullptr;
// get the definition
const Variable * variable = function->getArgumentVar(j);
if (variable) {
definitions[j] = variable->nameToken();
}
// get the declaration (search for first token with varId)
while (decl && !Token::Match(decl, ",|)|;")) {
// skip everything after the assignment because
// it could also have a varId or be the first
// token with a varId if there is no name token
if (decl->str() == "=") {
decl = decl->nextArgument();
break;
}
// skip over template
if (decl->link())
decl = decl->link();
else if (decl->varId())
declarations[j] = decl;
decl = decl->next();
}
if (Token::simpleMatch(decl, ","))
decl = decl->next();
}
// check for different argument order
if (warning) {
bool order_different = false;
for (int j = 0; j < function->argCount(); ++j) {
if (!declarations[j] || !definitions[j] || declarations[j]->str() == definitions[j]->str())
continue;
for (int k = 0; k < function->argCount(); ++k) {
if (j != k && definitions[k] && declarations[j]->str() == definitions[k]->str()) {
order_different = true;
break;
}
}
}
if (order_different) {
funcArgOrderDifferent(function->name(), function->argDef->next(), function->arg->next(), declarations, definitions);
continue;
}
}
// check for different argument names
if (style && inconclusive) {
for (int j = 0; j < function->argCount(); ++j) {
if (declarations[j] && definitions[j] && declarations[j]->str() != definitions[j]->str())
funcArgNamesDifferent(function->name(), j, declarations[j], definitions[j]);
}
}
}
}
void CheckOther::funcArgNamesDifferent(const std::string & functionName, nonneg int index,
const Token* declaration, const Token* definition)
{
std::list<const Token *> tokens = { declaration,definition };
reportError(tokens, Severity::style, "funcArgNamesDifferent",
"$symbol:" + functionName + "\n"
"Function '$symbol' argument " + std::to_string(index + 1) + " names different: declaration '" +
(declaration ? declaration->str() : std::string("A")) + "' definition '" +
(definition ? definition->str() : std::string("B")) + "'.", CWE628, Certainty::inconclusive);
}
void CheckOther::funcArgOrderDifferent(const std::string & functionName,
const Token* declaration, const Token* definition,
const std::vector<const Token *> & declarations,
const std::vector<const Token *> & definitions)
{
std::list<const Token *> tokens = {
!declarations.empty() ? declarations[0] ? declarations[0] : declaration : nullptr,
!definitions.empty() ? definitions[0] ? definitions[0] : definition : nullptr
};
std::string msg = "$symbol:" + functionName + "\nFunction '$symbol' argument order different: declaration '";
for (std::size_t i = 0; i < declarations.size(); ++i) {
if (i != 0)
msg += ", ";
if (declarations[i])
msg += declarations[i]->str();
}
msg += "' definition '";
for (std::size_t i = 0; i < definitions.size(); ++i) {
if (i != 0)
msg += ", ";
if (definitions[i])
msg += definitions[i]->str();
}
msg += "'";
reportError(tokens, Severity::warning, "funcArgOrderDifferent", msg, CWE683, Certainty::normal);
}
static const Token *findShadowed(const Scope *scope, const Variable& var, int linenr)
{
if (!scope)
return nullptr;
for (const Variable &v : scope->varlist) {
if (scope->isExecutable() && v.nameToken()->linenr() > linenr)
continue;
if (v.name() == var.name())
return v.nameToken();
}
auto it = std::find_if(scope->functionList.cbegin(), scope->functionList.cend(), [&](const Function& f) {
return f.type == Function::Type::eFunction && f.name() == var.name() && precedes(f.tokenDef, var.nameToken());
});
if (it != scope->functionList.end())
return it->tokenDef;
if (scope->type == Scope::eLambda)
return nullptr;
const Token* shadowed = findShadowed(scope->nestedIn, var, linenr);
if (!shadowed)
shadowed = findShadowed(scope->functionOf, var, linenr);
return shadowed;
}
void CheckOther::checkShadowVariables()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("shadowVariable"))
return;
logChecker("CheckOther::checkShadowVariables"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope & scope : symbolDatabase->scopeList) {
if (!scope.isExecutable() || scope.type == Scope::eLambda)
continue;
const Scope *functionScope = &scope;
while (functionScope && functionScope->type != Scope::ScopeType::eFunction && functionScope->type != Scope::ScopeType::eLambda)
functionScope = functionScope->nestedIn;
for (const Variable &var : scope.varlist) {
if (var.nameToken() && var.nameToken()->isExpandedMacro()) // #8903
continue;
if (functionScope && functionScope->type == Scope::ScopeType::eFunction && functionScope->function) {
const auto & argList = functionScope->function->argumentList;
auto it = std::find_if(argList.cbegin(), argList.cend(), [&](const Variable& arg) {
return arg.nameToken() && var.name() == arg.name();
});
if (it != argList.end()) {
shadowError(var.nameToken(), it->nameToken(), "argument");
continue;
}
}
const Token *shadowed = findShadowed(scope.nestedIn, var, var.nameToken()->linenr());
if (!shadowed)
shadowed = findShadowed(scope.functionOf, var, var.nameToken()->linenr());
if (!shadowed)
continue;
if (scope.type == Scope::eFunction && scope.className == var.name())
continue;
if (functionScope->functionOf && functionScope->functionOf->isClassOrStructOrUnion() && functionScope->function && functionScope->function->isStatic() &&
shadowed->variable() && !shadowed->variable()->isLocal())
continue;
shadowError(var.nameToken(), shadowed, (shadowed->varId() != 0) ? "variable" : "function");
}
}
}
void CheckOther::shadowError(const Token *var, const Token *shadowed, const std::string& type)
{
ErrorPath errorPath;
errorPath.emplace_back(shadowed, "Shadowed declaration");
errorPath.emplace_back(var, "Shadow variable");
const std::string &varname = var ? var->str() : type;
const std::string Type = char(std::toupper(type[0])) + type.substr(1);
const std::string id = "shadow" + Type;
const std::string message = "$symbol:" + varname + "\nLocal variable \'$symbol\' shadows outer " + type;
reportError(errorPath, Severity::style, id.c_str(), message, CWE398, Certainty::normal);
}
static bool isVariableExpression(const Token* tok)
{
if (tok->varId() != 0)
return true;
if (Token::simpleMatch(tok, "."))
return isVariableExpression(tok->astOperand1()) &&
isVariableExpression(tok->astOperand2());
if (Token::simpleMatch(tok, "["))
return isVariableExpression(tok->astOperand1());
return false;
}
static bool isVariableExprHidden(const Token* tok)
{
if (!tok)
return false;
if (!tok->astParent())
return false;
if (Token::simpleMatch(tok->astParent(), "*") && Token::simpleMatch(tok->astSibling(), "0"))
return true;
if (Token::simpleMatch(tok->astParent(), "&&") && Token::simpleMatch(tok->astSibling(), "false"))
return true;
if (Token::simpleMatch(tok->astParent(), "||") && Token::simpleMatch(tok->astSibling(), "true"))
return true;
return false;
}
void CheckOther::checkKnownArgument()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownArgument"))
return;
logChecker("CheckOther::checkKnownArgument"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *functionScope : symbolDatabase->functionScopes) {
for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!tok->hasKnownIntValue() || tok->isExpandedMacro())
continue;
if (Token::Match(tok, "++|--|%assign%"))
continue;
if (!Token::Match(tok->astParent(), "(|{|,"))
continue;
if (tok->astParent()->isCast() || (tok->isCast() && Token::Match(tok->astOperand2(), "++|--|%assign%")))
continue;
int argn = -1;
const Token* ftok = getTokenArgumentFunction(tok, argn);
if (!ftok)
continue;
if (ftok->isCast())
continue;
if (Token::Match(ftok, "if|while|switch|sizeof"))
continue;
if (tok == tok->astParent()->previous())
continue;
if (isConstVarExpression(tok))
continue;
if (Token::Match(tok->astOperand1(), "%name% ("))
continue;
const Token * tok2 = tok;
if (isCPPCast(tok2))
tok2 = tok2->astOperand2();
if (isVariableExpression(tok2))
continue;
if (tok->isComparisonOp() &&
isSameExpression(
true, tok->astOperand1(), tok->astOperand2(), *mSettings, true, true))
continue;
// ensure that there is a integer variable in expression with unknown value
const Token* vartok = nullptr;
visitAstNodes(tok, [&](const Token* child) {
if (Token::Match(child, "%var%|.|[")) {
if (child->hasKnownIntValue())
return ChildrenToVisit::none;
if (astIsIntegral(child, false) && !astIsPointer(child) && child->values().empty()) {
vartok = child;
return ChildrenToVisit::done;
}
}
return ChildrenToVisit::op1_and_op2;
});
if (!vartok)
continue;
if (vartok->astSibling() &&
findAstNode(vartok->astSibling(), [](const Token* child) {
return Token::simpleMatch(child, "sizeof");
}))
continue;
// ensure that function name does not contain "assert"
std::string funcname = ftok->str();
strTolower(funcname);
if (funcname.find("assert") != std::string::npos)
continue;
knownArgumentError(tok, ftok, &tok->values().front(), vartok->expressionString(), isVariableExprHidden(vartok));
}
}
}
void CheckOther::knownArgumentError(const Token *tok, const Token *ftok, const ValueFlow::Value *value, const std::string &varexpr, bool isVariableExpressionHidden)
{
if (!tok) {
reportError(tok, Severity::style, "knownArgument", "Argument 'x-x' to function 'func' is always 0. It does not matter what value 'x' has.");
reportError(tok, Severity::style, "knownArgumentHiddenVariableExpression", "Argument 'x*0' to function 'func' is always 0. Constant literal calculation disable/hide variable expression 'x'.");
return;
}
const MathLib::bigint intvalue = value->intvalue;
const std::string &expr = tok->expressionString();
const std::string &fun = ftok->str();
std::string ftype = "function ";
if (ftok->type())
ftype = "constructor ";
else if (fun == "{")
ftype = "init list ";
const char *id;
std::string errmsg = "Argument '" + expr + "' to " + ftype + fun + " is always " + std::to_string(intvalue) + ". ";
if (!isVariableExpressionHidden) {
id = "knownArgument";
errmsg += "It does not matter what value '" + varexpr + "' has.";
} else {
id = "knownArgumentHiddenVariableExpression";
errmsg += "Constant literal calculation disable/hide variable expression '" + varexpr + "'.";
}
const ErrorPath errorPath = getErrorPath(tok, value, errmsg);
reportError(errorPath, Severity::style, id, errmsg, CWE570, Certainty::normal);
}
void CheckOther::checkKnownPointerToBool()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownPointerToBool"))
return;
logChecker("CheckOther::checkKnownPointerToBool"); // style
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope* functionScope : symbolDatabase->functionScopes) {
for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!tok->hasKnownIntValue())
continue;
if (!astIsPointer(tok))
continue;
if (Token::Match(tok->astParent(), "?|!|&&|%oror%|%comp%"))
continue;
if (tok->astParent() && Token::Match(tok->astParent()->previous(), "if|while|switch|sizeof ("))
continue;
if (tok->isExpandedMacro())
continue;
if (findParent(tok, [](const Token* parent) {
return parent->isExpandedMacro();
}))
continue;
if (!isUsedAsBool(tok, *mSettings))
continue;
const ValueFlow::Value& value = tok->values().front();
knownPointerToBoolError(tok, &value);
}
}
}
void CheckOther::knownPointerToBoolError(const Token* tok, const ValueFlow::Value* value)
{
if (!tok) {
reportError(tok, Severity::style, "knownPointerToBool", "Pointer expression 'p' converted to bool is always true.");
return;
}
std::string cond = bool_to_string(value->intvalue);
const std::string& expr = tok->expressionString();
std::string errmsg = "Pointer expression '" + expr + "' converted to bool is always " + cond + ".";
const ErrorPath errorPath = getErrorPath(tok, value, errmsg);
reportError(errorPath, Severity::style, "knownPointerToBool", errmsg, CWE570, Certainty::normal);
}
void CheckOther::checkComparePointers()
{
logChecker("CheckOther::checkComparePointers");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *functionScope : symbolDatabase->functionScopes) {
for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "<|>|<=|>=|-"))
continue;
const Token *tok1 = tok->astOperand1();
const Token *tok2 = tok->astOperand2();
if (!astIsPointer(tok1) || !astIsPointer(tok2))
continue;
ValueFlow::Value v1 = ValueFlow::getLifetimeObjValue(tok1);
ValueFlow::Value v2 = ValueFlow::getLifetimeObjValue(tok2);
if (!v1.isLocalLifetimeValue() || !v2.isLocalLifetimeValue())
continue;
const Variable *var1 = v1.tokvalue->variable();
const Variable *var2 = v2.tokvalue->variable();
if (!var1 || !var2)
continue;
if (v1.tokvalue->varId() == v2.tokvalue->varId())
continue;
if (var1->isReference() || var2->isReference())
continue;
if (var1->isRValueReference() || var2->isRValueReference())
continue;
if (const Token* parent2 = getParentLifetime(v2.tokvalue, mSettings->library))
if (var1 == parent2->variable())
continue;
if (const Token* parent1 = getParentLifetime(v1.tokvalue, mSettings->library))
if (var2 == parent1->variable())
continue;
comparePointersError(tok, &v1, &v2);
}
}
}
void CheckOther::comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2)
{
ErrorPath errorPath;
std::string verb = "Comparing";
if (Token::simpleMatch(tok, "-"))
verb = "Subtracting";
const char * const id = (verb[0] == 'C') ? "comparePointers" : "subtractPointers";
if (v1) {
errorPath.emplace_back(v1->tokvalue->variable()->nameToken(), "Variable declared here.");
errorPath.insert(errorPath.end(), v1->errorPath.cbegin(), v1->errorPath.cend());
}
if (v2) {
errorPath.emplace_back(v2->tokvalue->variable()->nameToken(), "Variable declared here.");
errorPath.insert(errorPath.end(), v2->errorPath.cbegin(), v2->errorPath.cend());
}
errorPath.emplace_back(tok, "");
reportError(
errorPath, Severity::error, id, verb + " pointers that point to different objects", CWE570, Certainty::normal);
}
void CheckOther::checkModuloOfOne()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("moduloofone"))
return;
logChecker("CheckOther::checkModuloOfOne"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->astOperand2() || !tok->astOperand1())
continue;
if (tok->str() != "%")
continue;
if (!tok->valueType() || !tok->valueType()->isIntegral())
continue;
// Value flow..
const ValueFlow::Value *value = tok->astOperand2()->getValue(1LL);
if (value && value->isKnown())
checkModuloOfOneError(tok);
}
}
void CheckOther::checkModuloOfOneError(const Token *tok)
{
reportError(tok, Severity::style, "moduloofone", "Modulo of one is always equal to zero");
}
//-----------------------------------------------------------------------------
// Overlapping write (undefined behavior)
//-----------------------------------------------------------------------------
static bool getBufAndOffset(const Token *expr, const Token *&buf, MathLib::bigint *offset, const Settings& settings, MathLib::bigint* sizeValue = nullptr)
{
if (!expr)
return false;
const Token *bufToken, *offsetToken;
MathLib::bigint elementSize = 0;
if (expr->isUnaryOp("&") && Token::simpleMatch(expr->astOperand1(), "[")) {
bufToken = expr->astOperand1()->astOperand1();
offsetToken = expr->astOperand1()->astOperand2();
if (expr->astOperand1()->valueType())
elementSize = ValueFlow::getSizeOf(*expr->astOperand1()->valueType(), settings);
} else if (Token::Match(expr, "+|-") && expr->isBinaryOp()) {
const bool pointer1 = (expr->astOperand1()->valueType() && expr->astOperand1()->valueType()->pointer > 0);
const bool pointer2 = (expr->astOperand2()->valueType() && expr->astOperand2()->valueType()->pointer > 0);
if (pointer1 && !pointer2) {
bufToken = expr->astOperand1();
offsetToken = expr->astOperand2();
auto vt = *expr->astOperand1()->valueType();
--vt.pointer;
elementSize = ValueFlow::getSizeOf(vt, settings);
} else if (!pointer1 && pointer2) {
bufToken = expr->astOperand2();
offsetToken = expr->astOperand1();
auto vt = *expr->astOperand2()->valueType();
--vt.pointer;
elementSize = ValueFlow::getSizeOf(vt, settings);
} else {
return false;
}
} else if (expr->valueType() && expr->valueType()->pointer > 0) {
buf = expr;
*offset = 0;
auto vt = *expr->valueType();
--vt.pointer;
elementSize = ValueFlow::getSizeOf(vt, settings);
if (elementSize > 0) {
*offset *= elementSize;
if (sizeValue)
*sizeValue *= elementSize;
}
return true;
} else {
return false;
}
if (!bufToken->valueType() || !bufToken->valueType()->pointer)
return false;
if (!offsetToken->hasKnownIntValue())
return false;
buf = bufToken;
*offset = offsetToken->getKnownIntValue();
if (elementSize > 0) {
*offset *= elementSize;
if (sizeValue)
*sizeValue *= elementSize;
}
return true;
}
void CheckOther::checkOverlappingWrite()
{
logChecker("CheckOther::checkOverlappingWrite");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *functionScope : symbolDatabase->functionScopes) {
for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) {
if (tok->isAssignmentOp()) {
// check if LHS is a union member..
const Token * const lhs = tok->astOperand1();
if (!Token::simpleMatch(lhs, ".") || !lhs->isBinaryOp())
continue;
const Variable * const lhsvar = lhs->astOperand1()->variable();
if (!lhsvar || !lhsvar->typeScope() || lhsvar->typeScope()->type != Scope::ScopeType::eUnion)
continue;
const Token* const lhsmember = lhs->astOperand2();
if (!lhsmember)
continue;
// Is other union member used in RHS?
const Token *errorToken = nullptr;
visitAstNodes(tok->astOperand2(), [lhsvar, lhsmember, &errorToken](const Token *rhs) {
if (!Token::simpleMatch(rhs, "."))
return ChildrenToVisit::op1_and_op2;
if (!rhs->isBinaryOp() || rhs->astOperand1()->variable() != lhsvar)
return ChildrenToVisit::none;
if (lhsmember->str() == rhs->astOperand2()->str())
return ChildrenToVisit::none;
const Variable* rhsmembervar = rhs->astOperand2()->variable();
const Scope* varscope1 = lhsmember->variable() ? lhsmember->variable()->typeStartToken()->scope() : nullptr;
const Scope* varscope2 = rhsmembervar ? rhsmembervar->typeStartToken()->scope() : nullptr;
if (varscope1 && varscope1 == varscope2 && varscope1 != lhsvar->typeScope())
// lhsmember and rhsmember are declared in same anonymous scope inside union
return ChildrenToVisit::none;
errorToken = rhs->astOperand2();
return ChildrenToVisit::done;
});
if (errorToken)
overlappingWriteUnion(tok);
} else if (Token::Match(tok, "%name% (")) {
const Library::NonOverlappingData *nonOverlappingData = mSettings->library.getNonOverlappingData(tok);
if (!nonOverlappingData)
continue;
const std::vector<const Token *> args = getArguments(tok);
if (nonOverlappingData->ptr1Arg <= 0 || nonOverlappingData->ptr1Arg > args.size())
continue;
if (nonOverlappingData->ptr2Arg <= 0 || nonOverlappingData->ptr2Arg > args.size())
continue;
const Token *ptr1 = args[nonOverlappingData->ptr1Arg - 1];
if (ptr1->hasKnownIntValue() && ptr1->getKnownIntValue() == 0)
continue;
const Token *ptr2 = args[nonOverlappingData->ptr2Arg - 1];
if (ptr2->hasKnownIntValue() && ptr2->getKnownIntValue() == 0)
continue;
// TODO: nonOverlappingData->strlenArg
const int sizeArg = std::max(nonOverlappingData->sizeArg, nonOverlappingData->countArg);
if (sizeArg <= 0 || sizeArg > args.size()) {
if (nonOverlappingData->sizeArg == -1) {
ErrorPath errorPath;
constexpr bool macro = true;
constexpr bool pure = true;
constexpr bool follow = true;
if (!isSameExpression(macro, ptr1, ptr2, *mSettings, pure, follow, &errorPath))
continue;
overlappingWriteFunction(tok);
}
continue;
}
const bool isCountArg = nonOverlappingData->countArg > 0;
if (!args[sizeArg-1]->hasKnownIntValue())
continue;
MathLib::bigint sizeValue = args[sizeArg-1]->getKnownIntValue();
const Token *buf1, *buf2;
MathLib::bigint offset1, offset2;
if (!getBufAndOffset(ptr1, buf1, &offset1, *mSettings, isCountArg ? &sizeValue : nullptr))
continue;
if (!getBufAndOffset(ptr2, buf2, &offset2, *mSettings))
continue;
if (offset1 < offset2 && offset1 + sizeValue <= offset2)
continue;
if (offset2 < offset1 && offset2 + sizeValue <= offset1)
continue;
ErrorPath errorPath;
constexpr bool macro = true;
constexpr bool pure = true;
constexpr bool follow = true;
if (!isSameExpression(macro, buf1, buf2, *mSettings, pure, follow, &errorPath))
continue;
overlappingWriteFunction(tok);
}
}
}
}
void CheckOther::overlappingWriteUnion(const Token *tok)
{
reportError(tok, Severity::error, "overlappingWriteUnion", "Overlapping read/write of union is undefined behavior");
}
void CheckOther::overlappingWriteFunction(const Token *tok)
{
const std::string &funcname = tok ? tok->str() : emptyString;
reportError(tok, Severity::error, "overlappingWriteFunction", "Overlapping read/write in " + funcname + "() is undefined behavior");
}
| null |
846 | cpp | cppcheck | mathlib.cpp | lib/mathlib.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mathlib.h"
#include "errortypes.h"
#include "utils.h"
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <limits>
#include <locale>
#include <sstream>
#include <stdexcept>
#include <numeric>
#include <simplecpp.h>
const int MathLib::bigint_bits = 64;
MathLib::value::value(const std::string &s)
{
if (MathLib::isFloat(s)) {
mType = MathLib::value::Type::FLOAT;
mDoubleValue = MathLib::toDoubleNumber(s);
return;
}
if (!MathLib::isInt(s))
throw InternalError(nullptr, "Invalid value: " + s);
mType = MathLib::value::Type::INT;
mIntValue = MathLib::toBigNumber(s);
if (isIntHex(s) && mIntValue < 0)
mIsUnsigned = true;
// read suffix
if (s.size() >= 2U) {
for (std::size_t i = s.size() - 1U; i > 0U; --i) {
const char c = s[i];
if (c == 'u' || c == 'U')
mIsUnsigned = true;
else if (c == 'l' || c == 'L') {
if (mType == MathLib::value::Type::INT)
mType = MathLib::value::Type::LONG;
else if (mType == MathLib::value::Type::LONG)
mType = MathLib::value::Type::LONGLONG;
} else if (i > 2U && c == '4' && s[i-1] == '6' && s[i-2] == 'i')
mType = MathLib::value::Type::LONGLONG;
}
}
}
std::string MathLib::value::str() const
{
std::ostringstream ostr;
if (mType == MathLib::value::Type::FLOAT) {
if (std::isnan(mDoubleValue))
return "nan.0";
if (std::isinf(mDoubleValue))
return (mDoubleValue > 0) ? "inf.0" : "-inf.0";
ostr.precision(9);
ostr << std::fixed << mDoubleValue;
// remove trailing zeros
std::string ret(ostr.str());
std::string::size_type pos = ret.size() - 1U;
while (ret[pos] == '0')
pos--;
if (ret[pos] == '.')
++pos;
return ret.substr(0, pos+1);
}
if (mIsUnsigned)
ostr << static_cast<biguint>(mIntValue) << "U";
else
ostr << mIntValue;
if (mType == MathLib::value::Type::LONG)
ostr << "L";
else if (mType == MathLib::value::Type::LONGLONG)
ostr << "LL";
return ostr.str();
}
void MathLib::value::promote(const MathLib::value &v)
{
if (isInt() && v.isInt()) {
if (mType < v.mType) {
mType = v.mType;
mIsUnsigned = v.mIsUnsigned;
} else if (mType == v.mType) {
mIsUnsigned |= v.mIsUnsigned;
}
} else if (!isFloat()) {
mIsUnsigned = false;
mDoubleValue = mIntValue;
mType = MathLib::value::Type::FLOAT;
}
}
MathLib::value MathLib::value::calc(char op, const MathLib::value &v1, const MathLib::value &v2)
{
value temp(v1);
temp.promote(v2);
if (temp.isFloat()) {
switch (op) {
case '+':
temp.mDoubleValue += v2.getDoubleValue();
break;
case '-':
temp.mDoubleValue -= v2.getDoubleValue();
break;
case '*':
temp.mDoubleValue *= v2.getDoubleValue();
break;
case '/':
temp.mDoubleValue /= v2.getDoubleValue();
break;
case '%':
case '&':
case '|':
case '^':
throw InternalError(nullptr, "Invalid calculation");
default:
throw InternalError(nullptr, "Unhandled calculation");
}
} else if (temp.mIsUnsigned) {
switch (op) {
case '+':
temp.mIntValue += (unsigned long long)v2.mIntValue;
break;
case '-':
temp.mIntValue -= (unsigned long long)v2.mIntValue;
break;
case '*':
temp.mIntValue *= (unsigned long long)v2.mIntValue;
break;
case '/':
if (v2.mIntValue == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
if (v1.mIntValue == std::numeric_limits<bigint>::min() && std::abs(v2.mIntValue)<=1)
throw InternalError(nullptr, "Internal Error: Division overflow");
temp.mIntValue /= (unsigned long long)v2.mIntValue;
break;
case '%':
if (v2.mIntValue == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
temp.mIntValue %= (unsigned long long)v2.mIntValue;
break;
case '&':
temp.mIntValue &= (unsigned long long)v2.mIntValue;
break;
case '|':
temp.mIntValue |= (unsigned long long)v2.mIntValue;
break;
case '^':
temp.mIntValue ^= (unsigned long long)v2.mIntValue;
break;
default:
throw InternalError(nullptr, "Unhandled calculation");
}
} else {
switch (op) {
case '+':
temp.mIntValue += v2.mIntValue;
break;
case '-':
temp.mIntValue -= v2.mIntValue;
break;
case '*':
temp.mIntValue *= v2.mIntValue;
break;
case '/':
if (v2.mIntValue == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
if (v1.mIntValue == std::numeric_limits<bigint>::min() && std::abs(v2.mIntValue)<=1)
throw InternalError(nullptr, "Internal Error: Division overflow");
temp.mIntValue /= v2.mIntValue;
break;
case '%':
if (v2.mIntValue == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
temp.mIntValue %= v2.mIntValue;
break;
case '&':
temp.mIntValue &= v2.mIntValue;
break;
case '|':
temp.mIntValue |= v2.mIntValue;
break;
case '^':
temp.mIntValue ^= v2.mIntValue;
break;
default:
throw InternalError(nullptr, "Unhandled calculation");
}
}
return temp;
}
int MathLib::value::compare(const MathLib::value &v) const
{
value temp(*this);
temp.promote(v);
if (temp.isFloat()) {
if (temp.mDoubleValue < v.getDoubleValue())
return -1;
if (temp.mDoubleValue > v.getDoubleValue())
return 1;
return 0;
}
if (temp.mIsUnsigned) {
if ((unsigned long long)mIntValue < (unsigned long long)v.mIntValue)
return -1;
if ((unsigned long long)mIntValue > (unsigned long long)v.mIntValue)
return 1;
return 0;
}
if (mIntValue < v.mIntValue)
return -1;
if (mIntValue > v.mIntValue)
return 1;
return 0;
}
MathLib::value MathLib::value::add(int v) const
{
MathLib::value temp(*this);
if (temp.isInt())
temp.mIntValue += v;
else
temp.mDoubleValue += v;
return temp;
}
MathLib::value MathLib::value::shiftLeft(const MathLib::value &v) const
{
if (!isInt() || !v.isInt())
throw InternalError(nullptr, "Shift operand is not integer");
MathLib::value ret(*this);
if (v.mIntValue >= MathLib::bigint_bits) {
return ret;
}
ret.mIntValue <<= v.mIntValue;
return ret;
}
MathLib::value MathLib::value::shiftRight(const MathLib::value &v) const
{
if (!isInt() || !v.isInt())
throw InternalError(nullptr, "Shift operand is not integer");
MathLib::value ret(*this);
if (v.mIntValue >= MathLib::bigint_bits) {
return ret;
}
ret.mIntValue >>= v.mIntValue;
return ret;
}
// TODO: remove handling of non-literal stuff
MathLib::biguint MathLib::toBigUNumber(const std::string & str)
{
// hexadecimal numbers:
if (isIntHex(str)) {
try {
const biguint ret = std::stoull(str, nullptr, 16);
return ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str);
}
}
// octal numbers:
if (isOct(str)) {
try {
const biguint ret = std::stoull(str, nullptr, 8);
return ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str);
}
}
// binary numbers:
if (isBin(str)) {
biguint ret = 0;
for (std::string::size_type i = str[0] == '0'?2:3; i < str.length(); i++) {
if (str[i] != '1' && str[i] != '0')
break;
ret <<= 1;
if (str[i] == '1')
ret |= 1;
}
if (str[0] == '-')
ret = -ret;
return ret;
}
if (isFloat(str)) {
// Things are going to be less precise now: the value can't be represented in the biguint type.
// Use min/max values as an approximation. See #5843
// TODO: bail out when we are out of range?
const double doubleval = toDoubleNumber(str);
if (doubleval > (double)std::numeric_limits<biguint>::max())
return std::numeric_limits<biguint>::max();
// cast to bigint to avoid UBSAN warning about negative double being out-of-range
return static_cast<biguint>(static_cast<bigint>(doubleval));
}
if (isCharLiteral(str))
return simplecpp::characterLiteralToLL(str);
try {
std::size_t idx = 0;
const biguint ret = std::stoull(str, &idx, 10);
if (idx != str.size()) {
const std::string s = str.substr(idx);
if (!isValidIntegerSuffix(s, true))
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: input was not completely consumed: " + str);
}
return ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str);
}
}
unsigned int MathLib::encodeMultiChar(const std::string& str)
{
return std::accumulate(str.cbegin(), str.cend(), uint32_t(), [](uint32_t v, char c) {
return (v << 8) | c;
});
}
// TODO: remove handling of non-literal stuff
MathLib::bigint MathLib::toBigNumber(const std::string & str)
{
// hexadecimal numbers:
if (isIntHex(str)) {
try {
const biguint ret = std::stoull(str, nullptr, 16);
return (bigint)ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str);
}
}
// octal numbers:
if (isOct(str)) {
try {
const biguint ret = std::stoull(str, nullptr, 8);
return ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str);
}
}
// binary numbers:
if (isBin(str)) {
bigint ret = 0;
for (std::string::size_type i = str[0] == '0'?2:3; i < str.length(); i++) {
if (str[i] != '1' && str[i] != '0')
break;
ret <<= 1;
if (str[i] == '1')
ret |= 1;
}
if (str[0] == '-')
ret = -ret;
return ret;
}
if (isFloat(str)) {
// Things are going to be less precise now: the value can't be represented in the bigint type.
// Use min/max values as an approximation. See #5843
// TODO: bail out when we are out of range?
const double doubleval = toDoubleNumber(str);
if (doubleval > (double)std::numeric_limits<bigint>::max())
return std::numeric_limits<bigint>::max();
if (doubleval < (double)std::numeric_limits<bigint>::min())
return std::numeric_limits<bigint>::min();
return static_cast<bigint>(doubleval);
}
if (isCharLiteral(str))
return simplecpp::characterLiteralToLL(str);
try {
std::size_t idx = 0;
const biguint ret = std::stoull(str, &idx, 10);
if (idx != str.size()) {
const std::string s = str.substr(idx);
if (!isValidIntegerSuffix(s, true))
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: input was not completely consumed: " + str);
}
return ret;
} catch (const std::out_of_range& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str);
} catch (const std::invalid_argument& /*e*/) {
throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str);
}
}
// in-place conversion of (sub)string to double. Requires no heap.
static double myStod(const std::string& str, std::string::const_iterator from, std::string::const_iterator to, int base)
{
double result = 0.;
bool positivesign = true;
std::string::const_iterator it;
if ('+' == *from) {
it = from + 1;
} else if ('-' == *from) {
it = from + 1;
positivesign = false;
} else
it = from;
const std::size_t decimalsep = str.find('.', it-str.begin());
int distance;
if (std::string::npos == decimalsep) {
distance = to - it;
} else if (decimalsep > (to - str.begin()))
return 0.; // error handling??
else
distance = int(decimalsep)-(from - str.begin());
auto digitval = [&](char c) {
if ((10 < base) && (c > '9'))
return 10 + std::tolower(c) - 'a';
return c - '0';
};
for (; it!=to; ++it) {
if ('.' == *it)
continue;
--distance;
result += digitval(*it)* std::pow(base, distance);
}
return positivesign ? result : -result;
}
// Assuming a limited support of built-in hexadecimal floats (see C99, C++17) that is a fall-back implementation.
// Performance has been optimized WRT to heap activity, however the calculation part is not optimized.
static double floatHexToDoubleNumber(const std::string& str)
{
const std::size_t p = str.find_first_of("pP",3);
const double factor1 = myStod(str, str.cbegin() + 2, str.cbegin()+p, 16);
const bool suffix = (str.back() == 'f') || (str.back() == 'F') || (str.back() == 'l') || (str.back() == 'L');
const double exponent = myStod(str, str.cbegin() + p + 1, suffix ? str.cend()-1:str.cend(), 10);
const double factor2 = std::pow(2, exponent);
return factor1 * factor2;
}
double MathLib::toDoubleNumber(const std::string &str)
{
if (isCharLiteral(str)) {
try {
return simplecpp::characterLiteralToLL(str);
} catch (const std::exception& e) {
throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: characterLiteralToLL(" + str + ") => " + e.what());
}
}
if (isIntHex(str))
return static_cast<double>(toBigNumber(str));
#ifdef _LIBCPP_VERSION
if (isFloat(str)) // Workaround libc++ bug at https://github.com/llvm/llvm-project/issues/18156
// TODO: handle locale
// TODO: make sure all characters are being consumed
return std::strtod(str.c_str(), nullptr);
#endif
if (isFloatHex(str))
return floatHexToDoubleNumber(str);
// otherwise, convert to double
std::istringstream istr(str);
istr.imbue(std::locale::classic());
double ret;
if (!(istr >> ret))
throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: conversion failed: " + str);
std::string s;
if (istr >> s) {
if (isDecimalFloat(str))
return ret;
if (!isValidIntegerSuffix(s, true))
throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: " + str);
}
return ret;
}
template<> std::string MathLib::toString<double>(double value)
{
std::ostringstream result;
result.precision(12);
result << value;
std::string s = result.str();
if (s == "-0")
return "0.0";
if (s.find_first_of(".e") == std::string::npos)
return s + ".0";
return s;
}
bool MathLib::isFloat(const std::string &str)
{
return isDecimalFloat(str) || isFloatHex(str);
}
bool MathLib::isDecimalFloat(const std::string &str)
{
if (str.empty())
return false;
enum class State : std::uint8_t {
START, BASE_DIGITS1, LEADING_DECIMAL, TRAILING_DECIMAL, BASE_DIGITS2, E, MANTISSA_PLUSMINUS, MANTISSA_DIGITS, SUFFIX_F, SUFFIX_L, SUFFIX_LITERAL_LEADER, SUFFIX_LITERAL
} state = State::START;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case State::START:
if (*it=='.')
state = State::LEADING_DECIMAL;
else if (std::isdigit(static_cast<unsigned char>(*it)))
state = State::BASE_DIGITS1;
else
return false;
break;
case State::LEADING_DECIMAL:
if (std::isdigit(static_cast<unsigned char>(*it)))
state = State::BASE_DIGITS2;
else
return false;
break;
case State::BASE_DIGITS1:
if (*it=='e' || *it=='E')
state = State::E;
else if (*it=='.')
state = State::TRAILING_DECIMAL;
else if (!std::isdigit(static_cast<unsigned char>(*it)))
return false;
break;
case State::TRAILING_DECIMAL:
if (*it=='e' || *it=='E')
state = State::E;
else if (*it=='f' || *it=='F')
state = State::SUFFIX_F;
else if (*it=='l' || *it=='L')
state = State::SUFFIX_L;
else if (*it == '_')
state = State::SUFFIX_LITERAL_LEADER;
else if (std::isdigit(static_cast<unsigned char>(*it)))
state = State::BASE_DIGITS2;
else
return false;
break;
case State::BASE_DIGITS2:
if (*it=='e' || *it=='E')
state = State::E;
else if (*it=='f' || *it=='F')
state = State::SUFFIX_F;
else if (*it=='l' || *it=='L')
state = State::SUFFIX_L;
else if (*it == '_')
state = State::SUFFIX_LITERAL_LEADER;
else if (!std::isdigit(static_cast<unsigned char>(*it)))
return false;
break;
case State::E:
if (*it=='+' || *it=='-')
state = State::MANTISSA_PLUSMINUS;
else if (std::isdigit(static_cast<unsigned char>(*it)))
state = State::MANTISSA_DIGITS;
else
return false;
break;
case State::MANTISSA_PLUSMINUS:
if (!std::isdigit(static_cast<unsigned char>(*it)))
return false;
else
state = State::MANTISSA_DIGITS;
break;
case State::MANTISSA_DIGITS:
if (*it=='f' || *it=='F')
state = State::SUFFIX_F;
else if (*it=='l' || *it=='L')
state = State::SUFFIX_L;
else if (!std::isdigit(static_cast<unsigned char>(*it)))
return false;
break;
// Ensure at least one post _ char for user defined literals
case State::SUFFIX_LITERAL:
case State::SUFFIX_LITERAL_LEADER:
state = State::SUFFIX_LITERAL;
break;
case State::SUFFIX_F:
return false;
case State::SUFFIX_L:
return false;
}
}
return (state==State::BASE_DIGITS2 || state==State::MANTISSA_DIGITS || state==State::TRAILING_DECIMAL || state==State::SUFFIX_F || state==State::SUFFIX_L || (state==State::SUFFIX_LITERAL));
}
bool MathLib::isNegative(const std::string &str)
{
if (str.empty())
return false;
return (str[0] == '-');
}
bool MathLib::isPositive(const std::string &str)
{
if (str.empty())
return false;
return !MathLib::isNegative(str);
}
static bool isValidIntegerSuffixIt(std::string::const_iterator it, std::string::const_iterator end, bool supportMicrosoftExtensions=true)
{
enum class Status : std::uint8_t { START, SUFFIX_U, SUFFIX_UL, SUFFIX_ULL, SUFFIX_UZ, SUFFIX_L, SUFFIX_LU, SUFFIX_LL, SUFFIX_LLU, SUFFIX_I, SUFFIX_I6, SUFFIX_I64, SUFFIX_UI, SUFFIX_UI6, SUFFIX_UI64, SUFFIX_Z, SUFFIX_LITERAL_LEADER, SUFFIX_LITERAL } state = Status::START;
for (; it != end; ++it) {
switch (state) {
case Status::START:
if (*it == 'u' || *it == 'U')
state = Status::SUFFIX_U;
else if (*it == 'l' || *it == 'L')
state = Status::SUFFIX_L;
else if (*it == 'z' || *it == 'Z')
state = Status::SUFFIX_Z;
else if (supportMicrosoftExtensions && (*it == 'i' || *it == 'I'))
state = Status::SUFFIX_I;
else if (*it == '_')
state = Status::SUFFIX_LITERAL_LEADER;
else
return false;
break;
case Status::SUFFIX_U:
if (*it == 'l' || *it == 'L')
state = Status::SUFFIX_UL; // UL
else if (*it == 'z' || *it == 'Z')
state = Status::SUFFIX_UZ; // UZ
else if (supportMicrosoftExtensions && (*it == 'i' || *it == 'I'))
state = Status::SUFFIX_UI;
else
return false;
break;
case Status::SUFFIX_UL:
if (*it == 'l' || *it == 'L')
state = Status::SUFFIX_ULL; // ULL
else
return false;
break;
case Status::SUFFIX_L:
if (*it == 'u' || *it == 'U')
state = Status::SUFFIX_LU; // LU
else if (*it == 'l' || *it == 'L')
state = Status::SUFFIX_LL; // LL
else
return false;
break;
case Status::SUFFIX_LU:
return false;
case Status::SUFFIX_LL:
if (*it == 'u' || *it == 'U')
state = Status::SUFFIX_LLU; // LLU
else
return false;
break;
case Status::SUFFIX_I:
if (*it == '6')
state = Status::SUFFIX_I6;
else
return false;
break;
case Status::SUFFIX_I6:
if (*it == '4')
state = Status::SUFFIX_I64;
else
return false;
break;
case Status::SUFFIX_UI:
if (*it == '6')
state = Status::SUFFIX_UI6;
else
return false;
break;
case Status::SUFFIX_UI6:
if (*it == '4')
state = Status::SUFFIX_UI64;
else
return false;
break;
case Status::SUFFIX_Z:
if (*it == 'u' || *it == 'U')
state = Status::SUFFIX_UZ;
else
return false;
break;
// Ensure at least one post _ char for user defined literals
case Status::SUFFIX_LITERAL:
case Status::SUFFIX_LITERAL_LEADER:
state = Status::SUFFIX_LITERAL;
break;
default:
return false;
}
}
return ((state == Status::SUFFIX_U) ||
(state == Status::SUFFIX_L) ||
(state == Status::SUFFIX_Z) ||
(state == Status::SUFFIX_UL) ||
(state == Status::SUFFIX_UZ) ||
(state == Status::SUFFIX_LU) ||
(state == Status::SUFFIX_LL) ||
(state == Status::SUFFIX_ULL) ||
(state == Status::SUFFIX_LLU) ||
(state == Status::SUFFIX_I64) ||
(state == Status::SUFFIX_UI64) ||
(state == Status::SUFFIX_LITERAL));
}
// cppcheck-suppress unusedFunction
bool MathLib::isValidIntegerSuffix(const std::string& str, bool supportMicrosoftExtensions)
{
return isValidIntegerSuffixIt(str.cbegin(), str.cend(), supportMicrosoftExtensions);
}
/*! \brief Does the string represent an octal number?
* In case leading or trailing white space is provided, the function
* returns false.
* Additional information can be found here:
* http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
*
* \param str The string to check. In case the string is empty, the function returns false.
* \return Return true in case a octal number is provided and false otherwise.
**/
bool MathLib::isOct(const std::string& str)
{
enum class Status : std::uint8_t {
START, OCTAL_PREFIX, DIGITS
} state = Status::START;
if (str.empty())
return false;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case Status::START:
if (*it == '0')
state = Status::OCTAL_PREFIX;
else
return false;
break;
case Status::OCTAL_PREFIX:
if (isOctalDigit(static_cast<unsigned char>(*it)))
state = Status::DIGITS;
else
return false;
break;
case Status::DIGITS:
if (isOctalDigit(static_cast<unsigned char>(*it)))
state = Status::DIGITS;
else
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
return state == Status::DIGITS;
}
bool MathLib::isIntHex(const std::string& str)
{
enum class Status : std::uint8_t {
START, HEX_0, HEX_X, DIGIT
} state = Status::START;
if (str.empty())
return false;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case Status::START:
if (*it == '0')
state = Status::HEX_0;
else
return false;
break;
case Status::HEX_0:
if (*it == 'x' || *it == 'X')
state = Status::HEX_X;
else
return false;
break;
case Status::HEX_X:
if (isxdigit(static_cast<unsigned char>(*it)))
state = Status::DIGIT;
else
return false;
break;
case Status::DIGIT:
if (isxdigit(static_cast<unsigned char>(*it)))
; // state = Status::DIGIT;
else
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
return Status::DIGIT == state;
}
bool MathLib::isFloatHex(const std::string& str)
{
enum class Status : std::uint8_t {
START, HEX_0, HEX_X, WHOLE_NUMBER_DIGIT, POINT, FRACTION, EXPONENT_P, EXPONENT_SIGN, EXPONENT_DIGITS, EXPONENT_SUFFIX
} state = Status::START;
if (str.empty())
return false;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case Status::START:
if (*it == '0')
state = Status::HEX_0;
else
return false;
break;
case Status::HEX_0:
if (*it == 'x' || *it == 'X')
state = Status::HEX_X;
else
return false;
break;
case Status::HEX_X:
if (isxdigit(static_cast<unsigned char>(*it)))
state = Status::WHOLE_NUMBER_DIGIT;
else if (*it == '.')
state = Status::POINT;
else
return false;
break;
case Status::WHOLE_NUMBER_DIGIT:
if (isxdigit(static_cast<unsigned char>(*it)))
; // state = Status::WHOLE_NUMBER_DIGITS;
else if (*it=='.')
state = Status::FRACTION;
else if (*it=='p' || *it=='P')
state = Status::EXPONENT_P;
else
return false;
break;
case Status::POINT:
case Status::FRACTION:
if (isxdigit(static_cast<unsigned char>(*it)))
state = Status::FRACTION;
else if (*it == 'p' || *it == 'P')
state = Status::EXPONENT_P;
else
return false;
break;
case Status::EXPONENT_P:
if (isdigit(static_cast<unsigned char>(*it)))
state = Status::EXPONENT_DIGITS;
else if (*it == '+' || *it == '-')
state = Status::EXPONENT_SIGN;
else
return false;
break;
case Status::EXPONENT_SIGN:
if (isdigit(static_cast<unsigned char>(*it)))
state = Status::EXPONENT_DIGITS;
else
return false;
break;
case Status::EXPONENT_DIGITS:
if (isdigit(static_cast<unsigned char>(*it)))
; // state = Status::EXPONENT_DIGITS;
else if (*it == 'f' || *it == 'F' || *it == 'l' || *it == 'L')
state = Status::EXPONENT_SUFFIX;
else
return false;
break;
case Status::EXPONENT_SUFFIX:
return false;
}
}
return (Status::EXPONENT_DIGITS == state) || (Status::EXPONENT_SUFFIX == state);
}
/*! \brief Does the string represent a binary number?
* In case leading or trailing white space is provided, the function
* returns false.
* Additional information can be found here:
* http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html
*
* \param str The string to check. In case the string is empty, the function returns false.
* \return Return true in case a binary number is provided and false otherwise.
**/
bool MathLib::isBin(const std::string& str)
{
enum class Status : std::uint8_t {
START, GNU_BIN_PREFIX_0, GNU_BIN_PREFIX_B, DIGIT
} state = Status::START;
if (str.empty())
return false;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case Status::START:
if (*it == '0')
state = Status::GNU_BIN_PREFIX_0;
else
return false;
break;
case Status::GNU_BIN_PREFIX_0:
if (*it == 'b' || *it == 'B')
state = Status::GNU_BIN_PREFIX_B;
else
return false;
break;
case Status::GNU_BIN_PREFIX_B:
if (*it == '0' || *it == '1')
state = Status::DIGIT;
else
return false;
break;
case Status::DIGIT:
if (*it == '0' || *it == '1')
; // state = Status::DIGIT;
else
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
return state == Status::DIGIT;
}
bool MathLib::isDec(const std::string & str)
{
enum class Status : std::uint8_t {
START, DIGIT
} state = Status::START;
if (str.empty())
return false;
std::string::const_iterator it = str.cbegin();
if ('+' == *it || '-' == *it)
++it;
for (; it != str.cend(); ++it) {
switch (state) {
case Status::START:
if (isdigit(static_cast<unsigned char>(*it)))
state = Status::DIGIT;
else
return false;
break;
case Status::DIGIT:
if (isdigit(static_cast<unsigned char>(*it)))
state = Status::DIGIT;
else
return isValidIntegerSuffixIt(it,str.end());
break;
}
}
return state == Status::DIGIT;
}
bool MathLib::isInt(const std::string & str)
{
return isDec(str) || isIntHex(str) || isOct(str) || isBin(str);
}
std::string MathLib::getSuffix(const std::string& value)
{
if (value.size() > 3 && value[value.size() - 3] == 'i' && value[value.size() - 2] == '6' && value[value.size() - 1] == '4') {
if (value[value.size() - 4] == 'u')
return "ULL";
return "LL";
}
bool isUnsigned = false;
unsigned int longState = 0;
for (std::size_t i = 1U; i < value.size(); ++i) {
const char c = value[value.size() - i];
if (c == 'u' || c == 'U')
isUnsigned = true;
else if (c == 'L' || c == 'l')
longState++;
else break;
}
if (longState == 0)
return isUnsigned ? "U" : "";
if (longState == 1)
return isUnsigned ? "UL" : "L";
if (longState == 2)
return isUnsigned ? "ULL" : "LL";
return "";
}
static std::string intsuffix(const std::string & first, const std::string & second)
{
const std::string suffix1 = MathLib::getSuffix(first);
const std::string suffix2 = MathLib::getSuffix(second);
if (suffix1 == "ULL" || suffix2 == "ULL")
return "ULL";
if (suffix1 == "LL" || suffix2 == "LL")
return "LL";
if (suffix1 == "UL" || suffix2 == "UL")
return "UL";
if (suffix1 == "L" || suffix2 == "L")
return "L";
if (suffix1 == "U" || suffix2 == "U")
return "U";
return suffix1.empty() ? suffix2 : suffix1;
}
std::string MathLib::add(const std::string & first, const std::string & second)
{
#ifdef TEST_MATHLIB_VALUE
return (value(first) + value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return std::to_string(toBigNumber(first) + toBigNumber(second)) + intsuffix(first, second);
}
double d1 = toDoubleNumber(first);
double d2 = toDoubleNumber(second);
int count = 0;
while (d1 > 100000.0 * d2 && toString(d1+d2)==first && ++count<5)
d2 *= 10.0;
while (d2 > 100000.0 * d1 && toString(d1+d2)==second && ++count<5)
d1 *= 10.0;
return toString(d1 + d2);
#endif
}
std::string MathLib::subtract(const std::string &first, const std::string &second)
{
#ifdef TEST_MATHLIB_VALUE
return (value(first) - value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return std::to_string(toBigNumber(first) - toBigNumber(second)) + intsuffix(first, second);
}
if (first == second)
return "0.0";
double d1 = toDoubleNumber(first);
double d2 = toDoubleNumber(second);
int count = 0;
while (d1 > 100000.0 * d2 && toString(d1-d2)==first && ++count<5)
d2 *= 10.0;
while (d2 > 100000.0 * d1 && toString(d1-d2)==second && ++count<5)
d1 *= 10.0;
return toString(d1 - d2);
#endif
}
std::string MathLib::divide(const std::string &first, const std::string &second)
{
#ifdef TEST_MATHLIB_VALUE
return (value(first) / value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
const bigint a = toBigNumber(first);
const bigint b = toBigNumber(second);
if (b == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
if (a == std::numeric_limits<bigint>::min() && std::abs(b)<=1)
throw InternalError(nullptr, "Internal Error: Division overflow");
return std::to_string(toBigNumber(first) / b) + intsuffix(first, second);
}
if (isNullValue(second)) {
if (isNullValue(first))
return "nan.0";
return isPositive(first) == isPositive(second) ? "inf.0" : "-inf.0";
}
return toString(toDoubleNumber(first) / toDoubleNumber(second));
#endif
}
std::string MathLib::multiply(const std::string &first, const std::string &second)
{
#ifdef TEST_MATHLIB_VALUE
return (value(first) * value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
return std::to_string(toBigNumber(first) * toBigNumber(second)) + intsuffix(first, second);
}
return toString(toDoubleNumber(first) * toDoubleNumber(second));
#endif
}
std::string MathLib::mod(const std::string &first, const std::string &second)
{
#ifdef TEST_MATHLIB_VALUE
return (value(first) % value(second)).str();
#else
if (MathLib::isInt(first) && MathLib::isInt(second)) {
const bigint b = toBigNumber(second);
if (b == 0)
throw InternalError(nullptr, "Internal Error: Division by zero");
return std::to_string(toBigNumber(first) % b) + intsuffix(first, second);
}
return toString(std::fmod(toDoubleNumber(first),toDoubleNumber(second)));
#endif
}
std::string MathLib::calculate(const std::string &first, const std::string &second, char action)
{
switch (action) {
case '+':
return MathLib::add(first, second);
case '-':
return MathLib::subtract(first, second);
case '*':
return MathLib::multiply(first, second);
case '/':
return MathLib::divide(first, second);
case '%':
return MathLib::mod(first, second);
case '&':
return std::to_string(MathLib::toBigNumber(first) & MathLib::toBigNumber(second)) + intsuffix(first, second);
case '|':
return std::to_string(MathLib::toBigNumber(first) | MathLib::toBigNumber(second)) + intsuffix(first, second);
case '^':
return std::to_string(MathLib::toBigNumber(first) ^ MathLib::toBigNumber(second)) + intsuffix(first, second);
default:
throw InternalError(nullptr, std::string("Unexpected action '") + action + "' in MathLib::calculate(). Please report this to Cppcheck developers.");
}
}
std::string MathLib::sin(const std::string &tok)
{
return toString(std::sin(toDoubleNumber(tok)));
}
std::string MathLib::cos(const std::string &tok)
{
return toString(std::cos(toDoubleNumber(tok)));
}
std::string MathLib::tan(const std::string &tok)
{
return toString(std::tan(toDoubleNumber(tok)));
}
std::string MathLib::abs(const std::string &tok)
{
if (isNegative(tok))
return tok.substr(1, tok.length() - 1);
return tok;
}
bool MathLib::isEqual(const std::string &first, const std::string &second)
{
// this conversion is needed for formatting
// e.g. if first=0.1 and second=1.0E-1, the direct comparison of the strings would fail
return toString(toDoubleNumber(first)) == toString(toDoubleNumber(second));
}
bool MathLib::isNotEqual(const std::string &first, const std::string &second)
{
return !isEqual(first, second);
}
// cppcheck-suppress unusedFunction
bool MathLib::isGreater(const std::string &first, const std::string &second)
{
return toDoubleNumber(first) > toDoubleNumber(second);
}
// cppcheck-suppress unusedFunction
bool MathLib::isGreaterEqual(const std::string &first, const std::string &second)
{
return toDoubleNumber(first) >= toDoubleNumber(second);
}
// cppcheck-suppress unusedFunction
bool MathLib::isLess(const std::string &first, const std::string &second)
{
return toDoubleNumber(first) < toDoubleNumber(second);
}
bool MathLib::isLessEqual(const std::string &first, const std::string &second)
{
return toDoubleNumber(first) <= toDoubleNumber(second);
}
/*! \brief Does the string represent the numerical value of 0?
* In case leading or trailing white space is provided, the function
* returns false.
* Requirement for this function:
* - This code is allowed to be slow because of simplicity of the code.
*
* \param[in] str The string to check. In case the string is empty, the function returns false.
* \return Return true in case the string represents a numerical null value.
**/
bool MathLib::isNullValue(const std::string &str)
{
if (str.empty() || (!std::isdigit(static_cast<unsigned char>(str[0])) && (str[0] != '.' && str[0] != '-' && str[0] != '+')))
return false; // Has to be a number
if (!isInt(str) && !isFloat(str))
return false;
const bool isHex = isIntHex(str) || isFloatHex(str);
for (const char i : str) {
if (std::isdigit(static_cast<unsigned char>(i)) && i != '0') // May not contain digits other than 0
return false;
if (i == 'p' || i == 'P' || (!isHex && (i == 'E' || i == 'e')))
return true;
if (isHex && isxdigit(i) && i != '0')
return false;
}
return true;
}
bool MathLib::isOctalDigit(char c)
{
return (c >= '0' && c <= '7');
}
MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('+',v1,v2);
}
MathLib::value operator-(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('-',v1,v2);
}
MathLib::value operator*(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('*',v1,v2);
}
MathLib::value operator/(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('/',v1,v2);
}
MathLib::value operator%(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('%',v1,v2);
}
MathLib::value operator&(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('&',v1,v2);
}
MathLib::value operator|(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('|',v1,v2);
}
MathLib::value operator^(const MathLib::value &v1, const MathLib::value &v2)
{
return MathLib::value::calc('^',v1,v2);
}
MathLib::value operator<<(const MathLib::value &v1, const MathLib::value &v2)
{
return v1.shiftLeft(v2);
}
MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2)
{
return v1.shiftRight(v2);
}
| null |
847 | cpp | cppcheck | checkbufferoverrun.h | lib/checkbufferoverrun.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkbufferoverrunH
#define checkbufferoverrunH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "ctu.h"
#include "errortypes.h"
#include "mathlib.h"
#include "symboldatabase.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <map>
#include <string>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief buffer overruns and array index out of bounds
*
* Buffer overrun and array index out of bounds are pretty much the same.
* But I generally use 'array index' if the code contains []. And the given
* index is out of bounds.
* I generally use 'buffer overrun' if you for example call a strcpy or
* other function and pass a buffer and reads or writes too much data.
*/
class CPPCHECKLIB CheckBufferOverrun : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckBufferOverrun() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckBufferOverrun(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckBufferOverrun checkBufferOverrun(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkBufferOverrun.arrayIndex();
checkBufferOverrun.pointerArithmetic();
checkBufferOverrun.bufferOverflow();
checkBufferOverrun.arrayIndexThenCheck();
checkBufferOverrun.stringNotZeroTerminated();
checkBufferOverrun.objectIndex();
checkBufferOverrun.argumentSize();
checkBufferOverrun.negativeArraySize();
}
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckBufferOverrun c(nullptr, settings, errorLogger);
c.arrayIndexError(nullptr, std::vector<Dimension>(), std::vector<ValueFlow::Value>());
c.pointerArithmeticError(nullptr, nullptr, nullptr);
c.negativeIndexError(nullptr, std::vector<Dimension>(), std::vector<ValueFlow::Value>());
c.arrayIndexThenCheckError(nullptr, "i");
c.bufferOverflowError(nullptr, nullptr, Certainty::normal);
c.objectIndexError(nullptr, nullptr, true);
c.argumentSizeError(nullptr, "function", 1, "buffer", nullptr, nullptr);
c.negativeMemoryAllocationSizeError(nullptr, nullptr);
c.negativeArraySizeError(nullptr);
}
/** @brief Parse current TU and extract file info */
Check::FileInfo *getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const override;
/** @brief Analyse all file infos for all TU */
bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) override;
void arrayIndex();
void arrayIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes);
void negativeIndexError(const Token* tok,
const std::vector<Dimension>& dimensions,
const std::vector<ValueFlow::Value>& indexes);
void pointerArithmetic();
void pointerArithmeticError(const Token *tok, const Token *indexToken, const ValueFlow::Value *indexValue);
void bufferOverflow();
void bufferOverflowError(const Token *tok, const ValueFlow::Value *value, Certainty certainty);
void arrayIndexThenCheck();
void arrayIndexThenCheckError(const Token *tok, const std::string &indexName);
void stringNotZeroTerminated();
void terminateStrncpyError(const Token *tok, const std::string &varname);
void argumentSize();
void argumentSizeError(const Token *tok, const std::string &functionName, nonneg int paramIndex, const std::string ¶mExpression, const Variable *paramVar, const Variable *functionArg);
void negativeArraySize();
void negativeArraySizeError(const Token* tok);
void negativeMemoryAllocationSizeError(const Token* tok, const ValueFlow::Value* value); // provide a negative value to memory allocation function
void objectIndex();
void objectIndexError(const Token *tok, const ValueFlow::Value *v, bool known);
ValueFlow::Value getBufferSize(const Token *bufTok) const;
// CTU
static bool isCtuUnsafeBufferUsage(const Settings &settings, const Token *argtok, MathLib::bigint *offset, int type);
static bool isCtuUnsafeArrayIndex(const Settings &settings, const Token *argtok, MathLib::bigint *offset);
static bool isCtuUnsafePointerArith(const Settings &settings, const Token *argtok, MathLib::bigint *offset);
Check::FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const override;
static bool analyseWholeProgram1(const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap, const CTU::FileInfo::UnsafeUsage &unsafeUsage, int type, ErrorLogger &errorLogger, int maxCtuDepth);
static std::string myName() {
return "Bounds checking";
}
std::string classInfo() const override {
return "Out of bounds checking:\n"
"- Array index out of bounds\n"
"- Pointer arithmetic overflow\n"
"- Buffer overflow\n"
"- Dangerous usage of strncat()\n"
"- Using array index before checking it\n"
"- Partial string write that leads to buffer that is not zero terminated.\n"
"- Check for large enough arrays being passed to functions\n"
"- Allocating memory with a negative size\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkbufferoverrunH
| null |
848 | cpp | cppcheck | templatesimplifier.cpp | lib/templatesimplifier.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "templatesimplifier.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "mathlib.h"
#include "settings.h"
#include "standards.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <memory>
#include <stack>
#include <type_traits>
#include <utility>
static Token *skipRequires(Token *tok)
{
if (!Token::simpleMatch(tok, "requires"))
return tok;
while (Token::Match(tok, "%oror%|&&|requires %name%|(")) {
Token *after = tok->next();
if (after->str() == "(") {
tok = after->link()->next();
continue;
}
if (Token::simpleMatch(after, "requires (") && Token::simpleMatch(after->linkAt(1), ") {")) {
tok = after->linkAt(1)->linkAt(1)->next();
continue;
}
while (Token::Match(after, "%name% :: %name%"))
after = after->tokAt(2);
if (Token::Match(after, "%name% <")) {
after = after->next()->findClosingBracket();
tok = after ? after->next() : nullptr;
} else
break;
}
return tok;
}
namespace {
class FindToken {
public:
explicit FindToken(const Token *token) : mToken(token) {}
bool operator()(const TemplateSimplifier::TokenAndName &tokenAndName) const {
return tokenAndName.token() == mToken;
}
private:
const Token * const mToken;
};
class FindName {
public:
explicit FindName(std::string name) : mName(std::move(name)) {}
bool operator()(const TemplateSimplifier::TokenAndName &tokenAndName) const {
return tokenAndName.name() == mName;
}
private:
const std::string mName;
};
class FindFullName {
public:
explicit FindFullName(std::string fullName) : mFullName(std::move(fullName)) {}
bool operator()(const TemplateSimplifier::TokenAndName &tokenAndName) const {
return tokenAndName.fullName() == mFullName;
}
private:
const std::string mFullName;
};
}
TemplateSimplifier::TokenAndName::TokenAndName(Token *token, std::string scope) :
mToken(token), mScope(std::move(scope)), mName(mToken ? mToken->str() : ""),
mFullName(mScope.empty() ? mName : (mScope + " :: " + mName)),
mNameToken(nullptr), mParamEnd(nullptr), mFlags(0)
{
if (mToken) {
if (mToken->strAt(1) == "<") {
const Token *end = mToken->next()->findClosingBracket();
if (end && end->strAt(1) == "(") {
isFunction(true);
}
}
mToken->templateSimplifierPointer(this);
}
}
TemplateSimplifier::TokenAndName::TokenAndName(Token *token, std::string scope, const Token *nameToken, const Token *paramEnd) :
mToken(token), mScope(std::move(scope)), mName(nameToken->str()),
mFullName(mScope.empty() ? mName : (mScope + " :: " + mName)),
mNameToken(nameToken), mParamEnd(paramEnd), mFlags(0)
{
// only set flags for declaration
if (mToken && mNameToken && mParamEnd) {
isSpecialization(Token::simpleMatch(mToken, "template < >"));
if (!isSpecialization()) {
if (Token::simpleMatch(mToken->next()->findClosingBracket(), "> template <")) {
const Token * temp = mNameToken->tokAt(-2);
while (Token::Match(temp, ">|%name% ::")) {
if (temp->str() == ">")
temp = temp->findOpeningBracket()->previous();
else
temp = temp->tokAt(-2);
}
isPartialSpecialization(temp->strAt(1) == "<");
} else
isPartialSpecialization(mNameToken->strAt(1) == "<");
}
isAlias(mParamEnd->strAt(1) == "using");
if (isAlias() && isPartialSpecialization()) {
throw InternalError(mToken, "partial specialization of alias templates is not permitted", InternalError::SYNTAX);
}
if (isAlias() && isSpecialization()) {
throw InternalError(mToken, "explicit specialization of alias templates is not permitted", InternalError::SYNTAX);
}
isFriend(mParamEnd->strAt(1) == "friend");
const Token *next = mParamEnd->next();
if (isFriend())
next = next->next();
isClass(Token::Match(next, "class|struct|union %name% <|{|:|;|::"));
if (mToken->strAt(1) == "<" && !isSpecialization()) {
const Token *end = mToken->next()->findClosingBracket();
isVariadic(end && Token::findmatch(mToken->tokAt(2), "%name% ...", end));
}
const Token *tok1 = mNameToken->next();
if (tok1->str() == "<") {
const Token *closing = tok1->findClosingBracket();
if (closing)
tok1 = closing->next();
else
throw InternalError(mToken, "unsupported syntax", InternalError::SYNTAX);
}
isFunction(tok1->str() == "(");
isVariable(!isClass() && !isAlias() && !isFriend() && Token::Match(tok1, "=|;"));
if (!isFriend()) {
if (isVariable())
isForwardDeclaration(tok1->str() == ";");
else if (!isAlias()) {
if (isFunction())
tok1 = tok1->link()->next();
while (tok1 && !Token::Match(tok1, ";|{")) {
if (tok1->str() == "<")
tok1 = tok1->findClosingBracket();
else if (Token::Match(tok1, "(|[") && tok1->link())
tok1 = tok1->link();
if (tok1)
tok1 = tok1->next();
}
if (tok1)
isForwardDeclaration(tok1->str() == ";");
}
}
// check for member class or function and adjust scope
if ((isFunction() || isClass()) &&
(mNameToken->strAt(-1) == "::" || Token::simpleMatch(mNameToken->tokAt(-2), ":: ~"))) {
const Token * start = mNameToken;
if (start->strAt(-1) == "~")
start = start->previous();
const Token *end = start;
while (start && (Token::Match(start->tokAt(-2), "%name% ::") ||
(Token::simpleMatch(start->tokAt(-2), "> ::") &&
start->tokAt(-2)->findOpeningBracket() &&
Token::Match(start->tokAt(-2)->findOpeningBracket()->previous(), "%name% <")))) {
if (start->strAt(-2) == ">")
start = start->tokAt(-2)->findOpeningBracket()->previous();
else
start = start->tokAt(-2);
}
if (start && start != end) {
if (!mScope.empty())
mScope += " ::";
while (start && start->next() != end) {
if (start->str() == "<")
start = start->findClosingBracket();
else {
if (!mScope.empty())
mScope += " ";
mScope += start->str();
}
start = start->next();
}
if (start)
mFullName = mScope.empty() ? mName : (mScope + " :: " + mName);
}
}
}
// make sure at most only one family flag is set
assert(isClass() ? !(isFunction() || isVariable()) : true);
assert(isFunction() ? !(isClass() || isVariable()) : true);
assert(isVariable() ? !(isClass() || isFunction()) : true);
if (mToken)
mToken->templateSimplifierPointer(this);
}
TemplateSimplifier::TokenAndName::TokenAndName(const TokenAndName& other) :
mToken(other.mToken), mScope(other.mScope), mName(other.mName), mFullName(other.mFullName),
mNameToken(other.mNameToken), mParamEnd(other.mParamEnd), mFlags(other.mFlags)
{
if (mToken)
mToken->templateSimplifierPointer(this);
}
TemplateSimplifier::TokenAndName::~TokenAndName()
{
if (mToken && mToken->templateSimplifierPointers())
mToken->templateSimplifierPointers()->erase(this);
}
std::string TemplateSimplifier::TokenAndName::dump(const std::vector<std::string>& fileNames) const {
std::string ret = " <TokenAndName name=\"" + ErrorLogger::toxml(mName) + "\" file=\"" + ErrorLogger::toxml(fileNames.at(mToken->fileIndex())) + "\" line=\"" + std::to_string(mToken->linenr()) + "\">\n";
for (const Token* tok = mToken; tok && !Token::Match(tok, "[;{}]"); tok = tok->next())
ret += " <template-token str=\"" + ErrorLogger::toxml(tok->str()) + "\"/>\n";
return ret + " </TokenAndName>\n";
}
const Token * TemplateSimplifier::TokenAndName::aliasStartToken() const
{
if (mParamEnd)
return mParamEnd->tokAt(4);
return nullptr;
}
const Token * TemplateSimplifier::TokenAndName::aliasEndToken() const
{
if (aliasStartToken())
return Token::findsimplematch(aliasStartToken(), ";");
return nullptr;
}
bool TemplateSimplifier::TokenAndName::isAliasToken(const Token *tok) const
{
const Token *end = aliasEndToken();
for (const Token *tok1 = aliasStartToken(); tok1 != end; tok1 = tok1->next()) {
if (tok1 == tok)
return true;
}
return false;
}
TemplateSimplifier::TemplateSimplifier(Tokenizer &tokenizer)
: mTokenizer(tokenizer), mTokenList(mTokenizer.list), mSettings(mTokenizer.getSettings()),
mErrorLogger(mTokenizer.mErrorLogger)
{}
void TemplateSimplifier::checkComplicatedSyntaxErrorsInTemplates()
{
// check for more complicated syntax errors when using templates..
for (const Token *tok = mTokenList.front(); tok; tok = tok->next()) {
// skip executing scopes (ticket #3183)..
if (Token::simpleMatch(tok, "( {")) {
tok = tok->link();
if (!tok)
syntaxError(nullptr);
}
// skip executing scopes..
const Token *start = Tokenizer::startOfExecutableScope(tok);
if (start) {
tok = start->link();
}
// skip executing scopes (ticket #1985)..
else if (Token::simpleMatch(tok, "try {")) {
tok = tok->linkAt(1);
while (Token::simpleMatch(tok, "} catch (")) {
tok = tok->linkAt(2);
if (Token::simpleMatch(tok, ") {"))
tok = tok->linkAt(1);
}
}
if (!tok)
syntaxError(nullptr);
// not start of statement?
if (tok->previous() && !Token::Match(tok, "[;{}]"))
continue;
// skip starting tokens.. ;;; typedef typename foo::bar::..
while (Token::Match(tok, ";|{"))
tok = tok->next();
while (Token::Match(tok, "typedef|typename"))
tok = tok->next();
while (Token::Match(tok, "%type% ::"))
tok = tok->tokAt(2);
if (!tok)
break;
// template variable or type..
if (Token::Match(tok, "%type% <") && !Token::simpleMatch(tok, "template")) {
// these are used types..
std::set<std::string> usedtypes;
// parse this statement and see if the '<' and '>' are matching
unsigned int level = 0;
for (const Token *tok2 = tok; tok2 && !Token::simpleMatch(tok2, ";"); tok2 = tok2->next()) {
if (Token::simpleMatch(tok2, "{") &&
(!Token::Match(tok2->previous(), ">|%type%") || Token::simpleMatch(tok2->link(), "} ;")))
break;
if (tok2->str() == "(")
tok2 = tok2->link();
else if (tok2->str() == "<") {
bool inclevel = false;
if (Token::simpleMatch(tok2->previous(), "operator <"))
;
else if (level == 0 && Token::Match(tok2->previous(), "%type%")) {
// @todo add better expression detection
if (!(Token::Match(tok2->next(), "*| %type%|%num% ;") ||
Token::Match(tok2->next(), "*| %type% . %type% ;"))) {
inclevel = true;
}
} else if (tok2->next() && tok2->next()->isStandardType() && !Token::Match(tok2->tokAt(2), "(|{"))
inclevel = true;
else if (Token::simpleMatch(tok2, "< typename"))
inclevel = true;
else if (Token::Match(tok2->tokAt(-2), "<|, %type% <") && usedtypes.find(tok2->strAt(-1)) != usedtypes.end())
inclevel = true;
else if (Token::Match(tok2, "< %type%") && usedtypes.find(tok2->strAt(1)) != usedtypes.end())
inclevel = true;
else if (Token::Match(tok2, "< %type%")) {
// is the next token a type and not a variable/constant?
// assume it's a type if there comes another "<"
const Token *tok3 = tok2->next();
while (Token::Match(tok3, "%type% ::"))
tok3 = tok3->tokAt(2);
if (Token::Match(tok3, "%type% <"))
inclevel = true;
} else if (tok2->strAt(-1) == ">")
syntaxError(tok);
if (inclevel) {
++level;
if (Token::Match(tok2->tokAt(-2), "<|, %type% <"))
usedtypes.insert(tok2->strAt(-1));
}
} else if (tok2->str() == ">") {
if (level > 0)
--level;
} else if (tok2->str() == ">>") {
if (level > 0)
--level;
if (level > 0)
--level;
}
}
if (level > 0)
syntaxError(tok);
}
}
}
unsigned int TemplateSimplifier::templateParameters(const Token *tok)
{
unsigned int numberOfParameters = 1;
if (!tok)
return 0;
if (tok->str() != "<")
return 0;
if (Token::Match(tok->previous(), "%var% <"))
return 0;
tok = tok->next();
if (!tok || tok->str() == ">")
return 0;
unsigned int level = 0;
while (tok) {
// skip template template
if (level == 0 && Token::simpleMatch(tok, "template <")) {
const Token *closing = tok->next()->findClosingBracket();
if (closing) {
if (closing->str() == ">>")
return numberOfParameters;
tok = closing->next();
if (!tok)
syntaxError(tok);
if (Token::Match(tok, ">|>>|>>="))
return numberOfParameters;
if (tok->str() == ",") {
++numberOfParameters;
tok = tok->next();
continue;
}
} else
return 0;
}
// skip const/volatile
if (Token::Match(tok, "const|volatile"))
tok = tok->next();
// skip struct/union
if (Token::Match(tok, "struct|union"))
tok = tok->next();
// Skip '&'
if (Token::Match(tok, "& ::| %name%"))
tok = tok->next();
// Skip variadic types (Ticket #5774, #6059, #6172)
if (Token::simpleMatch(tok, "...")) {
if ((tok->previous()->isName() && !Token::Match(tok->tokAt(-2), "<|,|::")) ||
(!tok->previous()->isName() && !Token::Match(tok->previous(), ">|&|&&|*")))
return 0; // syntax error
tok = tok->next();
if (!tok)
return 0;
if (tok->str() == ">") {
if (level == 0)
return numberOfParameters;
--level;
} else if (tok->str() == ">>" || tok->str() == ">>=") {
if (level == 1)
return numberOfParameters;
level -= 2;
} else if (tok->str() == ",") {
if (level == 0)
++numberOfParameters;
tok = tok->next();
continue;
}
}
// Skip '=', '?', ':'
if (Token::Match(tok, "=|?|:"))
tok = tok->next();
if (!tok)
return 0;
// Skip links
if (Token::Match(tok, "(|{")) {
tok = tok->link();
if (tok)
tok = tok->next();
if (!tok)
return 0;
if (tok->str() == ">" && level == 0)
return numberOfParameters;
if ((tok->str() == ">>" || tok->str() == ">>=") && level == 1)
return numberOfParameters;
if (tok->str() == ",") {
if (level == 0)
++numberOfParameters;
tok = tok->next();
}
continue;
}
// skip std::
if (tok->str() == "::")
tok = tok->next();
while (Token::Match(tok, "%name% ::")) {
tok = tok->tokAt(2);
if (tok && tok->str() == "*") // Ticket #5759: Class member pointer as a template argument; skip '*'
tok = tok->next();
}
if (!tok)
return 0;
// num/type ..
if (!tok->isNumber() && tok->tokType() != Token::eChar && tok->tokType() != Token::eString && !tok->isName() && !tok->isOp())
return 0;
tok = tok->next();
if (!tok)
return 0;
// * / const
while (Token::Match(tok, "*|&|&&|const"))
tok = tok->next();
if (!tok)
return 0;
// Function pointer or prototype..
while (Token::Match(tok, "(|[")) {
if (!tok->link())
syntaxError(tok);
tok = tok->link()->next();
while (Token::Match(tok, "const|volatile")) // Ticket #5786: Skip function cv-qualifiers
tok = tok->next();
}
if (!tok)
return 0;
// inner template
if (tok->str() == "<" && tok->previous()->isName()) {
++level;
tok = tok->next();
}
if (!tok)
return 0;
// ,/>
while (Token::Match(tok, ">|>>|>>=")) {
if (level == 0)
return tok->str() == ">" && !Token::Match(tok->next(), "%num%") ? numberOfParameters : 0;
--level;
if (tok->str() == ">>" || tok->str() == ">>=") {
if (level == 0)
return !Token::Match(tok->next(), "%num%") ? numberOfParameters : 0;
--level;
}
tok = tok->next();
if (Token::Match(tok, "(|["))
tok = tok->link()->next();
if (!tok)
return 0;
}
if (tok->str() != ",")
continue;
if (level == 0)
++numberOfParameters;
tok = tok->next();
}
return 0;
}
template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
static T *findTemplateDeclarationEndImpl(T *tok)
{
if (Token::simpleMatch(tok, "template <")) {
tok = tok->next()->findClosingBracket();
if (tok)
tok = tok->next();
}
if (!tok)
return nullptr;
T * tok2 = tok;
bool in_init = false;
while (tok2 && !Token::Match(tok2, ";|{")) {
if (tok2->str() == "<")
tok2 = tok2->findClosingBracket();
else if (Token::Match(tok2, "(|[") && tok2->link())
tok2 = tok2->link();
else if (tok2->str() == ":")
in_init = true;
else if (in_init && Token::Match(tok2, "%name% (|{")) {
tok2 = tok2->linkAt(1);
if (tok2->strAt(1) == "{")
in_init = false;
}
if (tok2)
tok2 = tok2->next();
}
if (tok2 && tok2->str() == "{") {
tok = tok2->link();
if (tok && tok->strAt(1) == ";")
tok = tok->next();
} else if (tok2 && tok2->str() == ";")
tok = tok2;
else
tok = nullptr;
return tok;
}
Token *TemplateSimplifier::findTemplateDeclarationEnd(Token *tok)
{
return findTemplateDeclarationEndImpl(tok);
}
const Token *TemplateSimplifier::findTemplateDeclarationEnd(const Token *tok)
{
return findTemplateDeclarationEndImpl(tok);
}
void TemplateSimplifier::eraseTokens(Token *begin, const Token *end)
{
if (!begin || begin == end)
return;
while (begin->next() && begin->next() != end) {
begin->deleteNext();
}
}
void TemplateSimplifier::deleteToken(Token *tok)
{
if (tok->next())
tok->next()->deletePrevious();
else
tok->deleteThis();
}
static void invalidateForwardDecls(const Token* beg, const Token* end, std::map<Token*, Token*>* forwardDecls) {
if (!forwardDecls)
return;
for (auto& fwd : *forwardDecls) {
for (const Token* tok = beg; tok != end; tok = tok->next())
if (fwd.second == tok) {
fwd.second = nullptr;
break;
}
}
}
bool TemplateSimplifier::removeTemplate(Token *tok, std::map<Token*, Token*>* forwardDecls)
{
if (!Token::simpleMatch(tok, "template <"))
return false;
Token *end = findTemplateDeclarationEnd(tok);
if (end && end->next()) {
invalidateForwardDecls(tok, end->next(), forwardDecls);
eraseTokens(tok, end->next());
deleteToken(tok);
return true;
}
return false;
}
bool TemplateSimplifier::getTemplateDeclarations()
{
bool codeWithTemplates = false;
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "template <"))
continue;
// ignore template template parameter
if (tok->strAt(-1) == "<" || tok->strAt(-1) == ",")
continue;
// ignore nested template
if (tok->strAt(-1) == ">")
continue;
// skip to last nested template parameter
const Token *tok1 = tok;
while (tok1 && tok1->next()) {
const Token *closing = tok1->next()->findClosingBracket();
if (!Token::simpleMatch(closing, "> template <"))
break;
tok1 = closing->next();
}
if (!Token::Match(tok, "%any% %any%"))
syntaxError(tok);
if (tok->strAt(2)=="typename" &&
!Token::Match(tok->tokAt(3), "%name%|...|,|=|>"))
syntaxError(tok->next());
codeWithTemplates = true;
const Token * const parmEnd = tok1->next()->findClosingBracket();
for (const Token *tok2 = parmEnd; tok2; tok2 = tok2->next()) {
if (tok2->str() == "(" && tok2->link())
tok2 = tok2->link();
else if (tok2->str() == ")")
break;
// skip decltype(...)
else if (Token::simpleMatch(tok2, "decltype ("))
tok2 = tok2->linkAt(1);
else if (Token::Match(tok2, "{|=|;")) {
const int namepos = getTemplateNamePosition(parmEnd);
if (namepos > 0) {
TokenAndName decl(tok, tok->scopeInfo()->name, parmEnd->tokAt(namepos), parmEnd);
if (decl.isForwardDeclaration()) {
// Declaration => add to mTemplateForwardDeclarations
mTemplateForwardDeclarations.emplace_back(std::move(decl));
} else {
// Implementation => add to mTemplateDeclarations
mTemplateDeclarations.emplace_back(std::move(decl));
}
Token *end = findTemplateDeclarationEnd(tok);
if (end)
tok = end;
break;
}
}
}
}
return codeWithTemplates;
}
void TemplateSimplifier::addInstantiation(Token *token, const std::string &scope)
{
simplifyTemplateArgs(token->tokAt(2), token->next()->findClosingBracket());
TokenAndName instantiation(token, scope);
// check if instantiation already exists before adding it
const std::list<TokenAndName>::const_iterator it = std::find(mTemplateInstantiations.cbegin(),
mTemplateInstantiations.cend(),
instantiation);
if (it == mTemplateInstantiations.cend())
mTemplateInstantiations.emplace_back(std::move(instantiation));
}
static const Token* getFunctionToken(const Token* nameToken)
{
if (Token::Match(nameToken, "%name% ("))
return nameToken->next();
if (Token::Match(nameToken, "%name% <")) {
const Token* end = nameToken->next()->findClosingBracket();
if (Token::simpleMatch(end, "> ("))
return end->next();
}
return nullptr;
}
static void getFunctionArguments(const Token* nameToken, std::vector<const Token*>& args)
{
const Token* functionToken = getFunctionToken(nameToken);
if (!functionToken)
return;
const Token* argToken = functionToken->next();
if (argToken->str() == ")")
return;
args.push_back(argToken);
while ((argToken = argToken->nextArgumentBeforeCreateLinks2()))
args.push_back(argToken);
}
static bool isConstMethod(const Token* nameToken)
{
const Token* functionToken = getFunctionToken(nameToken);
if (!functionToken)
return false;
const Token* endToken = functionToken->link();
return Token::simpleMatch(endToken, ") const");
}
static bool areAllParamsTypes(const std::vector<const Token *> ¶ms)
{
if (params.empty())
return false;
return std::all_of(params.cbegin(), params.cend(), [](const Token* param) {
return Token::Match(param->previous(), "typename|class %name% ,|>");
});
}
void TemplateSimplifier::getTemplateInstantiations()
{
std::multimap<std::string, const TokenAndName *> functionNameMap;
for (const auto & decl : mTemplateDeclarations) {
if (decl.isFunction())
functionNameMap.emplace(decl.name(), &decl);
}
for (const auto & decl : mTemplateForwardDeclarations) {
if (decl.isFunction())
functionNameMap.emplace(decl.name(), &decl);
}
const Token *skip = nullptr;
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
// template definition.. skip it
if (Token::simpleMatch(tok, "template <")) {
tok = tok->next()->findClosingBracket();
if (!tok)
break;
const bool isUsing = tok->strAt(1) == "using";
if (isUsing && Token::Match(tok->tokAt(2), "%name% <")) {
// Can't have specialized type alias so ignore it
Token *tok2 = Token::findsimplematch(tok->tokAt(3), ";");
if (tok2)
tok = tok2;
} else if (tok->strAt(-1) == "<") {
// Don't ignore user specialization but don't consider it an instantiation.
// Instantiations in return type, function parameters, and executable code
// are not ignored.
const unsigned int pos = getTemplateNamePosition(tok);
if (pos > 0)
skip = tok->tokAt(pos);
} else {
// #7914
// Ignore template instantiations within template definitions: they will only be
// handled if the definition is actually instantiated
Token * tok2 = findTemplateDeclarationEnd(tok->next());
if (tok2)
tok = tok2;
}
} else if (Token::Match(tok, "template using %name% <")) {
// Can't have specialized type alias so ignore it
Token *tok2 = Token::findsimplematch(tok->tokAt(3), ";");
if (tok2)
tok = tok2;
} else if (Token::Match(tok, "using %name% <")) {
// Can't have specialized type alias so ignore it
Token *tok2 = Token::findsimplematch(tok->tokAt(2), ";");
if (tok2)
tok = tok2;
} else if (Token::Match(tok->previous(), "(|{|}|;|=|>|<<|:|.|*|&|return|<|,|!|[ %name% ::|<|(") ||
Token::Match(tok->previous(), "%type% %name% ::|<") ||
Token::Match(tok->tokAt(-2), "[,:] private|protected|public %name% ::|<")) {
if (!tok->scopeInfo())
syntaxError(tok);
std::string scopeName = tok->scopeInfo()->name;
std::string qualification;
Token * qualificationTok = tok;
while (Token::Match(tok, "%name% :: %name%")) {
qualification += (qualification.empty() ? "" : " :: ") + tok->str();
tok = tok->tokAt(2);
}
// skip specialization
if (tok == skip) {
skip = nullptr;
continue;
}
// look for function instantiation with type deduction
if (tok->strAt(1) == "(") {
std::vector<const Token *> instantiationArgs;
getFunctionArguments(tok, instantiationArgs);
std::string fullName;
if (!qualification.empty())
fullName = qualification + " :: " + tok->str();
else if (!scopeName.empty())
fullName = scopeName + " :: " + tok->str();
else
fullName = tok->str();
// get all declarations with this name
auto range = functionNameMap.equal_range(tok->str());
for (auto pos = range.first; pos != range.second; ++pos) {
// look for declaration with same qualification or constructor with same qualification
if (pos->second->fullName() == fullName ||
(pos->second->scope() == fullName && tok->str() == pos->second->name())) {
std::vector<const Token *> templateParams;
getTemplateParametersInDeclaration(pos->second->token()->tokAt(2), templateParams);
// todo: handle more than one template parameter
if (templateParams.size() != 1 || !areAllParamsTypes(templateParams))
continue;
std::vector<const Token *> declarationParams;
getFunctionArguments(pos->second->nameToken(), declarationParams);
// function argument counts must match
if (instantiationArgs.empty() || instantiationArgs.size() != declarationParams.size())
continue;
size_t match = 0;
size_t argMatch = 0;
for (size_t i = 0; i < declarationParams.size(); ++i) {
// fixme: only type deduction from literals is supported
const bool isArgLiteral = Token::Match(instantiationArgs[i], "%num%|%str%|%char%|%bool% ,|)");
if (isArgLiteral && Token::Match(declarationParams[i], "const| %type% &| %name%| ,|)")) {
match++;
// check if parameter types match
if (templateParams[0]->str() == declarationParams[i]->str())
argMatch = i;
else {
// todo: check if non-template args match for function overloads
}
}
}
if (match == declarationParams.size()) {
const Token *arg = instantiationArgs[argMatch];
tok->insertToken(">");
switch (arg->tokType()) {
case Token::eBoolean:
tok->insertToken("bool");
break;
case Token::eChar:
if (arg->isLong())
tok->insertToken("wchar_t");
else
tok->insertToken("char");
break;
case Token::eString:
tok->insertToken("*");
if (arg->isLong())
tok->insertToken("wchar_t");
else
tok->insertToken("char");
tok->insertToken("const");
break;
case Token::eNumber: {
MathLib::value num(arg->str());
if (num.isFloat()) {
// MathLib::getSuffix doesn't work for floating point numbers
const char suffix = arg->str().back();
if (suffix == 'f' || suffix == 'F')
tok->insertToken("float");
else if (suffix == 'l' || suffix == 'L') {
tok->insertToken("double");
tok->next()->isLong(true);
} else
tok->insertToken("double");
} else if (num.isInt()) {
std::string suffix = MathLib::getSuffix(tok->strAt(3));
if (suffix.find("LL") != std::string::npos) {
tok->insertToken("long");
tok->next()->isLong(true);
} else if (suffix.find('L') != std::string::npos)
tok->insertToken("long");
else
tok->insertToken("int");
if (suffix.find('U') != std::string::npos)
tok->next()->isUnsigned(true);
}
break;
}
default:
break;
}
tok->insertToken("<");
break;
}
}
}
}
if (!Token::Match(tok, "%name% <") ||
Token::Match(tok, "const_cast|dynamic_cast|reinterpret_cast|static_cast"))
continue;
if (tok == skip) {
skip = nullptr;
continue;
}
// Add inner template instantiations first => go to the ">"
// and then parse backwards, adding all seen instantiations
Token *tok2 = tok->next()->findClosingBracket();
// parse backwards and add template instantiations
// TODO
for (; tok2 && tok2 != tok; tok2 = tok2->previous()) {
if (Token::Match(tok2, ",|< %name% <") &&
(tok2->strAt(3) == ">" || templateParameters(tok2->tokAt(2)))) {
addInstantiation(tok2->next(), tok->scopeInfo()->name);
} else if (Token::Match(tok2->next(), "class|struct"))
tok2->deleteNext();
}
// Add outer template..
if (templateParameters(tok->next()) || tok->strAt(2) == ">") {
while (true) {
const std::string fullName = scopeName + (scopeName.empty()?"":" :: ") +
qualification + (qualification.empty()?"":" :: ") + tok->str();
const std::list<TokenAndName>::const_iterator it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(fullName));
if (it != mTemplateDeclarations.end()) {
// full name matches
addInstantiation(tok, it->scope());
break;
}
// full name doesn't match so try with using namespaces if available
bool found = false;
for (const auto & nameSpace : tok->scopeInfo()->usingNamespaces) {
std::string fullNameSpace = scopeName + (scopeName.empty()?"":" :: ") +
nameSpace + (qualification.empty()?"":" :: ") + qualification;
std::string newFullName = fullNameSpace + " :: " + tok->str();
const std::list<TokenAndName>::const_iterator it1 = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), FindFullName(std::move(newFullName)));
if (it1 != mTemplateDeclarations.end()) {
// insert using namespace into token stream
std::string::size_type offset = 0;
std::string::size_type pos = 0;
while ((pos = nameSpace.find(' ', offset)) != std::string::npos) {
qualificationTok->insertTokenBefore(nameSpace.substr(offset, pos - offset));
offset = pos + 1;
}
qualificationTok->insertTokenBefore(nameSpace.substr(offset));
qualificationTok->insertTokenBefore("::");
addInstantiation(tok, it1->scope());
found = true;
break;
}
}
if (found)
break;
if (scopeName.empty()) {
if (!qualification.empty())
addInstantiation(tok, qualification);
else
addInstantiation(tok, tok->scopeInfo()->name);
break;
}
const std::string::size_type pos = scopeName.rfind(" :: ");
scopeName = (pos == std::string::npos) ? std::string() : scopeName.substr(0,pos);
}
}
}
}
}
void TemplateSimplifier::useDefaultArgumentValues()
{
for (TokenAndName &declaration : mTemplateDeclarations)
useDefaultArgumentValues(declaration);
for (TokenAndName &declaration : mTemplateForwardDeclarations)
useDefaultArgumentValues(declaration);
}
void TemplateSimplifier::useDefaultArgumentValues(TokenAndName &declaration)
{
// Ticket #5762: Skip specialization tokens
if (declaration.isSpecialization() || declaration.isAlias() || declaration.isFriend())
return;
// template parameters with default value has syntax such as:
// x = y
// this list will contain all the '=' tokens for such arguments
struct Default {
Token *eq;
Token *end;
};
std::list<Default> eq;
// and this set the position of parameters with a default value
std::set<std::size_t> defaultedArgPos;
// parameter number. 1,2,3,..
std::size_t templatepar = 1;
// parameter depth
std::size_t templateParmDepth = 0;
// map type parameter name to index
std::map<std::string, unsigned int> typeParameterNames;
// Scan template declaration..
for (Token *tok = declaration.token()->next(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "template <")) {
Token* end = tok->next()->findClosingBracket();
if (end)
tok = end;
continue;
}
if (tok->link() && Token::Match(tok, "{|(|[")) { // Ticket #6835
tok = tok->link();
continue;
}
if (tok->str() == "<" &&
(tok->strAt(1) == ">" || (tok->previous()->isName() &&
typeParameterNames.find(tok->strAt(-1)) == typeParameterNames.end())))
++templateParmDepth;
// end of template parameters?
if (tok->str() == ">") {
if (templateParmDepth<2) {
if (!eq.empty())
eq.back().end = tok;
break;
}
--templateParmDepth;
}
// map type parameter name to index
if (Token::Match(tok, "typename|class|%type% %name% ,|>"))
typeParameterNames[tok->strAt(1)] = templatepar - 1;
// next template parameter
if (tok->str() == "," && (1 == templateParmDepth)) { // Ticket #5823: Properly count parameters
if (!eq.empty())
eq.back().end = tok;
++templatepar;
}
// default parameter value?
else if (Token::Match(tok, "= !!>")) {
if (defaultedArgPos.insert(templatepar).second) {
eq.emplace_back(Default{tok, nullptr});
} else {
// Ticket #5605: Syntax error (two equal signs for the same parameter), bail out
eq.clear();
break;
}
}
}
if (eq.empty())
return;
// iterate through all template instantiations
for (const TokenAndName &instantiation : mTemplateInstantiations) {
if (declaration.fullName() != instantiation.fullName())
continue;
// instantiation arguments..
std::vector<std::vector<const Token *>> instantiationArgs;
std::size_t index = 0;
const Token *end = instantiation.token()->next()->findClosingBracket();
if (!end)
continue;
if (end != instantiation.token()->tokAt(2))
instantiationArgs.resize(1);
for (const Token *tok1 = instantiation.token()->tokAt(2); tok1 && tok1 != end; tok1 = tok1->next()) {
if (tok1->link() && Token::Match(tok1, "{|(|[")) {
const Token *endLink = tok1->link();
do {
instantiationArgs[index].push_back(tok1);
tok1 = tok1->next();
} while (tok1 && tok1 != endLink);
instantiationArgs[index].push_back(tok1);
} else if (tok1->str() == "<" &&
(tok1->strAt(1) == ">" || (tok1->previous()->isName() &&
typeParameterNames.find(tok1->strAt(-1)) == typeParameterNames.end()))) {
const Token *endLink = tok1->findClosingBracket();
do {
instantiationArgs[index].push_back(tok1);
tok1 = tok1->next();
} while (tok1 && tok1 != endLink);
instantiationArgs[index].push_back(tok1);
} else if (tok1->str() == ",") {
++index;
instantiationArgs.resize(index + 1);
} else
instantiationArgs[index].push_back(tok1);
}
// count the parameters..
Token *tok = instantiation.token()->next();
unsigned int usedpar = templateParameters(tok);
Token *instantiationEnd = tok->findClosingBracket();
tok = instantiationEnd;
if (tok && tok->str() == ">") {
tok = tok->previous();
std::list<Default>::const_iterator it = eq.cbegin();
for (std::size_t i = (templatepar - eq.size()); it != eq.cend() && i < usedpar; ++i)
++it;
int count = 0;
while (it != eq.cend()) {
// check for end
if (!it->end) {
if (mSettings.debugwarnings && mSettings.severity.isEnabled(Severity::debug)) {
const std::list<const Token*> locationList(1, it->eq);
const ErrorMessage errmsg(locationList, &mTokenizer.list,
Severity::debug,
"noparamend",
"TemplateSimplifier couldn't find end of template parameter.",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
break;
}
if ((usedpar + count) && usedpar <= (instantiationArgs.size() + count)) {
tok->insertToken(",");
tok = tok->next();
}
std::stack<Token *> links;
for (const Token* from = it->eq->next(); from && from != it->end; from = from->next()) {
auto entry = typeParameterNames.find(from->str());
if (entry != typeParameterNames.end() && entry->second < instantiationArgs.size()) {
for (const Token *tok1 : instantiationArgs[entry->second]) {
tok->insertToken(tok1->str(), tok1->originalName());
tok = tok->next();
if (Token::Match(tok, "(|[|{"))
links.push(tok);
else if (!links.empty() && Token::Match(tok, ")|]|}")) {
Token::createMutualLinks(links.top(), tok);
links.pop();
}
}
} else {
tok->insertToken(from->str(), from->originalName());
tok = tok->next();
if (Token::Match(tok, "(|[|{"))
links.push(tok);
else if (!links.empty() && Token::Match(tok, ")|]|}")) {
Token::createMutualLinks(links.top(), tok);
links.pop();
}
}
}
++it;
count++;
usedpar++;
}
}
simplifyTemplateArgs(instantiation.token()->next(), instantiationEnd);
}
for (const auto & entry : eq) {
Token *const eqtok = entry.eq;
Token *tok2;
int indentlevel = 0;
for (tok2 = eqtok->next(); tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, ";|)|}|]")) { // bail out #6607
tok2 = nullptr;
break;
}
if (Token::Match(tok2, "(|{|["))
tok2 = tok2->link();
else if (Token::Match(tok2, "%type% <") && (tok2->strAt(2) == ">" || templateParameters(tok2->next()))) {
const std::list<TokenAndName>::const_iterator ti = std::find_if(mTemplateInstantiations.cbegin(),
mTemplateInstantiations.cend(),
FindToken(tok2));
if (ti != mTemplateInstantiations.end())
mTemplateInstantiations.erase(ti);
++indentlevel;
} else if (indentlevel > 0 && tok2->str() == ">")
--indentlevel;
else if (indentlevel == 0 && Token::Match(tok2, ",|>"))
break;
if (indentlevel < 0)
break;
}
// something went wrong, don't call eraseTokens()
// with a nullptr "end" parameter (=all remaining tokens).
if (!tok2)
continue;
// don't strip args from uninstantiated templates
const std::list<TokenAndName>::const_iterator ti2 = std::find_if(mTemplateInstantiations.cbegin(),
mTemplateInstantiations.cend(),
FindName(declaration.name()));
if (ti2 == mTemplateInstantiations.end())
continue;
eraseTokens(eqtok, tok2);
eqtok->deleteThis();
// update parameter end pointer
declaration.paramEnd(declaration.token()->next()->findClosingBracket());
}
}
void TemplateSimplifier::simplifyTemplateAliases()
{
for (std::list<TokenAndName>::const_iterator it1 = mTemplateDeclarations.cbegin(); it1 != mTemplateDeclarations.cend();) {
const TokenAndName &aliasDeclaration = *it1;
if (!aliasDeclaration.isAlias()) {
++it1;
continue;
}
// alias parameters..
std::vector<const Token *> aliasParameters;
getTemplateParametersInDeclaration(aliasDeclaration.token()->tokAt(2), aliasParameters);
std::map<std::string, unsigned int> aliasParameterNames;
for (unsigned int argnr = 0; argnr < aliasParameters.size(); ++argnr)
aliasParameterNames[aliasParameters[argnr]->str()] = argnr;
// Look for alias usages..
bool found = false;
for (std::list<TokenAndName>::const_iterator it2 = mTemplateInstantiations.cbegin(); it2 != mTemplateInstantiations.cend();) {
const TokenAndName &aliasUsage = *it2;
if (!aliasUsage.token() || aliasUsage.fullName() != aliasDeclaration.fullName()) {
++it2;
continue;
}
// don't recurse
if (aliasDeclaration.isAliasToken(aliasUsage.token())) {
++it2;
continue;
}
std::vector<std::pair<Token *, Token *>> args;
Token *tok2 = aliasUsage.token()->tokAt(2);
while (tok2) {
Token * const start = tok2;
while (tok2 && !Token::Match(tok2, "[,>;{}]")) {
if (tok2->link() && Token::Match(tok2, "(|["))
tok2 = tok2->link();
else if (tok2->str() == "<") {
tok2 = tok2->findClosingBracket();
if (!tok2)
break;
}
tok2 = tok2->next();
}
args.emplace_back(start, tok2);
if (tok2 && tok2->str() == ",") {
tok2 = tok2->next();
} else {
break;
}
}
if (!tok2 || tok2->str() != ">" ||
(!aliasDeclaration.isVariadic() && (args.size() != aliasParameters.size())) ||
(aliasDeclaration.isVariadic() && (args.size() < aliasParameters.size()))) {
++it2;
continue;
}
mChanged = true;
// copy template-id from declaration to after instantiation
Token * dst = aliasUsage.token()->next()->findClosingBracket();
const Token* end = TokenList::copyTokens(dst, aliasDeclaration.aliasStartToken(), aliasDeclaration.aliasEndToken()->previous(), false)->next();
// replace parameters
for (Token *tok1 = dst->next(); tok1 != end; tok1 = tok1->next()) {
if (!tok1->isName())
continue;
if (aliasParameterNames.find(tok1->str()) != aliasParameterNames.end()) {
const unsigned int argnr = aliasParameterNames[tok1->str()];
const Token * const fromStart = args[argnr].first;
const Token * const fromEnd = args[argnr].second->previous();
Token *temp = TokenList::copyTokens(tok1, fromStart, fromEnd, true);
const bool tempOK(temp != tok1->next());
tok1->deleteThis();
if (tempOK)
tok1 = temp; // skip over inserted parameters
} else if (tok1->str() == "typename")
tok1->deleteThis();
}
// add new instantiations
for (Token *tok1 = dst->next(); tok1 != end; tok1 = tok1->next()) {
if (!tok1->isName())
continue;
if (aliasParameterNames.find(tok2->str()) == aliasParameterNames.end()) {
// Create template instance..
if (Token::Match(tok1, "%name% <")) {
const std::list<TokenAndName>::const_iterator it = std::find_if(mTemplateInstantiations.cbegin(),
mTemplateInstantiations.cend(),
FindToken(tok1));
if (it != mTemplateInstantiations.cend())
addInstantiation(tok2, it->scope());
}
}
}
// erase the instantiation tokens
eraseTokens(aliasUsage.token()->previous(), dst->next());
found = true;
// erase this instantiation
it2 = mTemplateInstantiations.erase(it2);
}
if (found) {
auto *end = const_cast<Token *>(aliasDeclaration.aliasEndToken());
// remove declaration tokens
if (aliasDeclaration.token()->previous())
eraseTokens(aliasDeclaration.token()->previous(), end->next() ? end->next() : end);
else {
eraseTokens(mTokenList.front(), end->next() ? end->next() : end);
deleteToken(mTokenList.front());
}
// remove declaration
it1 = mTemplateDeclarations.erase(it1);
} else
++it1;
}
}
bool TemplateSimplifier::instantiateMatch(const Token *instance, const std::size_t numberOfArguments, bool variadic, const char patternAfter[])
{
assert(instance->strAt(1) == "<");
auto n = templateParameters(instance->next());
if (variadic ? (n + 1 < numberOfArguments) : (numberOfArguments != n))
return false;
if (patternAfter) {
const Token *tok = instance->next()->findClosingBracket();
if (!tok || !Token::Match(tok->next(), patternAfter))
return false;
}
// nothing mismatching was found..
return true;
}
// Utility function for TemplateSimplifier::getTemplateNamePosition, that works on template functions
bool TemplateSimplifier::getTemplateNamePositionTemplateFunction(const Token *tok, int &namepos)
{
namepos = 1;
while (tok && tok->next()) {
if (Token::Match(tok->next(), ";|{"))
return false;
// skip decltype(...)
if (Token::simpleMatch(tok->next(), "decltype (")) {
const Token * end = tok->linkAt(2)->previous();
while (tok->next() && tok != end) {
tok = tok->next();
namepos++;
}
} else if (Token::Match(tok->next(), "%type% <")) {
const Token *closing = tok->tokAt(2)->findClosingBracket();
if (closing) {
if (closing->strAt(1) == "(" && Tokenizer::isFunctionHead(closing->next(), ";|{|:"))
return true;
while (tok->next() && tok->next() != closing) {
tok = tok->next();
namepos++;
}
}
} else if (Token::Match(tok->next(), "%type% (") && Tokenizer::isFunctionHead(tok->tokAt(2), ";|{|:")) {
return true;
}
tok = tok->next();
namepos++;
}
return false;
}
bool TemplateSimplifier::getTemplateNamePositionTemplateVariable(const Token *tok, int &namepos)
{
namepos = 1;
while (tok && tok->next()) {
if (Token::Match(tok->next(), ";|{|(|using"))
return false;
// skip decltype(...)
if (Token::simpleMatch(tok->next(), "decltype (")) {
const Token * end = tok->linkAt(2);
while (tok->next() && tok != end) {
tok = tok->next();
namepos++;
}
} else if (Token::Match(tok->next(), "%type% <")) {
const Token *closing = tok->tokAt(2)->findClosingBracket();
if (closing) {
if (Token::Match(closing->next(), "=|;"))
return true;
while (tok->next() && tok->next() != closing) {
tok = tok->next();
namepos++;
}
}
} else if (Token::Match(tok->next(), "%type% =|;")) {
return true;
}
tok = tok->next();
namepos++;
}
return false;
}
bool TemplateSimplifier::getTemplateNamePositionTemplateClass(const Token *tok, int &namepos)
{
if (Token::Match(tok, "> friend| class|struct|union %type% :|<|;|{|::")) {
namepos = tok->strAt(1) == "friend" ? 3 : 2;
tok = tok->tokAt(namepos);
while (Token::Match(tok, "%type% :: %type%") ||
(Token::Match(tok, "%type% <") && Token::Match(tok->next()->findClosingBracket(), "> :: %type%"))) {
if (tok->strAt(1) == "::") {
tok = tok->tokAt(2);
namepos += 2;
} else {
const Token *end = tok->next()->findClosingBracket();
if (!end || !end->tokAt(2)) {
// syntax error
namepos = -1;
return true;
}
end = end->tokAt(2);
do {
tok = tok->next();
namepos += 1;
} while (tok && tok != end);
}
}
return true;
}
return false;
}
int TemplateSimplifier::getTemplateNamePosition(const Token *tok)
{
if (!tok || tok->str() != ">")
syntaxError(tok);
auto it = mTemplateNamePos.find(tok);
if (!mSettings.debugtemplate && it != mTemplateNamePos.end()) {
return it->second;
}
// get the position of the template name
int namepos = 0;
if (getTemplateNamePositionTemplateClass(tok, namepos))
;
else if (Token::Match(tok, "> using %name% =")) {
// types may not be defined in alias template declarations
if (!Token::Match(tok->tokAt(4), "class|struct|union|enum %name%| {"))
namepos = 2;
} else if (getTemplateNamePositionTemplateVariable(tok, namepos))
;
else if (!getTemplateNamePositionTemplateFunction(tok, namepos))
namepos = -1; // Name not found
mTemplateNamePos[tok] = namepos;
return namepos;
}
void TemplateSimplifier::addNamespace(const TokenAndName &templateDeclaration, const Token *tok)
{
// find start of qualification
const Token * tokStart = tok;
int offset = 0;
while (Token::Match(tokStart->tokAt(-2), "%name% ::")) {
tokStart = tokStart->tokAt(-2);
offset -= 2;
}
// decide if namespace needs to be inserted in or appended to token list
const bool insert = tokStart != tok;
std::string::size_type start = 0;
std::string::size_type end = 0;
bool inTemplate = false;
int level = 0;
while ((end = templateDeclaration.scope().find(' ', start)) != std::string::npos) {
std::string token = templateDeclaration.scope().substr(start, end - start);
// done if scopes overlap
if (token == tokStart->str() && tok->strAt(-1) != "::")
break;
if (token == "<") {
inTemplate = true;
++level;
}
if (inTemplate) {
if (insert)
mTokenList.back()->tokAt(offset)->str(mTokenList.back()->strAt(offset) + token);
else
mTokenList.back()->str(mTokenList.back()->str() + token);
if (token == ">") {
--level;
if (level == 0)
inTemplate = false;
}
} else {
if (insert)
mTokenList.back()->tokAt(offset)->insertToken(token, emptyString);
else
mTokenList.addtoken(token, tok->linenr(), tok->column(), tok->fileIndex());
}
start = end + 1;
}
// don't add if it already exists
std::string token = templateDeclaration.scope().substr(start, end - start);
if (token != tokStart->str() || tok->strAt(-1) != "::") {
if (insert) {
if (!inTemplate)
mTokenList.back()->tokAt(offset)->insertToken(templateDeclaration.scope().substr(start), emptyString);
else
mTokenList.back()->tokAt(offset)->str(mTokenList.back()->strAt(offset) + templateDeclaration.scope().substr(start));
mTokenList.back()->tokAt(offset)->insertToken("::", emptyString);
} else {
if (!inTemplate)
mTokenList.addtoken(templateDeclaration.scope().substr(start), tok->linenr(), tok->column(), tok->fileIndex());
else
mTokenList.back()->str(mTokenList.back()->str() + templateDeclaration.scope().substr(start));
mTokenList.addtoken("::", tok->linenr(), tok->column(), tok->fileIndex());
}
}
}
bool TemplateSimplifier::alreadyHasNamespace(const TokenAndName &templateDeclaration, const Token *tok)
{
const std::string& scope = templateDeclaration.scope();
// get the length in tokens of the namespace
std::string::size_type pos = 0;
int offset = -2;
while ((pos = scope.find("::", pos)) != std::string::npos) {
offset -= 2;
pos += 2;
}
return Token::simpleMatch(tok->tokAt(offset), scope.c_str(), scope.size());
}
struct newInstantiation {
newInstantiation(Token* t, std::string s) : token(t), scope(std::move(s)) {}
Token* token;
std::string scope;
};
void TemplateSimplifier::expandTemplate(
const TokenAndName &templateDeclaration,
const TokenAndName &templateInstantiation,
const std::vector<const Token *> &typeParametersInDeclaration,
const std::string &newName,
bool copy)
{
bool inTemplateDefinition = false;
const Token *startOfTemplateDeclaration = nullptr;
const Token *endOfTemplateDefinition = nullptr;
const Token * const templateDeclarationNameToken = templateDeclaration.nameToken();
const Token * const templateDeclarationToken = templateDeclaration.paramEnd();
const bool isClass = templateDeclaration.isClass();
const bool isFunction = templateDeclaration.isFunction();
const bool isSpecialization = templateDeclaration.isSpecialization();
const bool isVariable = templateDeclaration.isVariable();
std::vector<newInstantiation> newInstantiations;
// add forward declarations
if (copy && isClass) {
templateDeclaration.token()->insertTokenBefore(templateDeclarationToken->strAt(1));
templateDeclaration.token()->insertTokenBefore(newName);
templateDeclaration.token()->insertTokenBefore(";");
} else if ((isFunction && (copy || isSpecialization)) ||
(isVariable && !isSpecialization) ||
(isClass && isSpecialization && mTemplateSpecializationMap.find(templateDeclaration.token()) != mTemplateSpecializationMap.end())) {
Token * dst = templateDeclaration.token();
Token * dstStart = dst->previous();
bool isStatic = false;
std::string scope;
const Token * start;
const Token * end;
auto it = mTemplateForwardDeclarationsMap.find(dst);
if (!isSpecialization && it != mTemplateForwardDeclarationsMap.end()) {
dst = it->second;
dstStart = dst->previous();
const Token * temp1 = dst->tokAt(1)->findClosingBracket();
const Token * temp2 = temp1->tokAt(getTemplateNamePosition(temp1));
start = temp1->next();
end = temp2->linkAt(1)->next();
} else {
if (it != mTemplateForwardDeclarationsMap.end()) {
const std::list<TokenAndName>::const_iterator it1 = std::find_if(mTemplateForwardDeclarations.cbegin(),
mTemplateForwardDeclarations.cend(),
FindToken(it->second));
if (it1 != mTemplateForwardDeclarations.cend())
mMemberFunctionsToDelete.push_back(*it1);
}
auto it2 = mTemplateSpecializationMap.find(dst);
if (it2 != mTemplateSpecializationMap.end()) {
dst = it2->second;
dstStart = dst->previous();
isStatic = dst->next()->findClosingBracket()->strAt(1) == "static";
const Token * temp = templateDeclarationNameToken;
while (Token::Match(temp->tokAt(-2), "%name% ::")) {
scope.insert(0, temp->strAt(-2) + " :: ");
temp = temp->tokAt(-2);
}
}
start = templateDeclarationToken->next();
end = templateDeclarationNameToken->next();
if (end->str() == "<")
end = end->findClosingBracket()->next();
if (end->str() == "(")
end = end->link()->next();
else if (isVariable && end->str() == "=") {
const Token *temp = end->next();
while (temp && temp->str() != ";") {
if (temp->link() && Token::Match(temp, "{|[|("))
temp = temp->link();
temp = temp->next();
}
end = temp;
}
}
unsigned int typeindentlevel = 0;
while (end && !(typeindentlevel == 0 && Token::Match(end, ";|{|:"))) {
if (Token::Match(end, "<|(|{"))
++typeindentlevel;
else if (Token::Match(end, ">|)|}"))
--typeindentlevel;
end = end->next();
}
if (isStatic) {
dst->insertTokenBefore("static");
if (start) {
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
}
}
std::map<const Token *, Token *> links;
bool inAssignment = false;
while (start && start != end) {
if (isVariable && start->str() == "=")
inAssignment = true;
unsigned int itype = 0;
while (itype < typeParametersInDeclaration.size() && typeParametersInDeclaration[itype]->str() != start->str())
++itype;
if (itype < typeParametersInDeclaration.size() && itype < mTypesUsedInTemplateInstantiation.size() &&
(!isVariable || !Token::Match(typeParametersInDeclaration[itype]->previous(), "<|, %type% >|,"))) {
typeindentlevel = 0;
std::stack<Token *> brackets1; // holds "(" and "{" tokens
bool pointerType = false;
Token * const dst1 = dst->previous();
const bool isVariadicTemplateArg = templateDeclaration.isVariadic() && itype + 1 == typeParametersInDeclaration.size();
if (isVariadicTemplateArg && Token::Match(start, "%name% ... %name%"))
start = start->tokAt(2);
const std::string endStr(isVariadicTemplateArg ? ">" : ",>");
for (const Token *typetok = mTypesUsedInTemplateInstantiation[itype].token();
typetok && (typeindentlevel > 0 || endStr.find(typetok->str()[0]) == std::string::npos);
typetok = typetok->next()) {
if (typeindentlevel == 0 && typetok->str() == "*")
pointerType = true;
if (Token::simpleMatch(typetok, "..."))
continue;
if (Token::Match(typetok, "%name% <") && (typetok->strAt(2) == ">" || templateParameters(typetok->next())))
++typeindentlevel;
else if (typeindentlevel > 0 && typetok->str() == ">")
--typeindentlevel;
else if (typetok->str() == "(")
++typeindentlevel;
else if (typetok->str() == ")")
--typeindentlevel;
dst->insertToken(typetok->str(), typetok->originalName(), typetok->getMacroName(), true);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
Token *previous = dst->previous();
previous->isTemplateArg(true);
previous->isSigned(typetok->isSigned());
previous->isUnsigned(typetok->isUnsigned());
previous->isLong(typetok->isLong());
if (Token::Match(previous, "{|(|[")) {
brackets1.push(previous);
} else if (previous->str() == "}") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "{");
Token::createMutualLinks(brackets1.top(), previous);
brackets1.pop();
} else if (previous->str() == ")") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "(");
Token::createMutualLinks(brackets1.top(), previous);
brackets1.pop();
} else if (previous->str() == "]") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "[");
Token::createMutualLinks(brackets1.top(), previous);
brackets1.pop();
}
}
if (pointerType && Token::simpleMatch(dst1, "const")) {
dst->insertToken("const", dst1->originalName(), dst1->getMacroName(), true);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
dst1->deleteThis();
}
} else {
if (isSpecialization && !copy && !scope.empty() && Token::Match(start, (scope + templateDeclarationNameToken->str()).c_str())) {
// skip scope
while (start->strAt(1) != templateDeclarationNameToken->str())
start = start->next();
} else if (start->str() == templateDeclarationNameToken->str() &&
!(templateDeclaration.isFunction() && templateDeclaration.scope().empty() &&
(start->strAt(-1) == "." || Token::simpleMatch(start->tokAt(-2), ". template")))) {
if (start->strAt(1) != "<" || Token::Match(start, newName.c_str()) || !inAssignment) {
dst->insertTokenBefore(newName);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
if (start->strAt(1) == "<")
start = start->next()->findClosingBracket();
} else {
dst->insertTokenBefore(start->str());
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
newInstantiations.emplace_back(dst->previous(), templateDeclaration.scope());
}
} else {
// check if type is a template
if (start->strAt(1) == "<") {
// get the instantiated name
const Token * closing = start->next()->findClosingBracket();
if (closing) {
std::string name;
const Token * type = start;
while (type && type != closing->next()) {
if (!name.empty())
name += " ";
name += type->str();
type = type->next();
}
// check if type is instantiated
if (std::any_of(mTemplateInstantiations.cbegin(), mTemplateInstantiations.cend(), [&](const TokenAndName& inst) {
return Token::simpleMatch(inst.token(), name.c_str(), name.size());
})) {
// use the instantiated name
dst->insertTokenBefore(name);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
start = closing;
}
}
// just copy the token if it wasn't instantiated
if (start != closing) {
dst->insertToken(start->str(), start->originalName(), start->getMacroName(), true);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
dst->previous()->isSigned(start->isSigned());
dst->previous()->isUnsigned(start->isUnsigned());
dst->previous()->isLong(start->isLong());
}
} else {
dst->insertToken(start->str(), start->originalName(), start->getMacroName(), true);
dst->previous()->linenr(start->linenr());
dst->previous()->column(start->column());
dst->previous()->isSigned(start->isSigned());
dst->previous()->isUnsigned(start->isUnsigned());
dst->previous()->isLong(start->isLong());
}
}
if (!start)
continue;
if (start->link()) {
if (Token::Match(start, "[|{|(")) {
links[start->link()] = dst->previous();
} else if (Token::Match(start, "]|}|)")) {
std::map<const Token *, Token *>::const_iterator link = links.find(start);
// make sure link is valid
if (link != links.cend()) {
Token::createMutualLinks(link->second, dst->previous());
links.erase(start);
}
}
}
}
start = start->next();
}
dst->insertTokenBefore(";");
dst->previous()->linenr(dst->tokAt(-2)->linenr());
dst->previous()->column(dst->tokAt(-2)->column() + 1);
if (isVariable || isFunction)
simplifyTemplateArgs(dstStart, dst);
}
if (copy && (isClass || isFunction)) {
// check if this is an explicit instantiation
Token * start = templateInstantiation.token();
while (start && !Token::Match(start->previous(), "}|;|extern"))
start = start->previous();
if (Token::Match(start, "template !!<")) {
if (start->strAt(-1) == "extern")
start = start->previous();
mExplicitInstantiationsToDelete.emplace_back(start, "");
}
}
for (Token *tok3 = mTokenList.front(); tok3; tok3 = tok3 ? tok3->next() : nullptr) {
if (inTemplateDefinition) {
if (!endOfTemplateDefinition) {
if (isVariable) {
Token *temp = tok3->findClosingBracket();
if (temp) {
while (temp && temp->str() != ";") {
if (temp->link() && Token::Match(temp, "{|[|("))
temp = temp->link();
temp = temp->next();
}
endOfTemplateDefinition = temp;
}
} else if (tok3->str() == "{")
endOfTemplateDefinition = tok3->link();
}
if (tok3 == endOfTemplateDefinition) {
inTemplateDefinition = false;
startOfTemplateDeclaration = nullptr;
}
}
if (tok3->str()=="template") {
if (tok3->next() && tok3->strAt(1)=="<") {
std::vector<const Token *> localTypeParametersInDeclaration;
getTemplateParametersInDeclaration(tok3->tokAt(2), localTypeParametersInDeclaration);
inTemplateDefinition = localTypeParametersInDeclaration.size() == typeParametersInDeclaration.size(); // Partial specialization
} else {
inTemplateDefinition = false; // Only template instantiation
}
startOfTemplateDeclaration = tok3;
}
if (Token::Match(tok3, "(|["))
tok3 = tok3->link();
// Start of template..
if (tok3 == templateDeclarationToken) {
tok3 = tok3->next();
if (tok3->str() == "static")
tok3 = tok3->next();
}
// member function implemented outside class definition
else if (inTemplateDefinition &&
Token::Match(tok3, "%name% <") &&
templateInstantiation.name() == tok3->str() &&
instantiateMatch(tok3, typeParametersInDeclaration.size(), templateDeclaration.isVariadic(), ":: ~| %name% (")) {
// there must be template..
bool istemplate = false;
Token * tok5 = nullptr; // start of function return type
for (Token *prev = tok3; prev && !Token::Match(prev, "[;{}]"); prev = prev->previous()) {
if (prev->str() == "template") {
istemplate = true;
tok5 = prev;
break;
}
}
if (!istemplate)
continue;
const Token *tok4 = tok3->next()->findClosingBracket();
while (tok4 && tok4->str() != "(")
tok4 = tok4->next();
if (!Tokenizer::isFunctionHead(tok4, ":{"))
continue;
// find function return type start
tok5 = tok5->next()->findClosingBracket();
if (tok5)
tok5 = tok5->next();
// copy return type
std::stack<Token *> brackets2; // holds "(" and "{" tokens
while (tok5 && tok5 != tok3) {
// replace name if found
if (Token::Match(tok5, "%name% <") && tok5->str() == templateInstantiation.name()) {
if (copy) {
if (!templateDeclaration.scope().empty() && tok5->strAt(-1) != "::")
addNamespace(templateDeclaration, tok5);
mTokenList.addtoken(newName, tok5->linenr(), tok5->column(), tok5->fileIndex());
tok5 = tok5->next()->findClosingBracket();
} else {
tok5->str(newName);
eraseTokens(tok5, tok5->next()->findClosingBracket()->next());
}
} else if (copy) {
bool added = false;
if (tok5->isName() && !Token::Match(tok5, "class|typename|struct") && !tok5->isStandardType()) {
// search for this token in the type vector
unsigned int itype = 0;
while (itype < typeParametersInDeclaration.size() && typeParametersInDeclaration[itype]->str() != tok5->str())
++itype;
// replace type with given type..
if (itype < typeParametersInDeclaration.size() && itype < mTypesUsedInTemplateInstantiation.size()) {
std::stack<Token *> brackets1; // holds "(" and "{" tokens
for (const Token *typetok = mTypesUsedInTemplateInstantiation[itype].token();
typetok && !Token::Match(typetok, ",|>");
typetok = typetok->next()) {
if (!Token::simpleMatch(typetok, "...")) {
mTokenList.addtoken(typetok, tok5);
Token *back = mTokenList.back();
if (Token::Match(back, "{|(|[")) {
brackets1.push(back);
} else if (back->str() == "}") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "{");
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
} else if (back->str() == ")") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "(");
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
} else if (back->str() == "]") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "[");
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
}
back->isTemplateArg(true);
back->isUnsigned(typetok->isUnsigned());
back->isSigned(typetok->isSigned());
back->isLong(typetok->isLong());
added = true;
break;
}
}
}
}
if (!added) {
mTokenList.addtoken(tok5);
Token *back = mTokenList.back();
if (Token::Match(back, "{|(|[")) {
brackets2.push(back);
} else if (back->str() == "}") {
assert(brackets2.empty() == false);
assert(brackets2.top()->str() == "{");
Token::createMutualLinks(brackets2.top(), back);
brackets2.pop();
} else if (back->str() == ")") {
assert(brackets2.empty() == false);
assert(brackets2.top()->str() == "(");
Token::createMutualLinks(brackets2.top(), back);
brackets2.pop();
} else if (back->str() == "]") {
assert(brackets2.empty() == false);
assert(brackets2.top()->str() == "[");
Token::createMutualLinks(brackets2.top(), back);
brackets2.pop();
}
}
}
tok5 = tok5->next();
}
if (copy) {
if (!templateDeclaration.scope().empty() && tok3->strAt(-1) != "::")
addNamespace(templateDeclaration, tok3);
mTokenList.addtoken(newName, tok3->linenr(), tok3->column(), tok3->fileIndex());
}
while (tok3 && tok3->str() != "::")
tok3 = tok3->next();
const std::list<TokenAndName>::const_iterator it = std::find_if(mTemplateDeclarations.cbegin(),
mTemplateDeclarations.cend(),
FindToken(startOfTemplateDeclaration));
if (it != mTemplateDeclarations.cend())
mMemberFunctionsToDelete.push_back(*it);
}
// not part of template.. go on to next token
else
continue;
std::stack<Token *> brackets; // holds "(", "[" and "{" tokens
// FIXME use full name matching somehow
const std::string lastName = (templateInstantiation.name().find(' ') != std::string::npos) ? templateInstantiation.name().substr(templateInstantiation.name().rfind(' ')+1) : templateInstantiation.name();
std::stack<const Token *> templates;
int scopeCount = 0;
for (; tok3; tok3 = tok3->next()) {
if (tok3->str() == "{")
++scopeCount;
else if (tok3->str() == "}")
--scopeCount;
if (scopeCount < 0)
break;
if (tok3->isName() && !Token::Match(tok3, "class|typename|struct") && !tok3->isStandardType()) {
// search for this token in the type vector
unsigned int itype = 0;
while (itype < typeParametersInDeclaration.size() && typeParametersInDeclaration[itype]->str() != tok3->str())
++itype;
// replace type with given type..
if (itype < typeParametersInDeclaration.size() && itype < mTypesUsedInTemplateInstantiation.size()) {
unsigned int typeindentlevel = 0;
std::stack<Token *> brackets1; // holds "(" and "{" tokens
Token * const beforeTypeToken = mTokenList.back();
bool pointerType = false;
const bool isVariadicTemplateArg = templateDeclaration.isVariadic() && itype + 1 == typeParametersInDeclaration.size();
if (isVariadicTemplateArg && mTypesUsedInTemplateInstantiation.size() > 1 && !Token::simpleMatch(tok3->next(), "..."))
continue;
if (isVariadicTemplateArg && Token::Match(tok3, "%name% ... %name%"))
tok3 = tok3->tokAt(2);
const std::string endStr(isVariadicTemplateArg ? ">" : ",>");
for (Token *typetok = mTypesUsedInTemplateInstantiation[itype].token();
typetok && (typeindentlevel > 0 || endStr.find(typetok->str()[0]) == std::string::npos);
typetok = typetok->next()) {
if (typeindentlevel == 0 && typetok->str() == "*")
pointerType = true;
if (Token::simpleMatch(typetok, "..."))
continue;
if (Token::Match(typetok, "%name% <") &&
(typetok->strAt(2) == ">" || templateParameters(typetok->next()))) {
brackets1.push(typetok->next());
++typeindentlevel;
} else if (typeindentlevel > 0 && typetok->str() == ">" && brackets1.top()->str() == "<") {
--typeindentlevel;
brackets1.pop();
} else if (Token::Match(typetok, "const_cast|dynamic_cast|reinterpret_cast|static_cast <")) {
brackets1.push(typetok->next());
++typeindentlevel;
} else if (typetok->str() == "(")
++typeindentlevel;
else if (typetok->str() == ")")
--typeindentlevel;
Token *back;
if (copy) {
mTokenList.addtoken(typetok, tok3);
back = mTokenList.back();
} else
back = typetok;
if (Token::Match(back, "{|(|["))
brackets1.push(back);
else if (back->str() == "}") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "{");
if (copy)
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
} else if (back->str() == ")") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "(");
if (copy)
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
} else if (back->str() == "]") {
assert(brackets1.empty() == false);
assert(brackets1.top()->str() == "[");
if (copy)
Token::createMutualLinks(brackets1.top(), back);
brackets1.pop();
}
if (copy)
back->isTemplateArg(true);
}
if (pointerType && Token::simpleMatch(beforeTypeToken, "const")) {
mTokenList.addtoken(beforeTypeToken);
beforeTypeToken->deleteThis();
}
continue;
}
}
// replace name..
if (tok3->str() == lastName) {
if (Token::simpleMatch(tok3->next(), "<")) {
Token *closingBracket = tok3->next()->findClosingBracket();
if (closingBracket) {
// replace multi token name with single token name
if (tok3 == templateDeclarationNameToken ||
Token::Match(tok3, newName.c_str())) {
if (copy) {
mTokenList.addtoken(newName, tok3);
tok3 = closingBracket;
} else {
tok3->str(newName);
eraseTokens(tok3, closingBracket->next());
}
continue;
}
if (!templateDeclaration.scope().empty() &&
!alreadyHasNamespace(templateDeclaration, tok3) &&
!Token::Match(closingBracket->next(), "(|::")) {
if (copy)
addNamespace(templateDeclaration, tok3);
}
}
} else {
// don't modify friend
if (Token::Match(tok3->tokAt(-3), "> friend class|struct|union")) {
if (copy)
mTokenList.addtoken(tok3);
} else if (copy) {
// add namespace if necessary
if (!templateDeclaration.scope().empty() &&
(isClass ? tok3->strAt(1) != "(" : true)) {
addNamespace(templateDeclaration, tok3);
}
mTokenList.addtoken(newName, tok3);
} else if (!Token::Match(tok3->next(), "[:{=;[]),]"))
tok3->str(newName);
continue;
}
}
// copy
if (copy)
mTokenList.addtoken(tok3);
// look for template definitions
if (Token::simpleMatch(tok3, "template <")) {
Token * tok2 = findTemplateDeclarationEnd(tok3);
if (tok2)
templates.push(tok2);
} else if (!templates.empty() && templates.top() == tok3)
templates.pop();
if (Token::Match(tok3, "%type% <") &&
!Token::Match(tok3, "template|static_cast|const_cast|reinterpret_cast|dynamic_cast") &&
Token::Match(tok3->next()->findClosingBracket(), ">|>>")) {
const Token *closingBracket = tok3->next()->findClosingBracket();
if (Token::simpleMatch(closingBracket->next(), "&")) {
int num = 0;
const Token *par = tok3->next();
while (num < typeParametersInDeclaration.size() && par != closingBracket) {
const std::string pattern("[<,] " + typeParametersInDeclaration[num]->str() + " [,>]");
if (!Token::Match(par, pattern.c_str()))
break;
++num;
par = par->tokAt(2);
}
if (num < typeParametersInDeclaration.size() || par != closingBracket)
continue;
}
// don't add instantiations in template definitions
if (!templates.empty())
continue;
std::string scope;
const Token *prev = tok3;
for (; Token::Match(prev->tokAt(-2), "%name% ::"); prev = prev->tokAt(-2)) {
if (scope.empty())
scope = prev->strAt(-2);
else
scope = prev->strAt(-2) + " :: " + scope;
}
// check for global scope
if (prev->strAt(-1) != "::") {
// adjust for current scope
std::string token_scope = tok3->scopeInfo()->name;
const std::string::size_type end = token_scope.find_last_of(" :: ");
if (end != std::string::npos) {
token_scope.resize(end);
if (scope.empty())
scope = std::move(token_scope);
else
scope = token_scope + " :: " + scope;
}
}
if (copy)
newInstantiations.emplace_back(mTokenList.back(), std::move(scope));
else if (!inTemplateDefinition)
newInstantiations.emplace_back(tok3, std::move(scope));
}
// link() newly tokens manually
else if (copy) {
if (tok3->str() == "{") {
brackets.push(mTokenList.back());
} else if (tok3->str() == "(") {
brackets.push(mTokenList.back());
} else if (tok3->str() == "[") {
brackets.push(mTokenList.back());
} else if (tok3->str() == "}") {
assert(brackets.empty() == false);
assert(brackets.top()->str() == "{");
Token::createMutualLinks(brackets.top(), mTokenList.back());
brackets.pop();
if (brackets.empty() && !Token::Match(tok3, "} >|,|{")) {
inTemplateDefinition = false;
if (isClass && tok3->strAt(1) == ";") {
const Token* tokSemicolon = tok3->next();
mTokenList.addtoken(tokSemicolon, tokSemicolon->linenr(), tokSemicolon->column(), tokSemicolon->fileIndex());
}
break;
}
} else if (tok3->str() == ")") {
assert(brackets.empty() == false);
assert(brackets.top()->str() == "(");
Token::createMutualLinks(brackets.top(), mTokenList.back());
brackets.pop();
} else if (tok3->str() == "]") {
assert(brackets.empty() == false);
assert(brackets.top()->str() == "[");
Token::createMutualLinks(brackets.top(), mTokenList.back());
brackets.pop();
}
}
}
assert(brackets.empty());
}
// add new instantiations
for (const auto & inst : newInstantiations) {
if (!inst.token)
continue;
simplifyTemplateArgs(inst.token->tokAt(2), inst.token->next()->findClosingBracket(), &newInstantiations);
// only add recursive instantiation if its arguments are a constant expression
if (templateDeclaration.name() != inst.token->str() ||
(inst.token->tokAt(2)->isNumber() || inst.token->tokAt(2)->isStandardType()))
mTemplateInstantiations.emplace_back(inst.token, inst.scope);
}
}
static bool isLowerThanLogicalAnd(const Token *lower)
{
return lower->isAssignmentOp() || Token::Match(lower, "}|;|(|[|]|)|,|?|:|%oror%|return|throw|case");
}
static bool isLowerThanOr(const Token* lower)
{
return isLowerThanLogicalAnd(lower) || lower->str() == "&&";
}
static bool isLowerThanXor(const Token* lower)
{
return isLowerThanOr(lower) || lower->str() == "|";
}
static bool isLowerThanAnd(const Token* lower)
{
return isLowerThanXor(lower) || lower->str() == "^";
}
static bool isLowerThanShift(const Token* lower)
{
return isLowerThanAnd(lower) || lower->str() == "&";
}
static bool isLowerThanPlusMinus(const Token* lower)
{
return isLowerThanShift(lower) || Token::Match(lower, "%comp%|<<|>>");
}
static bool isLowerThanMulDiv(const Token* lower)
{
return isLowerThanPlusMinus(lower) || Token::Match(lower, "+|-");
}
static bool isLowerEqualThanMulDiv(const Token* lower)
{
return isLowerThanMulDiv(lower) || Token::Match(lower, "[*/%]");
}
bool TemplateSimplifier::simplifyNumericCalculations(Token *tok, bool isTemplate)
{
bool ret = false;
// (1-2)
while (tok->tokAt(3) && tok->isNumber() && tok->tokAt(2)->isNumber()) { // %any% %num% %any% %num% %any%
const Token *before = tok->previous();
if (!before)
break;
const Token* op = tok->next();
const Token* after = tok->tokAt(3);
const std::string &num1 = op->strAt(-1);
const std::string &num2 = op->strAt(1);
if (Token::Match(before, "* %num% /") && (num2 != "0") && num1 == MathLib::multiply(num2, MathLib::divide(num1, num2))) {
// Division where result is a whole number
} else if (!((op->str() == "*" && (isLowerThanMulDiv(before) || before->str() == "*") && isLowerEqualThanMulDiv(after)) || // associative
(Token::Match(op, "[/%]") && isLowerThanMulDiv(before) && isLowerEqualThanMulDiv(after)) || // NOT associative
(Token::Match(op, "[+-]") && isLowerThanMulDiv(before) && isLowerThanMulDiv(after)) || // Only partially (+) associative, but handled later
(Token::Match(op, ">>|<<") && isLowerThanShift(before) && isLowerThanPlusMinus(after)) || // NOT associative
(op->str() == "&" && isLowerThanShift(before) && isLowerThanShift(after)) || // associative
(op->str() == "^" && isLowerThanAnd(before) && isLowerThanAnd(after)) || // associative
(op->str() == "|" && isLowerThanXor(before) && isLowerThanXor(after)) || // associative
(op->str() == "&&" && isLowerThanOr(before) && isLowerThanOr(after)) ||
(op->str() == "||" && isLowerThanLogicalAnd(before) && isLowerThanLogicalAnd(after))))
break;
// Don't simplify "%num% / 0"
if (Token::Match(op, "[/%] 0")) {
if (isTemplate)
throw InternalError(op, "Instantiation error: Divide by zero in template instantiation.", InternalError::INSTANTIATION);
return ret;
}
// Integer operations
if (Token::Match(op, ">>|<<|&|^|%or%")) {
// Don't simplify if operand is negative, shifting with negative
// operand is UB. Bitmasking with negative operand is implementation
// defined behaviour.
if (MathLib::isNegative(num1) || MathLib::isNegative(num2))
break;
const MathLib::value v1(num1);
const MathLib::value v2(num2);
if (!v1.isInt() || !v2.isInt())
break;
switch (op->str()[0]) {
case '<':
tok->str((v1 << v2).str());
break;
case '>':
tok->str((v1 >> v2).str());
break;
case '&':
tok->str((v1 & v2).str());
break;
case '|':
tok->str((v1 | v2).str());
break;
case '^':
tok->str((v1 ^ v2).str());
break;
}
}
// Logical operations
else if (Token::Match(op, "%oror%|&&")) {
const bool op1 = !MathLib::isNullValue(num1);
const bool op2 = !MathLib::isNullValue(num2);
const bool result = (op->str() == "||") ? (op1 || op2) : (op1 && op2);
tok->str(result ? "1" : "0");
}
else if (Token::Match(tok->previous(), "- %num% - %num%"))
tok->str(MathLib::add(num1, num2));
else if (Token::Match(tok->previous(), "- %num% + %num%"))
tok->str(MathLib::subtract(num1, num2));
else {
try {
tok->str(MathLib::calculate(num1, num2, op->str()[0]));
} catch (InternalError &e) {
e.token = tok;
throw;
}
}
tok->deleteNext(2);
ret = true;
}
return ret;
}
static Token *skipTernaryOp(Token *tok, const Token *backToken)
{
unsigned int colonLevel = 1;
while (nullptr != (tok = tok->next())) {
if (tok->str() == "?") {
++colonLevel;
} else if (tok->str() == ":") {
--colonLevel;
if (colonLevel == 0) {
tok = tok->next();
break;
}
}
if (tok->link() && tok->str() == "(")
tok = tok->link();
else if (Token::Match(tok->next(), "[{};)]") || tok->next() == backToken)
break;
}
if (colonLevel > 0) // Ticket #5214: Make sure the ':' matches the proper '?'
return nullptr;
return tok;
}
static void invalidateInst(const Token* beg, const Token* end, std::vector<newInstantiation>* newInst) {
if (!newInst)
return;
for (auto& inst : *newInst) {
for (const Token* tok = beg; tok != end; tok = tok->next())
if (inst.token == tok) {
inst.token = nullptr;
break;
}
}
}
void TemplateSimplifier::simplifyTemplateArgs(Token *start, const Token *end, std::vector<newInstantiation>* newInst)
{
// start could be erased so use the token before start if available
Token * first = (start && start->previous()) ? start->previous() : mTokenList.front();
bool again = true;
while (again) {
again = false;
for (Token *tok = first->next(); tok && tok != end; tok = tok->next()) {
if (tok->str() == "sizeof") {
// sizeof('x')
if (Token::Match(tok->next(), "( %char% )")) {
tok->deleteNext();
tok->deleteThis();
tok->deleteNext();
tok->str(std::to_string(1));
again = true;
}
// sizeof ("text")
else if (Token::Match(tok->next(), "( %str% )")) {
tok->deleteNext();
tok->deleteThis();
tok->deleteNext();
tok->str(std::to_string(Token::getStrLength(tok) + 1));
again = true;
}
else if (Token::Match(tok->next(), "( %type% * )")) {
tok->str(std::to_string(mTokenizer.sizeOfType(tok->tokAt(3))));
tok->deleteNext(4);
again = true;
} else if (Token::simpleMatch(tok->next(), "( * )")) {
tok->str(std::to_string(mTokenizer.sizeOfType(tok->tokAt(2))));
tok->deleteNext(3);
again = true;
} else if (Token::Match(tok->next(), "( %type% )")) {
const unsigned int size = mTokenizer.sizeOfType(tok->tokAt(2));
if (size > 0) {
tok->str(std::to_string(size));
tok->deleteNext(3);
again = true;
}
} else if (tok->strAt(1) == "(") {
tok = tok->linkAt(1);
}
} else if (Token::Match(tok, "%num% %comp% %num%") &&
MathLib::isInt(tok->str()) &&
MathLib::isInt(tok->strAt(2))) {
if ((Token::Match(tok->previous(), "(|&&|%oror%|,") || tok == start) &&
(Token::Match(tok->tokAt(3), ")|&&|%oror%|?") || tok->tokAt(3) == end)) {
const MathLib::bigint op1(MathLib::toBigNumber(tok->str()));
const std::string &cmp(tok->strAt(1));
const MathLib::bigint op2(MathLib::toBigNumber(tok->strAt(2)));
std::string result;
if (cmp == "==")
result = bool_to_string(op1 == op2);
else if (cmp == "!=")
result = bool_to_string(op1 != op2);
else if (cmp == "<=")
result = bool_to_string(op1 <= op2);
else if (cmp == ">=")
result = bool_to_string(op1 >= op2);
else if (cmp == "<")
result = bool_to_string(op1 < op2);
else
result = bool_to_string(op1 > op2);
tok->str(result);
tok->deleteNext(2);
again = true;
tok = tok->previous();
}
}
}
if (simplifyCalculations(first->next(), end))
again = true;
for (Token *tok = first->next(); tok && tok != end; tok = tok->next()) {
if (tok->str() == "?" &&
((tok->previous()->isNumber() || tok->previous()->isBoolean()) ||
Token::Match(tok->tokAt(-3), "( %bool%|%num% )"))) {
const int offset = (tok->strAt(-1) == ")") ? 2 : 1;
// Find the token ":" then go to the next token
Token *colon = skipTernaryOp(tok, end);
if (!colon || colon->strAt(-1) != ":" || !colon->next())
continue;
//handle the GNU extension: "x ? : y" <-> "x ? x : y"
if (colon->previous() == tok->next())
tok->insertToken(tok->strAt(-offset));
// go back before the condition, if possible
tok = tok->tokAt(-2);
if (offset == 2) {
// go further back before the "("
tok = tok->tokAt(-2);
//simplify the parentheses
tok->deleteNext();
tok->next()->deleteNext();
}
if (Token::Match(tok->next(), "false|0")) {
invalidateInst(tok->next(), colon, newInst);
// Use code after colon, remove code before it.
Token::eraseTokens(tok, colon);
tok = tok->next();
again = true;
}
// The condition is true. Delete the operator after the ":"..
else {
// delete the condition token and the "?"
tok->deleteNext(2);
unsigned int ternaryOplevel = 0;
for (const Token *endTok = colon; endTok; endTok = endTok->next()) {
if (Token::Match(endTok, "(|[|{"))
endTok = endTok->link();
else if (endTok->str() == "<" && (endTok->strAt(1) == ">" || templateParameters(endTok)))
endTok = endTok->findClosingBracket();
else if (endTok->str() == "?")
++ternaryOplevel;
else if (Token::Match(endTok, ")|}|]|;|,|:|>")) {
if (endTok->str() == ":" && ternaryOplevel)
--ternaryOplevel;
else if (endTok->str() == ">" && !end)
;
else {
invalidateInst(colon->tokAt(-1), endTok, newInst);
Token::eraseTokens(colon->tokAt(-2), endTok);
again = true;
break;
}
}
}
}
}
}
for (Token *tok = first->next(); tok && tok != end; tok = tok->next()) {
if (Token::Match(tok, "( %num%|%bool% )") &&
(tok->previous() && !tok->previous()->isName())) {
tok->deleteThis();
tok->deleteNext();
again = true;
}
}
}
}
static bool validTokenStart(bool bounded, const Token *tok, const Token *frontToken, int offset)
{
if (!bounded)
return true;
if (frontToken)
frontToken = frontToken->previous();
while (tok && offset <= 0) {
if (tok == frontToken)
return false;
++offset;
tok = tok->previous();
}
return tok && offset > 0;
}
static bool validTokenEnd(bool bounded, const Token *tok, const Token *backToken, int offset)
{
if (!bounded)
return true;
while (tok && offset >= 0) {
if (tok == backToken)
return false;
--offset;
tok = tok->next();
}
return tok && offset < 0;
}
// TODO: This is not the correct class for simplifyCalculations(), so it
// should be moved away.
bool TemplateSimplifier::simplifyCalculations(Token* frontToken, const Token *backToken, bool isTemplate)
{
bool ret = false;
const bool bounded = frontToken || backToken;
if (!frontToken) {
frontToken = mTokenList.front();
}
for (Token *tok = frontToken; tok && tok != backToken; tok = tok->next()) {
// Remove parentheses around variable..
// keep parentheses here: dynamic_cast<Fred *>(p);
// keep parentheses here: A operator * (int);
// keep parentheses here: int ( * ( * f ) ( ... ) ) (int) ;
// keep parentheses here: int ( * * ( * compilerHookVector ) (void) ) ( ) ;
// keep parentheses here: operator new [] (size_t);
// keep parentheses here: Functor()(a ... )
// keep parentheses here: ) ( var ) ;
if (validTokenEnd(bounded, tok, backToken, 4) &&
(Token::Match(tok->next(), "( %name% ) ;|)|,|]") ||
(Token::Match(tok->next(), "( %name% ) %cop%") &&
(tok->tokAt(2)->varId()>0 ||
!Token::Match(tok->tokAt(4), "[*&+-~]")))) &&
!tok->isName() &&
tok->str() != ">" &&
tok->str() != ")" &&
tok->str() != "]") {
tok->deleteNext();
tok = tok->next();
tok->deleteNext();
ret = true;
}
if (validTokenEnd(bounded, tok, backToken, 3) &&
Token::Match(tok->previous(), "(|&&|%oror% %char% %comp% %num% &&|%oror%|)")) {
tok->str(std::to_string(MathLib::toBigNumber(tok->str())));
}
if (validTokenEnd(bounded, tok, backToken, 5) &&
Token::Match(tok, "decltype ( %type% { } )")) {
tok->deleteThis();
tok->deleteThis();
tok->deleteNext();
tok->deleteNext();
tok->deleteNext();
ret = true;
}
if (validTokenEnd(bounded, tok, backToken, 3) &&
Token::Match(tok, "decltype ( %bool%|%num% )")) {
tok->deleteThis();
tok->deleteThis();
if (tok->isBoolean())
tok->str("bool");
else if (MathLib::isFloat(tok->str())) {
// MathLib::getSuffix doesn't work for floating point numbers
const char suffix = tok->str().back();
if (suffix == 'f' || suffix == 'F')
tok->str("float");
else if (suffix == 'l' || suffix == 'L') {
tok->str("double");
tok->isLong(true);
} else
tok->str("double");
} else if (MathLib::isInt(tok->str())) {
std::string suffix = MathLib::getSuffix(tok->str());
if (suffix.find("LL") != std::string::npos) {
tok->str("long");
tok->isLong(true);
} else if (suffix.find('L') != std::string::npos)
tok->str("long");
else
tok->str("int");
tok->isUnsigned(suffix.find('U') != std::string::npos);
}
tok->deleteNext();
ret = true;
}
if (validTokenEnd(bounded, tok, backToken, 2) &&
(Token::Match(tok, "char|short|int|long { }") ||
Token::Match(tok, "char|short|int|long ( )"))) {
tok->str("0"); // FIXME add type suffix
tok->isSigned(false);
tok->isUnsigned(false);
tok->isLong(false);
tok->deleteNext();
tok->deleteNext();
ret = true;
}
if (tok && tok->isNumber()) {
if (validTokenEnd(bounded, tok, backToken, 2) &&
simplifyNumericCalculations(tok, isTemplate)) {
ret = true;
Token *prev = tok->tokAt(-2);
while (validTokenStart(bounded, tok, frontToken, -2) &&
prev && simplifyNumericCalculations(prev, isTemplate)) {
tok = prev;
prev = prev->tokAt(-2);
}
}
// Remove redundant conditions (0&&x) (1||x)
if (validTokenStart(bounded, tok, frontToken, -1) &&
validTokenEnd(bounded, tok, backToken, 1) &&
(Token::Match(tok->previous(), "[(=,] 0 &&") ||
Token::Match(tok->previous(), "[(=,] 1 %oror%"))) {
unsigned int par = 0;
const Token *tok2 = tok;
const bool andAnd = (tok->strAt(1) == "&&");
for (; tok2; tok2 = tok2->next()) {
if (tok2->str() == "(" || tok2->str() == "[")
++par;
else if (tok2->str() == ")" || tok2->str() == "]") {
if (par == 0)
break;
--par;
} else if (par == 0 && isLowerThanLogicalAnd(tok2) && (andAnd || tok2->str() != "||"))
break;
}
if (tok2) {
eraseTokens(tok, tok2);
ret = true;
}
continue;
}
if (tok->str() == "0" && validTokenStart(bounded, tok, frontToken, -1)) {
if (validTokenEnd(bounded, tok, backToken, 1) &&
((Token::Match(tok->previous(), "[+-] 0 %cop%|;") && isLowerThanMulDiv(tok->next())) ||
(Token::Match(tok->previous(), "%or% 0 %cop%|;") && isLowerThanXor(tok->next())))) {
tok = tok->previous();
if (Token::Match(tok->tokAt(-4), "[;{}] %name% = %name% [+-|] 0 ;") &&
tok->strAt(-3) == tok->strAt(-1)) {
tok = tok->tokAt(-4);
tok->deleteNext(5);
} else {
tok = tok->previous();
tok->deleteNext(2);
}
ret = true;
} else if (validTokenEnd(bounded, tok, backToken, 1) &&
(Token::Match(tok->previous(), "[=([,] 0 [+|]") ||
Token::Match(tok->previous(), "return|case 0 [+|]"))) {
tok = tok->previous();
tok->deleteNext(2);
ret = true;
} else if ((((Token::Match(tok->previous(), "[=[(,] 0 * %name%|%num% ,|]|)|;|=|%cop%") ||
Token::Match(tok->previous(), "return|case 0 *|&& %name%|%num% ,|:|;|=|%cop%")) &&
validTokenEnd(bounded, tok, backToken, 3)) ||
(((Token::Match(tok->previous(), "[=[(,] 0 * (") ||
Token::Match(tok->previous(), "return|case 0 *|&& (")) &&
validTokenEnd(bounded, tok, backToken, 2))))) {
tok->deleteNext();
if (tok->strAt(1) == "(")
eraseTokens(tok, tok->linkAt(1));
tok->deleteNext();
ret = true;
} else if (validTokenEnd(bounded, tok, backToken, 4) &&
(Token::Match(tok->previous(), "[=[(,] 0 && *|& %any% ,|]|)|;|=|%cop%") ||
Token::Match(tok->previous(), "return|case 0 && *|& %any% ,|:|;|=|%cop%"))) {
tok->deleteNext();
tok->deleteNext();
if (tok->strAt(1) == "(")
eraseTokens(tok, tok->linkAt(1));
tok->deleteNext();
ret = true;
}
}
if (tok->str() == "1" && validTokenStart(bounded, tok, frontToken, -1)) {
if (validTokenEnd(bounded, tok, backToken, 3) &&
(Token::Match(tok->previous(), "[=[(,] 1 %oror% %any% ,|]|)|;|=|%cop%") ||
Token::Match(tok->previous(), "return|case 1 %oror% %any% ,|:|;|=|%cop%"))) {
tok->deleteNext();
if (tok->strAt(1) == "(")
eraseTokens(tok, tok->linkAt(1));
tok->deleteNext();
ret = true;
} else if (validTokenEnd(bounded, tok, backToken, 4) &&
(Token::Match(tok->previous(), "[=[(,] 1 %oror% *|& %any% ,|]|)|;|=|%cop%") ||
Token::Match(tok->previous(), "return|case 1 %oror% *|& %any% ,|:|;|=|%cop%"))) {
tok->deleteNext();
tok->deleteNext();
if (tok->strAt(1) == "(")
eraseTokens(tok, tok->linkAt(1));
tok->deleteNext();
ret = true;
}
}
if ((Token::Match(tok->tokAt(-2), "%any% * 1") &&
validTokenStart(bounded, tok, frontToken, -2)) ||
(Token::Match(tok->previous(), "%any% 1 *") &&
validTokenStart(bounded, tok, frontToken, -1))) {
tok = tok->previous();
if (tok->str() == "*")
tok = tok->previous();
tok->deleteNext(2);
ret = true;
}
// Remove parentheses around number..
if (validTokenStart(bounded, tok, frontToken, -2) &&
Token::Match(tok->tokAt(-2), "%op%|< ( %num% )") &&
tok->strAt(-2) != ">") {
tok = tok->previous();
tok->deleteThis();
tok->deleteNext();
ret = true;
}
if (validTokenStart(bounded, tok, frontToken, -1) &&
validTokenEnd(bounded, tok, backToken, 1) &&
(Token::Match(tok->previous(), "( 0 [|+]") ||
Token::Match(tok->previous(), "[|+-] 0 )"))) {
tok = tok->previous();
if (Token::Match(tok, "[|+-]"))
tok = tok->previous();
tok->deleteNext(2);
ret = true;
}
if (validTokenEnd(bounded, tok, backToken, 2) &&
Token::Match(tok, "%num% %comp% %num%") &&
MathLib::isInt(tok->str()) &&
MathLib::isInt(tok->strAt(2))) {
if (validTokenStart(bounded, tok, frontToken, -1) &&
Token::Match(tok->previous(), "(|&&|%oror%") &&
Token::Match(tok->tokAt(3), ")|&&|%oror%|?")) {
const MathLib::bigint op1(MathLib::toBigNumber(tok->str()));
const std::string &cmp(tok->strAt(1));
const MathLib::bigint op2(MathLib::toBigNumber(tok->strAt(2)));
std::string result;
if (cmp == "==")
result = (op1 == op2) ? "1" : "0";
else if (cmp == "!=")
result = (op1 != op2) ? "1" : "0";
else if (cmp == "<=")
result = (op1 <= op2) ? "1" : "0";
else if (cmp == ">=")
result = (op1 >= op2) ? "1" : "0";
else if (cmp == "<")
result = (op1 < op2) ? "1" : "0";
else
result = (op1 > op2) ? "1" : "0";
tok->str(result);
tok->deleteNext(2);
ret = true;
tok = tok->previous();
}
}
}
}
return ret;
}
void TemplateSimplifier::getTemplateParametersInDeclaration(
const Token * tok,
std::vector<const Token *> & typeParametersInDeclaration)
{
assert(tok->strAt(-1) == "<");
typeParametersInDeclaration.clear();
const Token *end = tok->previous()->findClosingBracket();
bool inDefaultValue = false;
for (; tok && tok!= end; tok = tok->next()) {
if (Token::simpleMatch(tok, "template <")) {
const Token *closing = tok->next()->findClosingBracket();
if (closing)
tok = closing->next();
} else if (tok->link() && Token::Match(tok, "{|(|["))
tok = tok->link();
else if (Token::Match(tok, "%name% ,|>|=")) {
if (!inDefaultValue) {
typeParametersInDeclaration.push_back(tok);
if (tok->strAt(1) == "=")
inDefaultValue = true;
}
} else if (inDefaultValue) {
if (tok->str() == ",")
inDefaultValue = false;
else if (tok->str() == "<") {
const Token *closing = tok->findClosingBracket();
if (closing)
tok = closing;
}
}
}
}
bool TemplateSimplifier::matchSpecialization(
const Token *templateDeclarationNameToken,
const Token *templateInstantiationNameToken,
const std::list<const Token *> & specializations)
{
// Is there a matching specialization?
for (std::list<const Token *>::const_iterator it = specializations.cbegin(); it != specializations.cend(); ++it) {
if (!Token::Match(*it, "%name% <"))
continue;
const Token *startToken = (*it);
while (startToken->previous() && !Token::Match(startToken->previous(), "[;{}]"))
startToken = startToken->previous();
if (!Token::simpleMatch(startToken, "template <"))
continue;
// cppcheck-suppress shadowFunction - TODO: fix this
std::vector<const Token *> templateParameters;
getTemplateParametersInDeclaration(startToken->tokAt(2), templateParameters);
const Token *instToken = templateInstantiationNameToken->tokAt(2);
const Token *declToken = (*it)->tokAt(2);
const Token * const endToken = (*it)->next()->findClosingBracket();
if (!endToken)
continue;
while (declToken != endToken) {
if (declToken->str() != instToken->str() ||
declToken->isSigned() != instToken->isSigned() ||
declToken->isUnsigned() != instToken->isUnsigned() ||
declToken->isLong() != instToken->isLong()) {
int nr = 0;
while (nr < templateParameters.size() && templateParameters[nr]->str() != declToken->str())
++nr;
if (nr == templateParameters.size())
break;
}
declToken = declToken->next();
instToken = instToken->next();
}
if (declToken && instToken && declToken == endToken && instToken->str() == ">") {
// specialization matches.
return templateDeclarationNameToken == *it;
}
}
// No specialization matches. Return true if the declaration is not a specialization.
return Token::Match(templateDeclarationNameToken, "%name% !!<") &&
(templateDeclarationNameToken->str().find('<') == std::string::npos);
}
std::string TemplateSimplifier::getNewName(
Token *tok2,
std::list<std::string> &typeStringsUsedInTemplateInstantiation)
{
std::string typeForNewName;
unsigned int indentlevel = 0;
const Token * endToken = tok2->next()->findClosingBracket();
for (Token *tok3 = tok2->tokAt(2); tok3 != endToken && (indentlevel > 0 || tok3->str() != ">"); tok3 = tok3->next()) {
// #2721 - unhandled [ => bail out
if (tok3->str() == "[" && !Token::Match(tok3->next(), "%num%| ]")) {
typeForNewName.clear();
break;
}
if (!tok3->next()) {
typeForNewName.clear();
break;
}
if (Token::Match(tok3->tokAt(-2), "<|,|:: %name% <") && (tok3->strAt(1) == ">" || templateParameters(tok3)))
++indentlevel;
else if (indentlevel > 0 && Token::Match(tok3, "> ,|>|::"))
--indentlevel;
else if (indentlevel == 0 && Token::Match(tok3->previous(), "[<,]")) {
mTypesUsedInTemplateInstantiation.emplace_back(tok3, "");
}
if (Token::Match(tok3, "(|["))
++indentlevel;
else if (Token::Match(tok3, ")|]"))
--indentlevel;
const bool constconst = tok3->str() == "const" && tok3->strAt(1) == "const";
if (!constconst) {
if (tok3->isUnsigned())
typeStringsUsedInTemplateInstantiation.emplace_back("unsigned");
else if (tok3->isSigned())
typeStringsUsedInTemplateInstantiation.emplace_back("signed");
if (tok3->isLong())
typeStringsUsedInTemplateInstantiation.emplace_back("long");
typeStringsUsedInTemplateInstantiation.push_back(tok3->str());
}
// add additional type information
if (!constconst && !Token::Match(tok3, "class|struct|enum")) {
if (!typeForNewName.empty())
typeForNewName += ' ';
if (tok3->isUnsigned())
typeForNewName += "unsigned ";
else if (tok3->isSigned())
typeForNewName += "signed ";
if (tok3->isLong()) {
typeForNewName += "long ";
}
typeForNewName += tok3->str();
}
}
return typeForNewName;
}
bool TemplateSimplifier::simplifyTemplateInstantiations(
const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations,
const std::time_t maxtime,
std::set<std::string> &expandedtemplates)
{
// this variable is not used at the moment. The intention was to
// allow continuous instantiations until all templates has been expanded
//bool done = false;
// Contains tokens such as "T"
std::vector<const Token *> typeParametersInDeclaration;
getTemplateParametersInDeclaration(templateDeclaration.token()->tokAt(2), typeParametersInDeclaration);
const bool printDebug = mSettings.debugwarnings;
const bool specialized = templateDeclaration.isSpecialization();
const bool isfunc = templateDeclaration.isFunction();
const bool isVar = templateDeclaration.isVariable();
// locate template usage..
std::string::size_type numberOfTemplateInstantiations = mTemplateInstantiations.size();
unsigned int recursiveCount = 0;
bool instantiated = false;
for (const TokenAndName &instantiation : mTemplateInstantiations) {
// skip deleted instantiations
if (!instantiation.token())
continue;
if (numberOfTemplateInstantiations != mTemplateInstantiations.size()) {
numberOfTemplateInstantiations = mTemplateInstantiations.size();
++recursiveCount;
if (recursiveCount > mSettings.maxTemplateRecursion) {
if (mSettings.severity.isEnabled(Severity::information)) {
std::list<std::string> typeStringsUsedInTemplateInstantiation;
const std::string typeForNewName = templateDeclaration.name() + "<" + getNewName(instantiation.token(), typeStringsUsedInTemplateInstantiation) + ">";
const std::list<const Token *> callstack(1, instantiation.token());
const ErrorMessage errmsg(callstack,
&mTokenizer.list,
Severity::information,
"templateRecursion",
"TemplateSimplifier: max template recursion ("
+ std::to_string(mSettings.maxTemplateRecursion)
+ ") reached for template '"+typeForNewName+"'. You might want to limit Cppcheck recursion.",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
// bail out..
break;
}
}
// already simplified
if (!Token::Match(instantiation.token(), "%name% <"))
continue;
if (!((instantiation.fullName() == templateDeclaration.fullName()) ||
(instantiation.name() == templateDeclaration.name() &&
instantiation.fullName() == templateDeclaration.scope()))) {
// FIXME: fallback to not matching scopes until type deduction works
// names must match
if (instantiation.name() != templateDeclaration.name())
continue;
// scopes must match when present
if (!instantiation.scope().empty() && !templateDeclaration.scope().empty())
continue;
}
// make sure constructors and destructors don't match each other
if (templateDeclaration.nameToken()->strAt(-1) == "~" && instantiation.token()->strAt(-1) != "~")
continue;
// template families should match
if (!instantiation.isFunction() && templateDeclaration.isFunction()) {
// there are exceptions
if (!Token::simpleMatch(instantiation.token()->tokAt(-2), "decltype ("))
continue;
}
if (templateDeclaration.isFunction() && instantiation.isFunction()) {
std::vector<const Token*> declFuncArgs;
getFunctionArguments(templateDeclaration.nameToken(), declFuncArgs);
std::vector<const Token*> instFuncParams;
getFunctionArguments(instantiation.token(), instFuncParams);
if (declFuncArgs.size() != instFuncParams.size()) {
// check for default arguments
const Token* tok = templateDeclaration.nameToken()->tokAt(2);
const Token* end = templateDeclaration.nameToken()->linkAt(1);
size_t count = 0;
for (; tok != end; tok = tok->next()) {
if (tok->str() == "=")
count++;
}
if (instFuncParams.size() < (declFuncArgs.size() - count) || instFuncParams.size() > declFuncArgs.size())
continue;
}
}
// A global function can't be called through a pointer.
if (templateDeclaration.isFunction() && templateDeclaration.scope().empty() &&
(instantiation.token()->strAt(-1) == "." ||
Token::simpleMatch(instantiation.token()->tokAt(-2), ". template")))
continue;
if (!matchSpecialization(templateDeclaration.nameToken(), instantiation.token(), specializations))
continue;
Token * const tok2 = instantiation.token();
if (!mTokenList.getFiles().empty())
mErrorLogger.reportProgress(mTokenList.getFiles()[0], "TemplateSimplifier::simplifyTemplateInstantiations()", tok2->progressValue());
if (maxtime > 0 && std::time(nullptr) > maxtime) {
if (mSettings.debugwarnings) {
ErrorMessage::FileLocation loc(mTokenList.getFiles()[0], 0, 0);
ErrorMessage errmsg({std::move(loc)},
emptyString,
Severity::debug,
"Template instantiation maximum time exceeded",
"templateMaxTime",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
return false;
}
assert(mTokenList.validateToken(tok2)); // that assertion fails on examples from #6021
const Token *startToken = tok2;
while (Token::Match(startToken->tokAt(-2), ">|%name% :: %name%")) {
if (startToken->strAt(-2) == ">") {
const Token * tok3 = startToken->tokAt(-2)->findOpeningBracket();
if (tok3)
startToken = tok3->previous();
else
break;
} else
startToken = startToken->tokAt(-2);
}
if (Token::Match(startToken->previous(), ";|{|}|=|const") &&
(!specialized && !instantiateMatch(tok2, typeParametersInDeclaration.size(), templateDeclaration.isVariadic(), isfunc ? "(" : isVar ? ";|%op%|(" : "*|&|::| %name%")))
continue;
// New type..
mTypesUsedInTemplateInstantiation.clear();
std::list<std::string> typeStringsUsedInTemplateInstantiation;
std::string typeForNewName = getNewName(tok2, typeStringsUsedInTemplateInstantiation);
if ((typeForNewName.empty() && !templateDeclaration.isVariadic()) ||
(!typeParametersInDeclaration.empty() && !instantiateMatch(tok2, typeParametersInDeclaration.size(), templateDeclaration.isVariadic(), nullptr))) {
if (printDebug) {
std::list<const Token *> callstack(1, tok2);
mErrorLogger.reportErr(ErrorMessage(callstack, &mTokenList, Severity::debug, "templateInstantiation",
"Failed to instantiate template \"" + instantiation.name() + "\". The checking continues anyway.", Certainty::normal));
}
if (typeForNewName.empty())
continue;
break;
}
// New classname/funcname..
const std::string newName(templateDeclaration.name() + " < " + typeForNewName + " >");
const std::string newFullName(templateDeclaration.scope() + (templateDeclaration.scope().empty() ? "" : " :: ") + newName);
if (expandedtemplates.insert(newFullName).second) {
expandTemplate(templateDeclaration, instantiation, typeParametersInDeclaration, newName, !specialized && !isVar);
instantiated = true;
mChanged = true;
}
// Replace all these template usages..
replaceTemplateUsage(instantiation, typeStringsUsedInTemplateInstantiation, newName);
}
// process uninstantiated templates
// TODO: remove the specialized check and handle all uninstantiated templates someday.
if (!instantiated && specialized) {
auto * tok2 = const_cast<Token *>(templateDeclaration.nameToken());
if (!mTokenList.getFiles().empty())
mErrorLogger.reportProgress(mTokenList.getFiles()[0], "TemplateSimplifier::simplifyTemplateInstantiations()", tok2->progressValue());
if (maxtime > 0 && std::time(nullptr) > maxtime) {
if (mSettings.debugwarnings) {
ErrorMessage::FileLocation loc(mTokenList.getFiles()[0], 0, 0);
ErrorMessage errmsg({std::move(loc)},
emptyString,
Severity::debug,
"Template instantiation maximum time exceeded",
"templateMaxTime",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
return false;
}
assert(mTokenList.validateToken(tok2)); // that assertion fails on examples from #6021
Token *startToken = tok2;
while (Token::Match(startToken->tokAt(-2), ">|%name% :: %name%")) {
if (startToken->strAt(-2) == ">") {
Token * tok3 = startToken->tokAt(-2)->findOpeningBracket();
if (tok3)
startToken = tok3->previous();
else
break;
} else
startToken = startToken->tokAt(-2);
}
// TODO: re-enable when specialized check is removed
// if (Token::Match(startToken->previous(), ";|{|}|=|const") &&
// (!specialized && !instantiateMatch(tok2, typeParametersInDeclaration.size(), isfunc ? "(" : isVar ? ";|%op%|(" : "*|&|::| %name%")))
// return false;
// already simplified
if (!Token::Match(tok2, "%name% <"))
return false;
if (!matchSpecialization(templateDeclaration.nameToken(), tok2, specializations))
return false;
// New type..
mTypesUsedInTemplateInstantiation.clear();
std::list<std::string> typeStringsUsedInTemplateInstantiation;
std::string typeForNewName = getNewName(tok2, typeStringsUsedInTemplateInstantiation);
if (typeForNewName.empty()) {
if (printDebug) {
std::list<const Token *> callstack(1, tok2);
mErrorLogger.reportErr(ErrorMessage(callstack, &mTokenList, Severity::debug, "templateInstantiation",
"Failed to instantiate template \"" + templateDeclaration.name() + "\". The checking continues anyway.", Certainty::normal));
}
return false;
}
// New classname/funcname..
const std::string newName(templateDeclaration.name() + " < " + typeForNewName + " >");
const std::string newFullName(templateDeclaration.scope() + (templateDeclaration.scope().empty() ? "" : " :: ") + newName);
if (expandedtemplates.insert(newFullName).second) {
expandTemplate(templateDeclaration, templateDeclaration, typeParametersInDeclaration, newName, !specialized && !isVar);
instantiated = true;
mChanged = true;
}
// Replace all these template usages..
replaceTemplateUsage(templateDeclaration, typeStringsUsedInTemplateInstantiation, newName);
}
// Template has been instantiated .. then remove the template declaration
return instantiated;
}
static bool matchTemplateParameters(const Token *nameTok, const std::list<std::string> &strings)
{
std::list<std::string>::const_iterator it = strings.cbegin();
const Token *tok = nameTok->tokAt(2);
const Token *end = nameTok->next()->findClosingBracket();
if (!end)
return false;
while (tok && tok != end && it != strings.cend()) {
if (tok->isUnsigned()) {
if (*it != "unsigned")
return false;
++it;
if (it == strings.cend())
return false;
} else if (tok->isSigned()) {
if (*it != "signed")
return false;
++it;
if (it == strings.cend())
return false;
}
if (tok->isLong()) {
if (*it != "long")
return false;
++it;
if (it == strings.cend())
return false;
}
if (*it != tok->str())
return false;
tok = tok->next();
++it;
}
return it == strings.cend() && tok && tok->str() == ">";
}
void TemplateSimplifier::replaceTemplateUsage(
const TokenAndName &instantiation,
const std::list<std::string> &typeStringsUsedInTemplateInstantiation,
const std::string &newName)
{
std::list<std::pair<Token *, Token *>> removeTokens;
for (Token *nameTok = mTokenList.front(); nameTok; nameTok = nameTok->next()) {
if (!Token::Match(nameTok, "%name% <") ||
Token::Match(nameTok, "template|const_cast|dynamic_cast|reinterpret_cast|static_cast"))
continue;
std::set<TemplateSimplifier::TokenAndName*>* pointers = nameTok->templateSimplifierPointers();
// check if instantiation matches token instantiation from pointer
if (pointers && !pointers->empty()) {
// check full name
if (instantiation.fullName() != (*pointers->begin())->fullName()) {
// FIXME: fallback to just matching name
if (nameTok->str() != instantiation.name())
continue;
}
}
// no pointer available look at tokens directly
else {
// FIXME: fallback to just matching name
if (nameTok->str() != instantiation.name())
continue;
}
if (!matchTemplateParameters(nameTok, typeStringsUsedInTemplateInstantiation))
continue;
Token *tok2 = nameTok->next()->findClosingBracket();
if (!tok2)
break;
const Token * const nameTok1 = nameTok;
nameTok->str(newName);
// matching template usage => replace tokens..
// Foo < int > => Foo<int>
for (const Token *tok = nameTok1->next(); tok != tok2; tok = tok->next()) {
if (tok->isName() && tok->templateSimplifierPointers() && !tok->templateSimplifierPointers()->empty()) {
std::list<TokenAndName>::const_iterator ti;
for (ti = mTemplateInstantiations.cbegin(); ti != mTemplateInstantiations.cend();) {
if (ti->token() == tok) {
ti = mTemplateInstantiations.erase(ti);
break;
}
++ti;
}
}
}
// Fix crash in #9007
if (Token::simpleMatch(nameTok->previous(), ">"))
mTemplateNamePos.erase(nameTok->previous());
removeTokens.emplace_back(nameTok, tok2->next());
nameTok = tok2;
}
while (!removeTokens.empty()) {
eraseTokens(removeTokens.back().first, removeTokens.back().second);
removeTokens.pop_back();
}
}
static bool specMatch(
const TemplateSimplifier::TokenAndName &spec,
const TemplateSimplifier::TokenAndName &decl)
{
// make sure decl is really a declaration
if (decl.isPartialSpecialization() || decl.isSpecialization() || decl.isAlias() || decl.isFriend())
return false;
if (!spec.isSameFamily(decl))
return false;
// make sure the scopes and names match
if (spec.fullName() == decl.fullName()) {
if (spec.isFunction()) {
std::vector<const Token*> specArgs;
std::vector<const Token*> declArgs;
getFunctionArguments(spec.nameToken(), specArgs);
getFunctionArguments(decl.nameToken(), declArgs);
if (specArgs.size() == declArgs.size()) {
// @todo make sure function parameters also match
return true;
}
} else
return true;
}
return false;
}
void TemplateSimplifier::getSpecializations()
{
// try to locate a matching declaration for each user defined specialization
for (const auto& spec : mTemplateDeclarations) {
if (spec.isSpecialization()) {
auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), [&](const TokenAndName& decl) {
return specMatch(spec, decl);
});
if (it != mTemplateDeclarations.cend())
mTemplateSpecializationMap[spec.token()] = it->token();
else {
it = std::find_if(mTemplateForwardDeclarations.cbegin(), mTemplateForwardDeclarations.cend(), [&](const TokenAndName& decl) {
return specMatch(spec, decl);
});
if (it != mTemplateForwardDeclarations.cend())
mTemplateSpecializationMap[spec.token()] = it->token();
}
}
}
}
void TemplateSimplifier::getPartialSpecializations()
{
// try to locate a matching declaration for each user defined partial specialization
for (const auto& spec : mTemplateDeclarations) {
if (spec.isPartialSpecialization()) {
auto it = std::find_if(mTemplateDeclarations.cbegin(), mTemplateDeclarations.cend(), [&](const TokenAndName& decl) {
return specMatch(spec, decl);
});
if (it != mTemplateDeclarations.cend())
mTemplatePartialSpecializationMap[spec.token()] = it->token();
else {
it = std::find_if(mTemplateForwardDeclarations.cbegin(), mTemplateForwardDeclarations.cend(), [&](const TokenAndName& decl) {
return specMatch(spec, decl);
});
if (it != mTemplateForwardDeclarations.cend())
mTemplatePartialSpecializationMap[spec.token()] = it->token();
}
}
}
}
void TemplateSimplifier::fixForwardDeclaredDefaultArgumentValues()
{
// try to locate a matching declaration for each forward declaration
for (const auto & forwardDecl : mTemplateForwardDeclarations) {
std::vector<const Token *> params1;
getTemplateParametersInDeclaration(forwardDecl.token()->tokAt(2), params1);
for (auto & decl : mTemplateDeclarations) {
// skip partializations, type aliases and friends
if (decl.isPartialSpecialization() || decl.isAlias() || decl.isFriend())
continue;
std::vector<const Token *> params2;
getTemplateParametersInDeclaration(decl.token()->tokAt(2), params2);
// make sure the number of arguments match
if (params1.size() == params2.size()) {
// make sure the scopes and names match
if (forwardDecl.fullName() == decl.fullName()) {
// save forward declaration for lookup later
if ((decl.nameToken()->strAt(1) == "(" && forwardDecl.nameToken()->strAt(1) == "(") ||
(decl.nameToken()->strAt(1) == "{" && forwardDecl.nameToken()->strAt(1) == ";")) {
mTemplateForwardDeclarationsMap[decl.token()] = forwardDecl.token();
}
for (size_t k = 0; k < params1.size(); k++) {
// copy default value to declaration if not present
if (params1[k]->strAt(1) == "=" && params2[k]->strAt(1) != "=") {
int level = 0;
const Token *end = params1[k]->next();
while (end && !(level == 0 && Token::Match(end, ",|>"))) {
if (Token::Match(end, "{|(|<"))
level++;
else if (Token::Match(end, "}|)|>"))
level--;
end = end->next();
}
if (end)
TokenList::copyTokens(const_cast<Token *>(params2[k]), params1[k]->next(), end->previous());
}
}
// update parameter end pointer
decl.paramEnd(decl.token()->next()->findClosingBracket());
}
}
}
}
}
void TemplateSimplifier::printOut(const TokenAndName &tokenAndName, const std::string &indent) const
{
std::cout << indent << "token: ";
if (tokenAndName.token())
std::cout << "\"" << tokenAndName.token()->str() << "\" " << mTokenList.fileLine(tokenAndName.token());
else
std::cout << "nullptr";
std::cout << std::endl;
std::cout << indent << "scope: \"" << tokenAndName.scope() << "\"" << std::endl;
std::cout << indent << "name: \"" << tokenAndName.name() << "\"" << std::endl;
std::cout << indent << "fullName: \"" << tokenAndName.fullName() << "\"" << std::endl;
std::cout << indent << "nameToken: ";
if (tokenAndName.nameToken())
std::cout << "\"" << tokenAndName.nameToken()->str() << "\" " << mTokenList.fileLine(tokenAndName.nameToken());
else
std::cout << "nullptr";
std::cout << std::endl;
std::cout << indent << "paramEnd: ";
if (tokenAndName.paramEnd())
std::cout << "\"" << tokenAndName.paramEnd()->str() << "\" " << mTokenList.fileLine(tokenAndName.paramEnd());
else
std::cout << "nullptr";
std::cout << std::endl;
std::cout << indent << "flags: ";
if (tokenAndName.isClass())
std::cout << " isClass";
if (tokenAndName.isFunction())
std::cout << " isFunction";
if (tokenAndName.isVariable())
std::cout << " isVariable";
if (tokenAndName.isAlias())
std::cout << " isAlias";
if (tokenAndName.isSpecialization())
std::cout << " isSpecialization";
if (tokenAndName.isPartialSpecialization())
std::cout << " isPartialSpecialization";
if (tokenAndName.isForwardDeclaration())
std::cout << " isForwardDeclaration";
if (tokenAndName.isVariadic())
std::cout << " isVariadic";
if (tokenAndName.isFriend())
std::cout << " isFriend";
std::cout << std::endl;
if (tokenAndName.token() && !tokenAndName.paramEnd() && tokenAndName.token()->strAt(1) == "<") {
const Token *end = tokenAndName.token()->next()->findClosingBracket();
if (end) {
const Token *start = tokenAndName.token()->next();
std::cout << indent << "type: ";
while (start && start != end) {
if (start->isUnsigned())
std::cout << "unsigned";
else if (start->isSigned())
std::cout << "signed";
if (start->isLong())
std::cout << "long";
std::cout << start->str();
start = start->next();
}
std::cout << end->str() << std::endl;
}
} else if (tokenAndName.isAlias() && tokenAndName.paramEnd()) {
if (tokenAndName.aliasStartToken()) {
std::cout << indent << "aliasStartToken: \"" << tokenAndName.aliasStartToken()->str() << "\" "
<< mTokenList.fileLine(tokenAndName.aliasStartToken()) << std::endl;
}
if (tokenAndName.aliasEndToken()) {
std::cout << indent << "aliasEndToken: \"" << tokenAndName.aliasEndToken()->str() << "\" "
<< mTokenList.fileLine(tokenAndName.aliasEndToken()) << std::endl;
}
}
}
void TemplateSimplifier::printOut(const std::string & text) const
{
std::cout << std::endl;
std::cout << text << std::endl;
std::cout << std::endl;
std::cout << "mTemplateDeclarations: " << mTemplateDeclarations.size() << std::endl;
int count = 0;
for (const auto & decl : mTemplateDeclarations) {
std::cout << "mTemplateDeclarations[" << count++ << "]:" << std::endl;
printOut(decl);
}
std::cout << "mTemplateForwardDeclarations: " << mTemplateForwardDeclarations.size() << std::endl;
count = 0;
for (const auto & decl : mTemplateForwardDeclarations) {
std::cout << "mTemplateForwardDeclarations[" << count++ << "]:" << std::endl;
printOut(decl);
}
std::cout << "mTemplateForwardDeclarationsMap: " << mTemplateForwardDeclarationsMap.size() << std::endl;
unsigned int mapIndex = 0;
for (const auto & mapItem : mTemplateForwardDeclarationsMap) {
unsigned int declIndex = 0;
for (const auto & decl : mTemplateDeclarations) {
if (mapItem.first == decl.token()) {
unsigned int forwardIndex = 0;
for (const auto & forwardDecl : mTemplateForwardDeclarations) {
if (mapItem.second == forwardDecl.token()) {
std::cout << "mTemplateForwardDeclarationsMap[" << mapIndex << "]:" << std::endl;
std::cout << " mTemplateDeclarations[" << declIndex
<< "] => mTemplateForwardDeclarations[" << forwardIndex << "]" << std::endl;
break;
}
forwardIndex++;
}
break;
}
declIndex++;
}
mapIndex++;
}
std::cout << "mTemplateSpecializationMap: " << mTemplateSpecializationMap.size() << std::endl;
for (const auto & mapItem : mTemplateSpecializationMap) {
unsigned int decl1Index = 0;
for (const auto & decl1 : mTemplateDeclarations) {
if (decl1.isSpecialization() && mapItem.first == decl1.token()) {
bool found = false;
unsigned int decl2Index = 0;
for (const auto & decl2 : mTemplateDeclarations) {
if (mapItem.second == decl2.token()) {
std::cout << "mTemplateSpecializationMap[" << mapIndex << "]:" << std::endl;
std::cout << " mTemplateDeclarations[" << decl1Index
<< "] => mTemplateDeclarations[" << decl2Index << "]" << std::endl;
found = true;
break;
}
decl2Index++;
}
if (!found) {
decl2Index = 0;
for (const auto & decl2 : mTemplateForwardDeclarations) {
if (mapItem.second == decl2.token()) {
std::cout << "mTemplateSpecializationMap[" << mapIndex << "]:" << std::endl;
std::cout << " mTemplateDeclarations[" << decl1Index
<< "] => mTemplateForwardDeclarations[" << decl2Index << "]" << std::endl;
break;
}
decl2Index++;
}
}
break;
}
decl1Index++;
}
mapIndex++;
}
std::cout << "mTemplatePartialSpecializationMap: " << mTemplatePartialSpecializationMap.size() << std::endl;
for (const auto & mapItem : mTemplatePartialSpecializationMap) {
unsigned int decl1Index = 0;
for (const auto & decl1 : mTemplateDeclarations) {
if (mapItem.first == decl1.token()) {
bool found = false;
unsigned int decl2Index = 0;
for (const auto & decl2 : mTemplateDeclarations) {
if (mapItem.second == decl2.token()) {
std::cout << "mTemplatePartialSpecializationMap[" << mapIndex << "]:" << std::endl;
std::cout << " mTemplateDeclarations[" << decl1Index
<< "] => mTemplateDeclarations[" << decl2Index << "]" << std::endl;
found = true;
break;
}
decl2Index++;
}
if (!found) {
decl2Index = 0;
for (const auto & decl2 : mTemplateForwardDeclarations) {
if (mapItem.second == decl2.token()) {
std::cout << "mTemplatePartialSpecializationMap[" << mapIndex << "]:" << std::endl;
std::cout << " mTemplateDeclarations[" << decl1Index
<< "] => mTemplateForwardDeclarations[" << decl2Index << "]" << std::endl;
break;
}
decl2Index++;
}
}
break;
}
decl1Index++;
}
mapIndex++;
}
std::cout << "mTemplateInstantiations: " << mTemplateInstantiations.size() << std::endl;
count = 0;
for (const auto & decl : mTemplateInstantiations) {
std::cout << "mTemplateInstantiations[" << count++ << "]:" << std::endl;
printOut(decl);
}
}
void TemplateSimplifier::simplifyTemplates(const std::time_t maxtime)
{
// convert "sizeof ..." to "sizeof..."
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof ...")) {
tok->str("sizeof...");
tok->deleteNext();
}
}
// Remove "typename" unless used in template arguments or using type alias..
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "typename %name%") && !Token::Match(tok->tokAt(-3), "using %name% ="))
tok->deleteThis();
if (Token::simpleMatch(tok, "template <")) {
tok = tok->next()->findClosingBracket();
if (!tok)
break;
}
}
if (mSettings.standards.cpp >= Standards::CPP20) {
// Remove concepts/requires
// TODO concepts are not removed yet
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, ")|>|>> requires %name%|("))
continue;
const Token* end = skipRequires(tok->next());
if (end)
Token::eraseTokens(tok, end);
}
// explicit(bool)
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "explicit (")) {
const bool isFalse = Token::simpleMatch(tok->tokAt(2), "false )");
Token::eraseTokens(tok, tok->linkAt(1)->next());
if (isFalse)
tok->deleteThis();
}
}
}
mTokenizer.calculateScopes();
unsigned int passCount = 0;
constexpr unsigned int passCountMax = 10;
for (; passCount < passCountMax; ++passCount) {
if (passCount) {
// it may take more than one pass to simplify type aliases
bool usingChanged = false;
while (mTokenizer.simplifyUsing())
usingChanged = true;
if (!usingChanged && !mChanged)
break;
mChanged = usingChanged;
mTemplateDeclarations.clear();
mTemplateForwardDeclarations.clear();
mTemplateForwardDeclarationsMap.clear();
mTemplateSpecializationMap.clear();
mTemplatePartialSpecializationMap.clear();
mTemplateInstantiations.clear();
mInstantiatedTemplates.clear();
mExplicitInstantiationsToDelete.clear();
mTemplateNamePos.clear();
}
getTemplateDeclarations();
if (passCount == 0) {
mDump.clear();
for (const TokenAndName& t: mTemplateDeclarations)
mDump += t.dump(mTokenizer.list.getFiles());
for (const TokenAndName& t: mTemplateForwardDeclarations)
mDump += t.dump(mTokenizer.list.getFiles());
if (!mDump.empty())
mDump = " <TemplateSimplifier>\n" + mDump + " </TemplateSimplifier>\n";
}
// Make sure there is something to simplify.
if (mTemplateDeclarations.empty() && mTemplateForwardDeclarations.empty())
return;
if (mSettings.debugtemplate && mSettings.debugnormal) {
std::string title("Template Simplifier pass " + std::to_string(passCount + 1));
mTokenList.front()->printOut(std::cout, title.c_str(), mTokenList.getFiles());
}
// Copy default argument values from forward declaration to declaration
fixForwardDeclaredDefaultArgumentValues();
// Locate user defined specializations.
getSpecializations();
// Locate user defined partial specializations.
getPartialSpecializations();
// Locate possible instantiations of templates..
getTemplateInstantiations();
// Template arguments with default values
useDefaultArgumentValues();
simplifyTemplateAliases();
if (mSettings.debugtemplate)
printOut("### Template Simplifier pass " + std::to_string(passCount + 1) + " ###");
// Keep track of the order the names appear so sort can preserve that order
std::unordered_map<std::string, int> nameOrdinal;
int ordinal = 0;
for (const auto& decl : mTemplateDeclarations) {
nameOrdinal.emplace(decl.fullName(), ordinal++);
}
auto score = [&](const Token* arg) {
int i = 0;
for (const Token* tok = arg; tok; tok = tok->next()) {
if (tok->str() == ",")
return i;
if (tok->link() && Token::Match(tok, "(|{|["))
tok = tok->link();
else if (tok->str() == "<") {
const Token* temp = tok->findClosingBracket();
if (temp)
tok = temp;
} else if (Token::Match(tok, ")|;"))
return i;
else if (Token::simpleMatch(tok, "const"))
i--;
}
return 0;
};
// Sort so const parameters come first in the list
mTemplateDeclarations.sort([&](const TokenAndName& x, const TokenAndName& y) {
if (x.fullName() != y.fullName())
return nameOrdinal.at(x.fullName()) < nameOrdinal.at(y.fullName());
if (x.isFunction() && y.isFunction()) {
std::vector<const Token*> xargs;
getFunctionArguments(x.nameToken(), xargs);
std::vector<const Token*> yargs;
getFunctionArguments(y.nameToken(), yargs);
if (xargs.size() != yargs.size())
return xargs.size() < yargs.size();
if (isConstMethod(x.nameToken()) != isConstMethod(y.nameToken()))
return isConstMethod(x.nameToken());
return std::lexicographical_compare(xargs.begin(),
xargs.end(),
yargs.begin(),
yargs.end(),
[&](const Token* xarg, const Token* yarg) {
if (xarg != yarg)
return score(xarg) < score(yarg);
return false;
});
}
return false;
});
std::set<std::string> expandedtemplates;
for (std::list<TokenAndName>::const_reverse_iterator iter1 = mTemplateDeclarations.crbegin(); iter1 != mTemplateDeclarations.crend(); ++iter1) {
if (iter1->isAlias() || iter1->isFriend())
continue;
// get specializations..
std::list<const Token *> specializations;
for (std::list<TokenAndName>::const_iterator iter2 = mTemplateDeclarations.cbegin(); iter2 != mTemplateDeclarations.cend(); ++iter2) {
if (iter2->isAlias() || iter2->isFriend())
continue;
if (iter1->fullName() == iter2->fullName())
specializations.push_back(iter2->nameToken());
}
const bool instantiated = simplifyTemplateInstantiations(
*iter1,
specializations,
maxtime,
expandedtemplates);
if (instantiated) {
mInstantiatedTemplates.push_back(*iter1);
mTemplateNamePos.clear(); // positions might be invalid after instantiations
}
}
for (std::list<TokenAndName>::const_iterator it = mInstantiatedTemplates.cbegin(); it != mInstantiatedTemplates.cend(); ++it) {
auto decl = std::find_if(mTemplateDeclarations.begin(), mTemplateDeclarations.end(), [&it](const TokenAndName& decl) {
return decl.token() == it->token();
});
if (decl != mTemplateDeclarations.end()) {
if (it->isSpecialization()) {
// delete the "template < >"
Token * tok = it->token();
tok->deleteNext(2);
tok->deleteThis();
} else {
// remove forward declaration if found
auto it1 = mTemplateForwardDeclarationsMap.find(it->token());
if (it1 != mTemplateForwardDeclarationsMap.end())
removeTemplate(it1->second, &mTemplateForwardDeclarationsMap);
removeTemplate(it->token(), &mTemplateForwardDeclarationsMap);
}
mTemplateDeclarations.erase(decl);
}
}
// remove out of line member functions
while (!mMemberFunctionsToDelete.empty()) {
const std::list<TokenAndName>::iterator it = std::find_if(mTemplateDeclarations.begin(),
mTemplateDeclarations.end(),
FindToken(mMemberFunctionsToDelete.cbegin()->token()));
// multiple functions can share the same declaration so make sure it hasn't already been deleted
if (it != mTemplateDeclarations.end()) {
removeTemplate(it->token());
mTemplateDeclarations.erase(it);
} else {
const std::list<TokenAndName>::iterator it1 = std::find_if(mTemplateForwardDeclarations.begin(),
mTemplateForwardDeclarations.end(),
FindToken(mMemberFunctionsToDelete.cbegin()->token()));
// multiple functions can share the same declaration so make sure it hasn't already been deleted
if (it1 != mTemplateForwardDeclarations.end()) {
removeTemplate(it1->token());
mTemplateForwardDeclarations.erase(it1);
}
}
mMemberFunctionsToDelete.erase(mMemberFunctionsToDelete.begin());
}
// remove explicit instantiations
for (const TokenAndName& j : mExplicitInstantiationsToDelete) {
Token * start = j.token();
if (start) {
Token * end = start->next();
while (end && end->str() != ";")
end = end->next();
if (start->previous())
start = start->previous();
if (end && end->next())
end = end->next();
eraseTokens(start, end);
}
}
}
if (passCount == passCountMax) {
if (mSettings.debugwarnings) {
const std::list<const Token*> locationList(1, mTokenList.front());
const ErrorMessage errmsg(locationList, &mTokenizer.list,
Severity::debug,
"debug",
"TemplateSimplifier: pass count limit hit before simplifications were finished.",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
}
// Tweak uninstantiated C++17 fold expressions (... && args)
if (mSettings.standards.cpp >= Standards::CPP17) {
bool simplify = false;
for (Token *tok = mTokenList.front(); tok; tok = tok->next()) {
if (tok->str() == "template")
simplify = false;
if (tok->str() == "{")
simplify = true;
if (!simplify || tok->str() != "(")
continue;
const Token *op = nullptr;
const Token *args = nullptr;
if (Token::Match(tok, "( ... %op%")) {
op = tok->tokAt(2);
args = tok->link()->previous();
} else if (Token::Match(tok, "( %name% %op% ...")) {
op = tok->tokAt(2);
args = tok->link()->previous()->isName() ? nullptr : tok->next();
} else if (Token::Match(tok->link()->tokAt(-3), "%op% ... )")) {
op = tok->link()->tokAt(-2);
args = tok->next();
} else if (Token::Match(tok->link()->tokAt(-3), "... %op% %name% )")) {
op = tok->link()->tokAt(-2);
args = tok->next()->isName() ? nullptr : tok->link()->previous();
} else {
continue;
}
const std::string strop = op->str();
const std::string strargs = (args && args->isName()) ? args->str() : "";
Token::eraseTokens(tok, tok->link());
tok->insertToken(")");
if (!strargs.empty()) {
tok->insertToken("...");
tok->insertToken(strargs);
}
tok->insertToken("(");
Token::createMutualLinks(tok->next(), tok->link()->previous());
tok->insertToken("__cppcheck_fold_" + strop + "__");
}
}
}
void TemplateSimplifier::syntaxError(const Token *tok)
{
throw InternalError(tok, "syntax error", InternalError::SYNTAX);
}
| null |
849 | cpp | cppcheck | checkfunctions.cpp | lib/checkfunctions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Check functions
//---------------------------------------------------------------------------
#include "checkfunctions.h"
#include "astutils.h"
#include "mathlib.h"
#include "platform.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "valueflow.h"
#include "vfvalue.h"
#include <iomanip>
#include <list>
#include <sstream>
#include <unordered_map>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckFunctions instance;
}
static const CWE CWE252(252U); // Unchecked Return Value
static const CWE CWE477(477U); // Use of Obsolete Functions
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments
static const CWE CWE686(686U); // Function Call With Incorrect Argument Type
static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value
static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument
void CheckFunctions::checkProhibitedFunctions()
{
const bool checkAlloca = mSettings->severity.isEnabled(Severity::warning) && ((mTokenizer->isC() && mSettings->standards.c >= Standards::C99) || mSettings->standards.cpp >= Standards::CPP11);
logChecker("CheckFunctions::checkProhibitedFunctions");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% (") && tok->varId() == 0)
continue;
// alloca() is special as it depends on the code being C or C++, so it is not in Library
if (checkAlloca && Token::simpleMatch(tok, "alloca (") && (!tok->function() || tok->function()->nestedIn->type == Scope::eGlobal)) {
if (tok->isC()) {
if (mSettings->standards.c > Standards::C89)
reportError(tok, Severity::warning, "allocaCalled",
"$symbol:alloca\n"
"Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.\n"
"The obsolete function 'alloca' is called. In C99 and later it is recommended to use a variable length array or "
"a dynamically allocated array instead. The function 'alloca' is dangerous for many reasons "
"(http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice and http://linux.die.net/man/3/alloca).");
} else
reportError(tok, Severity::warning, "allocaCalled",
"$symbol:alloca\n"
"Obsolete function 'alloca' called.\n"
"The obsolete function 'alloca' is called. In C++11 and later it is recommended to use std::array<> or "
"a dynamically allocated array instead. The function 'alloca' is dangerous for many reasons "
"(http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice and http://linux.die.net/man/3/alloca).");
} else {
if (tok->function() && tok->function()->hasBody())
continue;
const Library::WarnInfo* wi = mSettings->library.getWarnInfo(tok);
if (wi) {
if (mSettings->severity.isEnabled(wi->severity) && ((tok->isC() && mSettings->standards.c >= wi->standards.c) || (tok->isCpp() && mSettings->standards.cpp >= wi->standards.cpp))) {
const std::string daca = mSettings->daca ? "prohibited" : "";
reportError(tok, wi->severity, daca + tok->str() + "Called", wi->message, CWE477, Certainty::normal);
}
}
}
}
}
}
//---------------------------------------------------------------------------
// Check <valid>, <strz> and <not-bool>
//---------------------------------------------------------------------------
void CheckFunctions::invalidFunctionUsage()
{
logChecker("CheckFunctions::invalidFunctionUsage");
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
tok = skipUnreachableBranch(tok);
if (!Token::Match(tok, "%name% ( !!)"))
continue;
const Token * const functionToken = tok;
const std::vector<const Token *> arguments = getArguments(tok);
for (int argnr = 1; argnr <= arguments.size(); ++argnr) {
const Token * const argtok = arguments[argnr-1];
// check <valid>...</valid>
const ValueFlow::Value *invalidValue = argtok->getInvalidValue(functionToken,argnr,*mSettings);
if (invalidValue) {
invalidFunctionArgError(argtok, functionToken->next()->astOperand1()->expressionString(), argnr, invalidValue, mSettings->library.validarg(functionToken, argnr));
}
if (astIsBool(argtok)) {
// check <not-bool>
if (mSettings->library.isboolargbad(functionToken, argnr))
invalidFunctionArgBoolError(argtok, functionToken->str(), argnr);
// Are the values 0 and 1 valid?
else if (!mSettings->library.isIntArgValid(functionToken, argnr, 0))
invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr));
else if (!mSettings->library.isIntArgValid(functionToken, argnr, 1))
invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr));
}
// check <strz>
if (mSettings->library.isargstrz(functionToken, argnr)) {
if (Token::Match(argtok, "& %var% !![") && argtok->next() && argtok->next()->valueType()) {
const ValueType * valueType = argtok->next()->valueType();
const Variable * variable = argtok->next()->variable();
if ((valueType->type == ValueType::Type::CHAR || valueType->type == ValueType::Type::WCHAR_T || (valueType->type == ValueType::Type::RECORD && Token::Match(argtok, "& %var% . %var% ,|)"))) &&
!variable->isArray() &&
(variable->isConst() || !variable->isGlobal()) &&
(!argtok->next()->hasKnownValue() || argtok->next()->getValue(0) == nullptr)) {
invalidFunctionArgStrError(argtok, functionToken->str(), argnr);
}
}
const ValueType* const valueType = argtok->valueType();
const Variable* const variable = argtok->variable();
// Is non-null terminated local variable of type char (e.g. char buf[] = {'x'};) ?
if (variable && variable->isLocal()
&& valueType && (valueType->type == ValueType::Type::CHAR || valueType->type == ValueType::Type::WCHAR_T)
&& !isVariablesChanged(variable->declEndToken(), functionToken, 0 /*indirect*/, { variable }, *mSettings)) {
const Token* varTok = variable->declEndToken();
MathLib::bigint count = -1; // Find out explicitly set count, e.g.: char buf[3] = {...}. Variable 'count' is set to 3 then.
if (varTok && Token::simpleMatch(varTok->astOperand1(), "["))
{
const Token* const countTok = varTok->astOperand1()->astOperand2();
if (countTok && countTok->hasKnownIntValue())
count = countTok->getKnownIntValue();
}
if (Token::simpleMatch(varTok, "= {")) {
varTok = varTok->tokAt(1);
auto charsUntilFirstZero = 0;
bool search = true;
while (search && varTok && !Token::simpleMatch(varTok->next(), "}")) {
varTok = varTok->next();
if (!Token::simpleMatch(varTok, ",")) {
if (Token::Match(varTok, "%op%")) {
varTok = varTok->next();
continue;
}
++charsUntilFirstZero;
if (varTok && varTok->hasKnownIntValue() && varTok->getKnownIntValue() == 0)
search=false; // stop counting for cases like char buf[3] = {'x', '\0', 'y'};
}
}
if (varTok && varTok->hasKnownIntValue() && varTok->getKnownIntValue() != 0
&& (count == -1 || (count > 0 && count <= charsUntilFirstZero))) {
invalidFunctionArgStrError(argtok, functionToken->str(), argnr);
}
} else if (count > -1 && Token::Match(varTok, "= %str%")) {
const Token* strTok = varTok->getValueTokenMinStrSize(*mSettings);
if (strTok) {
const int strSize = Token::getStrArraySize(strTok);
if (strSize > count && strTok->str().find('\0') == std::string::npos)
invalidFunctionArgStrError(argtok, functionToken->str(), argnr);
}
}
}
}
}
}
}
}
void CheckFunctions::invalidFunctionArgError(const Token *tok, const std::string &functionName, int argnr, const ValueFlow::Value *invalidValue, const std::string &validstr)
{
std::ostringstream errmsg;
errmsg << "$symbol:" << functionName << '\n';
if (invalidValue && invalidValue->condition)
errmsg << ValueFlow::eitherTheConditionIsRedundant(invalidValue->condition)
<< " or $symbol() argument nr " << argnr << " can have invalid value.";
else
errmsg << "Invalid $symbol() argument nr " << argnr << '.';
if (invalidValue)
errmsg << " The value is " << std::setprecision(10) << (invalidValue->isIntValue() ? invalidValue->intvalue : invalidValue->floatValue) << " but the valid values are '" << validstr << "'.";
else
errmsg << " The value is 0 or 1 (boolean) but the valid values are '" << validstr << "'.";
if (invalidValue)
reportError(getErrorPath(tok, invalidValue, "Invalid argument"),
invalidValue->errorSeverity() && invalidValue->isKnown() ? Severity::error : Severity::warning,
"invalidFunctionArg",
errmsg.str(),
CWE628,
invalidValue->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
else
reportError(tok,
Severity::error,
"invalidFunctionArg",
errmsg.str(),
CWE628,
Certainty::normal);
}
void CheckFunctions::invalidFunctionArgBoolError(const Token *tok, const std::string &functionName, int argnr)
{
std::ostringstream errmsg;
errmsg << "$symbol:" << functionName << '\n';
errmsg << "Invalid $symbol() argument nr " << argnr << ". A non-boolean value is required.";
reportError(tok, Severity::error, "invalidFunctionArgBool", errmsg.str(), CWE628, Certainty::normal);
}
void CheckFunctions::invalidFunctionArgStrError(const Token *tok, const std::string &functionName, nonneg int argnr)
{
std::ostringstream errmsg;
errmsg << "$symbol:" << functionName << '\n';
errmsg << "Invalid $symbol() argument nr " << argnr << ". A nul-terminated string is required.";
reportError(tok, Severity::error, "invalidFunctionArgStr", errmsg.str(), CWE628, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for ignored return values.
//---------------------------------------------------------------------------
void CheckFunctions::checkIgnoredReturnValue()
{
if (!mSettings->severity.isEnabled(Severity::warning) &&
!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("ignoredReturnValue"))
return;
logChecker("CheckFunctions::checkIgnoredReturnValue"); // style,warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// skip c++11 initialization, ({...})
if (Token::Match(tok, "%var%|(|,|return {"))
tok = tok->linkAt(1);
else if (Token::Match(tok, "[(<]") && tok->link())
tok = tok->link();
if (tok->varId() || tok->isKeyword() || tok->isStandardType() || !Token::Match(tok, "%name% ("))
continue;
const Token *parent = tok->next()->astParent();
while (Token::Match(parent, "%cop%")) {
if (Token::Match(parent, "<<|>>|*") && !parent->astParent())
break;
parent = parent->astParent();
}
if (parent)
continue;
if (!tok->scope()->isExecutable()) {
tok = tok->scope()->bodyEnd;
continue;
}
if ((!tok->function() || !Token::Match(tok->function()->retDef, "void %name%")) &&
tok->next()->astOperand1()) {
const Library::UseRetValType retvalTy = mSettings->library.getUseRetValType(tok);
const bool warn = (tok->function() && (tok->function()->isAttributeNodiscard() || tok->function()->isAttributePure() || tok->function()->isAttributeConst())) ||
// avoid duplicate warnings for resource-allocating functions
(retvalTy == Library::UseRetValType::DEFAULT && mSettings->library.getAllocFuncInfo(tok) == nullptr);
if (mSettings->severity.isEnabled(Severity::warning) && warn)
ignoredReturnValueError(tok, tok->next()->astOperand1()->expressionString());
else if (mSettings->severity.isEnabled(Severity::style) &&
retvalTy == Library::UseRetValType::ERROR_CODE)
ignoredReturnErrorCode(tok, tok->next()->astOperand1()->expressionString());
}
}
}
}
void CheckFunctions::ignoredReturnValueError(const Token* tok, const std::string& function)
{
reportError(tok, Severity::warning, "ignoredReturnValue",
"$symbol:" + function + "\nReturn value of function $symbol() is not used.", CWE252, Certainty::normal);
}
void CheckFunctions::ignoredReturnErrorCode(const Token* tok, const std::string& function)
{
reportError(tok, Severity::style, "ignoredReturnErrorCode",
"$symbol:" + function + "\nError code from the return value of function $symbol() is not used.", CWE252, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for ignored return values.
//---------------------------------------------------------------------------
static const Token *checkMissingReturnScope(const Token *tok, const Library &library);
void CheckFunctions::checkMissingReturn()
{
logChecker("CheckFunctions::checkMissingReturn");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
const Function *function = scope->function;
if (!function || !function->hasBody())
continue;
if (function->name() == "main" && !(mTokenizer->isC() && mSettings->standards.c < Standards::C99))
continue;
if (function->type != Function::Type::eFunction && function->type != Function::Type::eOperatorEqual)
continue;
if (Token::Match(function->retDef, "%name% (") && function->retDef->isUpperCaseName())
continue;
if (Function::returnsVoid(function, true))
continue;
const Token *errorToken = checkMissingReturnScope(scope->bodyEnd, mSettings->library);
if (errorToken)
missingReturnError(errorToken);
}
}
static bool isForwardJump(const Token *gotoToken)
{
if (!Token::Match(gotoToken, "goto %name% ;"))
return false;
for (const Token *prev = gotoToken; gotoToken; gotoToken = gotoToken->previous()) {
if (Token::Match(prev, "%name% :") && prev->str() == gotoToken->strAt(1))
return true;
if (prev->str() == "{" && prev->scope()->type == Scope::eFunction)
return false;
}
return false;
}
static const Token *checkMissingReturnScope(const Token *tok, const Library &library)
{
const Token *lastStatement = nullptr;
while ((tok = tok->previous()) != nullptr) {
if (tok->str() == ")")
tok = tok->link();
if (tok->str() == "{")
return lastStatement ? lastStatement : tok->next();
if (tok->str() == "}") {
for (const Token *prev = tok->link()->previous(); prev && prev->scope() == tok->scope() && !Token::Match(prev, "[;{}]"); prev = prev->previous()) {
if (prev->isKeyword() && Token::Match(prev, "return|throw"))
return nullptr;
if (prev->str() == "goto" && !isForwardJump(prev))
return nullptr;
}
if (tok->scope()->type == Scope::ScopeType::eSwitch) {
bool reachable = false;
for (const Token *switchToken = tok->link()->next(); switchToken != tok; switchToken = switchToken->next()) {
if (reachable && Token::simpleMatch(switchToken, "break ;")) {
if (Token::simpleMatch(switchToken->previous(), "}") && !checkMissingReturnScope(switchToken->previous(), library))
reachable = false;
else
return switchToken;
}
if (switchToken->isKeyword() && Token::Match(switchToken, "return|throw"))
reachable = false;
if (Token::Match(switchToken, "%name% (") && library.isnoreturn(switchToken))
reachable = false;
if (Token::Match(switchToken, "case|default"))
reachable = true;
else if (switchToken->str() == "{" && (switchToken->scope()->isLoopScope() || switchToken->scope()->type == Scope::ScopeType::eSwitch))
switchToken = switchToken->link();
}
if (!isExhaustiveSwitch(tok->link()))
return tok->link();
} else if (tok->scope()->type == Scope::ScopeType::eIf) {
const Token *condition = tok->scope()->classDef->next()->astOperand2();
if (condition && condition->hasKnownIntValue() && condition->getKnownIntValue() == 1)
return checkMissingReturnScope(tok, library);
return tok;
} else if (tok->scope()->type == Scope::ScopeType::eElse) {
const Token *errorToken = checkMissingReturnScope(tok, library);
if (errorToken)
return errorToken;
tok = tok->link();
if (Token::simpleMatch(tok->tokAt(-2), "} else {"))
return checkMissingReturnScope(tok->tokAt(-2), library);
return tok;
}
// FIXME
return nullptr;
}
if (tok->isKeyword() && Token::Match(tok, "return|throw"))
return nullptr;
if (tok->str() == "goto" && !isForwardJump(tok))
return nullptr;
if (Token::Match(tok, "%name% (") && library.isnoreturn(tok)) {
return nullptr;
}
if (Token::Match(tok->previous(), "[;{}] %name% (") && !library.isnotnoreturn(tok)) {
return nullptr;
}
if (Token::Match(tok, "[;{}] %name% :"))
return tok;
if (Token::Match(tok, "; !!}") && !lastStatement)
lastStatement = tok->next();
}
return nullptr;
}
void CheckFunctions::missingReturnError(const Token* tok)
{
reportError(tok, Severity::error, "missingReturn",
"Found an exit path from function with non-void return type that has missing return statement", CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// Detect passing wrong values to <cmath> functions like atan(0, x);
//---------------------------------------------------------------------------
void CheckFunctions::checkMathFunctions()
{
const bool styleC99 = mSettings->severity.isEnabled(Severity::style) && ((mTokenizer->isC() && mSettings->standards.c != Standards::C89) || (mTokenizer->isCPP() && mSettings->standards.cpp != Standards::CPP03));
const bool printWarnings = mSettings->severity.isEnabled(Severity::warning);
if (!styleC99 && !printWarnings && !mSettings->isPremiumEnabled("wrongmathcall"))
return;
logChecker("CheckFunctions::checkMathFunctions"); // style,warning,c99,c++11
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (tok->varId())
continue;
if (printWarnings && Token::Match(tok, "%name% ( !!)")) {
if (tok->strAt(-1) != "."
&& Token::Match(tok, "log|logf|logl|log10|log10f|log10l|log2|log2f|log2l ( %num% )")) {
const std::string& number = tok->strAt(2);
if ((MathLib::isInt(number) && MathLib::toBigNumber(number) <= 0) ||
(MathLib::isFloat(number) && MathLib::toDoubleNumber(number) <= 0.))
mathfunctionCallWarning(tok);
} else if (Token::Match(tok, "log1p|log1pf|log1pl ( %num% )")) {
const std::string& number = tok->strAt(2);
if ((MathLib::isInt(number) && MathLib::toBigNumber(number) <= -1) ||
(MathLib::isFloat(number) && MathLib::toDoubleNumber(number) <= -1.))
mathfunctionCallWarning(tok);
}
// atan2 ( x , y): x and y can not be zero, because this is mathematically not defined
else if (Token::Match(tok, "atan2|atan2f|atan2l ( %num% , %num% )")) {
if (MathLib::isNullValue(tok->strAt(2)) && MathLib::isNullValue(tok->strAt(4)))
mathfunctionCallWarning(tok, 2);
}
// fmod ( x , y) If y is zero, then either a range error will occur or the function will return zero (implementation-defined).
else if (Token::Match(tok, "fmod|fmodf|fmodl (")) {
const Token* nextArg = tok->tokAt(2)->nextArgument();
if (nextArg && MathLib::isNullValue(nextArg->str()))
mathfunctionCallWarning(tok, 2);
}
// pow ( x , y) If x is zero, and y is negative --> division by zero
else if (Token::Match(tok, "pow|powf|powl ( %num% , %num% )")) {
if (MathLib::isNullValue(tok->strAt(2)) && MathLib::isNegative(tok->strAt(4)))
mathfunctionCallWarning(tok, 2);
}
}
if (styleC99) {
if (Token::Match(tok, "%num% - erf (") && Tokenizer::isOneNumber(tok->str()) && tok->next()->astOperand2() == tok->tokAt(3)) {
mathfunctionCallWarning(tok, "1 - erf(x)", "erfc(x)");
} else if (Token::simpleMatch(tok, "exp (") && Token::Match(tok->linkAt(1), ") - %num%") && Tokenizer::isOneNumber(tok->linkAt(1)->strAt(2)) && tok->linkAt(1)->next()->astOperand1() == tok->next()) {
mathfunctionCallWarning(tok, "exp(x) - 1", "expm1(x)");
} else if (Token::simpleMatch(tok, "log (") && tok->next()->astOperand2()) {
const Token* plus = tok->next()->astOperand2();
if (plus->str() == "+" && ((plus->astOperand1() && Tokenizer::isOneNumber(plus->astOperand1()->str())) || (plus->astOperand2() && Tokenizer::isOneNumber(plus->astOperand2()->str()))))
mathfunctionCallWarning(tok, "log(1 + x)", "log1p(x)");
}
}
}
}
}
void CheckFunctions::mathfunctionCallWarning(const Token *tok, const nonneg int numParam)
{
if (tok) {
if (numParam == 1)
reportError(tok, Severity::warning, "wrongmathcall", "$symbol:" + tok->str() + "\nPassing value " + tok->strAt(2) + " to $symbol() leads to implementation-defined result.", CWE758, Certainty::normal);
else if (numParam == 2)
reportError(tok, Severity::warning, "wrongmathcall", "$symbol:" + tok->str() + "\nPassing values " + tok->strAt(2) + " and " + tok->strAt(4) + " to $symbol() leads to implementation-defined result.", CWE758, Certainty::normal);
} else
reportError(tok, Severity::warning, "wrongmathcall", "Passing value '#' to #() leads to implementation-defined result.", CWE758, Certainty::normal);
}
void CheckFunctions::mathfunctionCallWarning(const Token *tok, const std::string& oldexp, const std::string& newexp)
{
reportError(tok, Severity::style, "unpreciseMathCall", "Expression '" + oldexp + "' can be replaced by '" + newexp + "' to avoid loss of precision.", CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// memset(p, y, 0 /* bytes to fill */) <- 2nd and 3rd arguments inverted
//---------------------------------------------------------------------------
void CheckFunctions::memsetZeroBytes()
{
// FIXME:
// Replace this with library configuration.
// For instance:
// <arg nr="3">
// <warn knownIntValue="0" severity="warning" msg="..."/>
// </arg>
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckFunctions::memsetZeroBytes"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "memset|wmemset (") && (numberOfArguments(tok)==3)) {
const std::vector<const Token *> &arguments = getArguments(tok);
if (WRONG_DATA(arguments.size() != 3U, tok))
continue;
const Token* lastParamTok = arguments[2];
if (MathLib::isNullValue(lastParamTok->str()))
memsetZeroBytesError(tok);
}
}
}
}
void CheckFunctions::memsetZeroBytesError(const Token *tok)
{
const std::string summary("memset() called to fill 0 bytes.");
const std::string verbose(summary + " The second and third arguments might be inverted."
" The function memset ( void * ptr, int value, size_t num ) sets the"
" first num bytes of the block of memory pointed by ptr to the specified value.");
reportError(tok, Severity::warning, "memsetZeroBytes", summary + "\n" + verbose, CWE687, Certainty::normal);
}
void CheckFunctions::memsetInvalid2ndParam()
{
// FIXME:
// Replace this with library configuration.
// For instance:
// <arg nr="2">
// <not-float/>
// <warn possibleIntValue=":-129,256:" severity="warning" msg="..."/>
// </arg>
const bool printPortability = mSettings->severity.isEnabled(Severity::portability);
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
if (!printWarning && !printPortability)
return;
logChecker("CheckFunctions::memsetInvalid2ndParam"); // warning,portability
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) {
if (!Token::simpleMatch(tok, "memset ("))
continue;
const std::vector<const Token *> args = getArguments(tok);
if (args.size() != 3)
continue;
// Second parameter is zero literal, i.e. 0.0f
const Token * const secondParamTok = args[1];
if (Token::Match(secondParamTok, "%num% ,") && MathLib::isNullValue(secondParamTok->str()))
continue;
// Check if second parameter is a float variable or a float literal != 0.0f
if (printPortability && astIsFloat(secondParamTok,false)) {
memsetFloatError(secondParamTok, secondParamTok->expressionString());
}
if (printWarning && secondParamTok->isNumber()) { // Check if the second parameter is a literal and is out of range
const MathLib::bigint value = MathLib::toBigNumber(secondParamTok->str());
const long long sCharMin = mSettings->platform.signedCharMin();
const long long uCharMax = mSettings->platform.unsignedCharMax();
if (value < sCharMin || value > uCharMax)
memsetValueOutOfRangeError(secondParamTok, secondParamTok->str());
}
}
}
}
void CheckFunctions::memsetFloatError(const Token *tok, const std::string &var_value)
{
const std::string message("The 2nd memset() argument '" + var_value +
"' is a float, its representation is implementation defined.");
const std::string verbose(message + " memset() is used to set each byte of a block of memory to a specific value and"
" the actual representation of a floating-point value is implementation defined.");
reportError(tok, Severity::portability, "memsetFloat", message + "\n" + verbose, CWE688, Certainty::normal);
}
void CheckFunctions::memsetValueOutOfRangeError(const Token *tok, const std::string &value)
{
const std::string message("The 2nd memset() argument '" + value + "' doesn't fit into an 'unsigned char'.");
const std::string verbose(message + " The 2nd parameter is passed as an 'int', but the function fills the block of memory using the 'unsigned char' conversion of this value.");
reportError(tok, Severity::warning, "memsetValueOutOfRange", message + "\n" + verbose, CWE686, Certainty::normal);
}
//---------------------------------------------------------------------------
// --check-library => warn for unconfigured functions
//---------------------------------------------------------------------------
void CheckFunctions::checkLibraryMatchFunctions()
{
if (!mSettings->checkLibrary)
return;
bool insideNew = false;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->scope() || !tok->scope()->isExecutable())
continue;
if (tok->str() == "new")
insideNew = true;
else if (tok->str() == ";")
insideNew = false;
else if (insideNew)
continue;
if (tok->isKeyword() || !Token::Match(tok, "%name% ("))
continue;
if (tok->varId() != 0 || tok->type() || tok->isStandardType())
continue;
if (tok->linkAt(1)->strAt(1) == "(")
continue;
if (tok->function())
continue;
if (Token::simpleMatch(tok->astTop(), "throw"))
continue;
if (Token::simpleMatch(tok->astParent(), ".")) {
const Token* contTok = tok->astParent()->astOperand1();
if (astContainerAction(contTok, nullptr, mSettings) != Library::Container::Action::NO_ACTION)
continue;
if (astContainerYield(contTok, nullptr, mSettings) != Library::Container::Yield::NO_YIELD)
continue;
}
if (!mSettings->library.isNotLibraryFunction(tok))
continue;
const std::string &functionName = mSettings->library.getFunctionName(tok);
if (functionName.empty())
continue;
if (mSettings->library.functions().find(functionName) != mSettings->library.functions().end())
continue;
if (mSettings->library.podtype(tok->expressionString()))
continue;
if (mSettings->library.getTypeCheck("unusedvar", functionName) != Library::TypeCheck::def)
continue;
const Token* start = tok;
while (Token::Match(start->tokAt(-2), "%name% ::") && !start->tokAt(-2)->isKeyword())
start = start->tokAt(-2);
if (mSettings->library.detectContainerOrIterator(start))
continue;
reportError(tok,
Severity::information,
"checkLibraryFunction",
"--check-library: There is no matching configuration for function " + functionName + "()");
}
}
// Check for problems to compiler apply (Named) Return Value Optimization for local variable
// Technically we have different guarantees between standard versions
// details: https://en.cppreference.com/w/cpp/language/copy_elision
void CheckFunctions::returnLocalStdMove()
{
if (!mTokenizer->isCPP() || mSettings->standards.cpp < Standards::CPP11)
return;
if (!mSettings->severity.isEnabled(Severity::performance))
return;
logChecker("CheckFunctions::returnLocalStdMove"); // performance,c++11
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
// Expect return by-value
if (Function::returnsReference(scope->function, /*unknown*/ true, /*includeRValueRef*/ true))
continue;
const auto rets = Function::findReturns(scope->function);
for (const Token* ret : rets) {
if (!Token::simpleMatch(ret->tokAt(-3), "std :: move ("))
continue;
const Token* retval = ret->astOperand2();
// NRVO
if (retval->variable() && retval->variable()->isLocal() && !retval->variable()->isVolatile())
copyElisionError(retval);
// RVO
if (Token::Match(retval, "(|{") && !retval->isCast() && !(retval->valueType() && retval->valueType()->reference != Reference::None))
copyElisionError(retval);
}
}
}
void CheckFunctions::copyElisionError(const Token *tok)
{
reportError(tok,
Severity::performance,
"returnStdMoveLocal",
"Using std::move for returning object by-value from function will affect copy elision optimization."
" More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local");
}
void CheckFunctions::useStandardLibrary()
{
if (!mSettings->severity.isEnabled(Severity::style))
return;
logChecker("CheckFunctions::useStandardLibrary"); // style
for (const Scope& scope: mTokenizer->getSymbolDatabase()->scopeList) {
if (scope.type != Scope::ScopeType::eFor)
continue;
const Token *forToken = scope.classDef;
// for ( initToken ; condToken ; stepToken )
const Token* initToken = getInitTok(forToken);
if (!initToken)
continue;
const Token* condToken = getCondTok(forToken);
if (!condToken)
continue;
const Token* stepToken = getStepTok(forToken);
if (!stepToken)
continue;
// 1. we expect that idx variable will be initialized with 0
const Token* idxToken = initToken->astOperand1();
const Token* initVal = initToken->astOperand2();
if (!idxToken || !initVal || !initVal->hasKnownIntValue() || initVal->getKnownIntValue() != 0)
continue;
const auto idxVarId = idxToken->varId();
if (0 == idxVarId)
continue;
// 2. we expect that idx will be less of some variable
if (!condToken->isComparisonOp())
continue;
const auto& secondOp = condToken->str();
const bool isLess = "<" == secondOp &&
isConstExpression(condToken->astOperand2(), mSettings->library) &&
condToken->astOperand1()->varId() == idxVarId;
const bool isMore = ">" == secondOp &&
isConstExpression(condToken->astOperand1(), mSettings->library) &&
condToken->astOperand2()->varId() == idxVarId;
if (!(isLess || isMore))
continue;
// 3. we expect idx incrementing by 1
const bool inc = stepToken->str() == "++" && stepToken->astOperand1() && stepToken->astOperand1()->varId() == idxVarId;
const bool plusOne = stepToken->isBinaryOp() && stepToken->str() == "+=" &&
stepToken->astOperand1()->varId() == idxVarId &&
stepToken->astOperand2()->str() == "1";
if (!inc && !plusOne)
continue;
// technically using void* here is not correct but some compilers could allow it
const Token *tok = scope.bodyStart;
const std::string memcpyName = tok->isCpp() ? "std::memcpy" : "memcpy";
// (reinterpret_cast<uint8_t*>(dest))[i] = (reinterpret_cast<const uint8_t*>(src))[i];
if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = "
"(| reinterpret_cast < const| uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memcpyName);
continue;
}
// ((char*)dst)[i] = ((const char*)src)[i];
if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = "
"( ( const| uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memcpyName);
continue;
}
const static std::string memsetName = tok->isCpp() ? "std::memset" : "memset";
// ((char*)dst)[i] = 0;
if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = %char%|%num% ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memsetName);
continue;
}
// ((char*)dst)[i] = (const char*)0;
if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = "
"( const| uint8_t|int8_t|char ) (| %char%|%num% )| ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memsetName);
continue;
}
// (reinterpret_cast<uint8_t*>(dest))[i] = static_cast<const uint8_t>(0);
if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = "
"(| static_cast < const| uint8_t|int8_t|char > ( %char%|%num% ) )| ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memsetName);
continue;
}
// (reinterpret_cast<int8_t*>(dest))[i] = 0;
if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = "
"%char%|%num% ; }", idxVarId)) {
useStandardLibraryError(tok->next(), memsetName);
continue;
}
}
}
void CheckFunctions::useStandardLibraryError(const Token *tok, const std::string& expected)
{
reportError(tok, Severity::style,
"useStandardLibrary",
"Consider using " + expected + " instead of loop.");
}
| null |
850 | cpp | cppcheck | checkstl.cpp | lib/checkstl.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "checkstl.h"
#include "astutils.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "pathanalysis.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include "valueflow.h"
#include "checknullpointer.h"
#include <algorithm>
#include <iterator>
#include <list>
#include <map>
#include <set>
#include <sstream>
#include <tuple>
#include <unordered_map>
#include <utility>
#include <vector>
// Register this check class (by creating a static instance of it)
namespace {
CheckStl instance;
}
// CWE IDs used:
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE597(597U); // Use of Wrong Operator in String Comparison
static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments
static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime
static const CWE CWE667(667U); // Improper Locking
static const CWE CWE704(704U); // Incorrect Type Conversion or Cast
static const CWE CWE762(762U); // Mismatched Memory Management Routines
static const CWE CWE786(786U); // Access of Memory Location Before Start of Buffer
static const CWE CWE788(788U); // Access of Memory Location After End of Buffer
static const CWE CWE825(825U); // Expired Pointer Dereference
static const CWE CWE833(833U); // Deadlock
static const CWE CWE834(834U); // Excessive Iteration
static bool isElementAccessYield(Library::Container::Yield yield)
{
return contains({Library::Container::Yield::ITEM, Library::Container::Yield::AT_INDEX}, yield);
}
static bool containerAppendsElement(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
const Library::Container::Action action = container->getAction(parent->strAt(1));
if (contains({Library::Container::Action::INSERT,
Library::Container::Action::APPEND,
Library::Container::Action::CHANGE,
Library::Container::Action::CHANGE_INTERNAL,
Library::Container::Action::PUSH,
Library::Container::Action::RESIZE},
action))
return true;
}
return false;
}
static bool containerYieldsElement(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
const Library::Container::Yield yield = container->getYield(parent->strAt(1));
if (isElementAccessYield(yield))
return true;
}
return false;
}
static bool containerPopsElement(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
const Library::Container::Action action = container->getAction(parent->strAt(1));
if (contains({ Library::Container::Action::POP }, action))
return true;
}
return false;
}
static const Token* getContainerIndex(const Library::Container* container, const Token* parent)
{
if (Token::Match(parent, ". %name% (")) {
const Library::Container::Yield yield = container->getYield(parent->strAt(1));
if (yield == Library::Container::Yield::AT_INDEX && !Token::simpleMatch(parent->tokAt(2), "( )"))
return parent->tokAt(2)->astOperand2();
}
if (!container->arrayLike_indexOp && !container->stdStringLike)
return nullptr;
if (Token::simpleMatch(parent, "["))
return parent->astOperand2();
return nullptr;
}
static const Token* getContainerFromSize(const Library::Container* container, const Token* tok)
{
if (!tok)
return nullptr;
if (Token::Match(tok->tokAt(-2), ". %name% (")) {
const Library::Container::Yield yield = container->getYield(tok->strAt(-1));
if (yield == Library::Container::Yield::SIZE)
return tok->tokAt(-2)->astOperand1();
}
return nullptr;
}
void CheckStl::outOfBounds()
{
logChecker("CheckStl::outOfBounds");
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
const Library::Container *container = getLibraryContainer(tok);
if (!container || container->stdAssociativeLike)
continue;
const Token * parent = astParentSkipParens(tok);
const Token* accessTok = parent;
if (Token::simpleMatch(accessTok, ".") && Token::simpleMatch(accessTok->astParent(), "("))
accessTok = accessTok->astParent();
if (astIsIterator(accessTok) && Token::simpleMatch(accessTok->astParent(), "+"))
accessTok = accessTok->astParent();
const Token* indexTok = getContainerIndex(container, parent);
if (indexTok == tok)
continue;
for (const ValueFlow::Value &value : tok->values()) {
if (!value.isContainerSizeValue())
continue;
if (value.isImpossible())
continue;
if (value.isInconclusive() && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
if (!value.errorSeverity() && !mSettings->severity.isEnabled(Severity::warning))
continue;
if (value.intvalue == 0 && (indexTok ||
(containerYieldsElement(container, parent) && !containerAppendsElement(container, parent)) ||
containerPopsElement(container, parent))) {
std::string indexExpr;
if (indexTok && !indexTok->hasKnownValue())
indexExpr = indexTok->expressionString();
outOfBoundsError(accessTok, tok->expressionString(), &value, indexExpr, nullptr);
continue;
}
if (indexTok) {
std::vector<ValueFlow::Value> indexValues =
ValueFlow::isOutOfBounds(value, indexTok, mSettings->severity.isEnabled(Severity::warning));
if (!indexValues.empty()) {
outOfBoundsError(
accessTok, tok->expressionString(), &value, indexTok->expressionString(), &indexValues.front());
continue;
}
}
}
if (indexTok && !indexTok->hasKnownIntValue()) {
const ValueFlow::Value* value =
ValueFlow::findValue(indexTok->values(), *mSettings, [&](const ValueFlow::Value& v) {
if (!v.isSymbolicValue())
return false;
if (v.isImpossible())
return false;
if (v.intvalue < 0)
return false;
const Token* sizeTok = v.tokvalue;
if (sizeTok && sizeTok->isCast())
sizeTok = sizeTok->astOperand2() ? sizeTok->astOperand2() : sizeTok->astOperand1();
const Token* containerTok = getContainerFromSize(container, sizeTok);
if (!containerTok)
return false;
return containerTok->exprId() == tok->exprId();
});
if (!value)
continue;
outOfBoundsError(accessTok, tok->expressionString(), nullptr, indexTok->expressionString(), value);
}
}
}
}
static std::string indexValueString(const ValueFlow::Value& indexValue, const std::string& containerName = emptyString)
{
if (indexValue.isIteratorStartValue())
return "at position " + std::to_string(indexValue.intvalue) + " from the beginning";
if (indexValue.isIteratorEndValue())
return "at position " + std::to_string(-indexValue.intvalue) + " from the end";
std::string indexString = std::to_string(indexValue.intvalue);
if (indexValue.isSymbolicValue()) {
indexString = containerName + ".size()";
if (indexValue.intvalue != 0)
indexString += "+" + std::to_string(indexValue.intvalue);
}
if (indexValue.bound == ValueFlow::Value::Bound::Lower)
return "greater or equal to " + indexString;
return indexString;
}
void CheckStl::outOfBoundsError(const Token *tok, const std::string &containerName, const ValueFlow::Value *containerSize, const std::string &index, const ValueFlow::Value *indexValue)
{
// Do not warn if both the container size and index value are possible
if (containerSize && indexValue && containerSize->isPossible() && indexValue->isPossible())
return;
const std::string expression = tok ? tok->expressionString() : (containerName+"[x]");
std::string errmsg;
if (!containerSize) {
if (indexValue && indexValue->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(indexValue->condition) + " or '" + index +
"' can have the value " + indexValueString(*indexValue, containerName) + ". Expression '" +
expression + "' causes access out of bounds.";
else
errmsg = "Out of bounds access in expression '" + expression + "'";
} else if (containerSize->intvalue == 0) {
if (containerSize->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or expression '" + expression + "' causes access out of bounds.";
else if (indexValue == nullptr && !index.empty() && tok->valueType() && tok->valueType()->type == ValueType::ITERATOR)
errmsg = "Out of bounds access in expression '" + expression + "' because '$symbol' is empty and '" + index + "' may be non-zero.";
else
errmsg = "Out of bounds access in expression '" + expression + "' because '$symbol' is empty.";
} else if (indexValue) {
if (containerSize->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or size of '$symbol' can be " + std::to_string(containerSize->intvalue) + ". Expression '" + expression + "' causes access out of bounds.";
else if (indexValue->condition)
errmsg = ValueFlow::eitherTheConditionIsRedundant(indexValue->condition) + " or '" + index + "' can have the value " + indexValueString(*indexValue) + ". Expression '" + expression + "' causes access out of bounds.";
else
errmsg = "Out of bounds access in '" + expression + "', if '$symbol' size is " + std::to_string(containerSize->intvalue) + " and '" + index + "' is " + indexValueString(*indexValue);
} else {
// should not happen
return;
}
ErrorPath errorPath;
if (!indexValue)
errorPath = getErrorPath(tok, containerSize, "Access out of bounds");
else {
ErrorPath errorPath1 = getErrorPath(tok, containerSize, "Access out of bounds");
ErrorPath errorPath2 = getErrorPath(tok, indexValue, "Access out of bounds");
if (errorPath1.size() <= 1)
errorPath = std::move(errorPath2);
else if (errorPath2.size() <= 1)
errorPath = std::move(errorPath1);
else {
errorPath = std::move(errorPath1);
errorPath.splice(errorPath.end(), errorPath2);
}
}
reportError(errorPath,
(containerSize && !containerSize->errorSeverity()) || (indexValue && !indexValue->errorSeverity()) ? Severity::warning : Severity::error,
"containerOutOfBounds",
"$symbol:" + containerName +"\n" + errmsg,
CWE398,
(containerSize && containerSize->isInconclusive()) || (indexValue && indexValue->isInconclusive()) ? Certainty::inconclusive : Certainty::normal);
}
bool CheckStl::isContainerSize(const Token *containerToken, const Token *expr) const
{
if (!Token::simpleMatch(expr, "( )"))
return false;
if (!Token::Match(expr->astOperand1(), ". %name% ("))
return false;
if (!isSameExpression(false, containerToken, expr->astOperand1()->astOperand1(), *mSettings, false, false))
return false;
return containerToken->valueType()->container->getYield(expr->strAt(-1)) == Library::Container::Yield::SIZE;
}
bool CheckStl::isContainerSizeGE(const Token * containerToken, const Token *expr) const
{
if (!expr)
return false;
if (isContainerSize(containerToken, expr))
return true;
if (expr->str() == "*") {
const Token *mul;
if (isContainerSize(containerToken, expr->astOperand1()))
mul = expr->astOperand2();
else if (isContainerSize(containerToken, expr->astOperand2()))
mul = expr->astOperand1();
else
return false;
return mul && (!mul->hasKnownIntValue() || mul->values().front().intvalue != 0);
}
if (expr->str() == "+") {
const Token *op;
if (isContainerSize(containerToken, expr->astOperand1()))
op = expr->astOperand2();
else if (isContainerSize(containerToken, expr->astOperand2()))
op = expr->astOperand1();
else
return false;
return op && op->getValueGE(0, *mSettings);
}
return false;
}
void CheckStl::outOfBoundsIndexExpression()
{
logChecker("CheckStl::outOfBoundsIndexExpression");
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
if (!tok->isName() || !tok->valueType())
continue;
const Library::Container *container = tok->valueType()->container;
if (!container)
continue;
if (!container->arrayLike_indexOp && !container->stdStringLike)
continue;
if (!Token::Match(tok, "%name% ["))
continue;
if (isContainerSizeGE(tok, tok->next()->astOperand2()))
outOfBoundsIndexExpressionError(tok, tok->next()->astOperand2());
}
}
}
void CheckStl::outOfBoundsIndexExpressionError(const Token *tok, const Token *index)
{
const std::string varname = tok ? tok->str() : std::string("var");
const std::string i = index ? index->expressionString() : (varname + ".size()");
std::string errmsg = "Out of bounds access of $symbol, index '" + i + "' is out of bounds.";
reportError(tok,
Severity::error,
"containerOutOfBoundsIndexExpression",
"$symbol:" + varname +"\n" + errmsg,
CWE398,
Certainty::normal);
}
// Error message for bad iterator usage..
void CheckStl::invalidIteratorError(const Token *tok, const std::string &iteratorName)
{
reportError(tok, Severity::error, "invalidIterator1", "$symbol:"+iteratorName+"\nInvalid iterator: $symbol", CWE664, Certainty::normal);
}
void CheckStl::iteratorsError(const Token* tok, const std::string& containerName1, const std::string& containerName2)
{
reportError(tok, Severity::error, "iterators1",
"$symbol:" + containerName1 + "\n"
"$symbol:" + containerName2 + "\n"
"Same iterator is used with different containers '" + containerName1 + "' and '" + containerName2 + "'.", CWE664, Certainty::normal);
}
void CheckStl::iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName1, const std::string& containerName2)
{
std::list<const Token*> callstack = { tok, containerTok };
reportError(callstack, Severity::error, "iterators2",
"$symbol:" + containerName1 + "\n"
"$symbol:" + containerName2 + "\n"
"Same iterator is used with different containers '" + containerName1 + "' and '" + containerName2 + "'.", CWE664, Certainty::normal);
}
void CheckStl::iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName)
{
std::list<const Token*> callstack = { tok, containerTok };
reportError(callstack,
Severity::error,
"iterators3",
"$symbol:" + containerName +
"\n"
"Same iterator is used with containers '$symbol' that are temporaries or defined in different scopes.",
CWE664,
Certainty::normal);
}
// Error message used when dereferencing an iterator that has been erased..
void CheckStl::dereferenceErasedError(const Token *erased, const Token* deref, const std::string &itername, bool inconclusive)
{
if (erased) {
std::list<const Token*> callstack = { deref, erased };
reportError(callstack, Severity::error, "eraseDereference",
"$symbol:" + itername + "\n"
"Iterator '$symbol' used after element has been erased.\n"
"The iterator '$symbol' is invalid after the element it pointed to has been erased. "
"Dereferencing or comparing it with another iterator is invalid operation.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal);
} else {
reportError(deref, Severity::error, "eraseDereference",
"$symbol:" + itername + "\n"
"Invalid iterator '$symbol' used.\n"
"The iterator '$symbol' is invalid before being assigned. "
"Dereferencing or comparing it with another iterator is invalid operation.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
}
static const Token *skipMembers(const Token *tok)
{
while (Token::Match(tok, "%name% ."))
tok = tok->tokAt(2);
return tok;
}
static bool isIterator(const Variable *var, bool& inconclusiveType)
{
// Check that its an iterator
if (!var || !var->isLocal() || !Token::Match(var->typeEndToken(), "iterator|const_iterator|reverse_iterator|const_reverse_iterator|auto"))
return false;
inconclusiveType = false;
if (var->typeEndToken()->str() == "auto")
return (var->nameToken()->valueType() && var->nameToken()->valueType()->type == ValueType::Type::ITERATOR);
if (var->type()) { // If it is defined, ensure that it is defined like an iterator
// look for operator* and operator++
const Function* end = var->type()->getFunction("operator*");
const Function* incOperator = var->type()->getFunction("operator++");
if (!end || end->argCount() > 0 || !incOperator)
return false;
inconclusiveType = true; // heuristics only
}
return true;
}
static std::string getContainerName(const Token *containerToken)
{
if (!containerToken)
return std::string();
std::string ret(containerToken->str());
for (const Token *nametok = containerToken; nametok; nametok = nametok->tokAt(-2)) {
if (!Token::Match(nametok->tokAt(-2), "%name% ."))
break;
ret = nametok->strAt(-2) + '.' + ret;
}
return ret;
}
static bool isVector(const Token* tok)
{
if (!tok)
return false;
const Variable *var = tok->variable();
const Token *decltok = var ? var->typeStartToken() : nullptr;
return Token::simpleMatch(decltok, "std :: vector");
}
void CheckStl::iterators()
{
logChecker("CheckStl::iterators");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Filling map of iterators id and their scope begin
std::map<int, const Token*> iteratorScopeBeginInfo;
for (const Variable* var : symbolDatabase->variableList()) {
bool inconclusiveType=false;
if (!isIterator(var, inconclusiveType))
continue;
const int iteratorId = var->declarationId();
if (iteratorId != 0)
iteratorScopeBeginInfo[iteratorId] = var->nameToken();
}
for (const Variable* var : symbolDatabase->variableList()) {
bool inconclusiveType=false;
if (!isIterator(var, inconclusiveType))
continue;
if (inconclusiveType && !mSettings->certainty.isEnabled(Certainty::inconclusive))
continue;
const int iteratorId = var->declarationId();
// the validIterator flag says if the iterator has a valid value or not
bool validIterator = Token::Match(var->nameToken()->next(), "[(=:{[]");
const Scope* invalidationScope = nullptr;
// The container this iterator can be used with
const Token* containerToken = nullptr;
const Scope* containerAssignScope = nullptr;
// When "validatingToken" is reached the validIterator is set to true
const Token* validatingToken = nullptr;
const Token* eraseToken = nullptr;
// Scan through the rest of the code and see if the iterator is
// used against other containers.
for (const Token *tok2 = var->nameToken(); tok2 && tok2 != var->scope()->bodyEnd; tok2 = tok2->next()) {
if (invalidationScope && tok2 == invalidationScope->bodyEnd)
validIterator = true; // Assume that the iterator becomes valid again
if (containerAssignScope && tok2 == containerAssignScope->bodyEnd)
containerToken = nullptr; // We don't know which containers might be used with the iterator
if (tok2 == validatingToken) {
validIterator = true;
eraseToken = nullptr;
invalidationScope = nullptr;
}
// Is the iterator used in a insert/erase operation?
if (Token::Match(tok2, "%name% . insert|erase ( *| %varid% )|,", iteratorId) && !isVector(tok2)) {
const Token* itTok = tok2->tokAt(4);
if (itTok->str() == "*") {
if (tok2->strAt(2) == "insert")
continue;
itTok = itTok->next();
}
// It is bad to insert/erase an invalid iterator
if (!validIterator)
invalidIteratorError(tok2, itTok->str());
// If insert/erase is used on different container then
// report an error
if (containerToken && tok2->varId() != containerToken->varId()) {
// skip error message if container is a set..
const Variable *variableInfo = tok2->variable();
const Token *decltok = variableInfo ? variableInfo->typeStartToken() : nullptr;
if (Token::simpleMatch(decltok, "std :: set"))
continue; // No warning
// skip error message if the iterator is erased/inserted by value
if (itTok->strAt(-1) == "*")
continue;
// inserting iterator range..
if (tok2->strAt(2) == "insert") {
const Token *par2 = itTok->nextArgument();
if (!par2 || par2->nextArgument())
continue;
while (par2->str() != ")") {
if (par2->varId() == containerToken->varId())
break;
bool inconclusiveType2=false;
if (isIterator(par2->variable(), inconclusiveType2))
break; // TODO: check if iterator points at same container
if (par2->str() == "(")
par2 = par2->link();
par2 = par2->next();
}
if (par2->str() != ")")
continue;
}
// Not different containers if a reference is used..
if (containerToken && containerToken->variable() && containerToken->variable()->isReference()) {
const Token *nameToken = containerToken->variable()->nameToken();
if (Token::Match(nameToken, "%name% =")) {
const Token *name1 = nameToken->tokAt(2);
const Token *name2 = tok2;
while (Token::Match(name1, "%name%|.|::") && name2 && name1->str() == name2->str()) {
name1 = name1->next();
name2 = name2->next();
}
if (!Token::simpleMatch(name1, ";") || !Token::Match(name2, "[;,()=]"))
continue;
}
}
// Show error message, mismatching iterator is used.
iteratorsError(tok2, getContainerName(containerToken), getContainerName(tok2));
}
// invalidate the iterator if it is erased
else if (tok2->strAt(2) == "erase" && (tok2->strAt(4) != "*" || (containerToken && tok2->varId() == containerToken->varId()))) {
validIterator = false;
eraseToken = tok2;
invalidationScope = tok2->scope();
}
// skip the operation
tok2 = itTok->next();
}
// it = foo.erase(..
// taking the result of an erase is ok
else if (Token::Match(tok2, "%varid% = %name% .", iteratorId) &&
Token::simpleMatch(skipMembers(tok2->tokAt(2)), "erase (")) {
// the returned iterator is valid
validatingToken = skipMembers(tok2->tokAt(2))->linkAt(1);
tok2 = validatingToken->link();
}
// Reassign the iterator
else if (Token::Match(tok2, "%varid% = %name% .", iteratorId) &&
Token::Match(skipMembers(tok2->tokAt(2)), "begin|rbegin|cbegin|crbegin|find (")) {
validatingToken = skipMembers(tok2->tokAt(2))->linkAt(1);
containerToken = skipMembers(tok2->tokAt(2))->tokAt(-2);
if (containerToken->varId() == 0 || Token::simpleMatch(validatingToken, ") ."))
containerToken = nullptr;
containerAssignScope = tok2->scope();
// skip ahead
tok2 = validatingToken->link();
}
// Reassign the iterator
else if (Token::Match(tok2, "%varid% =", iteratorId)) {
break;
}
// Passing iterator to function. Iterator might be initialized
else if (Token::Match(tok2, "%varid% ,|)", iteratorId)) {
validIterator = true;
}
// Dereferencing invalid iterator?
else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) {
dereferenceErasedError(eraseToken, tok2, tok2->strAt(1), inconclusiveType);
tok2 = tok2->next();
} else if (!validIterator && Token::Match(tok2, "%varid% . %name%", iteratorId)) {
dereferenceErasedError(eraseToken, tok2, tok2->str(), inconclusiveType);
tok2 = tok2->tokAt(2);
}
// bailout handling. Assume that the iterator becomes valid if we see return/break.
// TODO: better handling
else if (tok2->scope() == invalidationScope && Token::Match(tok2, "return|break|continue")) {
validatingToken = Token::findsimplematch(tok2->next(), ";");
}
// bailout handling. Assume that the iterator becomes valid if we see else.
// TODO: better handling
else if (tok2->str() == "else") {
validIterator = true;
}
}
}
}
void CheckStl::mismatchingContainerIteratorError(const Token* containerTok, const Token* iterTok, const Token* containerTok2)
{
const std::string container(containerTok ? containerTok->expressionString() : std::string("v1"));
const std::string container2(containerTok2 ? containerTok2->expressionString() : std::string("v2"));
const std::string iter(iterTok ? iterTok->expressionString() : std::string("it"));
reportError(containerTok,
Severity::error,
"mismatchingContainerIterator",
"Iterator '" + iter + "' referring to container '" + container2 + "' is used with container '" + container + "'.",
CWE664,
Certainty::normal);
}
// Error message for bad iterator usage..
void CheckStl::mismatchingContainersError(const Token* tok1, const Token* tok2)
{
const std::string expr1(tok1 ? tok1->expressionString() : std::string("v1"));
const std::string expr2(tok2 ? tok2->expressionString() : std::string("v2"));
reportError(tok1,
Severity::error,
"mismatchingContainers",
"Iterators of different containers '" + expr1 + "' and '" + expr2 + "' are used together.",
CWE664,
Certainty::normal);
}
void CheckStl::mismatchingContainerExpressionError(const Token *tok1, const Token *tok2)
{
const std::string expr1(tok1 ? tok1->expressionString() : std::string("v1"));
const std::string expr2(tok2 ? tok2->expressionString() : std::string("v2"));
reportError(tok1, Severity::warning, "mismatchingContainerExpression",
"Iterators to containers from different expressions '" +
expr1 + "' and '" + expr2 + "' are used together.", CWE664, Certainty::normal);
}
void CheckStl::sameIteratorExpressionError(const Token *tok)
{
reportError(tok, Severity::style, "sameIteratorExpression", "Same iterators expression are used for algorithm.", CWE664, Certainty::normal);
}
static std::vector<const Token*> getAddressContainer(const Token* tok)
{
if (Token::simpleMatch(tok, "[") && tok->astOperand1())
return { tok->astOperand1() };
while (Token::simpleMatch(tok, "::") && tok->astOperand2())
tok = tok->astOperand2();
std::vector<ValueFlow::Value> values = ValueFlow::getLifetimeObjValues(tok, /*inconclusive*/ false);
std::vector<const Token*> res;
for (const auto& v : values) {
if (v.tokvalue)
res.emplace_back(v.tokvalue);
}
if (res.empty())
res.emplace_back(tok);
return res;
}
static bool isSameIteratorContainerExpression(const Token* tok1,
const Token* tok2,
const Settings& settings,
ValueFlow::Value::LifetimeKind kind = ValueFlow::Value::LifetimeKind::Iterator)
{
if (isSameExpression(false, tok1, tok2, settings, false, false)) {
return !astIsContainerOwned(tok1) || !isTemporary(tok1, &settings.library);
}
if (astContainerYield(tok2) == Library::Container::Yield::ITEM)
return true;
if (kind == ValueFlow::Value::LifetimeKind::Address || kind == ValueFlow::Value::LifetimeKind::Iterator) {
const auto address1 = getAddressContainer(tok1);
const auto address2 = getAddressContainer(tok2);
return std::any_of(address1.begin(), address1.end(), [&](const Token* tok1) {
return std::any_of(address2.begin(), address2.end(), [&](const Token* tok2) {
return isSameExpression(false, tok1, tok2, settings, false, false);
});
});
}
return false;
}
// First it groups the lifetimes together using std::partition with the lifetimes that refer to the same token or token of a subexpression.
// Then it finds the lifetime in that group that refers to the "highest" parent using std::min_element and adds that to the vector.
static std::vector<ValueFlow::Value> pruneLifetimes(std::vector<ValueFlow::Value> lifetimes)
{
std::vector<ValueFlow::Value> result;
auto start = lifetimes.begin();
while (start != lifetimes.end())
{
const Token* tok1 = start->tokvalue;
auto it = std::partition(start, lifetimes.end(), [&](const ValueFlow::Value& v) {
const Token* tok2 = v.tokvalue;
return start->lifetimeKind == v.lifetimeKind && (astHasToken(tok1, tok2) || astHasToken(tok2, tok1));
});
auto root = std::min_element(start, it, [](const ValueFlow::Value& x, const ValueFlow::Value& y) {
return x.tokvalue != y.tokvalue && astHasToken(x.tokvalue, y.tokvalue);
});
result.push_back(*root);
start = it;
}
return result;
}
static ValueFlow::Value getLifetimeIteratorValue(const Token* tok, MathLib::bigint path = 0)
{
auto findIterVal = [](const std::vector<ValueFlow::Value>& values, const std::vector<ValueFlow::Value>::const_iterator beg) {
return std::find_if(beg, values.cend(), [](const ValueFlow::Value& v) {
return v.lifetimeKind == ValueFlow::Value::LifetimeKind::Iterator;
});
};
std::vector<ValueFlow::Value> values = pruneLifetimes(ValueFlow::getLifetimeObjValues(tok, false, path));
auto it = findIterVal(values, values.begin());
if (it != values.end()) {
auto it2 = findIterVal(values, it + 1);
if (it2 == values.cend())
return *it;
}
if (values.size() == 1)
return values.front();
return ValueFlow::Value{};
}
bool CheckStl::checkIteratorPair(const Token* tok1, const Token* tok2)
{
if (!tok1)
return false;
if (!tok2)
return false;
ValueFlow::Value val1 = getLifetimeIteratorValue(tok1);
ValueFlow::Value val2 = getLifetimeIteratorValue(tok2);
if (val1.tokvalue && val2.tokvalue && val1.lifetimeKind == val2.lifetimeKind) {
if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Lambda)
return false;
if (tok1->astParent() == tok2->astParent() && Token::Match(tok1->astParent(), "%comp%|-")) {
if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Address)
return false;
if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Object &&
(!astIsContainer(val1.tokvalue) || !astIsContainer(val2.tokvalue)))
return false;
}
if (isSameIteratorContainerExpression(val1.tokvalue, val2.tokvalue, *mSettings, val1.lifetimeKind))
return false;
if (val1.tokvalue->expressionString() == val2.tokvalue->expressionString())
iteratorsError(tok1, val1.tokvalue, val1.tokvalue->expressionString());
else
mismatchingContainersError(val1.tokvalue, val2.tokvalue);
return true;
}
if (Token::Match(tok1->astParent(), "%comp%|-")) {
if (astIsIntegral(tok1, true) || astIsIntegral(tok2, true) ||
astIsFloat(tok1, true) || astIsFloat(tok2, true))
return false;
}
const Token* iter1 = getIteratorExpression(tok1);
const Token* iter2 = getIteratorExpression(tok2);
if (iter1 && iter2 && !isSameIteratorContainerExpression(iter1, iter2, *mSettings)) {
mismatchingContainerExpressionError(iter1, iter2);
return true;
}
return false;
}
namespace {
struct ArgIteratorInfo {
const Token* tok;
const Library::ArgumentChecks::IteratorInfo* info;
};
}
void CheckStl::mismatchingContainers()
{
logChecker("CheckStl::misMatchingContainers");
// Check if different containers are used in various calls of standard functions
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%comp%|-")) {
if (checkIteratorPair(tok->astOperand1(), tok->astOperand2()))
continue;
}
if (!Token::Match(tok, "%name% ( !!)"))
continue;
const Token * const ftok = tok;
const std::vector<const Token *> args = getArguments(ftok);
if (args.size() < 2)
continue;
// Group args together by container
std::map<int, std::vector<ArgIteratorInfo>> containers;
for (int argnr = 1; argnr <= args.size(); ++argnr) {
const Library::ArgumentChecks::IteratorInfo *i = mSettings->library.getArgIteratorInfo(ftok, argnr);
if (!i)
continue;
const Token * const argTok = args[argnr - 1];
containers[i->container].emplace_back(ArgIteratorInfo{argTok, i});
}
// Lambda is used to escape the nested loops
[&] {
for (const auto& p : containers)
{
const std::vector<ArgIteratorInfo>& cargs = p.second;
for (ArgIteratorInfo iter1 : cargs) {
for (ArgIteratorInfo iter2 : cargs) {
if (iter1.tok == iter2.tok)
continue;
if (iter1.info->first && iter2.info->last &&
isSameExpression(false, iter1.tok, iter2.tok, *mSettings, false, false))
sameIteratorExpressionError(iter1.tok);
if (checkIteratorPair(iter1.tok, iter2.tok))
return;
}
}
}
}();
}
}
for (const Variable *var : symbolDatabase->variableList()) {
if (var && var->isStlStringType() && Token::Match(var->nameToken(), "%var% (") &&
Token::Match(var->nameToken()->tokAt(2), "%name% . begin|cbegin|rbegin|crbegin ( ) , %name% . end|cend|rend|crend ( ) ,|)")) {
if (var->nameToken()->strAt(2) != var->nameToken()->strAt(8)) {
mismatchingContainersError(var->nameToken(), var->nameToken()->tokAt(2));
}
}
}
}
void CheckStl::mismatchingContainerIterator()
{
logChecker("CheckStl::misMatchingContainerIterator");
// Check if different containers are used in various calls of standard functions
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!astIsContainer(tok))
continue;
if (!astIsLHS(tok))
continue;
if (!Token::Match(tok->astParent(), ". %name% ( !!)"))
continue;
const Token* const ftok = tok->astParent()->next();
const std::vector<const Token *> args = getArguments(ftok);
const Library::Container * c = tok->valueType()->container;
const Library::Container::Action action = c->getAction(tok->strAt(2));
const Token* iterTok = nullptr;
if (action == Library::Container::Action::INSERT && args.size() == 2) {
// Skip if iterator pair
if (astIsIterator(args.back()))
continue;
if (!astIsIterator(args.front()))
continue;
iterTok = args.front();
} else if (action == Library::Container::Action::ERASE) {
if (!astIsIterator(args.front()))
continue;
iterTok = args.front();
} else {
continue;
}
ValueFlow::Value val = getLifetimeIteratorValue(iterTok);
if (!val.tokvalue)
continue;
if (!val.isKnown() && Token::simpleMatch(val.tokvalue->astParent(), ":"))
continue;
if (val.lifetimeKind != ValueFlow::Value::LifetimeKind::Iterator)
continue;
if (iterTok->str() == "*" && iterTok->astOperand1()->valueType() && iterTok->astOperand1()->valueType()->type == ValueType::ITERATOR)
continue;
if (isSameIteratorContainerExpression(tok, val.tokvalue, *mSettings))
continue;
mismatchingContainerIteratorError(tok, iterTok, val.tokvalue);
}
}
}
static const Token* getInvalidMethod(const Token* tok)
{
if (!astIsLHS(tok))
return nullptr;
if (Token::Match(tok->astParent(), ". assign|clear|swap"))
return tok->astParent()->next();
if (Token::Match(tok->astParent(), "%assign%"))
return tok->astParent();
const Token* ftok = nullptr;
if (Token::Match(tok->astParent(), ". %name% ("))
ftok = tok->astParent()->next();
if (!ftok)
return nullptr;
if (const Library::Container * c = tok->valueType()->container) {
const Library::Container::Action action = c->getAction(ftok->str());
if (c->unstableErase) {
if (action == Library::Container::Action::ERASE)
return ftok;
}
if (c->unstableInsert) {
if (action == Library::Container::Action::RESIZE)
return ftok;
if (action == Library::Container::Action::CLEAR)
return ftok;
if (action == Library::Container::Action::PUSH)
return ftok;
if (action == Library::Container::Action::POP)
return ftok;
if (action == Library::Container::Action::INSERT)
return ftok;
if (action == Library::Container::Action::CHANGE)
return ftok;
if (action == Library::Container::Action::CHANGE_INTERNAL)
return ftok;
if (Token::Match(ftok, "insert|emplace"))
return ftok;
}
}
return nullptr;
}
namespace {
struct InvalidContainerAnalyzer {
struct Info {
struct Reference {
const Token* tok;
ErrorPath errorPath;
const Token* ftok;
};
std::unordered_map<int, Reference> expressions;
void add(const std::vector<Reference>& refs) {
for (const Reference& r : refs) {
add(r);
}
}
void add(const Reference& r) {
if (!r.tok)
return;
expressions.emplace(r.tok->exprId(), r);
}
std::vector<Reference> invalidTokens() const {
std::vector<Reference> result;
std::transform(expressions.cbegin(), expressions.cend(), std::back_inserter(result), SelectMapValues{});
return result;
}
};
std::unordered_map<const Function*, Info> invalidMethods;
std::vector<Info::Reference> invalidatesContainer(const Token* tok) const {
std::vector<Info::Reference> result;
if (Token::Match(tok, "%name% (")) {
const Function* f = tok->function();
if (!f)
return result;
ErrorPathItem epi = std::make_pair(tok, "Calling function " + tok->str());
const bool dependsOnThis = exprDependsOnThis(tok->next());
auto it = invalidMethods.find(f);
if (it != invalidMethods.end()) {
std::vector<Info::Reference> refs = it->second.invalidTokens();
std::copy_if(refs.cbegin(), refs.cend(), std::back_inserter(result), [&](const Info::Reference& r) {
const Variable* var = r.tok->variable();
if (!var)
return false;
if (dependsOnThis && !var->isLocal() && !var->isGlobal() && !var->isStatic())
return true;
if (!var->isArgument())
return false;
if (!var->isReference())
return false;
return true;
});
std::vector<const Token*> args = getArguments(tok);
for (Info::Reference& r : result) {
r.errorPath.push_front(epi);
r.ftok = tok;
const Variable* var = r.tok->variable();
if (!var)
continue;
if (var->isArgument()) {
const int n = getArgumentPos(var, f);
const Token* tok2 = nullptr;
if (n >= 0 && n < args.size())
tok2 = args[n];
r.tok = tok2;
}
}
}
} else if (astIsContainer(tok)) {
const Token* ftok = getInvalidMethod(tok);
if (ftok) {
ErrorPath ep;
ep.emplace_front(ftok,
"After calling '" + ftok->expressionString() +
"', iterators or references to the container's data may be invalid .");
result.emplace_back(Info::Reference{tok, std::move(ep), ftok});
}
}
return result;
}
void analyze(const SymbolDatabase* symboldatabase) {
for (const Scope* scope : symboldatabase->functionScopes) {
const Function* f = scope->function;
if (!f)
continue;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "if|while|for|goto|return"))
break;
std::vector<Info::Reference> c = invalidatesContainer(tok);
if (c.empty())
continue;
invalidMethods[f].add(c);
}
}
}
};
}
static const Token* getLoopContainer(const Token* tok)
{
if (!Token::simpleMatch(tok, "for ("))
return nullptr;
const Token* sepTok = tok->next()->astOperand2();
if (!Token::simpleMatch(sepTok, ":"))
return nullptr;
return sepTok->astOperand2();
}
static const ValueFlow::Value* getInnerLifetime(const Token* tok,
nonneg int id,
ErrorPath* errorPath = nullptr,
int depth = 4)
{
if (depth < 0)
return nullptr;
if (!tok)
return nullptr;
for (const ValueFlow::Value& val : tok->values()) {
if (!val.isLocalLifetimeValue())
continue;
if (contains({ValueFlow::Value::LifetimeKind::Address,
ValueFlow::Value::LifetimeKind::SubObject,
ValueFlow::Value::LifetimeKind::Lambda},
val.lifetimeKind)) {
if (val.isInconclusive())
return nullptr;
if (val.capturetok)
if (const ValueFlow::Value* v = getInnerLifetime(val.capturetok, id, errorPath, depth - 1))
return v;
if (errorPath)
errorPath->insert(errorPath->end(), val.errorPath.cbegin(), val.errorPath.cend());
if (const ValueFlow::Value* v = getInnerLifetime(val.tokvalue, id, errorPath, depth - 1))
return v;
continue;
}
if (!val.tokvalue->variable())
continue;
if (val.tokvalue->varId() != id)
continue;
return &val;
}
return nullptr;
}
static const Token* endOfExpression(const Token* tok)
{
if (!tok)
return nullptr;
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent, "."))
parent = parent->astParent();
if (!parent)
return tok->next();
const Token* endToken = nextAfterAstRightmostLeaf(parent);
if (!endToken)
return parent->next();
return endToken;
}
void CheckStl::invalidContainer()
{
logChecker("CheckStl::invalidContainer");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
const Library& library = mSettings->library;
InvalidContainerAnalyzer analyzer;
analyzer.analyze(symbolDatabase);
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (const Token* contTok = getLoopContainer(tok)) {
const Token* blockStart = tok->linkAt(1)->next();
const Token* blockEnd = blockStart->link();
if (contTok->exprId() == 0)
continue;
if (!astIsContainer(contTok))
continue;
for (const Token* tok2 = blockStart; tok2 != blockEnd; tok2 = tok2->next()) {
bool bail = false;
for (const InvalidContainerAnalyzer::Info::Reference& r : analyzer.invalidatesContainer(tok2)) {
if (!astIsContainer(r.tok))
continue;
if (r.tok->exprId() != contTok->exprId())
continue;
const Scope* s = tok2->scope();
if (!s)
continue;
if (isReturnScope(s->bodyEnd, mSettings->library))
continue;
invalidContainerLoopError(r.ftok, tok, r.errorPath);
bail = true;
break;
}
if (bail)
break;
}
} else {
for (const InvalidContainerAnalyzer::Info::Reference& r : analyzer.invalidatesContainer(tok)) {
if (!astIsContainer(r.tok))
continue;
std::set<nonneg int> skipVarIds;
// Skip if the variable is assigned to
const Token* assignExpr = tok;
while (assignExpr->astParent()) {
const bool isRHS = astIsRHS(assignExpr);
assignExpr = assignExpr->astParent();
if (Token::Match(assignExpr, "%assign%")) {
if (!isRHS)
assignExpr = nullptr;
break;
}
}
if (Token::Match(assignExpr, "%assign%") && Token::Match(assignExpr->astOperand1(), "%var%"))
skipVarIds.insert(assignExpr->astOperand1()->varId());
const Token* endToken = endOfExpression(tok);
const ValueFlow::Value* v = nullptr;
ErrorPath errorPath;
PathAnalysis::Info info =
PathAnalysis{endToken, library}.forwardFind([&](const PathAnalysis::Info& info) {
if (!info.tok->variable())
return false;
if (info.tok->varId() == 0)
return false;
if (skipVarIds.count(info.tok->varId()) > 0)
return false;
// if (Token::simpleMatch(info.tok->next(), "."))
// return false;
if (Token::Match(info.tok->astParent(), "%assign%") && astIsLHS(info.tok))
skipVarIds.insert(info.tok->varId());
if (info.tok->variable()->isReference() && !isVariableDecl(info.tok) &&
reaches(info.tok->variable()->nameToken(), tok, library, nullptr)) {
ErrorPath ep;
bool addressOf = false;
const Variable* var = ValueFlow::getLifetimeVariable(info.tok, ep, *mSettings, &addressOf);
// Check the reference is created before the change
if (var && var->declarationId() == r.tok->varId() && !addressOf) {
// An argument always reaches
if (var->isArgument() ||
(!var->isReference() && !var->isRValueReference() && !isVariableDecl(tok) &&
reaches(var->nameToken(), tok, library, &ep))) {
errorPath = std::move(ep);
return true;
}
}
}
ErrorPath ep;
const ValueFlow::Value* val = getInnerLifetime(info.tok, r.tok->varId(), &ep);
// Check the iterator is created before the change
if (val && val->tokvalue != tok && reaches(val->tokvalue, tok, library, &ep)) {
v = val;
errorPath = std::move(ep);
return true;
}
return false;
});
if (!info.tok)
continue;
errorPath.insert(errorPath.end(), info.errorPath.cbegin(), info.errorPath.cend());
errorPath.insert(errorPath.end(), r.errorPath.cbegin(), r.errorPath.cend());
if (v) {
invalidContainerError(info.tok, r.tok, v, std::move(errorPath));
} else {
invalidContainerReferenceError(info.tok, r.tok, std::move(errorPath));
}
}
}
}
}
}
void CheckStl::invalidContainerLoopError(const Token* tok, const Token* loopTok, ErrorPath errorPath)
{
const std::string method = tok ? tok->str() : "erase";
errorPath.emplace_back(loopTok, "Iterating container here.");
// Remove duplicate entries from error path
errorPath.remove_if([&](const ErrorPathItem& epi) {
return epi.first == tok;
});
const std::string msg = "Calling '" + method + "' while iterating the container is invalid.";
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "invalidContainerLoop", msg, CWE664, Certainty::normal);
}
void CheckStl::invalidContainerError(const Token *tok, const Token * /*contTok*/, const ValueFlow::Value *val, ErrorPath errorPath)
{
const bool inconclusive = val ? val->isInconclusive() : false;
if (val)
errorPath.insert(errorPath.begin(), val->errorPath.cbegin(), val->errorPath.cend());
std::string msg = "Using " + lifetimeMessage(tok, val, errorPath);
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "invalidContainer", msg + " that may be invalid.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckStl::invalidContainerReferenceError(const Token* tok, const Token* contTok, ErrorPath errorPath)
{
std::string name = contTok ? contTok->expressionString() : "x";
std::string msg = "Reference to " + name;
errorPath.emplace_back(tok, "");
reportError(errorPath, Severity::error, "invalidContainerReference", msg + " that may be invalid.", CWE664, Certainty::normal);
}
void CheckStl::stlOutOfBounds()
{
logChecker("CheckStl::stlOutOfBounds");
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
// Scan through all scopes..
for (const Scope &scope : symbolDatabase->scopeList) {
const Token* tok = scope.classDef;
// only interested in conditions
if ((!scope.isLoopScope() && scope.type != Scope::eIf) || !tok)
continue;
const Token *condition = nullptr;
if (scope.type == Scope::eFor) {
if (Token::simpleMatch(tok->next()->astOperand2(), ";") && Token::simpleMatch(tok->next()->astOperand2()->astOperand2(), ";"))
condition = tok->next()->astOperand2()->astOperand2()->astOperand1();
} else if (Token::simpleMatch(tok, "do {") && Token::simpleMatch(tok->linkAt(1), "} while ("))
condition = tok->linkAt(1)->tokAt(2)->astOperand2();
else
condition = tok->next()->astOperand2();
if (!condition)
continue;
std::vector<const Token *> conds;
visitAstNodes(condition,
[&](const Token *cond) {
if (Token::Match(cond, "%oror%|&&"))
return ChildrenToVisit::op1_and_op2;
if (cond->isComparisonOp())
conds.emplace_back(cond);
return ChildrenToVisit::none;
});
for (const Token *cond : conds) {
const Token *vartok;
const Token *containerToken;
// check in the ast that cond is of the form "%var% <= %var% . %name% ( )"
if (cond->str() == "<=" && Token::Match(cond->astOperand1(), "%var%") &&
cond->astOperand2()->str() == "(" && cond->astOperand2()->astOperand1()->str() == "." &&
Token::Match(cond->astOperand2()->astOperand1()->astOperand1(), "%var%") &&
Token::Match(cond->astOperand2()->astOperand1()->astOperand2(), "%name%")) {
vartok = cond->astOperand1();
containerToken = cond->next();
} else {
continue;
}
if (containerToken->hasKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE))
continue;
// Is it a array like container?
const Library::Container* container = containerToken->valueType() ? containerToken->valueType()->container : nullptr;
if (!container)
continue;
if (container->getYield(containerToken->strAt(2)) != Library::Container::Yield::SIZE)
continue;
// variable id for loop variable.
const int numId = vartok->varId();
// variable id for the container variable
const int declarationId = containerToken->varId();
const std::string &containerName = containerToken->str();
for (const Token *tok3 = scope.bodyStart; tok3 && tok3 != scope.bodyEnd; tok3 = tok3->next()) {
if (tok3->varId() == declarationId) {
tok3 = tok3->next();
if (Token::Match(tok3, ". %name% ( )")) {
if (container->getYield(tok3->strAt(1)) == Library::Container::Yield::SIZE)
break;
} else if (container->arrayLike_indexOp && Token::Match(tok3, "[ %varid% ]", numId))
stlOutOfBoundsError(tok3, tok3->strAt(1), containerName, false);
else if (Token::Match(tok3, ". %name% ( %varid% )", numId)) {
const Library::Container::Yield yield = container->getYield(tok3->strAt(1));
if (yield == Library::Container::Yield::AT_INDEX)
stlOutOfBoundsError(tok3, tok3->strAt(3), containerName, true);
}
}
}
}
}
}
void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, const std::string &var, bool at)
{
if (at)
reportError(tok, Severity::error, "stlOutOfBounds", "$symbol:" + var + "\nWhen " + num + "==$symbol.size(), $symbol.at(" + num + ") is out of bounds.", CWE788, Certainty::normal);
else
reportError(tok, Severity::error, "stlOutOfBounds", "$symbol:" + var + "\nWhen " + num + "==$symbol.size(), $symbol[" + num + "] is out of bounds.", CWE788, Certainty::normal);
}
void CheckStl::negativeIndex()
{
logChecker("CheckStl::negativeIndex");
// Negative index is out of bounds..
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%var% [") || !tok->next()->astOperand2())
continue;
const Variable * const var = tok->variable();
if (!var || tok == var->nameToken())
continue;
const Library::Container * const container = mSettings->library.detectContainer(var->typeStartToken());
if (!container || !container->arrayLike_indexOp)
continue;
const ValueFlow::Value *index = tok->next()->astOperand2()->getValueLE(-1, *mSettings);
if (!index)
continue;
negativeIndexError(tok, *index);
}
}
}
void CheckStl::negativeIndexError(const Token *tok, const ValueFlow::Value &index)
{
const ErrorPath errorPath = getErrorPath(tok, &index, "Negative array index");
std::ostringstream errmsg;
if (index.condition)
errmsg << ValueFlow::eitherTheConditionIsRedundant(index.condition)
<< ", otherwise there is negative array index " << index.intvalue << ".";
else
errmsg << "Array index " << index.intvalue << " is out of bounds.";
const auto severity = index.errorSeverity() && index.isKnown() ? Severity::error : Severity::warning;
const auto certainty = index.isInconclusive() ? Certainty::inconclusive : Certainty::normal;
reportError(errorPath, severity, "negativeContainerIndex", errmsg.str(), CWE786, certainty);
}
void CheckStl::erase()
{
logChecker("CheckStl::erase");
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type == Scope::eFor && Token::simpleMatch(scope.classDef, "for (")) {
const Token *tok = scope.classDef->linkAt(1);
if (!Token::Match(tok->tokAt(-3), "; ++| %var% ++| ) {"))
continue;
tok = tok->previous();
if (!tok->isName())
tok = tok->previous();
eraseCheckLoopVar(scope, tok->variable());
} else if (scope.type == Scope::eWhile && Token::Match(scope.classDef, "while ( %var% !=")) {
eraseCheckLoopVar(scope, scope.classDef->tokAt(2)->variable());
}
}
}
void CheckStl::eraseCheckLoopVar(const Scope &scope, const Variable *var)
{
bool inconclusiveType=false;
if (!isIterator(var, inconclusiveType))
return;
for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) {
if (tok->str() != "(")
continue;
if (!Token::Match(tok->tokAt(-2), ". erase ( ++| %varid% )", var->declarationId()))
continue;
// Vector erases are handled by invalidContainer check
if (isVector(tok->tokAt(-3)))
continue;
if (Token::Match(tok->astParent(), "=|return"))
continue;
// Iterator is invalid..
int indentlevel = 0U;
const Token *tok2 = tok->link();
for (; tok2 != scope.bodyEnd; tok2 = tok2->next()) {
if (tok2->str() == "{") {
++indentlevel;
continue;
}
if (tok2->str() == "}") {
if (indentlevel > 0U)
--indentlevel;
else if (Token::simpleMatch(tok2, "} else {"))
tok2 = tok2->linkAt(2);
continue;
}
if (tok2->varId() == var->declarationId()) {
if (Token::simpleMatch(tok2->next(), "="))
break;
dereferenceErasedError(tok, tok2, tok2->str(), inconclusiveType);
break;
}
if (indentlevel == 0U && Token::Match(tok2, "break|return|goto"))
break;
}
if (tok2 == scope.bodyEnd)
dereferenceErasedError(tok, scope.classDef, var->nameToken()->str(), inconclusiveType);
}
}
void CheckStl::stlBoundaries()
{
logChecker("CheckStl::stlBoundaries");
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Variable* var : symbolDatabase->variableList()) {
if (!var || !var->scope() || !var->scope()->isExecutable())
continue;
const Library::Container* container = mSettings->library.detectIterator(var->typeStartToken());
if (!container || container->opLessAllowed)
continue;
const Token* const end = var->scope()->bodyEnd;
for (const Token *tok = var->nameToken(); tok != end; tok = tok->next()) {
if (Token::Match(tok, "!!* %varid% <", var->declarationId())) {
stlBoundariesError(tok);
} else if (Token::Match(tok, "> %varid% !!.", var->declarationId())) {
stlBoundariesError(tok);
}
}
}
}
// Error message for bad boundary usage..
void CheckStl::stlBoundariesError(const Token *tok)
{
reportError(tok, Severity::error, "stlBoundaries",
"Dangerous comparison using operator< on iterator.\n"
"Iterator compared with operator<. This is dangerous since the order of items in the "
"container is not guaranteed. One should use operator!= instead to compare iterators.", CWE664, Certainty::normal);
}
static bool if_findCompare(const Token * const tokBack, bool stdStringLike)
{
const Token *tok = tokBack->astParent();
if (!tok)
return true;
if (tok->isComparisonOp()) {
if (stdStringLike) {
const Token * const tokOther = tokBack->astSibling();
return !tokOther || !tokOther->hasKnownIntValue() || tokOther->getKnownIntValue() != 0;
}
return (!tok->astOperand1()->isNumber() && !tok->astOperand2()->isNumber());
}
if (tok->isArithmeticalOp()) // result is used in some calculation
return true; // TODO: check if there is a comparison of the result somewhere
if (tok->str() == ".")
return true; // Dereferencing is OK, the programmer might know that the element exists - TODO: An inconclusive warning might be appropriate
if (tok->isAssignmentOp())
return if_findCompare(tok, stdStringLike); // Go one step upwards in the AST
return false;
}
void CheckStl::if_find()
{
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
const bool printPerformance = mSettings->severity.isEnabled(Severity::performance);
if (!printWarning && !printPerformance)
return;
logChecker("CheckStl::if_find"); // warning,performance
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if ((scope.type != Scope::eIf && scope.type != Scope::eWhile) || !scope.classDef)
continue;
const Token *conditionStart = scope.classDef->next();
if (Token::simpleMatch(conditionStart->astOperand2(), ";"))
conditionStart = conditionStart->astOperand2();
for (const Token *tok = conditionStart; tok->str() != "{"; tok = tok->next()) {
const Token* funcTok = nullptr;
const Library::Container* container = nullptr;
if (Token::Match(tok, "%name% ("))
tok = tok->linkAt(1);
else if (tok->variable() && Token::Match(tok, "%var% . %name% (")) {
container = mSettings->library.detectContainer(tok->variable()->typeStartToken());
funcTok = tok->tokAt(2);
}
// check also for vector-like or pointer containers
else if (tok->variable() && tok->astParent() && (tok->astParent()->str() == "*" || tok->astParent()->str() == "[")) {
const Token *tok2 = tok->astParent();
if (!Token::Match(tok2->astParent(), ". %name% ("))
continue;
funcTok = tok2->astParent()->next();
if (tok->variable()->isArrayOrPointer())
container = mSettings->library.detectContainer(tok->variable()->typeStartToken());
else { // Container of container - find the inner container
container = mSettings->library.detectContainer(tok->variable()->typeStartToken()); // outer container
tok2 = Token::findsimplematch(tok->variable()->typeStartToken(), "<", tok->variable()->typeEndToken());
if (container && container->type_templateArgNo >= 0 && tok2) {
tok2 = tok2->next();
for (int j = 0; j < container->type_templateArgNo; j++)
tok2 = tok2->nextTemplateArgument();
container = mSettings->library.detectContainer(tok2); // inner container
} else
container = nullptr;
}
}
Library::Container::Action action{};
if (container &&
((action = container->getAction(funcTok->str())) == Library::Container::Action::FIND || action == Library::Container::Action::FIND_CONST)) {
if (if_findCompare(funcTok->next(), container->stdStringLike))
continue;
if (printWarning && container->getYield(funcTok->str()) == Library::Container::Yield::ITERATOR)
if_findError(tok, false);
else if (printPerformance && container->stdStringLike && funcTok->str() == "find")
if_findError(tok, true);
} else if (printWarning && Token::Match(tok, "std :: find|find_if (")) {
// check that result is checked properly
if (!if_findCompare(tok->tokAt(3), false)) {
if_findError(tok, false);
}
}
}
}
}
void CheckStl::if_findError(const Token *tok, bool str)
{
if (str && mSettings->standards.cpp >= Standards::CPP20)
reportError(tok, Severity::performance, "stlIfStrFind",
"Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n"
"Either inefficient or wrong usage of string::find(). string::starts_with() will be faster if "
"string::find's result is compared with 0, because it will not scan the whole "
"string. If your intention is to check that there are no findings in the string, "
"you should compare with std::string::npos.", CWE597, Certainty::normal);
if (!str)
reportError(tok, Severity::warning, "stlIfFind", "Suspicious condition. The result of find() is an iterator, but it is not properly checked.", CWE398, Certainty::normal);
}
static std::pair<const Token *, const Token *> isMapFind(const Token *tok)
{
if (!Token::simpleMatch(tok, "("))
return {};
if (!Token::simpleMatch(tok->astOperand1(), "."))
return {};
if (!astIsContainer(tok->astOperand1()->astOperand1()))
return {};
const Token * contTok = tok->astOperand1()->astOperand1();
const Library::Container * container = contTok->valueType()->container;
if (!container)
return {};
if (!container->stdAssociativeLike)
return {};
if (!Token::Match(tok->astOperand1(), ". find|count ("))
return {};
if (!tok->astOperand2())
return {};
return {contTok, tok->astOperand2()};
}
static const Token* skipLocalVars(const Token* const tok)
{
if (!tok)
return tok;
if (Token::simpleMatch(tok, "{"))
return skipLocalVars(tok->next());
if (tok->isAssignmentOp()) {
const Token *top = tok->astTop();
const Token *varTok = top->astOperand1();
const Variable *var = varTok->variable();
if (!var)
return tok;
if (var->scope() != tok->scope())
return tok;
const Token *endTok = nextAfterAstRightmostLeaf(top);
if (!endTok)
return tok;
return skipLocalVars(endTok->next());
}
return tok;
}
static const Token *findInsertValue(const Token *tok, const Token *containerTok, const Token *keyTok, const Settings &settings)
{
const Token *startTok = skipLocalVars(tok);
const Token *top = startTok->astTop();
const Token *icontainerTok = nullptr;
const Token *ikeyTok = nullptr;
const Token *ivalueTok = nullptr;
if (Token::simpleMatch(top, "=") && Token::simpleMatch(top->astOperand1(), "[")) {
icontainerTok = top->astOperand1()->astOperand1();
ikeyTok = top->astOperand1()->astOperand2();
ivalueTok = top->astOperand2();
}
if (Token::simpleMatch(top, "(") && Token::Match(top->astOperand1(), ". insert|emplace (") && !astIsIterator(top->astOperand1()->tokAt(2))) {
icontainerTok = top->astOperand1()->astOperand1();
const Token *itok = top->astOperand1()->tokAt(2)->astOperand2();
if (Token::simpleMatch(itok, ",")) {
ikeyTok = itok->astOperand1();
ivalueTok = itok->astOperand2();
} else {
ikeyTok = itok;
}
}
if (!ikeyTok || !icontainerTok)
return nullptr;
if (isSameExpression(true, containerTok, icontainerTok, settings, true, false) &&
isSameExpression(true, keyTok, ikeyTok, settings, true, true)) {
if (ivalueTok)
return ivalueTok;
return ikeyTok;
}
return nullptr;
}
void CheckStl::checkFindInsert()
{
if (!mSettings->severity.isEnabled(Severity::performance))
return;
logChecker("CheckStl::checkFindInsert"); // performance
const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "if ("))
continue;
if (!Token::simpleMatch(tok->linkAt(1), ") {"))
continue;
if (!Token::Match(tok->next()->astOperand2(), "%comp%"))
continue;
const Token *condTok = tok->next()->astOperand2();
const Token *containerTok;
const Token *keyTok;
std::tie(containerTok, keyTok) = isMapFind(condTok->astOperand1());
if (!containerTok)
continue;
// In < C++17 we only warn for small simple types
if (mSettings->standards.cpp < Standards::CPP17 && !(keyTok && keyTok->valueType() && (keyTok->valueType()->isIntegral() || keyTok->valueType()->pointer > 0)))
continue;
const Token *thenTok = tok->linkAt(1)->next();
const Token *valueTok = findInsertValue(thenTok, containerTok, keyTok, *mSettings);
if (!valueTok)
continue;
if (Token::simpleMatch(thenTok->link(), "} else {")) {
const Token *valueTok2 =
findInsertValue(thenTok->link()->tokAt(2), containerTok, keyTok, *mSettings);
if (!valueTok2)
continue;
if (isSameExpression(true, valueTok, valueTok2, *mSettings, true, true)) {
checkFindInsertError(valueTok);
}
} else {
checkFindInsertError(valueTok);
}
}
}
}
void CheckStl::checkFindInsertError(const Token *tok)
{
std::string replaceExpr;
if (tok && Token::simpleMatch(tok->astParent(), "=") && tok == tok->astParent()->astOperand2() && Token::simpleMatch(tok->astParent()->astOperand1(), "[")) {
if (mSettings->standards.cpp < Standards::CPP11)
// We will recommend using emplace/try_emplace instead
return;
const std::string f = (mSettings->standards.cpp < Standards::CPP17) ? "emplace" : "try_emplace";
replaceExpr = " Instead of '" + tok->astParent()->expressionString() + "' consider using '" +
tok->astParent()->astOperand1()->astOperand1()->expressionString() +
"." + f + "(" +
tok->astParent()->astOperand1()->astOperand2()->expressionString() +
", " +
tok->expressionString() +
");'.";
}
reportError(
tok, Severity::performance, "stlFindInsert", "Searching before insertion is not necessary." + replaceExpr, CWE398, Certainty::normal);
}
/**
* Is container.size() slow?
*/
static bool isCpp03ContainerSizeSlow(const Token *tok)
{
if (!tok)
return false;
const Variable* var = tok->variable();
return var && var->isStlType("list");
}
void CheckStl::size()
{
if (!mSettings->severity.isEnabled(Severity::performance))
return;
if (mSettings->standards.cpp >= Standards::CPP11)
return;
logChecker("CheckStl::size"); // performance,c++03
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%var% . size ( )") ||
Token::Match(tok, "%name% . %var% . size ( )")) {
// get the variable
const Token *varTok = tok;
if (tok->strAt(2) != "size")
varTok = varTok->tokAt(2);
const Token* const end = varTok->tokAt(5);
// check for comparison to zero
if ((!tok->previous()->isArithmeticalOp() && Token::Match(end, "==|<=|!=|> 0")) ||
(end->next() && !end->next()->isArithmeticalOp() && Token::Match(tok->tokAt(-2), "0 ==|>=|!=|<"))) {
if (isCpp03ContainerSizeSlow(varTok)) {
sizeError(varTok);
continue;
}
}
// check for comparison to one
if ((!tok->previous()->isArithmeticalOp() && Token::Match(end, ">=|< 1") && !end->tokAt(2)->isArithmeticalOp()) ||
(end->next() && !end->next()->isArithmeticalOp() && Token::Match(tok->tokAt(-2), "1 <=|>") && !tok->tokAt(-3)->isArithmeticalOp())) {
if (isCpp03ContainerSizeSlow(varTok))
sizeError(varTok);
}
// check for using as boolean expression
else if ((Token::Match(tok->tokAt(-2), "if|while (") && end->str() == ")") ||
(tok->previous()->tokType() == Token::eLogicalOp && Token::Match(end, "&&|)|,|;|%oror%"))) {
if (isCpp03ContainerSizeSlow(varTok))
sizeError(varTok);
}
}
}
}
}
void CheckStl::sizeError(const Token *tok)
{
const std::string varname = tok ? tok->str() : std::string("list");
reportError(tok, Severity::performance, "stlSize",
"$symbol:" + varname + "\n"
"Possible inefficient checking for '$symbol' emptiness.\n"
"Checking for '$symbol' emptiness might be inefficient. "
"Using $symbol.empty() instead of $symbol.size() can be faster. "
"$symbol.size() can take linear time but $symbol.empty() is "
"guaranteed to take constant time.", CWE398, Certainty::normal);
}
void CheckStl::redundantCondition()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("redundantIfRemove"))
return;
logChecker("CheckStl::redundantCondition"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
const Token* tok = scope.classDef->tokAt(2);
if (!Token::Match(tok, "%name% . find ( %any% ) != %name% . end|rend|cend|crend ( ) ) { %name% . remove|erase ( %any% ) ;"))
continue;
// Get tokens for the fields %name% and %any%
const Token *var1 = tok;
const Token *any1 = var1->tokAt(4);
const Token *var2 = any1->tokAt(3);
const Token *var3 = var2->tokAt(7);
const Token *any2 = var3->tokAt(4);
// Check if all the "%name%" fields are the same and if all the "%any%" are the same..
if (var1->str() == var2->str() &&
var2->str() == var3->str() &&
any1->str() == any2->str()) {
redundantIfRemoveError(tok);
}
}
}
void CheckStl::redundantIfRemoveError(const Token *tok)
{
reportError(tok, Severity::style, "redundantIfRemove",
"Redundant checking of STL container element existence before removing it.\n"
"Redundant checking of STL container element existence before removing it. "
"It is safe to call the remove method on a non-existing element.", CWE398, Certainty::normal);
}
void CheckStl::missingComparison()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckStl::missingComparison"); // warning
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eFor || !scope.classDef)
continue;
for (const Token *tok2 = scope.classDef->tokAt(2); tok2 != scope.bodyStart; tok2 = tok2->next()) {
if (tok2->str() == ";")
break;
if (!Token::Match(tok2, "%var% = %name% . begin|rbegin|cbegin|crbegin ( ) ; %name% != %name% . end|rend|cend|crend ( ) ; ++| %name% ++| ) {"))
continue;
// same container
if (tok2->strAt(2) != tok2->strAt(10))
break;
const int iteratorId(tok2->varId());
// same iterator
if (iteratorId == tok2->tokAt(10)->varId())
break;
// increment iterator
if (!Token::Match(tok2->tokAt(16), "++ %varid% )", iteratorId) &&
!Token::Match(tok2->tokAt(16), "%varid% ++ )", iteratorId)) {
break;
}
const Token *incrementToken = nullptr;
// Parse loop..
for (const Token *tok3 = scope.bodyStart; tok3 != scope.bodyEnd; tok3 = tok3->next()) {
if (tok3->varId() == iteratorId) {
if (Token::Match(tok3, "%varid% = %name% . insert ( ++| %varid% ++| ,", iteratorId)) {
// skip insertion..
tok3 = tok3->linkAt(6);
if (!tok3)
break;
} else if (Token::simpleMatch(tok3->astParent(), "++"))
incrementToken = tok3;
else if (Token::simpleMatch(tok3->astParent(), "+")) {
if (Token::Match(tok3->astSibling(), "%num%")) {
const Token* tokenGrandParent = tok3->astParent()->astParent();
if (Token::Match(tokenGrandParent, "==|!="))
break;
}
} else if (Token::Match(tok3->astParent(), "==|!="))
incrementToken = nullptr;
} else if (tok3->str() == "break" || tok3->str() == "return")
incrementToken = nullptr;
}
if (incrementToken)
missingComparisonError(incrementToken, tok2->tokAt(16));
}
}
}
void CheckStl::missingComparisonError(const Token *incrementToken1, const Token *incrementToken2)
{
std::list<const Token*> callstack = { incrementToken1,incrementToken2 };
std::ostringstream errmsg;
errmsg << "Missing bounds check for extra iterator increment in loop.\n"
<< "The iterator incrementing is suspicious - it is incremented at line ";
if (incrementToken1)
errmsg << incrementToken1->linenr();
errmsg << " and then at line ";
if (incrementToken2)
errmsg << incrementToken2->linenr();
errmsg << ". The loop might unintentionally skip an element in the container. "
<< "There is no comparison between these increments to prevent that the iterator is "
<< "incremented beyond the end.";
reportError(callstack, Severity::warning, "StlMissingComparison", errmsg.str(), CWE834, Certainty::normal);
}
static bool isLocal(const Token *tok)
{
const Variable *var = tok->variable();
return var && !var->isStatic() && var->isLocal();
}
namespace {
const std::set<std::string> stl_string_stream = {
"istringstream", "ostringstream", "stringstream", "wstringstream"
};
}
void CheckStl::string_c_str()
{
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
const bool printPerformance = mSettings->severity.isEnabled(Severity::performance);
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
logChecker("CheckStl::string_c_str");
// Find all functions that take std::string as argument
struct StrArg {
nonneg int n;
std::string argtype;
};
std::multimap<const Function*, StrArg> c_strFuncParam;
if (printPerformance) {
for (const Scope &scope : symbolDatabase->scopeList) {
for (const Function &func : scope.functionList) {
nonneg int numpar = 0;
for (const Variable &var : func.argumentList) {
numpar++;
if ((var.isStlStringType() || var.isStlStringViewType()) && (!var.isReference() || var.isConst()))
c_strFuncParam.emplace(&func, StrArg{ numpar, var.getTypeName() });
}
}
}
}
auto isString = [](const Token* str) -> bool {
while (Token::Match(str, "::|."))
str = str->astOperand2();
if (Token::Match(str, "(|[") && !(str->valueType() && str->valueType()->type == ValueType::ITERATOR))
str = str->previous();
return str && ((str->variable() && str->variable()->isStlStringType()) || // variable
(str->function() && isStlStringType(str->function()->retDef)) || // function returning string
(str->valueType() && str->valueType()->type == ValueType::ITERATOR && isStlStringType(str->valueType()->containerTypeToken))); // iterator pointing to string
};
// Try to detect common problems when using string::c_str()
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eFunction || !scope.function)
continue;
enum : std::uint8_t {charPtr, stdString, stdStringConstRef, Other} returnType = Other;
if (Token::Match(scope.function->tokenDef->tokAt(-2), "char|wchar_t *"))
returnType = charPtr;
else if (Token::Match(scope.function->tokenDef->tokAt(-5), "const std :: string|wstring &"))
returnType = stdStringConstRef;
else if (Token::Match(scope.function->tokenDef->tokAt(-3), "std :: string|wstring !!&"))
returnType = stdString;
for (const Token *tok = scope.bodyStart; tok && tok != scope.bodyEnd; tok = tok->next()) {
// Invalid usage..
if (Token::Match(tok, "throw %var% . c_str|data ( ) ;") && isLocal(tok->next()) &&
tok->next()->variable() && tok->next()->variable()->isStlStringType()) {
string_c_strThrowError(tok);
} else if (tok->variable() && tok->strAt(1) == "=") {
if (Token::Match(tok->tokAt(2), "%var% . str ( ) . c_str|data ( ) ;")) {
const Variable* var = tok->variable();
const Variable* var2 = tok->tokAt(2)->variable();
if (var->isPointer() && var2 && var2->isStlType(stl_string_stream))
string_c_strError(tok);
} else if (Token::Match(tok->tokAt(2), "%name% (") &&
Token::Match(tok->linkAt(3), ") . c_str|data ( ) ;") &&
tok->tokAt(2)->function() && Token::Match(tok->tokAt(2)->function()->retDef, "std :: string|wstring %name%")) {
const Variable* var = tok->variable();
if (var->isPointer())
string_c_strError(tok);
} else if (printPerformance && tok->tokAt(1)->astOperand2() && Token::Match(tok->tokAt(1)->astOperand2()->tokAt(-3), "%var% . c_str|data ( ) ;")) {
const Token* vartok = tok->tokAt(1)->astOperand2()->tokAt(-3);
if ((tok->variable()->isStlStringType() || tok->variable()->isStlStringViewType()) && vartok->variable() && vartok->variable()->isStlStringType())
string_c_strAssignment(tok, tok->variable()->getTypeName());
}
} else if (printPerformance && tok->function() && Token::Match(tok, "%name% ( !!)") && tok->str() != scope.className) {
const auto range = c_strFuncParam.equal_range(tok->function());
for (std::multimap<const Function*, StrArg>::const_iterator i = range.first; i != range.second; ++i) {
if (i->second.n == 0)
continue;
const Token* tok2 = tok->tokAt(2);
int j;
for (j = 0; tok2 && j < i->second.n - 1; j++)
tok2 = tok2->nextArgument();
if (tok2)
tok2 = tok2->nextArgument();
else
break;
if (!tok2 && j == i->second.n - 1)
tok2 = tok->linkAt(1);
else if (tok2)
tok2 = tok2->previous();
else
break;
if (tok2 && Token::Match(tok2->tokAt(-4), ". c_str|data ( )")) {
if (isString(tok2->tokAt(-4)->astOperand1())) {
string_c_strParam(tok, i->second.n, i->second.argtype);
} else if (Token::Match(tok2->tokAt(-9), "%name% . str ( )")) { // Check ss.str().c_str() as parameter
const Variable* ssVar = tok2->tokAt(-9)->variable();
if (ssVar && ssVar->isStlType(stl_string_stream))
string_c_strParam(tok, i->second.n, i->second.argtype);
}
}
}
} else if (printPerformance && Token::Match(tok, "%var% (|{ %var% . c_str|data ( ) !!,") &&
tok->variable() && (tok->variable()->isStlStringType() || tok->variable()->isStlStringViewType()) &&
tok->tokAt(2)->variable() && tok->tokAt(2)->variable()->isStlStringType()) {
string_c_strConstructor(tok, tok->variable()->getTypeName());
} else if (printPerformance && tok->next() && tok->next()->variable() && tok->next()->variable()->isStlStringType() && tok->valueType() && tok->valueType()->type == ValueType::CONTAINER &&
((Token::Match(tok->previous(), "%var% + %var% . c_str|data ( )") && tok->previous()->variable() && tok->previous()->variable()->isStlStringType()) ||
(Token::Match(tok->tokAt(-5), "%var% . c_str|data ( ) + %var%") && tok->tokAt(-5)->variable() && tok->tokAt(-5)->variable()->isStlStringType()))) {
string_c_strConcat(tok);
} else if (printPerformance && Token::simpleMatch(tok, "<<") && tok->astOperand2() && Token::Match(tok->astOperand2()->astOperand1(), ". c_str|data ( )")) {
const Token* str = tok->astOperand2()->astOperand1()->astOperand1();
if (isString(str)) {
const Token* strm = tok;
while (Token::simpleMatch(strm, "<<"))
strm = strm->astOperand1();
if (strm && strm->variable() && strm->variable()->isStlType())
string_c_strStream(tok);
}
}
// Using c_str() to get the return value is only dangerous if the function returns a char*
else if ((returnType == charPtr || (printPerformance && (returnType == stdString || returnType == stdStringConstRef))) && tok->str() == "return") {
bool err = false;
const Token* tok2 = tok->next();
if (Token::Match(tok2, "std :: string|wstring (") &&
Token::Match(tok2->linkAt(3), ") . c_str|data ( ) ;")) {
err = true;
} else if (Token::simpleMatch(tok2, "(") &&
Token::Match(tok2->link(), ") . c_str|data ( ) ;")) {
// Check for "+ localvar" or "+ std::string(" inside the bracket
bool is_implicit_std_string = printInconclusive;
const Token *search_end = tok2->link();
for (const Token *search_tok = tok2->next(); search_tok != search_end; search_tok = search_tok->next()) {
if (Token::Match(search_tok, "+ %var%") && isLocal(search_tok->next()) &&
search_tok->next()->variable() && search_tok->next()->variable()->isStlStringType()) {
is_implicit_std_string = true;
break;
}
if (Token::Match(search_tok, "+ std :: string|wstring (")) {
is_implicit_std_string = true;
break;
}
}
if (is_implicit_std_string)
err = true;
}
bool local = false;
bool ptrOrRef = false;
const Variable* lastVar = nullptr;
const Function* lastFunc = nullptr;
bool funcStr = false;
if (Token::Match(tok2, "%var% .")) {
local = isLocal(tok2);
bool refToNonLocal = false;
if (tok2->variable() && tok2->variable()->isReference()) {
const Token *refTok = tok2->variable()->nameToken();
refToNonLocal = true; // safe assumption is default to avoid FPs
if (Token::Match(refTok, "%var% = %var% .|;|["))
refToNonLocal = !isLocal(refTok->tokAt(2));
}
ptrOrRef = refToNonLocal || (tok2->variable() && (tok2->variable()->isPointer() || tok2->variable()->isSmartPointer()));
}
while (tok2) {
if (Token::Match(tok2, "%var% .|::")) {
if (ptrOrRef)
local = false;
lastVar = tok2->variable();
tok2 = tok2->tokAt(2);
} else if (Token::Match(tok2, "%name% (") && Token::simpleMatch(tok2->linkAt(1), ") .")) {
lastFunc = tok2->function();
local = false;
funcStr = tok2->str() == "str";
tok2 = tok2->linkAt(1)->tokAt(2);
} else
break;
}
if (Token::Match(tok2, "c_str|data ( ) ;")) {
if ((local || returnType != charPtr) && lastVar && lastVar->isStlStringType())
err = true;
else if (funcStr && lastVar && lastVar->isStlType(stl_string_stream))
err = true;
else if (lastFunc && Token::Match(lastFunc->tokenDef->tokAt(-3), "std :: string|wstring"))
err = true;
}
if (err) {
if (returnType == charPtr)
string_c_strError(tok);
else
string_c_strReturn(tok);
}
}
}
}
}
void CheckStl::string_c_strThrowError(const Token* tok)
{
reportError(tok, Severity::error, "stlcstrthrow", "Dangerous usage of c_str(). The value returned by c_str() is invalid after throwing exception.\n"
"Dangerous usage of c_str(). The string is destroyed after the c_str() call so the thrown pointer is invalid.");
}
void CheckStl::string_c_strError(const Token* tok)
{
reportError(tok, Severity::error, "stlcstr", "Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n"
"Dangerous usage of c_str(). The c_str() return value is only valid until its string is deleted.", CWE664, Certainty::normal);
}
void CheckStl::string_c_strReturn(const Token* tok)
{
reportError(tok, Severity::performance, "stlcstrReturn", "Returning the result of c_str() in a function that returns std::string is slow and redundant.\n"
"The conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly returning the string.", CWE704, Certainty::normal);
}
void CheckStl::string_c_strParam(const Token* tok, nonneg int number, const std::string& argtype)
{
std::ostringstream oss;
oss << "Passing the result of c_str() to a function that takes " << argtype << " as argument no. " << number << " is slow and redundant.\n"
"The conversion from const char* as returned by c_str() to " << argtype << " creates an unnecessary string copy or length calculation. Solve that by directly passing the string.";
reportError(tok, Severity::performance, "stlcstrParam", oss.str(), CWE704, Certainty::normal);
}
void CheckStl::string_c_strConstructor(const Token* tok, const std::string& argtype)
{
std::string msg = "Constructing a " + argtype + " from the result of c_str() is slow and redundant.\n"
"Constructing a " + argtype + " from const char* requires a call to strlen(). Solve that by directly passing the string.";
reportError(tok, Severity::performance, "stlcstrConstructor", msg, CWE704, Certainty::normal);
}
void CheckStl::string_c_strAssignment(const Token* tok, const std::string& argtype)
{
std::string msg = "Assigning the result of c_str() to a " + argtype + " is slow and redundant.\n"
"Assigning a const char* to a " + argtype + " requires a call to strlen(). Solve that by directly assigning the string.";
reportError(tok, Severity::performance, "stlcstrAssignment", msg, CWE704, Certainty::normal);
}
void CheckStl::string_c_strConcat(const Token* tok)
{
std::string msg = "Concatenating the result of c_str() and a std::string is slow and redundant.\n"
"Concatenating a const char* with a std::string requires a call to strlen(). Solve that by directly concatenating the strings.";
reportError(tok, Severity::performance, "stlcstrConcat", msg, CWE704, Certainty::normal);
}
void CheckStl::string_c_strStream(const Token* tok)
{
std::string msg = "Passing the result of c_str() to a stream is slow and redundant.\n"
"Passing a const char* to a stream requires a call to strlen(). Solve that by directly passing the string.";
reportError(tok, Severity::performance, "stlcstrStream", msg, CWE704, Certainty::normal);
}
//---------------------------------------------------------------------------
//
//---------------------------------------------------------------------------
namespace {
const std::set<std::string> stl_containers_with_empty_and_clear = {
"deque", "forward_list", "list",
"map", "multimap", "multiset", "set", "string",
"unordered_map", "unordered_multimap", "unordered_multiset",
"unordered_set", "vector", "wstring"
};
}
void CheckStl::uselessCalls()
{
const bool printPerformance = mSettings->severity.isEnabled(Severity::performance);
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
if (!printPerformance && !printWarning)
return;
logChecker("CheckStl::uselessCalls"); // performance,warning
const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (printWarning && Token::Match(tok, "%var% . compare|find|rfind|find_first_not_of|find_first_of|find_last_not_of|find_last_of ( %name% [,)]") &&
tok->varId() == tok->tokAt(4)->varId()) {
const Variable* var = tok->variable();
if (!var || !var->isStlType())
continue;
uselessCallsReturnValueError(tok->tokAt(4), tok->str(), tok->strAt(2));
} else if (printPerformance && Token::Match(tok, "%var% . swap ( %name% )") &&
tok->varId() == tok->tokAt(4)->varId()) {
const Variable* var = tok->variable();
if (!var || !var->isStlType())
continue;
uselessCallsSwapError(tok, tok->str());
} else if (printPerformance && Token::Match(tok, "%var% . substr (") && tok->variable() && tok->variable()->isStlStringType()) {
const Token* funcTok = tok->tokAt(3);
const std::vector<const Token*> args = getArguments(funcTok);
if (Token::Match(tok->tokAt(-2), "%var% =") && tok->varId() == tok->tokAt(-2)->varId() &&
!args.empty() && args[0]->hasKnownIntValue() && args[0]->getKnownIntValue() == 0) {
uselessCallsSubstrError(tok, Token::simpleMatch(funcTok->astParent(), "=") ? SubstrErrorType::PREFIX : SubstrErrorType::PREFIX_CONCAT);
} else if (args.empty() || (args[0]->hasKnownIntValue() && args[0]->getKnownIntValue() == 0 &&
(args.size() == 1 || (args.size() == 2 && tok->linkAt(3)->strAt(-1) == "npos" && !tok->linkAt(3)->previous()->variable())))) {
uselessCallsSubstrError(tok, SubstrErrorType::COPY);
} else if (args.size() == 2 && args[1]->hasKnownIntValue() && args[1]->getKnownIntValue() == 0) {
uselessCallsSubstrError(tok, SubstrErrorType::EMPTY);
}
} else if (printWarning && Token::Match(tok, "[{};] %var% . empty ( ) ;") &&
!tok->tokAt(4)->astParent() &&
tok->next()->variable() && tok->next()->variable()->isStlType(stl_containers_with_empty_and_clear))
uselessCallsEmptyError(tok->next());
else if (Token::Match(tok, "[{};] std :: remove|remove_if|unique (") && tok->tokAt(5)->nextArgument())
uselessCallsRemoveError(tok->next(), tok->strAt(3));
else if (printPerformance && tok->valueType() && tok->valueType()->type == ValueType::CONTAINER) {
if (Token::Match(tok, "%var% = { %var% . begin ( ) ,") && tok->varId() == tok->tokAt(3)->varId())
uselessCallsConstructorError(tok);
else if (const Variable* var = tok->variable()) {
std::string pattern = "%var% = ";
for (const Token* t = var->typeStartToken(); t != var->typeEndToken()->next(); t = t->next()) {
pattern += t->str();
pattern += ' ';
}
pattern += "{|( %varid% . begin ( ) ,";
if (Token::Match(tok, pattern.c_str(), tok->varId()))
uselessCallsConstructorError(tok);
}
}
}
}
}
void CheckStl::uselessCallsReturnValueError(const Token *tok, const std::string &varname, const std::string &function)
{
std::ostringstream errmsg;
errmsg << "$symbol:" << varname << '\n';
errmsg << "$symbol:" << function << '\n';
errmsg << "It is inefficient to call '" << varname << "." << function << "(" << varname << ")' as it always returns 0.\n"
<< "'std::string::" << function << "()' returns zero when given itself as parameter "
<< "(" << varname << "." << function << "(" << varname << ")). As it is currently the "
<< "code is inefficient. It is possible either the string searched ('"
<< varname << "') or searched for ('" << varname << "') is wrong.";
reportError(tok, Severity::warning, "uselessCallsCompare", errmsg.str(), CWE628, Certainty::normal);
}
void CheckStl::uselessCallsSwapError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::performance, "uselessCallsSwap",
"$symbol:" + varname + "\n"
"It is inefficient to swap a object with itself by calling '$symbol.swap($symbol)'\n"
"The 'swap()' function has no logical effect when given itself as parameter "
"($symbol.swap($symbol)). As it is currently the "
"code is inefficient. Is the object or the parameter wrong here?", CWE628, Certainty::normal);
}
void CheckStl::uselessCallsSubstrError(const Token *tok, SubstrErrorType type)
{
std::string msg = "Ineffective call of function 'substr' because ";
switch (type) {
case SubstrErrorType::EMPTY:
msg += "it returns an empty string.";
break;
case SubstrErrorType::COPY:
msg += "it returns a copy of the object. Use operator= instead.";
break;
case SubstrErrorType::PREFIX:
msg += "a prefix of the string is assigned to itself. Use resize() or pop_back() instead.";
break;
case SubstrErrorType::PREFIX_CONCAT:
msg += "a prefix of the string is assigned to itself. Use replace() instead.";
break;
}
reportError(tok, Severity::performance, "uselessCallsSubstr", msg, CWE398, Certainty::normal);
}
void CheckStl::uselessCallsConstructorError(const Token *tok)
{
const std::string msg = "Inefficient constructor call: container '" + tok->str() + "' is assigned a partial copy of itself. Use erase() or resize() instead.";
reportError(tok, Severity::performance, "uselessCallsConstructor", msg, CWE398, Certainty::normal);
}
void CheckStl::uselessCallsEmptyError(const Token *tok)
{
reportError(tok, Severity::warning, "uselessCallsEmpty", "Ineffective call of function 'empty()'. Did you intend to call 'clear()' instead?", CWE398, Certainty::normal);
}
void CheckStl::uselessCallsRemoveError(const Token *tok, const std::string& function)
{
reportError(tok, Severity::warning, "uselessCallsRemove",
"$symbol:" + function + "\n"
"Return value of std::$symbol() ignored. Elements remain in container.\n"
"The return value of std::$symbol() is ignored. This function returns an iterator to the end of the range containing those elements that should be kept. "
"Elements past new end remain valid but with unspecified values. Use the erase method of the container to delete them.", CWE762, Certainty::normal);
}
// Check for iterators being dereferenced before being checked for validity.
// E.g. if (*i && i != str.end()) { }
void CheckStl::checkDereferenceInvalidIterator()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckStl::checkDereferenceInvalidIterator"); // warning
// Iterate over "if", "while", and "for" conditions where there may
// be an iterator that is dereferenced before being checked for validity.
for (const Scope &scope : mTokenizer->getSymbolDatabase()->scopeList) {
if (!(scope.type == Scope::eIf || scope.isLoopScope()))
continue;
const Token* const tok = scope.classDef;
const Token* startOfCondition = tok->next();
if (scope.type == Scope::eDo)
startOfCondition = startOfCondition->link()->tokAt(2);
if (!startOfCondition) // ticket #6626 invalid code
continue;
const Token* endOfCondition = startOfCondition->link();
if (!endOfCondition)
continue;
// For "for" loops, only search between the two semicolons
if (scope.type == Scope::eFor) {
startOfCondition = Token::findsimplematch(tok->tokAt(2), ";", endOfCondition);
if (!startOfCondition)
continue;
endOfCondition = Token::findsimplematch(startOfCondition->next(), ";", endOfCondition);
if (!endOfCondition)
continue;
}
// Only consider conditions composed of all "&&" terms and
// conditions composed of all "||" terms
const bool isOrExpression =
Token::findsimplematch(startOfCondition, "||", endOfCondition) != nullptr;
const bool isAndExpression =
Token::findsimplematch(startOfCondition, "&&", endOfCondition) != nullptr;
// Look for a check of the validity of an iterator
const Token* validityCheckTok = nullptr;
if (!isOrExpression && isAndExpression) {
validityCheckTok =
Token::findmatch(startOfCondition, "&& %var% != %name% . end|rend|cend|crend ( )", endOfCondition);
} else if (isOrExpression && !isAndExpression) {
validityCheckTok =
Token::findmatch(startOfCondition, "%oror% %var% == %name% . end|rend|cend|crend ( )", endOfCondition);
}
if (!validityCheckTok)
continue;
const int iteratorVarId = validityCheckTok->next()->varId();
// If the iterator dereference is to the left of the check for
// the iterator's validity, report an error.
const Token* const dereferenceTok =
Token::findmatch(startOfCondition, "* %varid%", validityCheckTok, iteratorVarId);
if (dereferenceTok)
dereferenceInvalidIteratorError(dereferenceTok, dereferenceTok->strAt(1));
}
}
void CheckStl::checkDereferenceInvalidIterator2()
{
const bool printInconclusive = (mSettings->certainty.isEnabled(Certainty::inconclusive));
logChecker("CheckStl::checkDereferenceInvalidIterator2");
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "sizeof|decltype|typeid|typeof (")) {
tok = tok->linkAt(1);
continue;
}
if (Token::Match(tok, "%assign%"))
continue;
std::vector<ValueFlow::Value> contValues;
std::copy_if(tok->values().cbegin(), tok->values().cend(), std::back_inserter(contValues), [&](const ValueFlow::Value& value) {
if (value.isImpossible())
return false;
if (!printInconclusive && value.isInconclusive())
return false;
return value.isContainerSizeValue();
});
// Can iterator point to END or before START?
for (const ValueFlow::Value& value:tok->values()) {
if (value.isImpossible())
continue;
if (!printInconclusive && value.isInconclusive())
continue;
if (!value.isIteratorValue())
continue;
bool isInvalidIterator = false;
const ValueFlow::Value* cValue = nullptr;
if (value.isIteratorEndValue() && value.intvalue >= 0) {
isInvalidIterator = value.intvalue > 0;
} else if (value.isIteratorStartValue() && value.intvalue < 0) {
isInvalidIterator = true;
} else {
auto it = std::find_if(contValues.cbegin(), contValues.cend(), [&](const ValueFlow::Value& c) {
if (value.path != c.path)
return false;
if (value.isIteratorStartValue() && value.intvalue >= c.intvalue)
return true;
if (value.isIteratorEndValue() && -value.intvalue > c.intvalue)
return true;
return false;
});
if (it == contValues.end())
continue;
cValue = &*it;
if (value.isIteratorStartValue() && value.intvalue > cValue->intvalue)
isInvalidIterator = true;
}
bool inconclusive = false;
bool unknown = false;
const Token* emptyAdvance = nullptr;
const Token* advanceIndex = nullptr;
if (cValue && cValue->intvalue == 0) {
if (Token::Match(tok->astParent(), "+|-") && astIsIntegral(tok->astSibling(), false)) {
if (tok->astSibling() && tok->astSibling()->hasKnownIntValue()) {
if (tok->astSibling()->values().front().intvalue == 0)
continue;
} else {
advanceIndex = tok->astSibling();
}
emptyAdvance = tok->astParent();
} else if (Token::Match(tok->astParent(), "++|--")) {
emptyAdvance = tok->astParent();
}
}
if (!CheckNullPointer::isPointerDeRef(tok, unknown, *mSettings) && !isInvalidIterator && !emptyAdvance) {
if (!unknown)
continue;
inconclusive = true;
}
if (cValue) {
const ValueFlow::Value& lValue = getLifetimeIteratorValue(tok, cValue->path);
if (!lValue.isLifetimeValue())
continue;
if (emptyAdvance)
outOfBoundsError(emptyAdvance,
lValue.tokvalue->expressionString(),
cValue,
advanceIndex ? advanceIndex->expressionString() : emptyString,
nullptr);
else
outOfBoundsError(tok, lValue.tokvalue->expressionString(), cValue, tok->expressionString(), &value);
} else {
dereferenceInvalidIteratorError(tok, &value, inconclusive);
}
}
}
}
void CheckStl::dereferenceInvalidIteratorError(const Token* tok, const ValueFlow::Value *value, bool inconclusive)
{
const std::string& varname = tok ? tok->expressionString() : "var";
const std::string errmsgcond("$symbol:" + varname + '\n' + ValueFlow::eitherTheConditionIsRedundant(value ? value->condition : nullptr) + " or there is possible dereference of an invalid iterator: $symbol.");
if (!tok || !value) {
reportError(tok, Severity::error, "derefInvalidIterator", "Dereference of an invalid iterator", CWE825, Certainty::normal);
reportError(tok, Severity::warning, "derefInvalidIteratorRedundantCheck", errmsgcond, CWE825, Certainty::normal);
return;
}
if (!mSettings->isEnabled(value, inconclusive))
return;
const ErrorPath errorPath = getErrorPath(tok, value, "Dereference of an invalid iterator");
if (value->condition) {
reportError(errorPath, Severity::warning, "derefInvalidIteratorRedundantCheck", errmsgcond, CWE825, (inconclusive || value->isInconclusive()) ? Certainty::inconclusive : Certainty::normal);
} else {
std::string errmsg = std::string(value->isKnown() ? "Dereference" : "Possible dereference") + " of an invalid iterator";
if (!varname.empty())
errmsg = "$symbol:" + varname + '\n' + errmsg + ": $symbol";
reportError(errorPath,
value->isKnown() ? Severity::error : Severity::warning,
"derefInvalidIterator",
errmsg,
CWE825, (inconclusive || value->isInconclusive()) ? Certainty::inconclusive : Certainty::normal);
}
}
void CheckStl::dereferenceInvalidIteratorError(const Token* deref, const std::string &iterName)
{
reportError(deref, Severity::warning,
"derefInvalidIterator",
"$symbol:" + iterName + "\n"
"Possible dereference of an invalid iterator: $symbol\n"
"Possible dereference of an invalid iterator: $symbol. Make sure to check that the iterator is valid before dereferencing it - not after.", CWE825, Certainty::normal);
}
void CheckStl::useStlAlgorithmError(const Token *tok, const std::string &algoName)
{
reportError(tok, Severity::style, "useStlAlgorithm",
"Consider using " + algoName + " algorithm instead of a raw loop.", CWE398, Certainty::normal);
}
static bool isEarlyExit(const Token *start)
{
if (start->str() != "{")
return false;
const Token *endToken = start->link();
const Token *tok = Token::findmatch(start, "return|throw|break", endToken);
if (!tok)
return false;
const Token *endStatement = Token::findsimplematch(tok, "; }", endToken);
if (!endStatement)
return false;
if (endStatement->next() != endToken)
return false;
return true;
}
static const Token *singleStatement(const Token *start)
{
if (start->str() != "{")
return nullptr;
const Token *endToken = start->link();
const Token *endStatement = Token::findsimplematch(start->next(), ";");
if (!Token::simpleMatch(endStatement, "; }"))
return nullptr;
if (endStatement->next() != endToken)
return nullptr;
return endStatement;
}
static const Token *singleAssignInScope(const Token *start, nonneg int varid, bool &input, bool &hasBreak, const Settings& settings)
{
const Token *endStatement = singleStatement(start);
if (!endStatement)
return nullptr;
if (!Token::Match(start->next(), "%var% %assign%"))
return nullptr;
const Token *assignTok = start->tokAt(2);
if (isVariableChanged(assignTok->next(), endStatement, assignTok->astOperand1()->varId(), /*globalvar*/ false, settings))
return nullptr;
if (isVariableChanged(assignTok->next(), endStatement, varid, /*globalvar*/ false, settings))
return nullptr;
input = Token::findmatch(assignTok->next(), "%varid%", endStatement, varid) || !Token::Match(start->next(), "%var% =");
hasBreak = Token::simpleMatch(endStatement->previous(), "break");
return assignTok;
}
static const Token *singleMemberCallInScope(const Token *start, nonneg int varid, bool &input, const Settings& settings)
{
if (start->str() != "{")
return nullptr;
const Token *endToken = start->link();
if (!Token::Match(start->next(), "%var% . %name% ("))
return nullptr;
if (!Token::simpleMatch(start->linkAt(4), ") ; }"))
return nullptr;
const Token *endStatement = start->linkAt(4)->next();
if (endStatement->next() != endToken)
return nullptr;
const Token *dotTok = start->tokAt(2);
if (!Token::findmatch(dotTok->tokAt(2), "%varid%", endStatement, varid))
return nullptr;
input = Token::Match(start->next(), "%var% . %name% ( %varid% )", varid);
if (isVariableChanged(dotTok->next(), endStatement, dotTok->astOperand1()->varId(), /*globalvar*/ false, settings))
return nullptr;
return dotTok;
}
static const Token *singleIncrementInScope(const Token *start, nonneg int varid, bool &input)
{
if (start->str() != "{")
return nullptr;
const Token *varTok = nullptr;
if (Token::Match(start->next(), "++ %var% ; }"))
varTok = start->tokAt(2);
else if (Token::Match(start->next(), "%var% ++ ; }"))
varTok = start->tokAt(1);
if (!varTok)
return nullptr;
input = varTok->varId() == varid;
return varTok;
}
static const Token *singleConditionalInScope(const Token *start, nonneg int varid, const Settings& settings)
{
if (start->str() != "{")
return nullptr;
const Token *endToken = start->link();
if (!Token::simpleMatch(start->next(), "if ("))
return nullptr;
if (!Token::simpleMatch(start->linkAt(2), ") {"))
return nullptr;
const Token *bodyTok = start->linkAt(2)->next();
const Token *endBodyTok = bodyTok->link();
if (!Token::simpleMatch(endBodyTok, "} }"))
return nullptr;
if (endBodyTok->next() != endToken)
return nullptr;
if (!Token::findmatch(start, "%varid%", bodyTok, varid))
return nullptr;
if (isVariableChanged(start, bodyTok, varid, /*globalvar*/ false, settings))
return nullptr;
return bodyTok;
}
static bool addByOne(const Token *tok, nonneg int varid)
{
if (Token::Match(tok, "+= %any% ;") &&
tok->tokAt(1)->hasKnownIntValue() &&
tok->tokAt(1)->getValue(1)) {
return true;
}
if (Token::Match(tok, "= %varid% + %any% ;", varid) &&
tok->tokAt(3)->hasKnownIntValue() &&
tok->tokAt(3)->getValue(1)) {
return true;
}
return false;
}
static bool accumulateBoolLiteral(const Token *tok, nonneg int varid)
{
if (Token::Match(tok, "%assign% %bool% ;") &&
tok->tokAt(1)->hasKnownIntValue()) {
return true;
}
if (Token::Match(tok, "= %varid% %oror%|%or%|&&|& %bool% ;", varid) &&
tok->tokAt(3)->hasKnownIntValue()) {
return true;
}
return false;
}
static bool accumulateBool(const Token *tok, nonneg int varid)
{
// Missing %oreq% so we have to check both manually
if (Token::simpleMatch(tok, "&=") || Token::simpleMatch(tok, "|=")) {
return true;
}
if (Token::Match(tok, "= %varid% %oror%|%or%|&&|&", varid)) {
return true;
}
return false;
}
static bool hasVarIds(const Token *tok, nonneg int var1, nonneg int var2)
{
if (tok->astOperand1()->varId() == tok->astOperand2()->varId())
return false;
if (tok->astOperand1()->varId() == var1 || tok->astOperand1()->varId() == var2) {
if (tok->astOperand2()->varId() == var1 || tok->astOperand2()->varId() == var2) {
return true;
}
}
return false;
}
static std::string flipMinMax(const std::string &algo)
{
if (algo == "std::max_element")
return "std::min_element";
if (algo == "std::min_element")
return "std::max_element";
return algo;
}
static std::string minmaxCompare(const Token *condTok, nonneg int loopVar, nonneg int assignVar, bool invert = false)
{
if (!Token::Match(condTok, "<|<=|>=|>"))
return "std::accumulate";
if (!hasVarIds(condTok, loopVar, assignVar))
return "std::accumulate";
std::string algo = "std::max_element";
if (Token::Match(condTok, "<|<="))
algo = "std::min_element";
if (condTok->astOperand1()->varId() == assignVar)
algo = flipMinMax(algo);
if (invert)
algo = flipMinMax(algo);
return algo;
}
namespace {
struct LoopAnalyzer {
const Token* bodyTok = nullptr;
const Token* loopVar = nullptr;
const Settings* settings = nullptr;
std::set<nonneg int> varsChanged;
explicit LoopAnalyzer(const Token* tok, const Settings* psettings)
: bodyTok(tok->linkAt(1)->next()), settings(psettings)
{
const Token* splitTok = tok->next()->astOperand2();
if (Token::simpleMatch(splitTok, ":") && splitTok->previous()->varId() != 0) {
loopVar = splitTok->previous();
}
if (valid()) {
findChangedVariables();
}
}
bool isLoopVarChanged() const {
return varsChanged.count(loopVar->varId()) > 0;
}
bool isModified(const Token* tok) const
{
if (tok->variable() && tok->variable()->isConst())
return false;
int n = 1 + (astIsPointer(tok) ? 1 : 0);
for (int i = 0; i < n; i++) {
bool inconclusive = false;
if (isVariableChangedByFunctionCall(tok, i, *settings, &inconclusive))
return true;
if (inconclusive)
return true;
if (isVariableChanged(tok, i, *settings))
return true;
}
return false;
}
template<class Predicate, class F>
void findTokens(Predicate pred, F f) const
{
for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) {
if (pred(tok))
f(tok);
}
}
template<class Predicate>
const Token* findToken(Predicate pred) const
{
for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) {
if (pred(tok))
return tok;
}
return nullptr;
}
bool hasGotoOrBreak() const
{
return findToken([](const Token* tok) {
return Token::Match(tok, "goto|break");
});
}
bool valid() const {
return bodyTok && loopVar;
}
std::string findAlgo() const
{
if (!valid())
return "";
bool loopVarChanged = isLoopVarChanged();
if (!loopVarChanged && varsChanged.empty()) {
if (hasGotoOrBreak())
return "";
bool alwaysTrue = true;
bool alwaysFalse = true;
auto hasReturn = [](const Token* tok) {
return Token::simpleMatch(tok, "return");
};
findTokens(hasReturn, [&](const Token* tok) {
const Token* returnTok = tok->astOperand1();
if (!returnTok || !returnTok->hasKnownIntValue() || !astIsBool(returnTok)) {
alwaysTrue = false;
alwaysFalse = false;
return;
}
(returnTok->values().front().intvalue ? alwaysTrue : alwaysFalse) &= true;
(returnTok->values().front().intvalue ? alwaysFalse : alwaysTrue) &= false;
});
if (alwaysTrue == alwaysFalse)
return "";
if (alwaysTrue)
return "std::any_of";
return "std::all_of or std::none_of";
}
return "";
}
bool isLocalVar(const Variable* var) const
{
if (!var)
return false;
if (var->isPointer() || var->isReference())
return false;
if (var->declarationId() == loopVar->varId())
return false;
const Scope* scope = var->scope();
return scope && scope->isNestedIn(bodyTok->scope());
}
private:
void findChangedVariables()
{
std::set<nonneg int> vars;
for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) {
if (tok->varId() == 0)
continue;
if (vars.count(tok->varId()) > 0)
continue;
if (isLocalVar(tok->variable())) {
vars.insert(tok->varId());
continue;
}
if (!isModified(tok))
continue;
varsChanged.insert(tok->varId());
vars.insert(tok->varId());
}
}
};
} // namespace
void CheckStl::useStlAlgorithm()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("useStlAlgorithm"))
return;
logChecker("CheckStl::useStlAlgorithm"); // style
auto checkAssignee = [](const Token* tok) {
if (astIsBool(tok)) // std::accumulate is not a good fit for bool values, std::all/any/none_of return early
return false;
return !astIsContainer(tok); // don't warn for containers, where overloaded operators can be costly
};
auto isConditionWithoutSideEffects = [this](const Token* tok) -> bool {
if (!Token::simpleMatch(tok, "{") || !Token::simpleMatch(tok->previous(), ")"))
return false;
return isConstExpression(tok->linkAt(-1)->astOperand2(), mSettings->library);
};
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
// Parse range-based for loop
if (!Token::simpleMatch(tok, "for ("))
continue;
if (!Token::simpleMatch(tok->linkAt(1), ") {"))
continue;
LoopAnalyzer a{tok, mSettings};
std::string algoName = a.findAlgo();
if (!algoName.empty()) {
useStlAlgorithmError(tok, algoName);
continue;
}
const Token *bodyTok = tok->linkAt(1)->next();
const Token *splitTok = tok->next()->astOperand2();
const Token* loopVar{};
bool isIteratorLoop = false;
if (Token::simpleMatch(splitTok, ":")) {
loopVar = splitTok->previous();
if (loopVar->varId() == 0)
continue;
if (Token::simpleMatch(splitTok->astOperand2(), "{"))
continue;
}
else { // iterator-based loop?
const Token* initTok = getInitTok(tok);
const Token* condTok = getCondTok(tok);
const Token* stepTok = getStepTok(tok);
if (!initTok || !condTok || !stepTok)
continue;
loopVar = Token::Match(condTok, "%comp%") ? condTok->astOperand1() : nullptr;
if (!Token::Match(loopVar, "%var%") || !loopVar->valueType() || loopVar->valueType()->type != ValueType::Type::ITERATOR)
continue;
if (!Token::simpleMatch(initTok, "=") || !Token::Match(initTok->astOperand1(), "%varid%", loopVar->varId()))
continue;
if (!stepTok->isIncDecOp())
continue;
isIteratorLoop = true;
}
// Check for single assignment
bool useLoopVarInAssign{}, hasBreak{};
const Token *assignTok = singleAssignInScope(bodyTok, loopVar->varId(), useLoopVarInAssign, hasBreak, *mSettings);
if (assignTok) {
if (!checkAssignee(assignTok->astOperand1()))
continue;
const int assignVarId = assignTok->astOperand1()->varId();
std::string algo;
if (assignVarId == loopVar->varId()) {
if (useLoopVarInAssign)
algo = "std::transform";
else if (Token::Match(assignTok->next(), "%var%|%bool%|%num%|%char% ;"))
algo = "std::fill";
else if (Token::Match(assignTok->next(), "%name% ( )"))
algo = "std::generate";
else
algo = "std::fill or std::generate";
} else {
if (addByOne(assignTok, assignVarId))
algo = "std::distance";
else if (accumulateBool(assignTok, assignVarId))
algo = "std::any_of, std::all_of, std::none_of, or std::accumulate";
else if (Token::Match(assignTok, "= %var% <|<=|>=|> %var% ? %var% : %var%") && hasVarIds(assignTok->tokAt(6), loopVar->varId(), assignVarId))
algo = minmaxCompare(assignTok->tokAt(2), loopVar->varId(), assignVarId, assignTok->tokAt(5)->varId() == assignVarId);
else
algo = "std::accumulate";
}
useStlAlgorithmError(assignTok, algo);
continue;
}
// Check for container calls
bool useLoopVarInMemCall;
const Token *memberAccessTok = singleMemberCallInScope(bodyTok, loopVar->varId(), useLoopVarInMemCall, *mSettings);
if (memberAccessTok && !isIteratorLoop) {
const Token *memberCallTok = memberAccessTok->astOperand2();
const int contVarId = memberAccessTok->astOperand1()->varId();
if (contVarId == loopVar->varId())
continue;
if (memberCallTok->str() == "push_back" ||
memberCallTok->str() == "push_front" ||
memberCallTok->str() == "emplace_back") {
std::string algo;
if (useLoopVarInMemCall)
algo = "std::copy";
else
algo = "std::transform";
useStlAlgorithmError(memberCallTok, algo);
}
continue;
}
// Check for increment in loop
bool useLoopVarInIncrement;
const Token *incrementTok = singleIncrementInScope(bodyTok, loopVar->varId(), useLoopVarInIncrement);
if (incrementTok) {
std::string algo;
if (useLoopVarInIncrement)
algo = "std::transform";
else
algo = "std::distance";
useStlAlgorithmError(incrementTok, algo);
continue;
}
// Check for conditionals
const Token *condBodyTok = singleConditionalInScope(bodyTok, loopVar->varId(), *mSettings);
if (condBodyTok) {
// Check for single assign
assignTok = singleAssignInScope(condBodyTok, loopVar->varId(), useLoopVarInAssign, hasBreak, *mSettings);
if (assignTok) {
if (!checkAssignee(assignTok->astOperand1()))
continue;
const int assignVarId = assignTok->astOperand1()->varId();
std::string algo;
if (assignVarId == loopVar->varId()) {
if (useLoopVarInAssign)
algo = "std::transform";
else
algo = "std::replace_if";
} else {
if (addByOne(assignTok, assignVarId))
algo = "std::count_if";
else if (accumulateBoolLiteral(assignTok, assignVarId))
algo = "std::any_of, std::all_of, std::none_of, or std::accumulate";
else if (assignTok->str() != "=")
algo = "std::accumulate";
else if (hasBreak && isConditionWithoutSideEffects(condBodyTok))
algo = "std::any_of, std::all_of, std::none_of";
else
continue;
}
useStlAlgorithmError(assignTok, algo);
continue;
}
// Check for container call
memberAccessTok = singleMemberCallInScope(condBodyTok, loopVar->varId(), useLoopVarInMemCall, *mSettings);
if (memberAccessTok) {
const Token *memberCallTok = memberAccessTok->astOperand2();
const int contVarId = memberAccessTok->astOperand1()->varId();
if (contVarId == loopVar->varId())
continue;
if (memberCallTok->str() == "push_back" ||
memberCallTok->str() == "push_front" ||
memberCallTok->str() == "emplace_back") {
if (useLoopVarInMemCall)
useStlAlgorithmError(memberAccessTok, "std::copy_if");
// There is no transform_if to suggest
}
continue;
}
// Check for increment in loop
incrementTok = singleIncrementInScope(condBodyTok, loopVar->varId(), useLoopVarInIncrement);
if (incrementTok) {
std::string algo;
if (useLoopVarInIncrement)
algo = "std::transform";
else
algo = "std::count_if";
useStlAlgorithmError(incrementTok, algo);
continue;
}
// Check early return
if (isEarlyExit(condBodyTok)) {
const Token *loopVar2 = Token::findmatch(condBodyTok, "%varid%", condBodyTok->link(), loopVar->varId());
std::string algo;
if (loopVar2 ||
(isIteratorLoop && loopVar->variable() && precedes(loopVar->variable()->nameToken(), tok))) // iterator declared outside the loop
algo = "std::find_if";
else
algo = "std::any_of";
useStlAlgorithmError(condBodyTok, algo);
continue;
}
}
}
}
}
void CheckStl::knownEmptyContainerError(const Token *tok, const std::string& algo)
{
const std::string var = tok ? tok->expressionString() : std::string("var");
std::string msg;
if (astIsIterator(tok)) {
msg = "Using " + algo + " with iterator '" + var + "' that is always empty.";
} else {
msg = "Iterating over container '" + var + "' that is always empty.";
}
reportError(tok, Severity::style,
"knownEmptyContainer",
msg, CWE398, Certainty::normal);
}
static bool isKnownEmptyContainer(const Token* tok)
{
if (!tok)
return false;
return std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) {
if (!v.isKnown())
return false;
if (!v.isContainerSizeValue())
return false;
if (v.intvalue != 0)
return false;
return true;
});
}
void CheckStl::knownEmptyContainer()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownEmptyContainer"))
return;
logChecker("CheckStl::knownEmptyContainer"); // style
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%name% ( !!)"))
continue;
// Parse range-based for loop
if (tok->str() == "for") {
if (!Token::simpleMatch(tok->linkAt(1), ") {"))
continue;
const Token *splitTok = tok->next()->astOperand2();
if (!Token::simpleMatch(splitTok, ":"))
continue;
const Token* contTok = splitTok->astOperand2();
if (!isKnownEmptyContainer(contTok))
continue;
knownEmptyContainerError(contTok, emptyString);
} else {
const std::vector<const Token *> args = getArguments(tok);
if (args.empty())
continue;
for (int argnr = 1; argnr <= args.size(); ++argnr) {
const Library::ArgumentChecks::IteratorInfo *i = mSettings->library.getArgIteratorInfo(tok, argnr);
if (!i)
continue;
const Token * const argTok = args[argnr - 1];
if (!isKnownEmptyContainer(argTok))
continue;
knownEmptyContainerError(argTok, tok->str());
break;
}
}
}
}
}
void CheckStl::eraseIteratorOutOfBoundsError(const Token *ftok, const Token* itertok, const ValueFlow::Value* val)
{
if (!ftok || !itertok || !val) {
reportError(ftok, Severity::error, "eraseIteratorOutOfBounds",
"Calling function 'erase()' on the iterator 'iter' which is out of bounds.", CWE628, Certainty::normal);
reportError(ftok, Severity::warning, "eraseIteratorOutOfBoundsCond",
"Either the condition 'x' is redundant or function 'erase()' is called on the iterator 'iter' which is out of bounds.", CWE628, Certainty::normal);
return;
}
const std::string& func = ftok->str();
const std::string iter = itertok->expressionString();
const bool isConditional = val->isPossible();
std::string msg;
if (isConditional) {
msg = ValueFlow::eitherTheConditionIsRedundant(val->condition) + " or function '" + func + "()' is called on the iterator '" + iter + "' which is out of bounds.";
} else {
msg = "Calling function '" + func + "()' on the iterator '" + iter + "' which is out of bounds.";
}
const Severity severity = isConditional ? Severity::warning : Severity::error;
const std::string id = isConditional ? "eraseIteratorOutOfBoundsCond" : "eraseIteratorOutOfBounds";
reportError(ftok, severity,
id,
msg, CWE628, Certainty::normal);
}
static const ValueFlow::Value* getOOBIterValue(const Token* tok, const ValueFlow::Value* sizeVal)
{
auto it = std::find_if(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) {
if (v.isPossible() || v.isKnown()) {
switch (v.valueType) {
case ValueFlow::Value::ValueType::ITERATOR_END:
return v.intvalue >= 0;
case ValueFlow::Value::ValueType::ITERATOR_START:
return (v.intvalue < 0) || (sizeVal && v.intvalue >= sizeVal->intvalue);
default:
break;
}
}
return false;
});
return it != tok->values().end() ? &*it : nullptr;
}
void CheckStl::eraseIteratorOutOfBounds()
{
logChecker("CheckStl::eraseIteratorOutOfBounds");
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
if (!tok->valueType())
continue;
const Library::Container* container = tok->valueType()->container;
if (!container || !astIsLHS(tok) || !Token::simpleMatch(tok->astParent(), "."))
continue;
const Token* const ftok = tok->astParent()->astOperand2();
const Library::Container::Action action = container->getAction(ftok->str());
if (action != Library::Container::Action::ERASE)
continue;
const std::vector<const Token*> args = getArguments(ftok);
if (args.size() != 1) // TODO: check range overload
continue;
const ValueFlow::Value* sizeVal = tok->getKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE);
if (const ValueFlow::Value* errVal = getOOBIterValue(args[0], sizeVal))
eraseIteratorOutOfBoundsError(ftok, args[0], errVal);
}
}
}
static bool isMutex(const Variable* var)
{
const Token* tok = Token::typeDecl(var->nameToken()).first;
return Token::Match(tok, "std :: mutex|recursive_mutex|timed_mutex|recursive_timed_mutex|shared_mutex");
}
static bool isLockGuard(const Variable* var)
{
const Token* tok = Token::typeDecl(var->nameToken()).first;
return Token::Match(tok, "std :: lock_guard|unique_lock|scoped_lock|shared_lock");
}
static bool isLocalMutex(const Variable* var, const Scope* scope)
{
if (!var)
return false;
if (isLockGuard(var))
return false;
return !var->isReference() && !var->isRValueReference() && !var->isStatic() && var->scope() == scope;
}
void CheckStl::globalLockGuardError(const Token* tok)
{
reportError(tok, Severity::warning,
"globalLockGuard",
"Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.", CWE833, Certainty::normal);
}
void CheckStl::localMutexError(const Token* tok)
{
reportError(tok, Severity::warning,
"localMutex",
"The lock is ineffective because the mutex is locked at the same scope as the mutex itself.", CWE667, Certainty::normal);
}
void CheckStl::checkMutexes()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckStl::checkMutexes"); // warning
for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) {
std::set<nonneg int> checkedVars;
for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%var%"))
continue;
const Variable* var = tok->variable();
if (!var)
continue;
if (Token::Match(tok, "%var% . lock ( )")) {
if (!isMutex(var))
continue;
if (!checkedVars.insert(var->declarationId()).second)
continue;
if (isLocalMutex(var, tok->scope()))
localMutexError(tok);
} else if (Token::Match(tok, "%var% (|{ %var% )|}|,")) {
if (!isLockGuard(var))
continue;
const Variable* mvar = tok->tokAt(2)->variable();
if (!mvar)
continue;
if (!checkedVars.insert(mvar->declarationId()).second)
continue;
if (var->isStatic() || var->isGlobal())
globalLockGuardError(tok);
else if (isLocalMutex(mvar, tok->scope()))
localMutexError(tok);
}
}
}
}
| null |
851 | cpp | cppcheck | xml.h | lib/xml.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef xmlH
#define xmlH
#include "config.h"
#include "path.h"
#if defined(__GNUC__) && (__GNUC__ >= 14)
SUPPRESS_WARNING_GCC_PUSH("-Wsuggest-attribute=returns_nonnull")
#endif
SUPPRESS_WARNING_CLANG_PUSH("-Wzero-as-null-pointer-constant")
SUPPRESS_WARNING_CLANG_PUSH("-Wsuggest-destructor-override")
SUPPRESS_WARNING_CLANG_PUSH("-Winconsistent-missing-destructor-override")
SUPPRESS_WARNING_CLANG_PUSH("-Wformat") // happens with libc++ only
#include <tinyxml2.h> // IWYU pragma: export
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
SUPPRESS_WARNING_CLANG_POP
#if defined(__GNUC__) && (__GNUC__ >= 14)
SUPPRESS_WARNING_GCC_POP
#endif
inline static tinyxml2::XMLError xml_LoadFile(tinyxml2::XMLDocument& doc, const char* filename)
{
// tinyxml2 will fail with a misleading XML_ERROR_FILE_READ_ERROR when you try to load a directory as a XML file
if (Path::isDirectory(filename))
return tinyxml2::XMLError::XML_ERROR_FILE_NOT_FOUND;
return doc.LoadFile(filename);
}
#endif // xmlH
| null |
852 | cpp | cppcheck | checktype.h | lib/checktype.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checktypeH
#define checktypeH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include "vfvalue.h"
#include <list>
#include <string>
class ErrorLogger;
class Settings;
class Token;
class ValueType;
/// @addtogroup Checks
/// @{
/** @brief Various small checks */
class CPPCHECKLIB CheckType : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckType() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckType(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
// These are not "simplified" because casts can't be ignored
CheckType checkType(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkType.checkTooBigBitwiseShift();
checkType.checkIntegerOverflow();
checkType.checkSignConversion();
checkType.checkLongCast();
checkType.checkFloatToIntegerOverflow();
}
/** @brief %Check for bitwise shift with too big right operand */
void checkTooBigBitwiseShift();
/** @brief %Check for integer overflow */
void checkIntegerOverflow();
/** @brief %Check for dangerous sign conversion */
void checkSignConversion();
/** @brief %Check for implicit long cast of int result */
void checkLongCast();
/** @brief %Check for float to integer overflow */
void checkFloatToIntegerOverflow();
void checkFloatToIntegerOverflow(const Token *tok, const ValueType *vtint, const ValueType *vtfloat, const std::list<ValueFlow::Value> &floatValues);
// Error messages..
void tooBigBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits);
void tooBigSignedBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits);
void integerOverflowError(const Token *tok, const ValueFlow::Value &value, bool isOverflow = true);
void signConversionError(const Token *tok, const ValueFlow::Value *negativeValue, bool constvalue);
void longCastAssignError(const Token *tok, const ValueType* src = nullptr, const ValueType* tgt = nullptr);
void longCastReturnError(const Token *tok, const ValueType* src = nullptr, const ValueType* tgt = nullptr);
void floatToIntegerOverflowError(const Token *tok, const ValueFlow::Value &value);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckType c(nullptr, settings, errorLogger);
c.tooBigBitwiseShiftError(nullptr, 32, ValueFlow::Value(64));
c.tooBigSignedBitwiseShiftError(nullptr, 31, ValueFlow::Value(31));
c.integerOverflowError(nullptr, ValueFlow::Value(1LL<<32));
c.signConversionError(nullptr, nullptr, false);
c.longCastAssignError(nullptr);
c.longCastReturnError(nullptr);
ValueFlow::Value f;
f.valueType = ValueFlow::Value::ValueType::FLOAT;
f.floatValue = 1E100;
c.floatToIntegerOverflowError(nullptr, f);
}
static std::string myName() {
return "Type";
}
std::string classInfo() const override {
return "Type checks\n"
"- bitwise shift by too many bits (only enabled when --platform is used)\n"
"- signed integer overflow (only enabled when --platform is used)\n"
"- dangerous sign conversion, when signed value can be negative\n"
"- possible loss of information when assigning int result to long variable\n"
"- possible loss of information when returning int result as long return value\n"
"- float conversion overflow\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checktypeH
| null |
853 | cpp | cppcheck | tokenlist.h | lib/tokenlist.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef tokenlistH
#define tokenlistH
//---------------------------------------------------------------------------
#include "config.h"
#include "standards.h"
#include <cstddef>
#include <iosfwd>
#include <string>
#include <vector>
class Token;
class TokenList;
class Settings;
namespace simplecpp {
class TokenList;
}
/// @addtogroup Core
/// @{
/**
* @brief This struct stores pointers to the front and back tokens of the list this token is in.
*/
struct TokensFrontBack {
explicit TokensFrontBack(const TokenList& list) : list(list) {}
Token *front{};
Token* back{};
const TokenList& list;
};
class CPPCHECKLIB TokenList {
public:
// TODO: pass settings as reference
explicit TokenList(const Settings* settings);
~TokenList();
TokenList(const TokenList &) = delete;
TokenList &operator=(const TokenList &) = delete;
/** @return the source file path. e.g. "file.cpp" */
const std::string& getSourceFilePath() const;
/** @return true if the code is C */
bool isC() const;
/** @return true if the code is C++ */
bool isCPP() const;
// TODO: get rid of this
void setLang(Standards::Language lang, bool force = false);
/**
* Delete all tokens in given token list
* @param tok token list to delete
*/
static void deleteTokens(Token *tok);
void addtoken(const std::string& str, nonneg int lineno, nonneg int column, nonneg int fileno, bool split = false);
void addtoken(const std::string& str, const Token *locationTok);
void addtoken(const Token *tok, nonneg int lineno, nonneg int column, nonneg int fileno);
void addtoken(const Token *tok, const Token *locationTok);
void addtoken(const Token *tok);
static void insertTokens(Token *dest, const Token *src, nonneg int n);
/**
* Copy tokens.
* @param dest destination token where copied tokens will be inserted after
* @param first first token to copy
* @param last last token to copy
* @param one_line true=>copy all tokens to the same line as dest. false=>copy all tokens to dest while keeping the 'line breaks'
* @return new location of last token copied
*/
RET_NONNULL static Token *copyTokens(Token *dest, const Token *first, const Token *last, bool one_line = true);
/**
* Create tokens from code.
* The code must be preprocessed first:
* - multiline strings are not handled.
* - UTF in the code are not handled.
* - comments are not handled.
* @param code input stream for code
* @param file0 source file name
*/
bool createTokens(std::istream &code, const std::string& file0);
bool createTokens(std::istream &code, Standards::Language lang);
void createTokens(simplecpp::TokenList&& tokenList);
/** Deallocate list */
void deallocateTokens();
/** append file name if seen the first time; return its index in any case */
int appendFileIfNew(std::string fileName);
/** get first token of list */
const Token *front() const {
return mTokensFrontBack.front;
}
// NOLINTNEXTLINE(readability-make-member-function-const) - do not allow usage of mutable pointer from const object
Token *front() {
return mTokensFrontBack.front;
}
/** get last token of list */
const Token *back() const {
return mTokensFrontBack.back;
}
// NOLINTNEXTLINE(readability-make-member-function-const) - do not allow usage of mutable pointer from const object
Token *back() {
return mTokensFrontBack.back;
}
/**
* Get filenames (the sourcefile + the files it include).
* The first filename is the filename for the sourcefile
* @return vector with filenames
*/
const std::vector<std::string>& getFiles() const {
return mFiles;
}
std::string getOrigFile(const Token *tok) const;
/**
* get filename for given token
* @param tok The given token
* @return filename for the given token
*/
const std::string& file(const Token *tok) const;
/**
* Get file:line for a given token
* @param tok given token
* @return location for given token
*/
std::string fileLine(const Token *tok) const;
/**
* Calculates a hash of the token list used to compare multiple
* token lists with each other as quickly as possible.
*/
std::size_t calculateHash() const;
/**
* Create abstract syntax tree.
*/
void createAst() const;
/**
* Check abstract syntax tree.
* Throws InternalError on failure
*/
void validateAst(bool print) const;
/**
* Verify that the given token is an element of the tokenlist.
* That method is implemented for debugging purposes.
* @param[in] tok token to be checked
* \return true if token was found in tokenlist, false else. In case of nullptr true is returned.
*/
bool validateToken(const Token* tok) const;
/**
* Convert platform dependent types to standard types.
* 32 bits: size_t -> unsigned long
* 64 bits: size_t -> unsigned long long
*/
void simplifyPlatformTypes();
/**
* Collapse compound standard types into a single token.
* unsigned long long int => long _isUnsigned=true,_isLong=true
*/
void simplifyStdType();
void clangSetOrigFiles();
bool isKeyword(const std::string &str) const;
private:
void determineCppC();
bool createTokensInternal(std::istream &code, const std::string& file0);
/** Token list */
TokensFrontBack mTokensFrontBack;
/** filenames for the tokenized source code (source + included) */
std::vector<std::string> mFiles;
/** Original filenames for the tokenized source code (source + included) */
std::vector<std::string> mOrigFiles;
/** settings */
const Settings* const mSettings{};
/** File is known to be C/C++ code */
Standards::Language mLang{Standards::Language::None};
};
/// @}
const Token* isLambdaCaptureList(const Token* tok);
const Token* findLambdaEndTokenWithoutAST(const Token* tok);
//---------------------------------------------------------------------------
#endif // tokenlistH
| null |
854 | cpp | cppcheck | standards.h | lib/standards.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef standardsH
#define standardsH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <string>
/// @addtogroup Core
/// @{
/**
* @brief This is just a container for standards settings.
* This struct contains all possible standards that cppcheck recognize.
*/
struct CPPCHECKLIB Standards {
enum Language : std::uint8_t { None, C, CPP };
/** C code standard */
enum cstd_t : std::uint8_t { C89, C99, C11, C17, C23, CLatest = C23 } c = CLatest;
/** C++ code standard */
enum cppstd_t : std::uint8_t { CPP03, CPP11, CPP14, CPP17, CPP20, CPP23, CPP26, CPPLatest = CPP26 } cpp = CPPLatest;
/** --std value given on command line */
std::string stdValueC;
/** --std value given on command line */
std::string stdValueCPP;
bool setC(std::string str);
std::string getC() const;
static std::string getC(cstd_t c_std);
static cstd_t getC(const std::string &std);
bool setCPP(std::string str);
std::string getCPP() const;
static std::string getCPP(cppstd_t std);
static cppstd_t getCPP(const std::string &std);
bool setStd(const std::string& str);
};
/// @}
//---------------------------------------------------------------------------
#endif // standardsH
| null |
855 | cpp | cppcheck | checkuninitvar.cpp | lib/checkuninitvar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkuninitvar.h"
#include "astutils.h"
#include "ctu.h"
#include "errorlogger.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "checknullpointer.h" // CheckNullPointer::isPointerDeref
#include <algorithm>
#include <cassert>
#include <functional>
#include <initializer_list>
#include <list>
#include <map>
#include <unordered_set>
#include <vector>
//---------------------------------------------------------------------------
// CWE ids used:
static const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE(457U);
// Register this check class (by creating a static instance of it)
namespace {
CheckUninitVar instance;
}
//---------------------------------------------------------------------------
// get ast parent, skip possible address-of and casts
static const Token *getAstParentSkipPossibleCastAndAddressOf(const Token *vartok, bool *unknown)
{
if (unknown)
*unknown = false;
if (!vartok)
return nullptr;
const Token *parent = vartok->astParent();
while (Token::Match(parent, ".|::"))
parent = parent->astParent();
if (!parent)
return nullptr;
if (parent->isUnaryOp("&"))
parent = parent->astParent();
else if (parent->str() == "&" && vartok == parent->astOperand2() && Token::Match(parent->astOperand1()->previous(), "( %type% )")) {
parent = parent->astParent();
if (unknown)
*unknown = true;
}
while (parent && parent->isCast())
parent = parent->astParent();
return parent;
}
static std::map<nonneg int, VariableValue> getVariableValues(const Token* tok) {
std::map<nonneg int, VariableValue> ret;
if (!tok || !tok->scope()->isExecutable())
return ret;
while (tok && tok->str() != "{") {
if (tok->str() == "}") {
if (tok->link()->isBinaryOp())
tok = tok->link()->previous();
else
break;
}
if (Token::Match(tok, "%var% =|{") && tok->next()->isBinaryOp() && tok->varId() && ret.count(tok->varId()) == 0) {
const Token* rhs = tok->next()->astOperand2();
if (rhs && rhs->hasKnownIntValue())
ret[tok->varId()] = VariableValue(rhs->getKnownIntValue());
}
tok = tok->previous();
}
return ret;
}
bool CheckUninitVar::diag(const Token* tok)
{
if (!tok)
return true;
while (Token::Match(tok->astParent(), "*|&|."))
tok = tok->astParent();
return !mUninitDiags.insert(tok).second;
}
void CheckUninitVar::check()
{
logChecker("CheckUninitVar::check");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::set<std::string> arrayTypeDefs;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% [") && tok->variable() && Token::Match(tok->variable()->typeStartToken(), "%type% %var% ;"))
arrayTypeDefs.insert(tok->variable()->typeStartToken()->str());
}
// check every executable scope
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.isExecutable()) {
checkScope(&scope, arrayTypeDefs);
}
}
}
void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs)
{
for (const Variable &var : scope->varlist) {
if ((mTokenizer->isCPP() && var.type() && !var.isPointer() && var.type()->needInitialization != Type::NeedInitialization::True) ||
var.isStatic() || var.isExtern() || var.isReference())
continue;
// don't warn for try/catch exception variable
if (var.isThrow())
continue;
if (Token::Match(var.nameToken()->next(), "[({:]"))
continue;
if (Token::Match(var.nameToken(), "%name% =")) { // Variable is initialized, but Rhs might be not
checkRhs(var.nameToken(), var, NO_ALLOC, 0U, emptyString);
continue;
}
if (Token::Match(var.nameToken(), "%name% ) (") && Token::simpleMatch(var.nameToken()->linkAt(2), ") =")) { // Function pointer is initialized, but Rhs might be not
checkRhs(var.nameToken()->linkAt(2)->next(), var, NO_ALLOC, 0U, emptyString);
continue;
}
if (var.isArray() || var.isPointerToArray()) {
const Token *tok = var.nameToken()->next();
if (var.isPointerToArray())
tok = tok->next();
while (Token::simpleMatch(tok->link(), "] ["))
tok = tok->link()->next();
if (Token::Match(tok->link(), "] =|{|("))
continue;
}
bool stdtype = var.typeStartToken()->isC() && arrayTypeDefs.find(var.typeStartToken()->str()) == arrayTypeDefs.end();
const Token* tok = var.typeStartToken();
for (; tok != var.nameToken() && tok->str() != "<"; tok = tok->next()) {
if (tok->isStandardType() || tok->isEnumType())
stdtype = true;
}
if (var.isArray() && !stdtype) { // std::array
if (!(var.isStlType() && Token::simpleMatch(var.typeStartToken(), "std :: array") && var.valueType() &&
var.valueType()->containerTypeToken && var.valueType()->containerTypeToken->isStandardType()))
continue;
}
while (tok && tok->str() != ";")
tok = tok->next();
if (!tok)
continue;
if (tok->astParent() && Token::simpleMatch(tok->astParent()->previous(), "for (") && Token::simpleMatch(tok->astParent()->link()->next(), "{") &&
checkLoopBody(tok->astParent()->link()->next(), var, var.isArray() ? ARRAY : NO_ALLOC, emptyString, true))
continue;
if (var.isArray()) {
bool init = false;
for (const Token *parent = var.nameToken(); parent; parent = parent->astParent()) {
if (parent->str() == "=") {
init = true;
break;
}
}
if (!init) {
Alloc alloc = ARRAY;
std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken());
checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue);
}
continue;
}
if (stdtype || var.isPointer()) {
Alloc alloc = NO_ALLOC;
std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken());
checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue);
}
if (var.type())
checkStruct(tok, var);
}
if (scope->function) {
for (const Variable &arg : scope->function->argumentList) {
if (arg.declarationId() && Token::Match(arg.typeStartToken(), "%type% * %name% [,)]")) {
// Treat the pointer as initialized until it is assigned by malloc
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "[;{}] %varid% =", arg.declarationId()))
continue;
const Token *allocFuncCallToken = findAllocFuncCallToken(tok->tokAt(2)->astOperand2(), mSettings->library);
if (!allocFuncCallToken)
continue;
const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(allocFuncCallToken);
if (!allocFunc || allocFunc->initData)
continue;
if (arg.typeStartToken()->strAt(-1) == "struct" || (arg.type() && arg.type()->isStructType()))
checkStruct(tok, arg);
else if (arg.typeStartToken()->isStandardType() || arg.typeStartToken()->isEnumType()) {
Alloc alloc = NO_ALLOC;
std::map<nonneg int, VariableValue> variableValue;
checkScopeForVariable(tok->next(), arg, nullptr, nullptr, &alloc, emptyString, variableValue);
}
}
}
}
}
}
void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar)
{
const Token *typeToken = structvar.typeStartToken();
while (Token::Match(typeToken, "%name% ::"))
typeToken = typeToken->tokAt(2);
const SymbolDatabase * symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope2 : symbolDatabase->classAndStructScopes) {
if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) {
for (const Variable &var : scope2->varlist) {
if (var.isStatic() || var.hasDefault() || var.isArray() ||
(!mTokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::NeedInitialization::True)))
continue;
// is the variable declared in a inner union?
bool innerunion = false;
for (const Scope *innerScope : scope2->nestedList) {
if (innerScope->type == Scope::eUnion) {
if (var.typeStartToken()->linenr() >= innerScope->bodyStart->linenr() &&
var.typeStartToken()->linenr() <= innerScope->bodyEnd->linenr()) {
innerunion = true;
break;
}
}
}
if (!innerunion) {
Alloc alloc = NO_ALLOC;
const Token *tok2 = tok;
if (tok->str() == "}")
tok2 = tok2->next();
std::map<nonneg int, VariableValue> variableValue = getVariableValues(structvar.typeStartToken());
checkScopeForVariable(tok2, structvar, nullptr, nullptr, &alloc, var.name(), variableValue);
}
}
}
}
}
static VariableValue operator!(VariableValue v)
{
v.notEqual = !v.notEqual;
return v;
}
static bool operator==(const VariableValue & v, MathLib::bigint i)
{
return v.notEqual ? (i != v.value) : (i == v.value);
}
static bool operator!=(const VariableValue & v, MathLib::bigint i)
{
return v.notEqual ? (i == v.value) : (i != v.value);
}
static void conditionAlwaysTrueOrFalse(const Token *tok, const std::map<nonneg int, VariableValue> &variableValue, bool *alwaysTrue, bool *alwaysFalse)
{
if (!tok)
return;
if (tok->hasKnownIntValue()) {
if (tok->getKnownIntValue() == 0)
*alwaysFalse = true;
else
*alwaysTrue = true;
return;
}
if (tok->isName() || tok->str() == ".") {
while (tok && tok->str() == ".")
tok = tok->astOperand2();
const std::map<nonneg int, VariableValue>::const_iterator it = variableValue.find(tok ? tok->varId() : ~0U);
if (it != variableValue.end()) {
*alwaysTrue = (it->second != 0LL);
*alwaysFalse = (it->second == 0LL);
}
}
else if (tok->isComparisonOp()) {
if (variableValue.empty()) {
return;
}
const Token *vartok, *numtok;
if (tok->astOperand2() && tok->astOperand2()->isNumber()) {
vartok = tok->astOperand1();
numtok = tok->astOperand2();
} else if (tok->astOperand1() && tok->astOperand1()->isNumber()) {
vartok = tok->astOperand2();
numtok = tok->astOperand1();
} else {
return;
}
while (vartok && vartok->str() == ".")
vartok = vartok->astOperand2();
const std::map<nonneg int, VariableValue>::const_iterator it = variableValue.find(vartok ? vartok->varId() : ~0U);
if (it == variableValue.end())
return;
if (tok->str() == "==")
*alwaysTrue = (it->second == MathLib::toBigNumber(numtok->str()));
else if (tok->str() == "!=")
*alwaysTrue = (it->second != MathLib::toBigNumber(numtok->str()));
else
return;
*alwaysFalse = !(*alwaysTrue);
}
else if (tok->str() == "!") {
bool t=false,f=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t, &f);
if (t || f) {
*alwaysTrue = !t;
*alwaysFalse = !f;
}
}
else if (tok->str() == "||") {
bool t1=false, f1=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1);
bool t2=false, f2=false;
if (!t1)
conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2);
*alwaysTrue = (t1 || t2);
*alwaysFalse = (f1 && f2);
}
else if (tok->str() == "&&") {
bool t1=false, f1=false;
conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1);
bool t2=false, f2=false;
if (!f1)
conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2);
*alwaysTrue = (t1 && t2);
*alwaysFalse = (f1 || f2);
}
}
static bool isVariableUsed(const Token *tok, const Variable& var)
{
if (!tok)
return false;
if (tok->str() == "&" && !tok->astOperand2())
return false;
if (tok->isConstOp())
return isVariableUsed(tok->astOperand1(),var) || isVariableUsed(tok->astOperand2(),var);
if (tok->varId() != var.declarationId())
return false;
if (!var.isArray())
return true;
const Token *parent = tok->astParent();
while (Token::Match(parent, "[?:]"))
parent = parent->astParent();
// no dereference, then array is not "used"
if (!Token::Match(parent, "*|["))
return false;
const Token *parent2 = parent->astParent();
// TODO: handle function calls. There is a TODO assertion in TestUninitVar::uninitvar_arrays
return !parent2 || parent2->isConstOp() || (parent2->str() == "=" && parent2->astOperand2() == parent);
}
bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar, std::map<nonneg int, VariableValue>& variableValue)
{
const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable declaration, rather than a fundef
const bool printDebug = mSettings->debugwarnings;
if (possibleInit)
*possibleInit = false;
int number_of_if = 0;
if (var.declarationId() == 0U)
return true;
for (; tok; tok = tok->next()) {
// End of scope..
if (tok->str() == "}") {
if (number_of_if && possibleInit)
*possibleInit = true;
// might be a noreturn function..
if (mTokenizer->isScopeNoReturn(tok)) {
if (noreturn)
*noreturn = true;
return false;
}
break;
}
// Unconditional inner scope, try, lambda, init list
if (tok->str() == "{" && Token::Match(tok->previous(), ",|;|{|}|]|try")) {
bool possibleInitInner = false;
if (checkScopeForVariable(tok->next(), var, &possibleInitInner, noreturn, alloc, membervar, variableValue))
return true;
tok = tok->link();
if (possibleInitInner) {
number_of_if = 1;
if (possibleInit)
*possibleInit = true;
}
continue;
}
// track values of other variables..
if (Token::Match(tok->previous(), "[;{}.] %var% =")) {
if (tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue())
variableValue[tok->varId()] = VariableValue(tok->next()->astOperand2()->getKnownIntValue());
else if (Token::Match(tok->previous(), "[;{}] %var% = - %name% ;"))
variableValue[tok->varId()] = !VariableValue(0);
else
variableValue.erase(tok->varId());
}
// Inner scope..
else if (Token::simpleMatch(tok, "if (")) {
bool alwaysTrue = false;
bool alwaysFalse = false;
// Is variable assigned in condition?
if (!membervar.empty()) {
for (const Token *cond = tok->linkAt(1); cond != tok; cond = cond->previous()) {
if (cond->varId() == var.declarationId() && isMemberVariableAssignment(cond, membervar))
return true;
}
}
conditionAlwaysTrueOrFalse(tok->next()->astOperand2(), variableValue, &alwaysTrue, &alwaysFalse);
// initialization / usage in condition..
if (!alwaysTrue && checkIfForWhileHead(tok->next(), var, suppressErrors, (number_of_if == 0), *alloc, membervar))
return true;
// checking if a not-zero variable is zero => bail out
nonneg int condVarId = 0;
VariableValue condVarValue(0);
const Token *condVarTok = nullptr;
if (alwaysFalse)
;
else if (astIsVariableComparison(tok->next()->astOperand2(), "!=", "0", &condVarTok)) {
const std::map<nonneg int,VariableValue>::const_iterator it = variableValue.find(condVarTok->varId());
if (it != variableValue.cend() && it->second != 0)
return true; // this scope is not fully analysed => return true
condVarId = condVarTok->varId();
condVarValue = !VariableValue(0);
} else if (Token::Match(tok->next()->astOperand2(), "==|!=")) {
const Token *condition = tok->next()->astOperand2();
const Token *lhs = condition->astOperand1();
const Token *rhs = condition->astOperand2();
const Token *vartok = (lhs && lhs->hasKnownIntValue()) ? rhs : lhs;
const Token *numtok = (lhs == vartok) ? rhs : lhs;
while (Token::simpleMatch(vartok, "."))
vartok = vartok->astOperand2();
if (vartok && vartok->varId() && numtok && numtok->hasKnownIntValue()) {
const std::map<nonneg int,VariableValue>::const_iterator it = variableValue.find(vartok->varId());
if (it != variableValue.cend() && it->second != numtok->getKnownIntValue())
return true; // this scope is not fully analysed => return true
condVarId = vartok->varId();
condVarValue = VariableValue(numtok->getKnownIntValue());
if (condition->str() == "!=")
condVarValue = !condVarValue;
}
}
// goto the {
tok = tok->linkAt(1)->next();
if (!tok)
break;
if (tok->str() == "{") {
bool possibleInitIf((!alwaysTrue && number_of_if > 0) || suppressErrors);
bool noreturnIf = false;
std::map<nonneg int, VariableValue> varValueIf(variableValue);
const bool initif = !alwaysFalse && checkScopeForVariable(tok->next(), var, &possibleInitIf, &noreturnIf, alloc, membervar, varValueIf);
// bail out for such code:
// if (a) x=0; // conditional initialization
// if (b) return; // cppcheck doesn't know if b can be false when a is false.
// x++; // it's possible x is always initialized
if (!alwaysTrue && noreturnIf && number_of_if > 0) {
if (printDebug) {
std::string condition;
for (const Token *tok2 = tok->linkAt(-1); tok2 != tok; tok2 = tok2->next()) {
condition += tok2->str();
if (tok2->isName() && tok2->next()->isName())
condition += ' ';
}
reportError(tok, Severity::debug, "bailoutUninitVar", "bailout uninitialized variable checking for '" + var.name() + "'. can't determine if this condition can be false when previous condition is false: " + condition);
}
return true;
}
if (alwaysTrue && (initif || noreturnIf))
return true;
if (!alwaysFalse && !initif && !noreturnIf)
variableValue = varValueIf;
if (initif && condVarId > 0)
variableValue[condVarId] = !condVarValue;
// goto the }
tok = tok->link();
if (!Token::simpleMatch(tok, "} else {")) {
if (initif || possibleInitIf) {
++number_of_if;
if (number_of_if >= 2)
return true;
}
} else {
// goto the {
tok = tok->tokAt(2);
bool possibleInitElse((!alwaysFalse && number_of_if > 0) || suppressErrors);
bool noreturnElse = false;
std::map<nonneg int, VariableValue> varValueElse(variableValue);
const bool initelse = !alwaysTrue && checkScopeForVariable(tok->next(), var, &possibleInitElse, &noreturnElse, alloc, membervar, varValueElse);
if (!alwaysTrue && !initelse && !noreturnElse)
variableValue = varValueElse;
if (initelse && condVarId > 0 && !noreturnIf && !noreturnElse)
variableValue[condVarId] = condVarValue;
// goto the }
tok = tok->link();
if ((alwaysFalse || initif || noreturnIf) &&
(alwaysTrue || initelse || noreturnElse))
return true;
if (initif || initelse || possibleInitElse)
++number_of_if;
if (!initif && !noreturnIf)
variableValue.insert(varValueIf.cbegin(), varValueIf.cend());
if (!initelse && !noreturnElse)
variableValue.insert(varValueElse.cbegin(), varValueElse.cend());
}
}
}
// = { .. }
else if (Token::simpleMatch(tok, "= {") || (Token::Match(tok, "%name% {") && tok->variable() && tok == tok->variable()->nameToken())) {
// end token
const Token *end = tok->linkAt(1);
// If address of variable is taken in the block then bail out
if (var.isPointer() || var.isArray()) {
if (Token::findmatch(tok->tokAt(2), "%varid%", end, var.declarationId()))
return true;
} else if (Token::findmatch(tok->tokAt(2), "& %varid%", end, var.declarationId())) {
return true;
}
const Token *errorToken = nullptr;
visitAstNodes(tok->next(),
[&](const Token *child) {
if (child->isUnaryOp("&"))
return ChildrenToVisit::none;
if (child->str() == "," || child->str() == "{" || child->isConstOp())
return ChildrenToVisit::op1_and_op2;
if (child->str() == "." && Token::Match(child->astOperand1(), "%varid%", var.declarationId()) && child->astOperand2() && child->astOperand2()->str() == membervar) {
errorToken = child;
return ChildrenToVisit::done;
}
return ChildrenToVisit::none;
});
if (errorToken) {
uninitStructMemberError(errorToken->astOperand2(), errorToken->astOperand1()->str() + "." + membervar);
return true;
}
// Skip block
tok = end;
continue;
}
// skip sizeof / offsetof
if (isUnevaluated(tok))
tok = tok->linkAt(1);
// for/while..
else if (Token::Match(tok, "for|while (") || Token::simpleMatch(tok, "do {")) {
const bool forwhile = Token::Match(tok, "for|while (");
// is variable initialized in for-head?
if (forwhile && checkIfForWhileHead(tok->next(), var, tok->str() == "for", false, *alloc, membervar))
return true;
// goto the {
const Token *tok2 = forwhile ? tok->linkAt(1)->next() : tok->next();
if (tok2 && tok2->str() == "{") {
const bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors);
// variable is initialized in the loop..
if (init)
return true;
// is variable used in for-head?
bool initcond = false;
if (!suppressErrors) {
const Token *startCond = forwhile ? tok->next() : tok->linkAt(1)->tokAt(2);
initcond = checkIfForWhileHead(startCond, var, false, (number_of_if == 0), *alloc, membervar);
}
// goto "}"
tok = tok2->link();
// do-while => goto ")"
if (!forwhile) {
// Assert that the tokens are '} while ('
if (!Token::simpleMatch(tok, "} while (")) {
if (printDebug)
reportError(tok,Severity::debug,emptyString,"assertion failed '} while ('");
break;
}
// Goto ')'
tok = tok->linkAt(2);
if (!tok)
// bailout : invalid code / bad tokenizer
break;
if (initcond)
// variable is initialized in while-condition
return true;
}
}
}
// Unknown or unhandled inner scope
else if (Token::simpleMatch(tok, ") {") || (Token::Match(tok, "%name% {") && tok->str() != "try" && !(tok->variable() && tok == tok->variable()->nameToken()))) {
if (tok->str() == "struct" || tok->str() == "union") {
tok = tok->linkAt(1);
continue;
}
return true;
}
// bailout if there is ({
if (Token::simpleMatch(tok, "( {")) {
return true;
}
// bailout if there is assembler code or setjmp
if (Token::Match(tok, "asm|setjmp (")) {
return true;
}
// bailout if there is a goto label
if (Token::Match(tok, "[;{}] %name% :")) {
return true;
}
// bailout if there is a pointer to member
if (Token::Match(tok, "%varid% . *", var.declarationId())) {
return true;
}
if (tok->str() == "?") {
if (!tok->astOperand2())
return true;
const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
if (err)
uninitvarError(tok, var.nameToken()->str(), *alloc);
// Todo: skip expression if there is no error
return true;
}
if (Token::Match(tok, "return|break|continue|throw|goto")) {
if (noreturn)
*noreturn = true;
tok = tok->next();
while (tok && tok->str() != ";") {
// variable is seen..
if (tok->varId() == var.declarationId()) {
if (!membervar.empty()) {
if (!suppressErrors && Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && Token::Match(tok->next()->astParent(), "%cop%|return|throw|?"))
uninitStructMemberError(tok, tok->str() + "." + membervar);
else if (tok->isCpp() && !suppressErrors && Token::Match(tok, "%name%") && Token::Match(tok->astParent(), "return|throw|?")) {
if (std::any_of(tok->values().cbegin(), tok->values().cend(), [](const ValueFlow::Value& v) {
return v.isUninitValue() && !v.isInconclusive();
}))
uninitStructMemberError(tok, tok->str() + "." + membervar);
}
}
// Use variable
else if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc))
uninitvarError(tok, tok->str(), *alloc);
return true;
}
if (isUnevaluated(tok))
tok = tok->linkAt(1);
else if (tok->str() == "?") {
if (!tok->astOperand2())
return true;
const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
if (err)
uninitvarError(tok, var.nameToken()->str(), *alloc);
return true;
}
tok = tok->next();
}
return (noreturn == nullptr);
}
// variable is seen..
if (tok->varId() == var.declarationId()) {
// calling function that returns uninit data through pointer..
if (var.isPointer() && Token::simpleMatch(tok->next(), "=")) {
const Token *rhs = tok->next()->astOperand2();
while (rhs && rhs->isCast())
rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1();
if (rhs && Token::Match(rhs->previous(), "%name% (")) {
const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(rhs->astOperand1());
if (allocFunc && !allocFunc->initData) {
*alloc = NO_CTOR_CALL;
continue;
}
}
}
if (mTokenizer->isCPP() && var.isPointer() && (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType() || (var.type() && var.type()->needInitialization == Type::NeedInitialization::True)) && Token::simpleMatch(tok->next(), "= new")) {
*alloc = CTOR_CALL;
// type has constructor(s)
if (var.typeScope() && var.typeScope()->numConstructors > 0)
return true;
// standard or enum type: check if new initializes the allocated memory
if (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType()) {
// scalar new with initialization
if (Token::Match(tok->next(), "= new %type% ("))
return true;
// array new
if (Token::Match(tok->next(), "= new %type% [") && Token::simpleMatch(tok->linkAt(4), "] ("))
return true;
}
continue;
}
if (!membervar.empty()) {
if (isMemberVariableAssignment(tok, membervar)) {
checkRhs(tok, var, *alloc, number_of_if, membervar);
return true;
}
if (isMemberVariableUsage(tok, var.isPointer(), *alloc, membervar)) {
uninitStructMemberError(tok, tok->str() + "." + membervar);
return true;
}
if (Token::Match(tok->previous(), "[(,] %name% [,)]"))
return true;
if (Token::Match(tok->previous(), "= %var% . %var% ;") && membervar == tok->strAt(2))
return true;
} else {
// Use variable
if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc)) {
uninitvarError(tok, tok->str(), *alloc);
return true;
}
const Token *parent = tok;
while (parent->astParent() && ((astIsLHS(parent) && parent->astParent()->str() == "[") || parent->astParent()->isUnaryOp("*"))) {
parent = parent->astParent();
if (parent->str() == "[") {
if (const Token *errorToken = checkExpr(parent->astOperand2(), var, *alloc, number_of_if==0)) {
if (!suppressErrors)
uninitvarError(errorToken, errorToken->expressionString(), *alloc);
return true;
}
}
}
if (Token::simpleMatch(parent->astParent(), "=") && astIsLHS(parent)) {
const Token *eq = parent->astParent();
if (const Token *errorToken = checkExpr(eq->astOperand2(), var, *alloc, number_of_if==0)) {
if (!suppressErrors)
uninitvarError(errorToken, errorToken->expressionString(), *alloc);
return true;
}
}
// assume that variable is assigned
return true;
}
}
}
return false;
}
const Token* CheckUninitVar::checkExpr(const Token* tok, const Variable& var, const Alloc alloc, bool known, bool* bailout) const
{
if (!tok)
return nullptr;
if (isUnevaluated(tok->previous()))
return nullptr;
if (tok->astOperand1()) {
bool bailout1 = false;
const Token *errorToken = checkExpr(tok->astOperand1(), var, alloc, known, &bailout1);
if (bailout && bailout1)
*bailout = true;
if (errorToken)
return errorToken;
if ((bailout1 || !known) && Token::Match(tok, "%oror%|&&|?"))
return nullptr;
}
if (tok->astOperand2())
return checkExpr(tok->astOperand2(), var, alloc, known, bailout);
if (tok->varId() == var.declarationId()) {
const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc);
if (errorToken)
return errorToken;
if (bailout)
*bailout = true;
}
return nullptr;
}
bool CheckUninitVar::checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar)
{
const Token * const endpar = startparentheses->link();
if (Token::Match(startparentheses, "( ! %name% %oror%") && startparentheses->tokAt(2)->getValue(0))
suppressErrors = true;
for (const Token *tok = startparentheses->next(); tok && tok != endpar; tok = tok->next()) {
if (tok->varId() == var.declarationId()) {
if (Token::Match(tok, "%name% . %name%")) {
if (membervar.empty())
return true;
if (tok->strAt(2) == membervar) {
if (isMemberVariableAssignment(tok, membervar))
return true;
if (!suppressErrors && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
uninitStructMemberError(tok, tok->str() + "." + membervar);
}
continue;
}
if (const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc)) {
if (suppressErrors)
continue;
uninitvarError(errorToken, errorToken->expressionString(), alloc);
}
return true;
}
// skip sizeof / offsetof
if (isUnevaluated(tok))
tok = tok->linkAt(1);
if ((!isuninit || !membervar.empty()) && tok->str() == "&&")
suppressErrors = true;
}
return false;
}
/** recursively check loop, return error token */
const Token* CheckUninitVar::checkLoopBodyRecursive(const Token *start, const Variable& var, const Alloc alloc, const std::string &membervar, bool &bailout, bool &alwaysReturns) const
{
assert(start->str() == "{");
const Token *errorToken = nullptr;
const Token *const end = start->link();
for (const Token *tok = start->next(); tok != end; tok = tok->next()) {
// skip sizeof / offsetof
if (isUnevaluated(tok)) {
tok = tok->linkAt(1);
continue;
}
if (Token::Match(tok, "asm ( %str% ) ;")) {
bailout = true;
return nullptr;
}
// for loop; skip third expression until loop body has been analyzed..
if (tok->str() == ";" && Token::simpleMatch(tok->astParent(), ";") && Token::simpleMatch(tok->astParent()->astParent(), "(")) {
const Token *top = tok->astParent()->astParent();
if (!Token::simpleMatch(top->previous(), "for (") || !Token::simpleMatch(top->link(), ") {"))
continue;
const Token *bodyStart = top->link()->next();
const Token *errorToken1 = checkLoopBodyRecursive(bodyStart, var, alloc, membervar, bailout, alwaysReturns);
if (!errorToken)
errorToken = errorToken1;
bailout |= alwaysReturns;
if (bailout)
return nullptr;
}
// for loop; skip loop body if there is third expression
if (Token::simpleMatch(tok, ") {") &&
Token::simpleMatch(tok->link()->previous(), "for (") &&
Token::simpleMatch(tok->link()->astOperand2(), ";") &&
Token::simpleMatch(tok->link()->astOperand2()->astOperand2(), ";")) {
tok = tok->linkAt(1);
}
if (tok->str() == "{") {
// switch => bailout
if (tok->scope() && tok->scope()->type == Scope::ScopeType::eSwitch) {
bailout = true;
return nullptr;
}
bool alwaysReturnsUnused;
const Token *errorToken1 = checkLoopBodyRecursive(tok, var, alloc, membervar, bailout, alwaysReturnsUnused);
tok = tok->link();
if (Token::simpleMatch(tok, "} else {")) {
const Token *elseBody = tok->tokAt(2);
const Token *errorToken2 = checkLoopBodyRecursive(elseBody, var, alloc, membervar, bailout, alwaysReturnsUnused);
tok = elseBody->link();
if (errorToken1 && errorToken2)
return errorToken1;
if (errorToken2)
errorToken = errorToken2;
}
if (bailout)
return nullptr;
if (!errorToken)
errorToken = errorToken1;
}
if (Token::simpleMatch(tok, "return")) {
bool returnWithoutVar = true;
while (tok && !Token::simpleMatch(tok, ";")) {
if (tok->isVariable() && tok->variable() == &var) {
returnWithoutVar = false;
break;
}
tok = tok->next();
}
if (returnWithoutVar) {
alwaysReturns = true;
return nullptr;
}
}
if (!tok)
break;
if (tok->varId() != var.declarationId())
continue;
bool conditionalUsage = false;
for (const Token* parent = tok; parent; parent = parent->astParent()) {
if (Token::Match(parent->astParent(), "%oror%|&&|?") && astIsRHS(parent)) {
conditionalUsage = true;
break;
}
}
if (!membervar.empty()) {
if (isMemberVariableAssignment(tok, membervar)) {
bool assign = true;
bool rhs = false;
// Used for tracking if an ")" is inner or outer
const Token *rpar = nullptr;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "=")
rhs = true;
// Look at inner expressions but not outer expressions
if (!rpar && tok2->str() == "(")
rpar = tok2->link();
else if (tok2->str() == ")") {
// No rpar => this is an outer right parenthesis
if (!rpar)
break;
if (rpar == tok2)
rpar = nullptr;
}
if (tok2->str() == ";" || (!rpar && tok2->str() == ","))
break;
if (rhs && tok2->varId() == var.declarationId() && isMemberVariableUsage(tok2, var.isPointer(), alloc, membervar)) {
assign = false;
break;
}
}
if (assign) {
bailout = true;
return nullptr;
}
}
if (isMemberVariableUsage(tok, var.isPointer(), alloc, membervar)) {
if (!conditionalUsage)
return tok;
if (!errorToken)
errorToken = tok;
} else if (Token::Match(tok->previous(), "[(,] %name% [,)]")) {
bailout = true;
return nullptr;
}
} else {
if (const Token *errtok = isVariableUsage(tok, var.isPointer(), alloc)) {
if (!conditionalUsage)
return errtok;
if (!errorToken)
errorToken = errtok;
} else if (tok->strAt(1) == "=") {
bool varIsUsedInRhs = false;
visitAstNodes(tok->next()->astOperand2(), [&](const Token * t) {
if (!t)
return ChildrenToVisit::none;
if (t->varId() == var.declarationId()) {
varIsUsedInRhs = true;
return ChildrenToVisit::done;
}
if (isUnevaluated(t->previous()))
return ChildrenToVisit::none;
return ChildrenToVisit::op1_and_op2;
});
if (!varIsUsedInRhs) {
bailout = true;
return nullptr;
}
} else {
bailout = true;
return nullptr;
}
}
}
return errorToken;
}
bool CheckUninitVar::checkLoopBody(const Token *tok, const Variable& var, const Alloc alloc, const std::string &membervar, const bool suppressErrors)
{
bool bailout = false;
bool alwaysReturns = false;
const Token *errorToken = checkLoopBodyRecursive(tok, var, alloc, membervar, bailout, alwaysReturns);
if (!suppressErrors && !bailout && !alwaysReturns && errorToken) {
if (membervar.empty())
uninitvarError(errorToken, errorToken->expressionString(), alloc);
else
uninitStructMemberError(errorToken, errorToken->expressionString() + "." + membervar);
return true;
}
return bailout || alwaysReturns;
}
void CheckUninitVar::checkRhs(const Token *tok, const Variable &var, Alloc alloc, nonneg int number_of_if, const std::string &membervar)
{
bool rhs = false;
int indent = 0;
while (nullptr != (tok = tok->next())) {
if (tok->str() == "=")
rhs = true;
else if (rhs && tok->varId() == var.declarationId()) {
if (membervar.empty() && isVariableUsage(tok, var.isPointer(), alloc))
uninitvarError(tok, tok->str(), alloc);
else if (!membervar.empty() && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar))
uninitStructMemberError(tok, tok->str() + "." + membervar);
else if (Token::Match(tok, "%var% ="))
break;
else if (Token::Match(tok->previous(), "[(,&]"))
break;
} else if (tok->str() == ";" || (indent==0 && tok->str() == ","))
break;
else if (tok->str() == "(")
++indent;
else if (tok->str() == ")") {
if (indent == 0)
break;
--indent;
} else if (tok->str() == "?" && tok->astOperand2()) {
const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var);
const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var);
const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0);
if (err)
uninitvarError(tok, var.nameToken()->str(), alloc);
break;
} else if (isUnevaluated(tok))
tok = tok->linkAt(1);
}
}
static bool astIsLhs(const Token *tok)
{
return tok && tok->astParent() && tok == tok->astParent()->astOperand1();
}
static bool astIsRhs(const Token *tok)
{
return tok && tok->astParent() && tok == tok->astParent()->astOperand2();
}
static bool isVoidCast(const Token *tok)
{
return Token::simpleMatch(tok, "(") && tok->isCast() && tok->valueType() && tok->valueType()->type == ValueType::Type::VOID && tok->valueType()->pointer == 0;
}
const Token* CheckUninitVar::isVariableUsage(const Token *vartok, const Library& library, bool pointer, Alloc alloc, int indirect)
{
const bool cpp = vartok->isCpp();
const Token *valueExpr = vartok; // non-dereferenced , no address of value as variable
while (Token::Match(valueExpr->astParent(), ".|::") && astIsRhs(valueExpr))
valueExpr = valueExpr->astParent();
// stuff we ignore..
while (valueExpr->astParent()) {
// *&x
if (valueExpr->astParent()->isUnaryOp("&") && valueExpr->astParent()->astParent() && valueExpr->astParent()->astParent()->isUnaryOp("*"))
valueExpr = valueExpr->astParent()->astParent();
// (type &)x
else if (valueExpr->astParent()->isCast() && valueExpr->astParent()->isUnaryOp("(") && Token::simpleMatch(valueExpr->astParent()->link()->previous(), "& )"))
valueExpr = valueExpr->astParent();
// designated initializers: {.x | { ... , .x
else if (Token::simpleMatch(valueExpr->astParent(), ".") &&
Token::Match(valueExpr->astParent()->previous(), ",|{"))
valueExpr = valueExpr->astParent();
else
break;
}
if (!pointer) {
if (Token::Match(vartok, "%name% [.(]") && vartok->variable() && !vartok->variable()->isPointer())
return nullptr;
while (Token::simpleMatch(valueExpr->astParent(), ".") && astIsLhs(valueExpr) && valueExpr->astParent()->valueType() && valueExpr->astParent()->valueType()->pointer == 0)
valueExpr = valueExpr->astParent();
}
const Token *derefValue = nullptr; // dereferenced value expression
if (alloc != NO_ALLOC) {
const int arrayDim = (vartok->variable() && vartok->variable()->isArray()) ? vartok->variable()->dimensions().size() : 1;
int deref = 0;
derefValue = valueExpr;
while (Token::Match(derefValue->astParent(), "+|-|*|[|.") ||
(derefValue->astParent() && derefValue->astParent()->isCast()) ||
(deref < arrayDim && Token::simpleMatch(derefValue->astParent(), "&") && derefValue->astParent()->isBinaryOp())) {
const Token * const derefValueParent = derefValue->astParent();
if (derefValueParent->str() == "*") {
if (derefValueParent->isUnaryOp("*"))
++deref;
else
break;
} else if (derefValueParent->str() == "[") {
if (astIsLhs(derefValue))
++deref;
else
break;
} else if (Token::Match(derefValueParent, "[+-]")) {
if (deref >= arrayDim)
break;
} else if (derefValueParent->str() == ".")
++deref;
derefValue = derefValueParent;
if (deref < arrayDim)
valueExpr = derefValue;
}
if (deref < arrayDim) {
// todo compare deref with array dimensions
derefValue = nullptr;
}
} else if (vartok->astParent() && vartok->astParent()->isUnaryOp("&")) {
const Token *child = vartok->astParent();
const Token *parent = child->astParent();
while (parent && (parent->isCast() || parent->str() == "+")) {
child = parent;
parent = child->astParent();
}
if (parent && (parent->isUnaryOp("*") || (parent->str() == "[" && astIsLhs(child))))
derefValue = parent;
}
if (!valueExpr->astParent())
return nullptr;
// FIXME handle address of!!
if (derefValue && derefValue->astParent() && derefValue->astParent()->isUnaryOp("&"))
return nullptr;
// BAILOUT for binary & without parent
if (Token::simpleMatch(valueExpr->astParent(), "&") && astIsRhs(valueExpr) && Token::Match(valueExpr->astParent()->tokAt(-3), "( %name% ) &"))
return nullptr;
// safe operations
if (isVoidCast(valueExpr->astParent()))
return nullptr;
if (Token::simpleMatch(valueExpr->astParent(), ".")) {
const Token *parent = valueExpr->astParent();
while (Token::simpleMatch(parent, "."))
parent = parent->astParent();
if (isVoidCast(parent))
return nullptr;
}
if (alloc != NO_ALLOC) {
if (Token::Match(valueExpr->astParent(), "%comp%|%oror%|&&|?|!"))
return nullptr;
if (Token::Match(valueExpr->astParent(), "%or%|&") && valueExpr->astParent()->isBinaryOp())
return nullptr;
if (alloc == CTOR_CALL && derefValue && Token::simpleMatch(derefValue->astParent(), "(") && astIsLhs(derefValue))
return nullptr;
if (Token::simpleMatch(valueExpr->astParent(), "return"))
return nullptr;
}
// Passing variable to function..
if (Token::Match(valueExpr->astParent(), "[(,]") && (valueExpr->astParent()->str() == "," || astIsRhs(valueExpr))) {
const Token *parent = valueExpr->astParent();
while (Token::simpleMatch(parent, ","))
parent = parent->astParent();
if (Token::simpleMatch(parent, "{"))
return valueExpr;
const int use = isFunctionParUsage(valueExpr, library, pointer, alloc, indirect);
return (use>0) ? valueExpr : nullptr;
}
if (derefValue && Token::Match(derefValue->astParent(), "[(,]") && (derefValue->astParent()->str() == "," || astIsRhs(derefValue))) {
const int use = isFunctionParUsage(derefValue, library, false, NO_ALLOC, indirect);
return (use>0) ? derefValue : nullptr;
}
if (valueExpr->astParent()->isUnaryOp("&")) {
const Token *parent = valueExpr->astParent();
if (Token::Match(parent->astParent(), "[(,]") && (parent->astParent()->str() == "," || astIsRhs(parent))) {
const int use = isFunctionParUsage(valueExpr, library, pointer, alloc, indirect);
return (use>0) ? valueExpr : nullptr;
}
return nullptr;
}
// Assignments;
// * Is this LHS in assignment
// * Passing address in RHS to pointer variable
{
const Token *tok = derefValue ? derefValue : valueExpr;
if (alloc == NO_ALLOC) {
while (tok->valueType() && tok->valueType()->pointer == 0 && Token::simpleMatch(tok->astParent(), "."))
tok = tok->astParent();
}
if (Token::simpleMatch(tok->astParent(), "=")) {
if (astIsLhs(tok)) {
if (alloc == ARRAY || !derefValue || !derefValue->isUnaryOp("*") || !pointer)
return nullptr;
const Token* deref = derefValue->astOperand1();
while (deref && deref->isCast())
deref = deref->astOperand1();
if (deref == vartok || Token::simpleMatch(deref, "+"))
return nullptr;
}
if (alloc != NO_ALLOC && astIsRhs(valueExpr))
return nullptr;
}
}
// Initialize reference variable
if (Token::Match((derefValue ? derefValue : vartok)->astParent(), "(|=") && astIsRhs(derefValue ? derefValue : vartok)) {
const Token *rhstok = derefValue ? derefValue : vartok;
const Token *lhstok = rhstok->astParent()->astOperand1();
const Variable *lhsvar = lhstok ? lhstok->variable() : nullptr;
if (lhsvar && lhsvar->isReference() && lhsvar->nameToken() == lhstok)
return nullptr;
}
// range for loop
if (Token::simpleMatch(valueExpr->astParent(), ":") &&
valueExpr->astParent()->astParent() &&
Token::simpleMatch(valueExpr->astParent()->astParent()->previous(), "for (")) {
if (astIsLhs(valueExpr))
return nullptr;
// Taking value by reference?
const Token *lhs = valueExpr->astParent()->astOperand1();
if (lhs && lhs->variable() && lhs->variable()->nameToken() == lhs && lhs->variable()->isReference())
return nullptr;
}
// Stream read/write
// FIXME this code is a hack!!
if (cpp && Token::Match(valueExpr->astParent(), "<<|>>")) {
if (isLikelyStreamRead(vartok->previous()))
return nullptr;
if (const auto* vt = valueExpr->valueType()) {
if (vt->type == ValueType::Type::VOID)
return nullptr;
// passing a char* to a stream will dereference it
if ((alloc == CTOR_CALL || alloc == ARRAY) && vt->pointer && vt->type != ValueType::Type::CHAR && vt->type != ValueType::Type::WCHAR_T)
return nullptr;
}
}
if (astIsRhs(derefValue) && isLikelyStreamRead(derefValue->astParent()))
return nullptr;
// Assignment with overloaded &
if (cpp && Token::simpleMatch(valueExpr->astParent(), "&") && astIsRhs(valueExpr)) {
const Token *parent = valueExpr->astParent();
while (Token::simpleMatch(parent, "&") && parent->isBinaryOp())
parent = parent->astParent();
if (!parent) {
const Token *lhs = valueExpr->astParent();
while (Token::simpleMatch(lhs, "&") && lhs->isBinaryOp())
lhs = lhs->astOperand1();
if (lhs && lhs->isName() && (!lhs->valueType() || lhs->valueType()->type <= ValueType::Type::CONTAINER))
return nullptr; // <- possible assignment
}
}
return derefValue ? derefValue : valueExpr;
}
const Token* CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect) const
{
return isVariableUsage(vartok, mSettings->library, pointer, alloc, indirect);
}
/***
* Is function parameter "used" so a "usage of uninitialized variable" can
* be written? If parameter is passed "by value" then it is "used". If it
* is passed "by reference" then it is not necessarily "used".
* @return -1 => unknown 0 => not used 1 => used
*/
int CheckUninitVar::isFunctionParUsage(const Token *vartok, const Library& library, bool pointer, Alloc alloc, int indirect)
{
bool unknown = false;
const Token *parent = getAstParentSkipPossibleCastAndAddressOf(vartok, &unknown);
if (unknown || !Token::Match(parent, "[(,]"))
return -1;
// locate start parentheses in function call..
int argumentNumber = 0;
const Token *start = vartok;
while (start && !Token::Match(start, "[;{}(]")) {
if (start->str() == ")")
start = start->link();
else if (start->str() == ",")
++argumentNumber;
start = start->previous();
}
if (!start)
return -1;
if (Token::simpleMatch(start->link(), ") {") && Token::Match(start->previous(), "if|for|while|switch"))
return (!pointer || alloc == NO_ALLOC);
// is this a function call?
if (Token::Match(start->previous(), "%name% (")) {
const bool address(vartok->strAt(-1) == "&");
const bool array(vartok->variable() && vartok->variable()->isArray());
// check how function handle uninitialized data arguments..
const Function *func = start->previous()->function();
if (func) {
const Variable *arg = func->getArgumentVar(argumentNumber);
if (arg) {
const Token *argStart = arg->typeStartToken();
if (!address && !array && Token::Match(argStart, "%type% %name%| [,)]"))
return 1;
if (pointer && !address && alloc == NO_ALLOC && Token::Match(argStart, "%type% * %name% [,)]"))
return 1;
while (argStart->previous() && argStart->previous()->isName())
argStart = argStart->previous();
if (Token::Match(argStart, "const %type% & %name% [,)]")) {
// If it's a record it's ok to pass a partially uninitialized struct.
if (vartok->variable() && vartok->variable()->valueType() && vartok->variable()->valueType()->type == ValueType::Type::RECORD)
return -1;
return 1;
}
if ((pointer || address) && Token::Match(argStart, "const %type% %name% [") && Token::Match(argStart->linkAt(3), "] [,)]"))
return 1;
}
} else if (Token::Match(start->previous(), "if|while|for")) {
// control-flow statement reading the variable "by value"
return alloc == NO_ALLOC;
} else {
const bool isnullbad = library.isnullargbad(start->previous(), argumentNumber + 1);
if (indirect == 0 && pointer && !address && isnullbad && alloc == NO_ALLOC)
return 1;
bool hasIndirect = false;
const bool isuninitbad = library.isuninitargbad(start->previous(), argumentNumber + 1, indirect, &hasIndirect);
if (alloc != NO_ALLOC)
return (isnullbad || hasIndirect) && isuninitbad;
return isuninitbad && (!address || isnullbad);
}
}
// unknown
return -1;
}
int CheckUninitVar::isFunctionParUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect) const
{
return CheckUninitVar::isFunctionParUsage(vartok, mSettings->library, pointer, alloc, indirect);
}
bool CheckUninitVar::isMemberVariableAssignment(const Token *tok, const std::string &membervar) const
{
if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar) {
if (Token::Match(tok->tokAt(3), "[=.[]"))
return true;
if (Token::Match(tok->tokAt(-2), "[(,=] &"))
return true;
if (isLikelyStreamRead(tok->previous()))
return true;
if ((tok->previous() && tok->previous()->isConstOp()) || Token::Match(tok->previous(), "[|="))
; // member variable usage
else if (tok->tokAt(3)->isConstOp())
; // member variable usage
else if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") &&
1 == isFunctionParUsage(tok, false, NO_ALLOC)) {
return false;
} else
return true;
} else if (tok->strAt(1) == "=")
return true;
else if (Token::Match(tok, "%var% . %name% (")) {
const Token *ftok = tok->tokAt(2);
if (!ftok->function() || !ftok->function()->isConst())
// TODO: Try to determine if membervar is assigned in method
return true;
} else if (tok->strAt(-1) == "&") {
if (Token::Match(tok->tokAt(-2), "[(,] & %name%")) {
// locate start parentheses in function call..
int argumentNumber = 0;
const Token *ftok = tok;
while (ftok && !Token::Match(ftok, "[;{}(]")) {
if (ftok->str() == ")")
ftok = ftok->link();
else if (ftok->str() == ",")
++argumentNumber;
ftok = ftok->previous();
}
// is this a function call?
ftok = ftok ? ftok->previous() : nullptr;
if (Token::Match(ftok, "%name% (")) {
// check how function handle uninitialized data arguments..
const Function *function = ftok->function();
if (!function && mSettings) {
// Function definition not seen, check if direction is specified in the library configuration
const Library::ArgumentChecks::Direction argDirection = mSettings->library.getArgDirection(ftok, 1 + argumentNumber);
if (argDirection == Library::ArgumentChecks::Direction::DIR_IN)
return false;
if (argDirection == Library::ArgumentChecks::Direction::DIR_OUT)
return true;
}
const Variable *arg = function ? function->getArgumentVar(argumentNumber) : nullptr;
const Token *argStart = arg ? arg->typeStartToken() : nullptr;
while (argStart && argStart->previous() && argStart->previous()->isName())
argStart = argStart->previous();
if (Token::Match(argStart, "const struct| %type% * const| %name% [,)]"))
return false;
}
else if (ftok && Token::simpleMatch(ftok->previous(), "= * ("))
return false;
}
return true;
}
return false;
}
bool CheckUninitVar::isMemberVariableUsage(const Token *tok, bool isPointer, Alloc alloc, const std::string &membervar) const
{
if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") &&
tok->strAt(2) == membervar) {
const int use = isFunctionParUsage(tok, isPointer, alloc);
if (use == 1)
return true;
}
if (isMemberVariableAssignment(tok, membervar))
return false;
if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && !(tok->tokAt(-2)->variable() && tok->tokAt(-2)->variable()->isReference())) {
const Token *parent = tok->next()->astParent();
return !parent || !parent->isUnaryOp("&");
}
if (!isPointer && !Token::simpleMatch(tok->astParent(), ".") && Token::Match(tok->previous(), "[(,] %name% [,)]") && isVariableUsage(tok, isPointer, alloc))
return true;
if (!isPointer && Token::Match(tok->previous(), "= %name% ;")) {
const Token* lhs = tok->previous()->astOperand1();
return !(lhs && lhs->variable() && lhs->variable()->isReference() && lhs == lhs->variable()->nameToken());
}
// = *(&var);
if (!isPointer &&
Token::simpleMatch(tok->astParent(),"&") &&
Token::simpleMatch(tok->astParent()->astParent(),"*") &&
Token::Match(tok->astParent()->astParent()->astParent(), "= * (| &") &&
tok->astParent()->astParent()->astParent()->astOperand2() == tok->astParent()->astParent())
return true;
// TODO: this used to be experimental - enable or remove see #5586
if ((false) && // NOLINT(readability-simplify-boolean-expr)
!isPointer &&
Token::Match(tok->tokAt(-2), "[(,] & %name% [,)]") &&
isVariableUsage(tok, isPointer, alloc))
return true;
return false;
}
void CheckUninitVar::uninitdataError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::error, "uninitdata", "$symbol:" + varname + "\nMemory is allocated but not initialized: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal);
}
void CheckUninitVar::uninitvarError(const Token *tok, const std::string &varname, ErrorPath errorPath)
{
if (diag(tok))
return;
errorPath.emplace_back(tok, "");
reportError(errorPath,
Severity::error,
"legacyUninitvar",
"$symbol:" + varname + "\nUninitialized variable: $symbol",
CWE_USE_OF_UNINITIALIZED_VARIABLE,
Certainty::normal);
}
void CheckUninitVar::uninitvarError(const Token* tok, const ValueFlow::Value& v)
{
if (!mSettings->isEnabled(&v))
return;
if (diag(tok))
return;
const Token* ltok = tok;
if (tok && Token::simpleMatch(tok->astParent(), ".") && astIsRHS(tok))
ltok = tok->astParent();
const std::string& varname = ltok ? ltok->expressionString() : "x";
ErrorPath errorPath = v.errorPath;
errorPath.emplace_back(tok, "");
auto severity = v.isKnown() ? Severity::error : Severity::warning;
auto certainty = v.isInconclusive() ? Certainty::inconclusive : Certainty::normal;
if (v.subexpressions.empty()) {
reportError(errorPath,
severity,
"uninitvar",
"$symbol:" + varname + "\nUninitialized variable: $symbol",
CWE_USE_OF_UNINITIALIZED_VARIABLE,
certainty);
return;
}
std::string vars = v.subexpressions.size() == 1 ? "variable: " : "variables: ";
std::string prefix;
for (const std::string& var : v.subexpressions) {
vars += prefix + varname + "." + var;
prefix = ", ";
}
reportError(errorPath,
severity,
"uninitvar",
"$symbol:" + varname + "\nUninitialized " + vars,
CWE_USE_OF_UNINITIALIZED_VARIABLE,
certainty);
}
void CheckUninitVar::uninitStructMemberError(const Token *tok, const std::string &membername)
{
reportError(tok,
Severity::error,
"uninitStructMember",
"$symbol:" + membername + "\nUninitialized struct member: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal);
}
void CheckUninitVar::valueFlowUninit()
{
logChecker("CheckUninitVar::valueFlowUninit");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
std::unordered_set<nonneg int> ids;
for (const bool subfunction : {false, true}) {
// check every executable scope
for (const Scope* scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (isUnevaluated(tok)) {
tok = tok->linkAt(1);
continue;
}
if (ids.count(tok->exprId()) > 0)
continue;
if (!tok->variable() && !tok->isUnaryOp("*") && !tok->isUnaryOp("&"))
continue;
if (Token::Match(tok, "%name% ("))
continue;
const Token* parent = tok->astParent();
while (Token::simpleMatch(parent, "."))
parent = parent->astParent();
if (parent && parent->isUnaryOp("&"))
continue;
if (isVoidCast(parent))
continue;
auto v = std::find_if(
tok->values().cbegin(), tok->values().cend(), std::mem_fn(&ValueFlow::Value::isUninitValue));
if (v == tok->values().cend())
continue;
if (v->tokvalue && ids.count(v->tokvalue->exprId()) > 0)
continue;
if (subfunction == (v->path == 0))
continue;
if (v->isInconclusive())
continue;
if (v->indirect > 1 || v->indirect < 0)
continue;
bool uninitderef = false;
if (tok->variable()) {
bool unknown;
const bool isarray = tok->variable()->isArray();
if (isarray && tok->variable()->isMember())
continue; // Todo: this is a bailout
if (isarray && tok->variable()->isStlType() && Token::simpleMatch(tok->astParent(), ".")) {
const auto yield = astContainerYield(tok);
if (yield != Library::Container::Yield::AT_INDEX && yield != Library::Container::Yield::ITEM)
continue;
}
const bool deref = CheckNullPointer::isPointerDeRef(tok, unknown, *mSettings);
uninitderef = deref && v->indirect == 0;
const bool isleaf = isLeafDot(tok) || uninitderef;
if (!isleaf && Token::Match(tok->astParent(), ". %name%") && (tok->astParent()->next()->varId() || tok->astParent()->next()->isEnumerator()))
continue;
}
const ExprUsage usage = getExprUsage(tok, v->indirect, *mSettings);
if (usage == ExprUsage::NotUsed || usage == ExprUsage::Inconclusive)
continue;
if (!v->subexpressions.empty() && usage == ExprUsage::PassedByReference)
continue;
if (usage != ExprUsage::Used) {
if (!(Token::Match(tok->astParent(), ". %name% (|[") && uninitderef) &&
isVariableChanged(tok, v->indirect, *mSettings))
continue;
bool inconclusive = false;
if (isVariableChangedByFunctionCall(tok, v->indirect, *mSettings, &inconclusive) || inconclusive)
continue;
}
uninitvarError(tok, *v);
ids.insert(tok->exprId());
if (v->tokvalue)
ids.insert(v->tokvalue->exprId());
}
}
}
}
// NOLINTNEXTLINE(readability-non-const-parameter) - used as callback so we need to preserve the signature
static bool isVariableUsage(const Settings &settings, const Token *vartok, MathLib::bigint *value)
{
(void)value;
return CheckUninitVar::isVariableUsage(vartok, settings.library, true, CheckUninitVar::Alloc::ARRAY);
}
// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now
// see https://trac.cppcheck.net/ticket/12108 for more details
#ifdef __clang__
inline namespace CheckUninitVar_internal
#else
namespace
#endif
{
/* data for multifile checking */
class MyFileInfo : public Check::FileInfo {
public:
/** function arguments that data are unconditionally read */
std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage;
/** Convert data into xml string */
std::string toString() const override
{
return CTU::toString(unsafeUsage);
}
};
}
Check::FileInfo *CheckUninitVar::getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const
{
const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::getUnsafeUsage(tokenizer, settings, ::isVariableUsage);
if (unsafeUsage.empty())
return nullptr;
auto *fileInfo = new MyFileInfo;
fileInfo->unsafeUsage = unsafeUsage;
return fileInfo;
}
Check::FileInfo * CheckUninitVar::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const
{
const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::loadUnsafeUsageListFromXml(xmlElement);
if (unsafeUsage.empty())
return nullptr;
auto *fileInfo = new MyFileInfo;
fileInfo->unsafeUsage = unsafeUsage;
return fileInfo;
}
bool CheckUninitVar::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger)
{
if (!ctu)
return false;
bool foundErrors = false;
(void)settings; // This argument is unused
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap();
for (const Check::FileInfo* fi1 : fileInfo) {
const auto *fi = dynamic_cast<const MyFileInfo*>(fi1);
if (!fi)
continue;
for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) {
const CTU::FileInfo::FunctionCall *functionCall = nullptr;
const std::list<ErrorMessage::FileLocation> &locationList =
CTU::FileInfo::getErrorPath(CTU::FileInfo::InvalidValueType::uninit,
unsafeUsage,
callsMap,
"Using argument ARG",
&functionCall,
false,
settings.maxCtuDepth);
if (locationList.empty())
continue;
const ErrorMessage errmsg(locationList,
emptyString,
Severity::error,
"Using argument " + unsafeUsage.myArgumentName + " that points at uninitialized variable " + functionCall->callArgumentExpression,
"ctuuninitvar",
CWE_USE_OF_UNINITIALIZED_VARIABLE,
Certainty::normal);
errorLogger.reportErr(errmsg);
foundErrors = true;
}
}
return foundErrors;
}
| null |
856 | cpp | cppcheck | clangimport.cpp | lib/clangimport.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "clangimport.h"
#include "errortypes.h"
#include "mathlib.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <memory>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <numeric>
static const std::string AccessSpecDecl = "AccessSpecDecl";
static const std::string ArraySubscriptExpr = "ArraySubscriptExpr";
static const std::string BinaryOperator = "BinaryOperator";
static const std::string BreakStmt = "BreakStmt";
static const std::string CallExpr = "CallExpr";
static const std::string CaseStmt = "CaseStmt";
static const std::string CharacterLiteral = "CharacterLiteral";
static const std::string ClassTemplateDecl = "ClassTemplateDecl";
static const std::string ClassTemplateSpecializationDecl = "ClassTemplateSpecializationDecl";
static const std::string ConditionalOperator = "ConditionalOperator";
static const std::string ConstantExpr = "ConstantExpr";
static const std::string CompoundAssignOperator = "CompoundAssignOperator";
static const std::string CompoundStmt = "CompoundStmt";
static const std::string ContinueStmt = "ContinueStmt";
static const std::string CStyleCastExpr = "CStyleCastExpr";
static const std::string CXXBindTemporaryExpr = "CXXBindTemporaryExpr";
static const std::string CXXBoolLiteralExpr = "CXXBoolLiteralExpr";
static const std::string CXXConstructorDecl = "CXXConstructorDecl";
static const std::string CXXConstructExpr = "CXXConstructExpr";
static const std::string CXXDefaultArgExpr = "CXXDefaultArgExpr";
static const std::string CXXDeleteExpr = "CXXDeleteExpr";
static const std::string CXXDestructorDecl = "CXXDestructorDecl";
static const std::string CXXForRangeStmt = "CXXForRangeStmt";
static const std::string CXXFunctionalCastExpr = "CXXFunctionalCastExpr";
static const std::string CXXMemberCallExpr = "CXXMemberCallExpr";
static const std::string CXXMethodDecl = "CXXMethodDecl";
static const std::string CXXNewExpr = "CXXNewExpr";
static const std::string CXXNullPtrLiteralExpr = "CXXNullPtrLiteralExpr";
static const std::string CXXOperatorCallExpr = "CXXOperatorCallExpr";
static const std::string CXXRecordDecl = "CXXRecordDecl";
static const std::string CXXStaticCastExpr = "CXXStaticCastExpr";
static const std::string CXXStdInitializerListExpr = "CXXStdInitializerListExpr";
static const std::string CXXTemporaryObjectExpr = "CXXTemporaryObjectExpr";
static const std::string CXXThisExpr = "CXXThisExpr";
static const std::string CXXThrowExpr = "CXXThrowExpr";
static const std::string DeclRefExpr = "DeclRefExpr";
static const std::string DeclStmt = "DeclStmt";
static const std::string DefaultStmt = "DefaultStmt";
static const std::string DoStmt = "DoStmt";
static const std::string EnumConstantDecl = "EnumConstantDecl";
static const std::string EnumDecl = "EnumDecl";
static const std::string ExprWithCleanups = "ExprWithCleanups";
static const std::string FieldDecl = "FieldDecl";
static const std::string FloatingLiteral = "FloatingLiteral";
static const std::string ForStmt = "ForStmt";
static const std::string FunctionDecl = "FunctionDecl";
static const std::string FunctionTemplateDecl = "FunctionTemplateDecl";
static const std::string GotoStmt = "GotoStmt";
static const std::string IfStmt = "IfStmt";
static const std::string ImplicitCastExpr = "ImplicitCastExpr";
static const std::string InitListExpr = "InitListExpr";
static const std::string IntegerLiteral = "IntegerLiteral";
static const std::string LabelStmt = "LabelStmt";
static const std::string LinkageSpecDecl = "LinkageSpecDecl";
static const std::string MaterializeTemporaryExpr = "MaterializeTemporaryExpr";
static const std::string MemberExpr = "MemberExpr";
static const std::string NamespaceDecl = "NamespaceDecl";
static const std::string NullStmt = "NullStmt";
static const std::string ParenExpr = "ParenExpr";
static const std::string ParmVarDecl = "ParmVarDecl";
static const std::string RecordDecl = "RecordDecl";
static const std::string ReturnStmt = "ReturnStmt";
static const std::string StringLiteral = "StringLiteral";
static const std::string SwitchStmt = "SwitchStmt";
static const std::string TemplateArgument = "TemplateArgument";
static const std::string TypedefDecl = "TypedefDecl";
static const std::string UnaryOperator = "UnaryOperator";
static const std::string UnaryExprOrTypeTraitExpr = "UnaryExprOrTypeTraitExpr";
static const std::string VarDecl = "VarDecl";
static const std::string WhileStmt = "WhileStmt";
static std::string unquote(const std::string &s)
{
return (s[0] == '\'') ? s.substr(1, s.size() - 2) : s;
}
static std::vector<std::string> splitString(const std::string &line)
{
std::vector<std::string> ret;
std::string::size_type pos1 = line.find_first_not_of(' ');
while (pos1 < line.size()) {
std::string::size_type pos2;
if (std::strchr("*()", line[pos1])) {
ret.push_back(line.substr(pos1,1));
pos1 = line.find_first_not_of(' ', pos1 + 1);
continue;
}
if (line[pos1] == '<')
pos2 = line.find('>', pos1);
else if (line[pos1] == '\"')
pos2 = line.find('\"', pos1+1);
else if (line[pos1] == '\'') {
pos2 = line.find('\'', pos1+1);
if (pos2 < (int)line.size() - 3 && line.compare(pos2, 3, "\':\'", 0, 3) == 0)
pos2 = line.find('\'', pos2 + 3);
} else {
pos2 = pos1;
while (pos2 < line.size() && (line[pos2] == '_' || line[pos2] == ':' || std::isalnum((unsigned char)line[pos2])))
++pos2;
if (pos2 > pos1 && pos2 < line.size() && line[pos2] == '<' && std::isalpha(line[pos1])) {
int tlevel = 1;
while (++pos2 < line.size() && tlevel > 0) {
if (line[pos2] == '<')
++tlevel;
else if (line[pos2] == '>')
--tlevel;
}
if (tlevel == 0 && pos2 < line.size() && line[pos2] == ' ') {
ret.push_back(line.substr(pos1, pos2-pos1));
pos1 = pos2 + 1;
continue;
}
}
pos2 = line.find(' ', pos1) - 1;
if ((std::isalpha(line[pos1]) || line[pos1] == '_') &&
line.find("::", pos1) < pos2 &&
line.find("::", pos1) < line.find('<', pos1)) {
pos2 = line.find("::", pos1);
ret.push_back(line.substr(pos1, pos2-pos1));
ret.emplace_back("::");
pos1 = pos2 + 2;
continue;
}
if ((std::isalpha(line[pos1]) || line[pos1] == '_') &&
line.find('<', pos1) < pos2 &&
line.find("<<",pos1) != line.find('<',pos1) &&
line.find('>', pos1) != std::string::npos &&
line.find('>', pos1) > pos2) {
int level = 0;
for (pos2 = pos1; pos2 < line.size(); ++pos2) {
if (line[pos2] == '<')
++level;
else if (line[pos2] == '>') {
if (level <= 1)
break;
--level;
}
}
if (level > 1 && pos2 + 1 >= line.size())
return std::vector<std::string> {};
pos2 = line.find(' ', pos2);
if (pos2 != std::string::npos)
--pos2;
}
}
if (pos2 == std::string::npos) {
ret.push_back(line.substr(pos1));
break;
}
ret.push_back(line.substr(pos1, pos2+1-pos1));
pos1 = line.find_first_not_of(' ', pos2 + 1);
}
return ret;
}
namespace clangimport {
struct Data {
struct Decl {
explicit Decl(Scope *scope) : scope(scope) {}
Decl(Token *def, Variable *var) : def(def), var(var) {}
Decl(Token *def, Function *function) : def(def), function(function) {}
Decl(Token *def, Enumerator *enumerator) : def(def), enumerator(enumerator) {}
void ref(Token *tok) const {
if (enumerator)
tok->enumerator(enumerator);
if (function)
tok->function(function);
if (var) {
tok->variable(var);
tok->varId(var->declarationId());
}
}
Token* def{};
Enumerator* enumerator{};
Function* function{};
Scope* scope{};
Variable* var{};
};
const Settings *mSettings = nullptr;
SymbolDatabase *mSymbolDatabase = nullptr;
int enumValue = 0;
void enumDecl(const std::string &addr, Token *nameToken, Enumerator *enumerator) {
Decl decl(nameToken, enumerator);
mDeclMap.emplace(addr, decl);
nameToken->enumerator(enumerator);
notFound(addr);
}
void funcDecl(const std::string &addr, Token *nameToken, Function *function) {
Decl decl(nameToken, function);
mDeclMap.emplace(addr, decl);
nameToken->function(function);
notFound(addr);
}
void scopeDecl(const std::string &addr, Scope *scope) {
Decl decl(scope);
mDeclMap.emplace(addr, decl);
}
void varDecl(const std::string &addr, Token *def, Variable *var) {
Decl decl(def, var);
mDeclMap.emplace(addr, decl);
def->varId(++mVarId);
def->variable(var);
if (def->valueType())
var->setValueType(*def->valueType());
notFound(addr);
}
void replaceVarDecl(const Variable *from, Variable *to) {
for (auto &it: mDeclMap) {
Decl &decl = it.second;
if (decl.var == from)
decl.var = to;
}
}
void ref(const std::string &addr, Token *tok) {
auto it = mDeclMap.find(addr);
if (it != mDeclMap.end())
it->second.ref(tok);
else
mNotFound[addr].push_back(tok);
}
std::vector<const Variable *> getVariableList() const {
std::vector<const Variable *> ret;
ret.resize(mVarId + 1, nullptr);
for (const auto& it: mDeclMap) {
if (it.second.var)
ret[it.second.var->declarationId()] = it.second.var;
}
return ret;
}
bool hasDecl(const std::string &addr) const {
return mDeclMap.find(addr) != mDeclMap.end();
}
const Scope *getScope(const std::string &addr) {
auto it = mDeclMap.find(addr);
return (it == mDeclMap.end() ? nullptr : it->second.scope);
}
// "}" tokens that are not end-of-scope
std::set<Token *> mNotScope;
std::map<const Scope *, AccessControl> scopeAccessControl;
private:
void notFound(const std::string &addr) {
auto it = mNotFound.find(addr);
if (it != mNotFound.end()) {
for (Token *reftok: it->second)
ref(addr, reftok);
mNotFound.erase(it);
}
}
std::map<std::string, Decl> mDeclMap;
std::map<std::string, std::vector<Token *>> mNotFound;
int mVarId = 0;
};
class AstNode;
using AstNodePtr = std::shared_ptr<AstNode>;
class AstNode {
public:
AstNode(std::string nodeType, const std::string &ext, Data *data)
: nodeType(std::move(nodeType)), mExtTokens(splitString(ext)), mData(data)
{}
std::string nodeType;
std::vector<AstNodePtr> children;
bool isPrologueTypedefDecl() const;
void setLocations(TokenList &tokenList, int file, int line, int col);
void dumpAst(int num = 0, int indent = 0) const;
void createTokens1(TokenList &tokenList) {
//dumpAst(); // TODO: reactivate or remove
if (isPrologueTypedefDecl())
return;
if (!tokenList.back()) {
setLocations(tokenList, 0, 1, 1);
}
else
setLocations(tokenList, tokenList.back()->fileIndex(), tokenList.back()->linenr(), 1);
createTokens(tokenList);
if (nodeType == VarDecl || nodeType == RecordDecl || nodeType == TypedefDecl)
addtoken(tokenList, ";");
mData->mNotScope.clear();
}
AstNodePtr getChild(int c) {
if (c >= children.size()) {
std::ostringstream err;
err << "ClangImport: AstNodePtr::getChild(" << c << ") out of bounds. children.size=" << children.size() << " " << nodeType;
for (const std::string &s: mExtTokens)
err << " " << s;
throw InternalError(nullptr, err.str());
}
return children[c];
}
private:
Token *createTokens(TokenList &tokenList);
Token *addtoken(TokenList &tokenList, const std::string &str, bool valueType=true);
const ::Type *addTypeTokens(TokenList &tokenList, const std::string &str, const Scope *scope = nullptr);
void addFullScopeNameTokens(TokenList &tokenList, const Scope *recordScope);
Scope *createScope(TokenList &tokenList, Scope::ScopeType scopeType, AstNodePtr astNode, const Token *def);
Scope *createScope(TokenList &tokenList, Scope::ScopeType scopeType, const std::vector<AstNodePtr> &children2, const Token *def);
RET_NONNULL Token *createTokensCall(TokenList &tokenList);
void createTokensFunctionDecl(TokenList &tokenList);
void createTokensForCXXRecord(TokenList &tokenList);
Token *createTokensVarDecl(TokenList &tokenList);
std::string getSpelling() const;
std::string getType(int index = 0) const;
std::string getFullType(int index = 0) const;
bool isDefinition() const;
std::string getTemplateParameters() const;
const Scope *getNestedInScope(TokenList &tokenList);
void setValueType(Token *tok);
int mFile = 0;
int mLine = 1;
int mCol = 1;
std::vector<std::string> mExtTokens;
Data *mData;
};
}
std::string clangimport::AstNode::getSpelling() const
{
if (nodeType == CompoundAssignOperator) {
std::size_t typeIndex = 1;
while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'')
typeIndex++;
// name is next quoted token
std::size_t nameIndex = typeIndex + 1;
while (nameIndex < mExtTokens.size() && mExtTokens[nameIndex][0] != '\'')
nameIndex++;
return (nameIndex < mExtTokens.size()) ? unquote(mExtTokens[nameIndex]) : "";
}
if (nodeType == UnaryExprOrTypeTraitExpr) {
std::size_t typeIndex = 1;
while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'')
typeIndex++;
const std::size_t nameIndex = typeIndex + 1;
return (nameIndex < mExtTokens.size()) ? unquote(mExtTokens[nameIndex]) : "";
}
int typeIndex = mExtTokens.size() - 1;
if (nodeType == FunctionDecl || nodeType == CXXConstructorDecl || nodeType == CXXMethodDecl) {
while (typeIndex >= 0 && mExtTokens[typeIndex][0] != '\'')
typeIndex--;
if (typeIndex <= 0)
return "";
}
if (nodeType == DeclRefExpr) {
while (typeIndex > 0 && std::isalpha(mExtTokens[typeIndex][0]))
typeIndex--;
if (typeIndex <= 0)
return "";
}
const std::string &str = mExtTokens[typeIndex - 1];
if (startsWith(str,"col:"))
return "";
if (startsWith(str,"<invalid"))
return "";
if (nodeType == RecordDecl && str == "struct")
return "";
return str;
}
std::string clangimport::AstNode::getType(int index) const
{
std::string type = getFullType(index);
if (type.find(" (") != std::string::npos) {
const std::string::size_type pos = type.find(" (");
type[pos] = '\'';
type.erase(pos+1);
}
if (type.find(" *(") != std::string::npos) {
const std::string::size_type pos = type.find(" *(") + 2;
type[pos] = '\'';
type.erase(pos+1);
}
if (type.find(" &(") != std::string::npos) {
const std::string::size_type pos = type.find(" &(") + 2;
type[pos] = '\'';
type.erase(pos+1);
}
return unquote(type);
}
std::string clangimport::AstNode::getFullType(int index) const
{
std::size_t typeIndex = 1;
while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'')
typeIndex++;
if (typeIndex >= mExtTokens.size())
return "";
std::string type = mExtTokens[typeIndex];
if (type.find("\':\'") != std::string::npos) {
if (index == 0)
type.erase(type.find("\':\'") + 1);
else
type.erase(0, type.find("\':\'") + 2);
}
return type;
}
bool clangimport::AstNode::isDefinition() const
{
return contains(mExtTokens, "definition");
}
std::string clangimport::AstNode::getTemplateParameters() const
{
if (children.empty() || children[0]->nodeType != TemplateArgument)
return "";
std::string templateParameters;
for (const AstNodePtr& child: children) {
if (child->nodeType == TemplateArgument) {
if (templateParameters.empty())
templateParameters = "<";
else
templateParameters += ",";
templateParameters += unquote(child->mExtTokens.back());
}
}
return templateParameters + ">";
}
// cppcheck-suppress unusedFunction // only used in comment
void clangimport::AstNode::dumpAst(int num, int indent) const
{
(void)num;
std::cout << std::string(indent, ' ') << nodeType;
for (const auto& tok: mExtTokens)
std::cout << " " << tok;
std::cout << std::endl;
for (int c = 0; c < children.size(); ++c) {
if (children[c])
children[c]->dumpAst(c, indent + 2);
else
std::cout << std::string(indent + 2, ' ') << "<<<<NULL>>>>>" << std::endl;
}
}
bool clangimport::AstNode::isPrologueTypedefDecl() const
{
// these TypedefDecl are included in *any* AST dump and we should ignore them as they should not be of interest to us
// see https://github.com/llvm/llvm-project/issues/120228#issuecomment-2549212109 for an explanation
if (nodeType != TypedefDecl)
return false;
// TODO: use different values to indicate "<invalid sloc>"?
if (mFile != 0 || mLine != 1 || mCol != 1)
return false;
// TODO: match without using children
if (children.empty())
return false;
if (children[0].get()->mExtTokens.size() < 2)
return false;
const auto& type = children[0].get()->mExtTokens[1];
if (type == "'__int128'" ||
type == "'unsigned __int128'" ||
type == "'struct __NSConstantString_tag'" ||
type == "'char *'" ||
type == "'struct __va_list_tag[1]'")
{
// NOLINTNEXTLINE(readability-simplify-boolean-expr)
return true;
}
return false;
}
void clangimport::AstNode::setLocations(TokenList &tokenList, int file, int line, int col)
{
if (mExtTokens.size() >= 2)
{
const std::string &ext = mExtTokens[1];
if (startsWith(ext, "<col:"))
col = strToInt<int>(ext.substr(5, ext.find_first_of(",>", 5) - 5));
else if (startsWith(ext, "<line:")) {
line = strToInt<int>(ext.substr(6, ext.find_first_of(":,>", 6) - 6));
const auto pos = ext.find(", col:");
if (pos != std::string::npos)
col = strToInt<int>(ext.substr(pos+6, ext.find_first_of(":,>", pos+6) - (pos+6)));
} else if (ext[0] == '<') {
const std::string::size_type colon = ext.find(':');
if (colon != std::string::npos) {
const bool windowsPath = colon == 2 && ext.size() > 3 && ext[2] == ':';
const std::string::size_type sep1 = windowsPath ? ext.find(':', 4) : colon;
const std::string::size_type sep2 = ext.find(':', sep1 + 1);
file = tokenList.appendFileIfNew(ext.substr(1, sep1 - 1));
line = strToInt<int>(ext.substr(sep1 + 1, sep2 - sep1 - 1));
}
else {
// "<invalid sloc>" are encountered in every AST dump by some built-in TypedefDecl
// an completely empty location block was encountered with a CompoundStmt
if (ext != "<<invalid sloc>" && ext != "<>")
throw InternalError(nullptr, "invalid AST location: " + ext, InternalError::AST);
}
}
}
mFile = file;
mLine = line;
mCol = col;
for (const auto& child: children) {
if (child)
child->setLocations(tokenList, file, line, col);
}
}
Token *clangimport::AstNode::addtoken(TokenList &tokenList, const std::string &str, bool valueType)
{
const Scope *scope = getNestedInScope(tokenList);
tokenList.addtoken(str, mLine, mCol, mFile);
tokenList.back()->scope(scope);
if (valueType)
setValueType(tokenList.back());
return tokenList.back();
}
const ::Type * clangimport::AstNode::addTypeTokens(TokenList &tokenList, const std::string &str, const Scope *scope)
{
if (str.find("\':\'") != std::string::npos) {
return addTypeTokens(tokenList, str.substr(0, str.find("\':\'") + 1), scope);
}
if (startsWith(str, "'enum (anonymous"))
return nullptr;
std::string type;
if (str.find(" (") != std::string::npos) {
if (str.find('<') != std::string::npos)
type = str.substr(1, str.find('<')) + "...>";
else
type = str.substr(1,str.find(" (")-1);
} else
type = unquote(str);
if (type.find("(*)(") != std::string::npos) {
type.erase(type.find("(*)("));
type += "*";
}
if (type.find('(') != std::string::npos)
type.erase(type.find('('));
// TODO: put in a helper?
std::stack<Token *> lpar;
for (const std::string &s: splitString(type)) {
Token *tok = addtoken(tokenList, s, false);
if (tok->str() == "(")
lpar.push(tok);
else if (tok->str() == ")") {
Token::createMutualLinks(tok, lpar.top());
lpar.pop();
}
}
// Set Type
if (!scope) {
scope = tokenList.back() ? tokenList.back()->scope() : nullptr;
if (!scope)
return nullptr;
}
for (const Token *typeToken = tokenList.back(); Token::Match(typeToken, "&|*|%name%"); typeToken = typeToken->previous()) {
if (!typeToken->isName())
continue;
const ::Type *recordType = scope->check->findVariableType(scope, typeToken);
if (recordType) {
const_cast<Token*>(typeToken)->type(recordType);
return recordType;
}
}
return nullptr;
}
void clangimport::AstNode::addFullScopeNameTokens(TokenList &tokenList, const Scope *recordScope)
{
if (!recordScope)
return;
std::list<const Scope *> scopes;
while (recordScope && recordScope != tokenList.back()->scope() && !recordScope->isExecutable()) {
scopes.push_front(recordScope);
recordScope = recordScope->nestedIn;
}
for (const Scope *s: scopes) {
if (!s->className.empty()) {
addtoken(tokenList, s->className);
addtoken(tokenList, "::");
}
}
}
const Scope *clangimport::AstNode::getNestedInScope(TokenList &tokenList)
{
if (!tokenList.back())
return &mData->mSymbolDatabase->scopeList.front();
if (tokenList.back()->str() == "}" && mData->mNotScope.find(tokenList.back()) == mData->mNotScope.end())
return tokenList.back()->scope()->nestedIn;
return tokenList.back()->scope();
}
void clangimport::AstNode::setValueType(Token *tok)
{
for (int i = 0; i < 2; i++) {
const std::string &type = getType(i);
if (type.find('<') != std::string::npos)
// TODO
continue;
TokenList decl(nullptr);
decl.setLang(tok->isCpp() ? Standards::Language::CPP : Standards::Language::C);
addTypeTokens(decl, type, tok->scope());
if (!decl.front())
break;
const ValueType valueType = ValueType::parseDecl(decl.front(), *mData->mSettings);
if (valueType.type != ValueType::Type::UNKNOWN_TYPE) {
tok->setValueType(new ValueType(valueType));
break;
}
}
}
Scope *clangimport::AstNode::createScope(TokenList &tokenList, Scope::ScopeType scopeType, AstNodePtr astNode, const Token *def)
{
std::vector<AstNodePtr> children2{std::move(astNode)};
return createScope(tokenList, scopeType, children2, def);
}
Scope *clangimport::AstNode::createScope(TokenList &tokenList, Scope::ScopeType scopeType, const std::vector<AstNodePtr> & children2, const Token *def)
{
SymbolDatabase *symbolDatabase = mData->mSymbolDatabase;
auto *nestedIn = const_cast<Scope *>(getNestedInScope(tokenList));
symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nestedIn);
Scope *scope = &symbolDatabase->scopeList.back();
if (scopeType == Scope::ScopeType::eEnum)
scope->enumeratorList.reserve(children2.size());
nestedIn->nestedList.push_back(scope);
scope->type = scopeType;
scope->classDef = def;
scope->check = nestedIn->check;
if (Token::Match(def, "if|for|while (")) {
std::map<const Variable *, const Variable *> replaceVar;
for (const Token *vartok = def->tokAt(2); vartok; vartok = vartok->next()) {
if (!vartok->variable())
continue;
if (vartok->variable()->nameToken() == vartok) {
const Variable *from = vartok->variable();
scope->varlist.emplace_back(*from, scope);
Variable *to = &scope->varlist.back();
replaceVar[from] = to;
mData->replaceVarDecl(from, to);
}
if (replaceVar.find(vartok->variable()) != replaceVar.end())
const_cast<Token *>(vartok)->variable(replaceVar[vartok->variable()]);
}
std::list<Variable> &varlist = const_cast<Scope *>(def->scope())->varlist;
for (std::list<Variable>::const_iterator var = varlist.cbegin(); var != varlist.cend();) {
if (replaceVar.find(&(*var)) != replaceVar.end())
var = varlist.erase(var);
else
++var;
}
}
scope->bodyStart = addtoken(tokenList, "{");
tokenList.back()->scope(scope);
mData->scopeAccessControl[scope] = scope->defaultAccess();
if (!children2.empty()) {
for (const AstNodePtr &astNode: children2) {
if (astNode->nodeType == "VisibilityAttr")
continue;
if (astNode->nodeType == AccessSpecDecl) {
if (contains(astNode->mExtTokens, "private"))
mData->scopeAccessControl[scope] = AccessControl::Private;
else if (contains(astNode->mExtTokens, "protected"))
mData->scopeAccessControl[scope] = AccessControl::Protected;
else if (contains(astNode->mExtTokens, "public"))
mData->scopeAccessControl[scope] = AccessControl::Public;
continue;
}
astNode->createTokens(tokenList);
if (scopeType == Scope::ScopeType::eEnum)
astNode->addtoken(tokenList, ",");
else if (!Token::Match(tokenList.back(), "[;{}]"))
astNode->addtoken(tokenList, ";");
}
}
scope->bodyEnd = addtoken(tokenList, "}");
Token::createMutualLinks(const_cast<Token*>(scope->bodyStart), const_cast<Token*>(scope->bodyEnd));
mData->scopeAccessControl.erase(scope);
return scope;
}
Token *clangimport::AstNode::createTokens(TokenList &tokenList)
{
if (nodeType == ArraySubscriptExpr) {
Token *array = getChild(0)->createTokens(tokenList);
Token *bracket1 = addtoken(tokenList, "[");
Token *index = children[1]->createTokens(tokenList);
Token *bracket2 = addtoken(tokenList, "]");
bracket1->astOperand1(array);
bracket1->astOperand2(index);
bracket1->link(bracket2);
bracket2->link(bracket1);
return bracket1;
}
if (nodeType == BinaryOperator) {
Token *tok1 = getChild(0)->createTokens(tokenList);
Token *binop = addtoken(tokenList, unquote(mExtTokens.back()));
Token *tok2 = children[1]->createTokens(tokenList);
binop->astOperand1(tok1);
binop->astOperand2(tok2);
return binop;
}
if (nodeType == BreakStmt)
return addtoken(tokenList, "break");
if (nodeType == CharacterLiteral) {
const int c = MathLib::toBigNumber(mExtTokens.back());
if (c == 0)
return addtoken(tokenList, "\'\\0\'");
if (c == '\r')
return addtoken(tokenList, "\'\\r\'");
if (c == '\n')
return addtoken(tokenList, "\'\\n\'");
if (c == '\t')
return addtoken(tokenList, "\'\\t\'");
if (c == '\\')
return addtoken(tokenList, "\'\\\\\'");
if (c < ' ' || c >= 0x80) {
std::ostringstream hex;
hex << std::hex << ((c>>4) & 0xf) << (c&0xf);
return addtoken(tokenList, "\'\\x" + hex.str() + "\'");
}
return addtoken(tokenList, std::string("\'") + char(c) + std::string("\'"));
}
if (nodeType == CallExpr)
return createTokensCall(tokenList);
if (nodeType == CaseStmt) {
Token *caseToken = addtoken(tokenList, "case");
Token *exprToken = getChild(0)->createTokens(tokenList);
caseToken->astOperand1(exprToken);
addtoken(tokenList, ":");
children.back()->createTokens(tokenList);
return nullptr;
}
if (nodeType == ClassTemplateDecl) {
for (const AstNodePtr& child: children) {
if (child->nodeType == ClassTemplateSpecializationDecl)
child->createTokens(tokenList);
}
return nullptr;
}
if (nodeType == ClassTemplateSpecializationDecl) {
createTokensForCXXRecord(tokenList);
return nullptr;
}
if (nodeType == ConditionalOperator) {
Token *expr1 = getChild(0)->createTokens(tokenList);
Token *tok1 = addtoken(tokenList, "?");
Token *expr2 = children[1]->createTokens(tokenList);
Token *tok2 = addtoken(tokenList, ":");
Token *expr3 = children[2]->createTokens(tokenList);
tok2->astOperand1(expr2);
tok2->astOperand2(expr3);
tok1->astOperand1(expr1);
tok1->astOperand2(tok2);
return tok1;
}
if (nodeType == CompoundAssignOperator) {
Token *lhs = getChild(0)->createTokens(tokenList);
Token *assign = addtoken(tokenList, getSpelling());
Token *rhs = children[1]->createTokens(tokenList);
assign->astOperand1(lhs);
assign->astOperand2(rhs);
return assign;
}
if (nodeType == CompoundStmt) {
for (const AstNodePtr& child: children) {
child->createTokens(tokenList);
if (!Token::Match(tokenList.back(), "[;{}]"))
child->addtoken(tokenList, ";");
}
return nullptr;
}
if (nodeType == ConstantExpr)
return children.back()->createTokens(tokenList);
if (nodeType == ContinueStmt)
return addtoken(tokenList, "continue");
if (nodeType == CStyleCastExpr) {
Token *par1 = addtoken(tokenList, "(");
addTypeTokens(tokenList, '\'' + getType() + '\'');
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(getChild(0)->createTokens(tokenList));
return par1;
}
if (nodeType == CXXBindTemporaryExpr)
return getChild(0)->createTokens(tokenList);
if (nodeType == CXXBoolLiteralExpr) {
addtoken(tokenList, mExtTokens.back());
tokenList.back()->setValueType(new ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0));
return tokenList.back();
}
if (nodeType == CXXConstructExpr) {
if (!children.empty())
return getChild(0)->createTokens(tokenList);
addTypeTokens(tokenList, '\'' + getType() + '\'');
Token *type = tokenList.back();
Token *par1 = addtoken(tokenList, "(");
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(type);
return par1;
}
if (nodeType == CXXConstructorDecl) {
createTokensFunctionDecl(tokenList);
return nullptr;
}
if (nodeType == CXXDeleteExpr) {
addtoken(tokenList, "delete");
getChild(0)->createTokens(tokenList);
return nullptr;
}
if (nodeType == CXXDestructorDecl) {
createTokensFunctionDecl(tokenList);
return nullptr;
}
if (nodeType == CXXForRangeStmt) {
Token *forToken = addtoken(tokenList, "for");
Token *par1 = addtoken(tokenList, "(");
AstNodePtr varDecl;
if (children[6]->nodeType == DeclStmt)
varDecl = getChild(6)->getChild(0);
else
varDecl = getChild(5)->getChild(0);
varDecl->mExtTokens.pop_back();
varDecl->children.clear();
Token *expr1 = varDecl->createTokens(tokenList);
Token *colon = addtoken(tokenList, ":");
AstNodePtr range;
for (std::size_t i = 0; i < 2; i++) {
if (children[i] && children[i]->nodeType == DeclStmt && children[i]->getChild(0)->nodeType == VarDecl) {
range = children[i]->getChild(0)->getChild(0);
break;
}
}
if (!range)
throw InternalError(tokenList.back(), "Failed to import CXXForRangeStmt. Range?");
Token *expr2 = range->createTokens(tokenList);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
colon->astOperand1(expr1);
colon->astOperand2(expr2);
par1->astOperand1(forToken);
par1->astOperand2(colon);
createScope(tokenList, Scope::ScopeType::eFor, children.back(), forToken);
return nullptr;
}
if (nodeType == CXXMethodDecl) {
for (std::size_t i = 0; i+1 < mExtTokens.size(); ++i) {
if (mExtTokens[i] == "prev" && !mData->hasDecl(mExtTokens[i+1]))
return nullptr;
}
createTokensFunctionDecl(tokenList);
return nullptr;
}
if (nodeType == CXXMemberCallExpr)
return createTokensCall(tokenList);
if (nodeType == CXXNewExpr) {
Token *newtok = addtoken(tokenList, "new");
if (children.size() == 1 && getChild(0)->nodeType == CXXConstructExpr) {
newtok->astOperand1(getChild(0)->createTokens(tokenList));
return newtok;
}
std::string type = getType();
if (type.find('*') != std::string::npos)
type = type.erase(type.rfind('*'));
addTypeTokens(tokenList, type);
if (!children.empty()) {
Token *bracket1 = addtoken(tokenList, "[");
getChild(0)->createTokens(tokenList);
Token *bracket2 = addtoken(tokenList, "]");
bracket1->link(bracket2);
bracket2->link(bracket1);
}
return newtok;
}
if (nodeType == CXXNullPtrLiteralExpr)
return addtoken(tokenList, "nullptr");
if (nodeType == CXXOperatorCallExpr)
return createTokensCall(tokenList);
if (nodeType == CXXRecordDecl) {
createTokensForCXXRecord(tokenList);
return nullptr;
}
if (nodeType == CXXStaticCastExpr || nodeType == CXXFunctionalCastExpr) {
Token *cast = addtoken(tokenList, getSpelling());
Token *par1 = addtoken(tokenList, "(");
Token *expr = getChild(0)->createTokens(tokenList);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(cast);
par1->astOperand2(expr);
setValueType(par1);
return par1;
}
if (nodeType == CXXStdInitializerListExpr)
return getChild(0)->createTokens(tokenList);
if (nodeType == CXXTemporaryObjectExpr && !children.empty())
return getChild(0)->createTokens(tokenList);
if (nodeType == CXXThisExpr)
return addtoken(tokenList, "this");
if (nodeType == CXXThrowExpr) {
Token *t = addtoken(tokenList, "throw");
t->astOperand1(getChild(0)->createTokens(tokenList));
return t;
}
if (nodeType == DeclRefExpr) {
int addrIndex = mExtTokens.size() - 1;
while (addrIndex > 1 && !startsWith(mExtTokens[addrIndex],"0x"))
--addrIndex;
const std::string addr = mExtTokens[addrIndex];
std::string name = unquote(getSpelling());
Token *reftok = addtoken(tokenList, name.empty() ? "<NoName>" : std::move(name));
mData->ref(addr, reftok);
return reftok;
}
if (nodeType == DeclStmt)
return getChild(0)->createTokens(tokenList);
if (nodeType == DefaultStmt) {
addtoken(tokenList, "default");
addtoken(tokenList, ":");
children.back()->createTokens(tokenList);
return nullptr;
}
if (nodeType == DoStmt) {
addtoken(tokenList, "do");
createScope(tokenList, Scope::ScopeType::eDo, getChild(0), tokenList.back());
Token *tok1 = addtoken(tokenList, "while");
Token *par1 = addtoken(tokenList, "(");
Token *expr = children[1]->createTokens(tokenList);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(tok1);
par1->astOperand2(expr);
return nullptr;
}
if (nodeType == EnumConstantDecl) {
Token *nameToken = addtoken(tokenList, getSpelling());
auto *scope = const_cast<Scope *>(nameToken->scope());
scope->enumeratorList.emplace_back(nameToken->scope());
Enumerator *e = &scope->enumeratorList.back();
e->name = nameToken;
e->value = mData->enumValue++;
e->value_known = true;
mData->enumDecl(mExtTokens.front(), nameToken, e);
return nameToken;
}
if (nodeType == EnumDecl) {
int colIndex = mExtTokens.size() - 1;
while (colIndex > 0 && !startsWith(mExtTokens[colIndex],"col:") && !startsWith(mExtTokens[colIndex],"line:"))
--colIndex;
if (colIndex == 0)
return nullptr;
mData->enumValue = 0;
Token *enumtok = addtoken(tokenList, "enum");
const Token *nametok = nullptr;
{
int nameIndex = mExtTokens.size() - 1;
while (nameIndex > colIndex && mExtTokens[nameIndex][0] == '\'')
--nameIndex;
if (nameIndex > colIndex)
nametok = addtoken(tokenList, mExtTokens[nameIndex]);
if (mExtTokens.back()[0] == '\'') {
addtoken(tokenList, ":");
addTypeTokens(tokenList, mExtTokens.back());
}
}
Scope *enumscope = createScope(tokenList, Scope::ScopeType::eEnum, children, enumtok);
if (nametok)
enumscope->className = nametok->str();
if (enumscope->bodyEnd && Token::simpleMatch(enumscope->bodyEnd->previous(), ", }"))
const_cast<Token *>(enumscope->bodyEnd)->deletePrevious();
// Create enum type
mData->mSymbolDatabase->typeList.emplace_back(enumtok, enumscope, enumtok->scope());
enumscope->definedType = &mData->mSymbolDatabase->typeList.back();
if (nametok)
const_cast<Scope *>(enumtok->scope())->definedTypesMap[nametok->str()] = enumscope->definedType;
return nullptr;
}
if (nodeType == ExprWithCleanups)
return getChild(0)->createTokens(tokenList);
if (nodeType == FieldDecl)
return createTokensVarDecl(tokenList);
if (nodeType == FloatingLiteral)
return addtoken(tokenList, mExtTokens.back());
if (nodeType == ForStmt) {
Token *forToken = addtoken(tokenList, "for");
Token *par1 = addtoken(tokenList, "(");
Token *expr1 = getChild(0) ? children[0]->createTokens(tokenList) : nullptr;
Token *sep1 = addtoken(tokenList, ";");
Token *expr2 = children[2] ? children[2]->createTokens(tokenList) : nullptr;
Token *sep2 = addtoken(tokenList, ";");
Token *expr3 = children[3] ? children[3]->createTokens(tokenList) : nullptr;
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(forToken);
par1->astOperand2(sep1);
sep1->astOperand1(expr1);
sep1->astOperand2(sep2);
sep2->astOperand1(expr2);
sep2->astOperand2(expr3);
createScope(tokenList, Scope::ScopeType::eFor, children[4], forToken);
return nullptr;
}
if (nodeType == FunctionDecl) {
createTokensFunctionDecl(tokenList);
return nullptr;
}
if (nodeType == FunctionTemplateDecl) {
bool first = true;
for (const AstNodePtr& child: children) {
if (child->nodeType == FunctionDecl) {
if (!first)
child->createTokens(tokenList);
first = false;
}
}
return nullptr;
}
if (nodeType == GotoStmt) {
addtoken(tokenList, "goto");
addtoken(tokenList, unquote(mExtTokens[mExtTokens.size() - 2]));
addtoken(tokenList, ";");
return nullptr;
}
if (nodeType == IfStmt) {
AstNodePtr cond;
AstNodePtr thenCode;
AstNodePtr elseCode;
if (children.size() == 2) {
cond = children[children.size() - 2];
thenCode = children[children.size() - 1];
} else {
cond = children[children.size() - 3];
thenCode = children[children.size() - 2];
elseCode = children[children.size() - 1];
}
Token *iftok = addtoken(tokenList, "if");
Token *par1 = addtoken(tokenList, "(");
par1->astOperand1(iftok);
par1->astOperand2(cond->createTokens(tokenList));
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
createScope(tokenList, Scope::ScopeType::eIf, std::move(thenCode), iftok);
if (elseCode) {
elseCode->addtoken(tokenList, "else");
createScope(tokenList, Scope::ScopeType::eElse, std::move(elseCode), tokenList.back());
}
return nullptr;
}
if (nodeType == ImplicitCastExpr) {
Token *expr = getChild(0)->createTokens(tokenList);
if (!expr->valueType() || contains(mExtTokens, "<ArrayToPointerDecay>"))
setValueType(expr);
return expr;
}
if (nodeType == InitListExpr) {
const Scope *scope = tokenList.back()->scope();
Token *start = addtoken(tokenList, "{");
start->scope(scope);
for (const AstNodePtr& child: children) {
if (tokenList.back()->str() != "{")
addtoken(tokenList, ",");
child->createTokens(tokenList);
}
Token *end = addtoken(tokenList, "}");
end->scope(scope);
start->link(end);
end->link(start);
mData->mNotScope.insert(end);
return start;
}
if (nodeType == IntegerLiteral)
return addtoken(tokenList, mExtTokens.back());
if (nodeType == LabelStmt) {
addtoken(tokenList, unquote(mExtTokens.back()));
addtoken(tokenList, ":");
for (const auto& child: children)
child->createTokens(tokenList);
return nullptr;
}
if (nodeType == LinkageSpecDecl)
return nullptr;
if (nodeType == MaterializeTemporaryExpr)
return getChild(0)->createTokens(tokenList);
if (nodeType == MemberExpr) {
Token *s = getChild(0)->createTokens(tokenList);
Token *dot = addtoken(tokenList, ".");
std::string memberName = getSpelling();
if (startsWith(memberName, "->")) {
dot->originalName("->");
memberName = memberName.substr(2);
} else if (startsWith(memberName, ".")) {
memberName = memberName.substr(1);
}
if (memberName.empty())
memberName = "<unknown>";
Token *member = addtoken(tokenList, memberName);
mData->ref(mExtTokens.back(), member);
dot->astOperand1(s);
dot->astOperand2(member);
return dot;
}
if (nodeType == NamespaceDecl) {
if (children.empty())
return nullptr;
const Token *defToken = addtoken(tokenList, "namespace");
const std::string &s = mExtTokens[mExtTokens.size() - 2];
const Token* nameToken = (startsWith(s, "col:") || startsWith(s, "line:")) ?
addtoken(tokenList, mExtTokens.back()) : nullptr;
Scope *scope = createScope(tokenList, Scope::ScopeType::eNamespace, children, defToken);
if (nameToken)
scope->className = nameToken->str();
return nullptr;
}
if (nodeType == NullStmt)
return addtoken(tokenList, ";");
if (nodeType == ParenExpr) {
Token *par1 = addtoken(tokenList, "(");
Token *expr = getChild(0)->createTokens(tokenList);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
return expr;
}
if (nodeType == RecordDecl) {
const Token *classDef = addtoken(tokenList, "struct");
const std::string &recordName = getSpelling();
if (!recordName.empty())
addtoken(tokenList, getSpelling());
if (!isDefinition()) {
addtoken(tokenList, ";");
return nullptr;
}
Scope *recordScope = createScope(tokenList, Scope::ScopeType::eStruct, children, classDef);
mData->mSymbolDatabase->typeList.emplace_back(classDef, recordScope, classDef->scope());
recordScope->definedType = &mData->mSymbolDatabase->typeList.back();
if (!recordName.empty()) {
recordScope->className = recordName;
const_cast<Scope *>(classDef->scope())->definedTypesMap[recordName] = recordScope->definedType;
}
return nullptr;
}
if (nodeType == ReturnStmt) {
Token *tok1 = addtoken(tokenList, "return");
if (!children.empty()) {
getChild(0)->setValueType(tok1);
tok1->astOperand1(getChild(0)->createTokens(tokenList));
}
return tok1;
}
if (nodeType == StringLiteral)
return addtoken(tokenList, mExtTokens.back());
if (nodeType == SwitchStmt) {
Token *tok1 = addtoken(tokenList, "switch");
Token *par1 = addtoken(tokenList, "(");
Token *expr = children[children.size() - 2]->createTokens(tokenList);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(tok1);
par1->astOperand2(expr);
createScope(tokenList, Scope::ScopeType::eSwitch, children.back(), tok1);
return nullptr;
}
if (nodeType == TypedefDecl) {
addtoken(tokenList, "typedef");
addTypeTokens(tokenList, getType());
return addtoken(tokenList, getSpelling());
}
if (nodeType == UnaryOperator) {
int index = (int)mExtTokens.size() - 1;
while (index > 0 && mExtTokens[index][0] != '\'')
--index;
Token *unop = addtoken(tokenList, unquote(mExtTokens[index]));
unop->astOperand1(getChild(0)->createTokens(tokenList));
return unop;
}
if (nodeType == UnaryExprOrTypeTraitExpr) {
Token *tok1 = addtoken(tokenList, getSpelling());
Token *par1 = addtoken(tokenList, "(");
if (children.empty())
addTypeTokens(tokenList, mExtTokens.back());
else {
AstNodePtr child = getChild(0);
if (child && child->nodeType == ParenExpr)
child = child->getChild(0);
Token *expr = child->createTokens(tokenList);
child->setValueType(expr);
par1->astOperand2(expr);
}
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
par1->astOperand1(tok1);
par1->astOperand2(par1->next());
setValueType(par1);
return par1;
}
if (nodeType == VarDecl)
return createTokensVarDecl(tokenList);
if (nodeType == WhileStmt) {
AstNodePtr cond = children[children.size() - 2];
AstNodePtr body = children.back();
Token *whiletok = addtoken(tokenList, "while");
Token *par1 = addtoken(tokenList, "(");
par1->astOperand1(whiletok);
par1->astOperand2(cond->createTokens(tokenList));
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
createScope(tokenList, Scope::ScopeType::eWhile, std::move(body), whiletok);
return nullptr;
}
return addtoken(tokenList, "?" + nodeType + "?");
}
Token * clangimport::AstNode::createTokensCall(TokenList &tokenList)
{
int firstParam;
Token *f;
if (nodeType == CXXOperatorCallExpr) {
firstParam = 2;
Token *obj = getChild(1)->createTokens(tokenList);
Token *dot = addtoken(tokenList, ".");
Token *op = getChild(0)->createTokens(tokenList);
dot->astOperand1(obj);
dot->astOperand2(op);
f = dot;
} else {
firstParam = 1;
f = getChild(0)->createTokens(tokenList);
}
f->setValueType(nullptr);
Token *par1 = addtoken(tokenList, "(");
par1->astOperand1(f);
std::size_t args = 0;
while (args < children.size() && children[args]->nodeType != CXXDefaultArgExpr)
args++;
Token *child = nullptr;
for (std::size_t c = firstParam; c < args; ++c) {
if (child) {
Token *comma = addtoken(tokenList, ",");
comma->setValueType(nullptr);
comma->astOperand1(child);
comma->astOperand2(children[c]->createTokens(tokenList));
child = comma;
} else {
child = children[c]->createTokens(tokenList);
}
}
par1->astOperand2(child);
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
return par1;
}
void clangimport::AstNode::createTokensFunctionDecl(TokenList &tokenList)
{
const bool prev = contains(mExtTokens, "prev");
const bool hasBody = !children.empty() && children.back()->nodeType == CompoundStmt;
const bool isStatic = contains(mExtTokens, "static");
const bool isInline = contains(mExtTokens, "inline");
const Token *startToken = nullptr;
SymbolDatabase *symbolDatabase = mData->mSymbolDatabase;
if (nodeType != CXXConstructorDecl && nodeType != CXXDestructorDecl) {
if (isStatic)
addtoken(tokenList, "static");
if (isInline)
addtoken(tokenList, "inline");
const Token * const before = tokenList.back();
addTypeTokens(tokenList, '\'' + getType() + '\'');
startToken = before ? before->next() : tokenList.front();
}
if (mExtTokens.size() > 4 && mExtTokens[1] == "parent")
addFullScopeNameTokens(tokenList, mData->getScope(mExtTokens[2]));
Token *nameToken = addtoken(tokenList, getSpelling() + getTemplateParameters());
auto *nestedIn = const_cast<Scope *>(nameToken->scope());
if (prev) {
const std::string addr = *(std::find(mExtTokens.cbegin(), mExtTokens.cend(), "prev") + 1);
mData->ref(addr, nameToken);
}
if (!nameToken->function()) {
nestedIn->functionList.emplace_back(nameToken, unquote(getFullType()));
mData->funcDecl(mExtTokens.front(), nameToken, &nestedIn->functionList.back());
if (nodeType == CXXConstructorDecl)
nestedIn->functionList.back().type = Function::Type::eConstructor;
else if (nodeType == CXXDestructorDecl)
nestedIn->functionList.back().type = Function::Type::eDestructor;
else
nestedIn->functionList.back().retDef = startToken;
}
auto * const function = const_cast<Function*>(nameToken->function());
if (!prev) {
auto accessControl = mData->scopeAccessControl.find(tokenList.back()->scope());
if (accessControl != mData->scopeAccessControl.end())
function->access = accessControl->second;
}
Scope *scope = nullptr;
if (hasBody) {
symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nestedIn);
scope = &symbolDatabase->scopeList.back();
scope->check = symbolDatabase;
scope->function = function;
scope->classDef = nameToken;
scope->type = Scope::ScopeType::eFunction;
scope->className = nameToken->str();
nestedIn->nestedList.push_back(scope);
function->hasBody(true);
function->functionScope = scope;
}
Token *par1 = addtoken(tokenList, "(");
if (!function->arg)
function->arg = par1;
function->token = nameToken;
if (!function->nestedIn)
function->nestedIn = nestedIn;
function->argDef = par1;
// Function arguments
for (int i = 0; i < children.size(); ++i) {
AstNodePtr child = children[i];
if (child->nodeType != ParmVarDecl)
continue;
if (tokenList.back() != par1)
addtoken(tokenList, ",");
const Type *recordType = addTypeTokens(tokenList, child->mExtTokens.back(), nestedIn);
const Token *typeEndToken = tokenList.back();
const std::string spelling = child->getSpelling();
Token *vartok = nullptr;
if (!spelling.empty())
vartok = child->addtoken(tokenList, spelling);
if (!prev) {
function->argumentList.emplace_back(vartok, child->getType(), nullptr, typeEndToken, i, AccessControl::Argument, recordType, scope);
if (vartok) {
const std::string addr = child->mExtTokens[0];
mData->varDecl(addr, vartok, &function->argumentList.back());
}
} else if (vartok) {
const std::string addr = child->mExtTokens[0];
mData->ref(addr, vartok);
}
}
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
if (function->isConst())
addtoken(tokenList, "const");
// Function body
if (hasBody) {
symbolDatabase->functionScopes.push_back(scope);
Token *bodyStart = addtoken(tokenList, "{");
bodyStart->scope(scope);
children.back()->createTokens(tokenList);
Token *bodyEnd = addtoken(tokenList, "}");
scope->bodyStart = bodyStart;
scope->bodyEnd = bodyEnd;
bodyStart->link(bodyEnd);
bodyEnd->link(bodyStart);
} else {
if (nodeType == CXXConstructorDecl && contains(mExtTokens, "default")) {
addtoken(tokenList, "=");
addtoken(tokenList, "default");
}
addtoken(tokenList, ";");
}
}
void clangimport::AstNode::createTokensForCXXRecord(TokenList &tokenList)
{
const bool isStruct = contains(mExtTokens, "struct");
Token * const classToken = addtoken(tokenList, isStruct ? "struct" : "class");
std::string className;
if (mExtTokens[mExtTokens.size() - 2] == (isStruct?"struct":"class"))
className = mExtTokens.back();
else
className = mExtTokens[mExtTokens.size() - 2];
className += getTemplateParameters();
/*Token *nameToken =*/ addtoken(tokenList, className);
// base classes
bool firstBase = true;
for (const AstNodePtr &child: children) {
if (child->nodeType == "public" || child->nodeType == "protected" || child->nodeType == "private") {
addtoken(tokenList, firstBase ? ":" : ",");
addtoken(tokenList, child->nodeType);
addtoken(tokenList, unquote(child->mExtTokens.back()));
firstBase = false;
}
}
// definition
if (isDefinition()) {
std::vector<AstNodePtr> children2;
std::copy_if(children.cbegin(), children.cend(), std::back_inserter(children2), [](const AstNodePtr& child) {
return child->nodeType == CXXConstructorDecl ||
child->nodeType == CXXDestructorDecl ||
child->nodeType == CXXMethodDecl ||
child->nodeType == FieldDecl ||
child->nodeType == VarDecl ||
child->nodeType == AccessSpecDecl ||
child->nodeType == TypedefDecl;
});
Scope *scope = createScope(tokenList, isStruct ? Scope::ScopeType::eStruct : Scope::ScopeType::eClass, children2, classToken);
const std::string addr = mExtTokens[0];
mData->scopeDecl(addr, scope);
scope->className = className;
mData->mSymbolDatabase->typeList.emplace_back(classToken, scope, classToken->scope());
scope->definedType = &mData->mSymbolDatabase->typeList.back();
const_cast<Scope *>(classToken->scope())->definedTypesMap[className] = scope->definedType;
}
addtoken(tokenList, ";");
tokenList.back()->scope(classToken->scope());
}
Token * clangimport::AstNode::createTokensVarDecl(TokenList &tokenList)
{
const std::string addr = mExtTokens.front();
if (contains(mExtTokens, "static"))
addtoken(tokenList, "static");
int typeIndex = mExtTokens.size() - 1;
while (typeIndex > 1 && std::isalpha(mExtTokens[typeIndex][0]))
typeIndex--;
const std::string type = mExtTokens[typeIndex];
const std::string name = mExtTokens[typeIndex - 1];
const Token *startToken = tokenList.back();
const ::Type *recordType = addTypeTokens(tokenList, type);
if (!startToken)
startToken = tokenList.front();
else if (startToken->str() != "static")
startToken = startToken->next();
Token *vartok1 = addtoken(tokenList, name);
auto *scope = const_cast<Scope *>(tokenList.back()->scope());
scope->varlist.emplace_back(vartok1, unquote(type), startToken, vartok1->previous(), 0, scope->defaultAccess(), recordType, scope);
mData->varDecl(addr, vartok1, &scope->varlist.back());
if (mExtTokens.back() == "cinit" && !children.empty()) {
Token *eq = addtoken(tokenList, "=");
eq->astOperand1(vartok1);
eq->astOperand2(children.back()->createTokens(tokenList));
return eq;
}
if (mExtTokens.back() == "callinit") {
Token *par1 = addtoken(tokenList, "(");
par1->astOperand1(vartok1);
par1->astOperand2(getChild(0)->createTokens(tokenList));
Token *par2 = addtoken(tokenList, ")");
par1->link(par2);
par2->link(par1);
return par1;
}
if (mExtTokens.back() == "listinit") {
return getChild(0)->createTokens(tokenList);
}
return vartok1;
}
static void setTypes(TokenList &tokenList)
{
for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
for (Token *typeToken = tok->tokAt(2); typeToken->str() != ")"; typeToken = typeToken->next()) {
if (typeToken->type())
continue;
typeToken->type(typeToken->scope()->findType(typeToken->str()));
}
}
}
}
static void setValues(const Tokenizer &tokenizer, const SymbolDatabase *symbolDatabase)
{
const Settings & settings = tokenizer.getSettings();
for (const Scope& scope : symbolDatabase->scopeList) {
if (!scope.definedType)
continue;
MathLib::bigint typeSize = 0;
for (const Variable &var: scope.varlist) {
const int mul = std::accumulate(var.dimensions().cbegin(), var.dimensions().cend(), 1, [](int v, const Dimension& dim) {
return v * dim.num;
});
if (var.valueType())
typeSize += mul * var.valueType()->typeSize(settings.platform, true);
}
scope.definedType->sizeOf = typeSize;
}
for (auto *tok = const_cast<Token*>(tokenizer.tokens()); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "sizeof (")) {
ValueType vt = ValueType::parseDecl(tok->tokAt(2), settings);
const MathLib::bigint sz = vt.typeSize(settings.platform, true);
if (sz <= 0)
continue;
long long mul = 1;
for (const Token *arrtok = tok->linkAt(1)->previous(); arrtok; arrtok = arrtok->previous()) {
const std::string &a = arrtok->str();
if (a.size() > 2 && a[0] == '[' && a.back() == ']')
mul *= strToInt<long long>(a.substr(1));
else
break;
}
ValueFlow::Value v(mul * sz);
v.setKnown();
tok->next()->addValue(v);
}
}
}
void clangimport::parseClangAstDump(Tokenizer &tokenizer, std::istream &f)
{
TokenList &tokenList = tokenizer.list;
tokenizer.createSymbolDatabase();
auto *symbolDatabase = const_cast<SymbolDatabase *>(tokenizer.getSymbolDatabase());
symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nullptr);
symbolDatabase->scopeList.back().type = Scope::ScopeType::eGlobal;
symbolDatabase->scopeList.back().check = symbolDatabase;
clangimport::Data data;
data.mSettings = &tokenizer.getSettings();
data.mSymbolDatabase = symbolDatabase;
std::string line;
std::vector<AstNodePtr> tree;
while (std::getline(f,line)) {
const std::string::size_type pos1 = line.find('-');
if (pos1 == std::string::npos)
continue;
if (!tree.empty() && line.substr(pos1) == "-<<<NULL>>>") {
const int level = (pos1 - 1) / 2;
tree[level - 1]->children.push_back(nullptr);
continue;
}
const std::string::size_type pos2 = line.find(' ', pos1);
if (pos2 < pos1 + 4 || pos2 == std::string::npos)
continue;
const std::string nodeType = line.substr(pos1+1, pos2 - pos1 - 1);
const std::string ext = line.substr(pos2);
if (pos1 == 1 && endsWith(nodeType, "Decl")) {
if (!tree.empty())
tree[0]->createTokens1(tokenList);
tree.clear();
tree.push_back(std::make_shared<AstNode>(nodeType, ext, &data));
continue;
}
const int level = (pos1 - 1) / 2;
if (level == 0 || level > tree.size())
continue;
AstNodePtr newNode = std::make_shared<AstNode>(nodeType, ext, &data);
tree[level - 1]->children.push_back(newNode);
if (level >= tree.size())
tree.push_back(std::move(newNode));
else
tree[level] = std::move(newNode);
}
if (!tree.empty())
tree[0]->createTokens1(tokenList);
// Validation
for (const Token *tok = tokenList.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "(|)|[|]|{|}") && !tok->link())
throw InternalError(tok, "Token::link() is not set properly");
}
if (tokenList.front())
tokenList.front()->assignIndexes();
symbolDatabase->clangSetVariables(data.getVariableList());
symbolDatabase->createSymbolDatabaseExprIds();
tokenList.clangSetOrigFiles();
setTypes(tokenList);
setValues(tokenizer, symbolDatabase);
}
| null |
857 | cpp | cppcheck | checkleakautovar.h | lib/checkleakautovar.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkleakautovarH
#define checkleakautovarH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "library.h"
#include "tokenize.h"
#include <cstdint>
#include <map>
#include <set>
#include <string>
#include <utility>
class ErrorLogger;
class Settings;
class Token;
class CPPCHECKLIB VarInfo {
public:
enum AllocStatus : std::int8_t { REALLOC = -3, OWNED = -2, DEALLOC = -1, NOALLOC = 0, ALLOC = 1 };
struct AllocInfo {
AllocStatus status;
/** Allocation type. If it is a positive value then it corresponds to
* a Library allocation id. A negative value is a builtin
* checkleakautovar allocation type.
*/
int type;
int reallocedFromType = -1;
const Token * allocTok;
explicit AllocInfo(int type_ = 0, AllocStatus status_ = NOALLOC, const Token* allocTok_ = nullptr) : status(status_), type(type_), allocTok(allocTok_) {}
bool managed() const {
return status < 0;
}
};
enum Usage : std::uint8_t { USED, NORET };
std::map<int, AllocInfo> alloctype;
std::map<int, std::pair<const Token*, Usage>> possibleUsage;
std::set<int> conditionalAlloc;
std::set<int> referenced;
void clear() {
alloctype.clear();
possibleUsage.clear();
conditionalAlloc.clear();
referenced.clear();
}
void erase(nonneg int varid) {
alloctype.erase(varid);
possibleUsage.erase(varid);
conditionalAlloc.erase(varid);
referenced.erase(varid);
}
void swap(VarInfo &other) NOEXCEPT {
alloctype.swap(other.alloctype);
possibleUsage.swap(other.possibleUsage);
conditionalAlloc.swap(other.conditionalAlloc);
referenced.swap(other.referenced);
}
void reallocToAlloc(nonneg int varid) {
const AllocInfo& alloc = alloctype[varid];
if (alloc.reallocedFromType >= 0) {
const std::map<int, VarInfo::AllocInfo>::iterator it = alloctype.find(alloc.reallocedFromType);
if (it != alloctype.end() && it->second.status == REALLOC) {
it->second.status = ALLOC;
}
}
}
/** set possible usage for all variables */
void possibleUsageAll(const std::pair<const Token*, Usage>& functionUsage);
};
/// @addtogroup Checks
/// @{
/**
* @brief Check for leaks
*/
class CPPCHECKLIB CheckLeakAutoVar : public Check {
public:
/** This constructor is used when registering the CheckLeakAutoVar */
CheckLeakAutoVar() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckLeakAutoVar(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckLeakAutoVar checkLeakAutoVar(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkLeakAutoVar.check();
}
/** check for leaks in all scopes */
void check();
/** check for leaks in a function scope */
bool checkScope(const Token * startToken,
VarInfo &varInfo,
std::set<int> notzero,
nonneg int recursiveCount);
/** Check token inside expression.
* @param tok token inside expression.
* @param varInfo Variable info
* @return next token to process (if no other checks needed for this token). NULL if other checks could be performed.
*/
const Token * checkTokenInsideExpression(const Token * tok, VarInfo &varInfo, bool inFuncCall = false);
/** parse function call */
void functionCall(const Token *tokName, const Token *tokOpeningPar, VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Library::AllocFunc* af);
/** parse changes in allocation status */
void changeAllocStatus(VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Token* tok, const Token* arg);
/** update allocation status if reallocation function */
void changeAllocStatusIfRealloc(std::map<int, VarInfo::AllocInfo> &alloctype, const Token *fTok, const Token *retTok) const;
/** return. either "return" or end of variable scope is seen */
void ret(const Token *tok, VarInfo &varInfo, bool isEndOfScope = false);
/** if variable is allocated then there is a leak */
void leakIfAllocated(const Token *vartok, const VarInfo &varInfo);
void leakError(const Token* tok, const std::string &varname, int type) const;
void mismatchError(const Token* deallocTok, const Token* allocTok, const std::string &varname) const;
void deallocUseError(const Token *tok, const std::string &varname) const;
void deallocReturnError(const Token *tok, const Token *deallocTok, const std::string &varname);
void doubleFreeError(const Token *tok, const Token *prevFreeTok, const std::string &varname, int type);
/** message: user configuration is needed to complete analysis */
void configurationInfo(const Token* tok, const std::pair<const Token*, VarInfo::Usage>& functionUsage);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckLeakAutoVar c(nullptr, settings, errorLogger);
c.deallocReturnError(nullptr, nullptr, "p");
c.configurationInfo(nullptr, { nullptr, VarInfo::USED }); // user configuration is needed to complete analysis
c.doubleFreeError(nullptr, nullptr, "varname", 0);
}
static std::string myName() {
return "Leaks (auto variables)";
}
std::string classInfo() const override {
return "Detect when a auto variable is allocated but not deallocated or deallocated twice.\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkleakautovarH
| null |
858 | cpp | cppcheck | addoninfo.h | lib/addoninfo.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef addonInfoH
#define addonInfoH
#include "config.h"
#include <string>
struct CPPCHECKLIB AddonInfo {
std::string name;
std::string scriptFile; // addon script
std::string executable; // addon executable
std::string args; // special extra arguments
std::string python; // script interpreter
bool ctu = false;
std::string runScript;
std::string getAddonInfo(const std::string &fileName, const std::string &exename, bool debug = false);
};
#endif // addonInfoH
| null |
859 | cpp | cppcheck | checkcondition.h | lib/checkcondition.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkconditionH
#define checkconditionH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "mathlib.h"
#include "errortypes.h"
#include "tokenize.h"
#include <set>
#include <string>
class Settings;
class Token;
class ErrorLogger;
class ValueType;
namespace ValueFlow {
class Value;
}
/// @addtogroup Checks
/// @{
/**
* @brief Check for condition mismatches
*/
class CPPCHECKLIB CheckCondition : public Check {
public:
/** This constructor is used when registering the CheckAssignIf */
CheckCondition() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckCondition(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckCondition checkCondition(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkCondition.multiCondition();
checkCondition.clarifyCondition(); // not simplified because ifAssign
checkCondition.multiCondition2();
checkCondition.checkIncorrectLogicOperator();
checkCondition.checkInvalidTestForOverflow();
checkCondition.duplicateCondition();
checkCondition.checkPointerAdditionResultNotNull();
checkCondition.checkDuplicateConditionalAssign();
checkCondition.assignIf();
checkCondition.checkBadBitmaskCheck();
checkCondition.comparison();
checkCondition.checkModuloAlwaysTrueFalse();
checkCondition.checkAssignmentInCondition();
checkCondition.checkCompareValueOutOfTypeRange();
checkCondition.alwaysTrueFalse();
}
/** mismatching assignment / comparison */
void assignIf();
/** parse scopes recursively */
bool assignIfParseScope(const Token * assignTok,
const Token * startTok,
nonneg int varid,
bool islocal,
char bitop,
MathLib::bigint num);
/** check bitmask using | instead of & */
void checkBadBitmaskCheck();
/** mismatching lhs and rhs in comparison */
void comparison();
void duplicateCondition();
/** match 'if' and 'else if' conditions */
void multiCondition();
/**
* multiconditions #2
* - Opposite inner conditions => always false
* - (TODO) Same/Overlapping inner condition => always true
* - same condition after early exit => always false
**/
void multiCondition2();
/** @brief %Check for testing for mutual exclusion over ||*/
void checkIncorrectLogicOperator();
/** @brief %Check for suspicious usage of modulo (e.g. "if(var % 4 == 4)") */
void checkModuloAlwaysTrueFalse();
/** @brief Suspicious condition (assignment+comparison) */
void clarifyCondition();
/** @brief Condition is always true/false */
void alwaysTrueFalse();
/** @brief %Check for invalid test for overflow 'x+100 < x' */
void checkInvalidTestForOverflow();
/** @brief Check if pointer addition result is NULL '(ptr + 1) == NULL' */
void checkPointerAdditionResultNotNull();
void checkDuplicateConditionalAssign();
/** @brief Assignment in condition */
void checkAssignmentInCondition();
// The conditions that have been diagnosed
std::set<const Token*> mCondDiags;
bool diag(const Token* tok, bool insert=true);
bool isAliased(const std::set<int> &vars) const;
bool isOverlappingCond(const Token * cond1, const Token * cond2, bool pure) const;
void assignIfError(const Token *tok1, const Token *tok2, const std::string &condition, bool result);
void mismatchingBitAndError(const Token *tok1, MathLib::bigint num1, const Token *tok2, MathLib::bigint num2);
void badBitmaskCheckError(const Token *tok, bool isNoOp = false);
void comparisonError(const Token *tok,
const std::string &bitop,
MathLib::bigint value1,
const std::string &op,
MathLib::bigint value2,
bool result);
void duplicateConditionError(const Token *tok1, const Token *tok2, ErrorPath errorPath);
void overlappingElseIfConditionError(const Token *tok, nonneg int line1);
void oppositeElseIfConditionError(const Token *ifCond, const Token *elseIfCond, ErrorPath errorPath);
void oppositeInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath);
void identicalInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath);
void identicalConditionAfterEarlyExitError(const Token *cond1, const Token *cond2, ErrorPath errorPath);
void incorrectLogicOperatorError(const Token *tok, const std::string &condition, bool always, bool inconclusive, ErrorPath errors);
void redundantConditionError(const Token *tok, const std::string &text, bool inconclusive);
void moduloAlwaysTrueFalseError(const Token* tok, const std::string& maxVal);
void clarifyConditionError(const Token *tok, bool assign, bool boolop);
void alwaysTrueFalseError(const Token* tok, const Token* condition, const ValueFlow::Value* value);
void invalidTestForOverflow(const Token* tok, const ValueType *valueType, const std::string &replace);
void pointerAdditionResultNotNullError(const Token *tok, const Token *calc);
void duplicateConditionalAssignError(const Token *condTok, const Token* assignTok, bool isRedundant = false);
void assignmentInCondition(const Token *eq);
void checkCompareValueOutOfTypeRange();
void compareValueOutOfTypeRangeError(const Token *comparison, const std::string &type, MathLib::bigint value, bool result);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckCondition c(nullptr, settings, errorLogger);
c.assignIfError(nullptr, nullptr, emptyString, false);
c.badBitmaskCheckError(nullptr);
c.comparisonError(nullptr, "&", 6, "==", 1, false);
c.duplicateConditionError(nullptr, nullptr, ErrorPath{});
c.overlappingElseIfConditionError(nullptr, 1);
c.mismatchingBitAndError(nullptr, 0xf0, nullptr, 1);
c.oppositeInnerConditionError(nullptr, nullptr, ErrorPath{});
c.identicalInnerConditionError(nullptr, nullptr, ErrorPath{});
c.identicalConditionAfterEarlyExitError(nullptr, nullptr, ErrorPath{});
c.incorrectLogicOperatorError(nullptr, "foo > 3 && foo < 4", true, false, ErrorPath{});
c.redundantConditionError(nullptr, "If x > 11 the condition x > 10 is always true.", false);
c.moduloAlwaysTrueFalseError(nullptr, "1");
c.clarifyConditionError(nullptr, true, false);
c.alwaysTrueFalseError(nullptr, nullptr, nullptr);
c.invalidTestForOverflow(nullptr, nullptr, "false");
c.pointerAdditionResultNotNullError(nullptr, nullptr);
c.duplicateConditionalAssignError(nullptr, nullptr);
c.assignmentInCondition(nullptr);
c.compareValueOutOfTypeRangeError(nullptr, "unsigned char", 256, true);
}
static std::string myName() {
return "Condition";
}
std::string classInfo() const override {
return "Match conditions with assignments and other conditions:\n"
"- Mismatching assignment and comparison => comparison is always true/false\n"
"- Mismatching lhs and rhs in comparison => comparison is always true/false\n"
"- Detect usage of | where & should be used\n"
"- Duplicate condition and assignment\n"
"- Detect matching 'if' and 'else if' conditions\n"
"- Mismatching bitand (a &= 0xf0; a &= 1; => a = 0)\n"
"- Opposite inner condition is always false\n"
"- Identical condition after early exit is always false\n"
"- Condition that is always true/false\n"
"- Mutual exclusion over || always evaluating to true\n"
"- Comparisons of modulo results that are always true/false.\n"
"- Known variable values => condition is always true/false\n"
"- Invalid test for overflow. Some mainstream compilers remove such overflow tests when optimising code.\n"
"- Suspicious assignment of container/iterator in condition => condition is always true.\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkconditionH
| null |
860 | cpp | cppcheck | pathanalysis.h | lib/pathanalysis.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GUARD_PATHANALYSIS_H
#define GUARD_PATHANALYSIS_H
#include "errortypes.h"
#include <cstdint>
#include <functional>
#include <list>
#include <utility>
class Library;
class Scope;
class Token;
struct PathAnalysis {
enum class Progress : std::uint8_t {
Continue,
Break
};
PathAnalysis(const Token* start, const Library& library)
: start(start), library(&library)
{}
const Token * start;
const Library * library;
struct Info {
const Token* tok;
ErrorPath errorPath;
bool known;
};
void forward(const std::function<Progress(const Info&)>& f) const;
Info forwardFind(std::function<bool(const Info&)> pred) const {
Info result{};
forward([&](const Info& info) {
if (pred(info)) {
result = info;
return Progress::Break;
}
return Progress::Continue;
});
return result;
}
private:
static Progress forwardRecursive(const Token* tok, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f);
Progress forwardRange(const Token* startToken, const Token* endToken, Info info, const std::function<Progress(const Info&)>& f) const;
static const Scope* findOuterScope(const Scope * scope);
static std::pair<bool, bool> checkCond(const Token * tok, bool& known);
};
/**
* @brief Returns true if there is a path between the two tokens
*
* @param start Starting point of the path
* @param dest The path destination
* @param errorPath Adds the path traversal to the errorPath
*/
bool reaches(const Token * start, const Token * dest, const Library& library, ErrorPath* errorPath);
#endif
| null |
861 | cpp | cppcheck | vf_analyzers.h | lib/vf_analyzers.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef vfAnalyzers
#define vfAnalyzers
#include "analyzer.h"
#include "valueptr.h"
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
class Token;
class Variable;
class Settings;
namespace ValueFlow {
class Value;
}
ValuePtr<Analyzer> makeMultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& settings);
ValuePtr<Analyzer> makeSameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s);
ValuePtr<Analyzer> makeOppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s);
using PartialReadContainer = std::vector<std::pair<Token *, ValueFlow::Value>>;
ValuePtr<Analyzer> makeMemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s);
ValuePtr<Analyzer> makeAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings);
ValuePtr<Analyzer> makeReverseAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings);
#endif // vfAnalyzers
| null |
862 | cpp | cppcheck | checkbool.h | lib/checkbool.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkboolH
#define checkboolH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief checks dealing with suspicious usage of boolean type (not for evaluating conditions) */
class CPPCHECKLIB CheckBool : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckBool() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckBool(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckBool checkBool(&tokenizer, &tokenizer.getSettings(), errorLogger);
// Checks
checkBool.checkComparisonOfBoolExpressionWithInt();
checkBool.checkComparisonOfBoolWithInt();
checkBool.checkAssignBoolToFloat();
checkBool.pointerArithBool();
checkBool.returnValueOfFunctionReturningBool();
checkBool.checkComparisonOfFuncReturningBool();
checkBool.checkComparisonOfBoolWithBool();
checkBool.checkIncrementBoolean();
checkBool.checkAssignBoolToPointer();
checkBool.checkBitwiseOnBoolean();
}
/** @brief %Check for comparison of function returning bool*/
void checkComparisonOfFuncReturningBool();
/** @brief %Check for comparison of variable of type bool*/
void checkComparisonOfBoolWithBool();
/** @brief %Check for using postfix increment on bool */
void checkIncrementBoolean();
/** @brief %Check for suspicious comparison of a bool and a non-zero (and non-one) value (e.g. "if (!x==4)") */
void checkComparisonOfBoolWithInt();
/** @brief assigning bool to pointer */
void checkAssignBoolToPointer();
/** @brief assigning bool to float */
void checkAssignBoolToFloat();
/** @brief %Check for using bool in bitwise expression */
void checkBitwiseOnBoolean();
/** @brief %Check for comparing a bool expression with an integer other than 0 or 1 */
void checkComparisonOfBoolExpressionWithInt();
/** @brief %Check for 'if (p+1)' etc. either somebody forgot to dereference, or else somebody uses pointer overflow */
void pointerArithBool();
void pointerArithBoolCond(const Token *tok);
/** @brief %Check if a function returning bool returns an integer other than 0 or 1 */
void returnValueOfFunctionReturningBool();
// Error messages..
void comparisonOfFuncReturningBoolError(const Token *tok, const std::string &expression);
void comparisonOfTwoFuncsReturningBoolError(const Token *tok, const std::string &expression1, const std::string &expression2);
void comparisonOfBoolWithBoolError(const Token *tok, const std::string &expression);
void incrementBooleanError(const Token *tok);
void comparisonOfBoolWithInvalidComparator(const Token *tok, const std::string &expression);
void assignBoolToPointerError(const Token *tok);
void assignBoolToFloatError(const Token *tok);
void bitwiseOnBooleanError(const Token* tok, const std::string& expression, const std::string& op, bool isCompound = false);
void comparisonOfBoolExpressionWithIntError(const Token *tok, bool not0or1);
void pointerArithBoolError(const Token *tok);
void returnValueBoolError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckBool c(nullptr, settings, errorLogger);
c.assignBoolToPointerError(nullptr);
c.assignBoolToFloatError(nullptr);
c.comparisonOfFuncReturningBoolError(nullptr, "func_name");
c.comparisonOfTwoFuncsReturningBoolError(nullptr, "func_name1", "func_name2");
c.comparisonOfBoolWithBoolError(nullptr, "var_name");
c.incrementBooleanError(nullptr);
c.bitwiseOnBooleanError(nullptr, "expression", "&&");
c.comparisonOfBoolExpressionWithIntError(nullptr, true);
c.pointerArithBoolError(nullptr);
c.comparisonOfBoolWithInvalidComparator(nullptr, "expression");
c.returnValueBoolError(nullptr);
}
static std::string myName() {
return "Boolean";
}
std::string classInfo() const override {
return "Boolean type checks\n"
"- using increment on boolean\n"
"- comparison of a boolean expression with an integer other than 0 or 1\n"
"- comparison of a function returning boolean value using relational operator\n"
"- comparison of a boolean value with boolean value using relational operator\n"
"- using bool in bitwise expression\n"
"- pointer addition in condition (either dereference is forgot or pointer overflow is required to make the condition false)\n"
"- Assigning bool value to pointer or float\n"
"- Returning an integer other than 0 or 1 from a function with boolean return value\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkboolH
| null |
863 | cpp | cppcheck | vf_settokenvalue.cpp | lib/vf_settokenvalue.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vf_settokenvalue.h"
#include "astutils.h"
#include "calculate.h"
#include "config.h"
#include "library.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "utils.h"
#include "valueflow.h"
#include "vfvalue.h"
#include "vf_common.h"
#include <algorithm>
#include <climits>
#include <cstddef>
#include <functional>
#include <list>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
namespace ValueFlow
{
static Library::Container::Yield getContainerYield(Token* tok, const Settings& settings, Token*& parent)
{
if (Token::Match(tok, ". %name% (") && tok->astParent() == tok->tokAt(2) && tok->astOperand1() &&
tok->astOperand1()->valueType()) {
const Library::Container* c = getLibraryContainer(tok->astOperand1());
parent = tok->astParent();
return c ? c->getYield(tok->strAt(1)) : Library::Container::Yield::NO_YIELD;
}
if (Token::Match(tok->previous(), "%name% (")) {
parent = tok;
if (const Library::Function* f = settings.library.getFunction(tok->previous())) {
return f->containerYield;
}
}
return Library::Container::Yield::NO_YIELD;
}
static Value truncateImplicitConversion(Token* parent, const Value& value, const Settings& settings)
{
if (!value.isIntValue() && !value.isFloatValue())
return value;
if (!parent)
return value;
if (!parent->isBinaryOp())
return value;
if (!parent->isConstOp())
return value;
if (!astIsIntegral(parent->astOperand1(), false))
return value;
if (!astIsIntegral(parent->astOperand2(), false))
return value;
const ValueType* vt1 = parent->astOperand1()->valueType();
const ValueType* vt2 = parent->astOperand2()->valueType();
// If the sign is the same there is no truncation
if (vt1->sign == vt2->sign)
return value;
const size_t n1 = getSizeOf(*vt1, settings);
const size_t n2 = getSizeOf(*vt2, settings);
ValueType::Sign sign = ValueType::Sign::UNSIGNED;
if (n1 < n2)
sign = vt2->sign;
else if (n1 > n2)
sign = vt1->sign;
Value v = castValue(value, sign, std::max(n1, n2) * 8);
v.wideintvalue = value.intvalue;
return v;
}
static const Token *getCastTypeStartToken(const Token *parent, const Settings& settings)
{
// TODO: This might be a generic utility function?
if (!Token::Match(parent, "{|("))
return nullptr;
// Functional cast
if (parent->isBinaryOp() && Token::Match(parent->astOperand1(), "%type% (|{") &&
parent->astOperand1()->tokType() == Token::eType && astIsPrimitive(parent))
return parent->astOperand1();
if (parent->str() != "(")
return nullptr;
if (!parent->astOperand2() && Token::Match(parent, "( %name%|::")) {
const Token* ftok = parent->next();
if (ftok->isStandardType())
return ftok;
if (Token::simpleMatch(ftok, "::"))
ftok = ftok->next();
while (Token::Match(ftok, "%name% ::"))
ftok = ftok->tokAt(2);
if (settings.library.isNotLibraryFunction(ftok))
return parent->next();
}
if (parent->astOperand2() && Token::Match(parent->astOperand1(), "const_cast|dynamic_cast|reinterpret_cast|static_cast <"))
return parent->astOperand1()->tokAt(2);
return nullptr;
}
static bool isNumeric(const Value& value) {
return value.isIntValue() || value.isFloatValue();
}
static void setTokenValueCast(Token *parent, const ValueType &valueType, const Value &value, const Settings &settings)
{
if (valueType.pointer || value.isImpossible())
setTokenValue(parent,value,settings);
else if (valueType.type == ValueType::Type::CHAR)
setTokenValue(parent, castValue(value, valueType.sign, settings.platform.char_bit), settings);
else if (valueType.type == ValueType::Type::SHORT)
setTokenValue(parent, castValue(value, valueType.sign, settings.platform.short_bit), settings);
else if (valueType.type == ValueType::Type::INT)
setTokenValue(parent, castValue(value, valueType.sign, settings.platform.int_bit), settings);
else if (valueType.type == ValueType::Type::LONG)
setTokenValue(parent, castValue(value, valueType.sign, settings.platform.long_bit), settings);
else if (valueType.type == ValueType::Type::LONGLONG)
setTokenValue(parent, castValue(value, valueType.sign, settings.platform.long_long_bit), settings);
else if (valueType.isFloat() && isNumeric(value)) {
Value floatValue = value;
floatValue.valueType = Value::ValueType::FLOAT;
if (value.isIntValue())
floatValue.floatValue = value.intvalue;
setTokenValue(parent, std::move(floatValue), settings);
} else if (value.isIntValue()) {
const long long charMax = settings.platform.signedCharMax();
const long long charMin = settings.platform.signedCharMin();
if (charMin <= value.intvalue && value.intvalue <= charMax) {
// unknown type, but value is small so there should be no truncation etc
setTokenValue(parent,value,settings);
}
}
}
// does the operation cause a loss of information?
static bool isNonInvertibleOperation(const Token* tok)
{
return !Token::Match(tok, "+|-");
}
static bool isComputableValue(const Token* parent, const Value& value)
{
const bool noninvertible = isNonInvertibleOperation(parent);
if (noninvertible && value.isImpossible())
return false;
if (!value.isIntValue() && !value.isFloatValue() && !value.isTokValue() && !value.isIteratorValue())
return false;
if (value.isIteratorValue() && !Token::Match(parent, "+|-"))
return false;
if (value.isTokValue() && (!parent->isComparisonOp() || !Token::Match(value.tokvalue, "{|%str%")))
return false;
return true;
}
/** Set token value for cast */
static bool isCompatibleValueTypes(Value::ValueType x, Value::ValueType y)
{
static const std::unordered_map<Value::ValueType,
std::unordered_set<Value::ValueType, EnumClassHash>,
EnumClassHash>
compatibleTypes = {
{Value::ValueType::INT,
{Value::ValueType::FLOAT,
Value::ValueType::SYMBOLIC,
Value::ValueType::TOK}},
{Value::ValueType::FLOAT, {Value::ValueType::INT}},
{Value::ValueType::TOK, {Value::ValueType::INT}},
{Value::ValueType::ITERATOR_START, {Value::ValueType::INT}},
{Value::ValueType::ITERATOR_END, {Value::ValueType::INT}},
};
if (x == y)
return true;
auto it = compatibleTypes.find(x);
if (it == compatibleTypes.end())
return false;
return it->second.count(y) > 0;
}
static bool isCompatibleValues(const Value& value1, const Value& value2)
{
if (value1.isSymbolicValue() && value2.isSymbolicValue() && value1.tokvalue->exprId() != value2.tokvalue->exprId())
return false;
if (!isCompatibleValueTypes(value1.valueType, value2.valueType))
return false;
if (value1.isKnown() || value2.isKnown())
return true;
if (value1.isImpossible() || value2.isImpossible())
return false;
if (value1.varId == 0 || value2.varId == 0)
return true;
if (value1.varId == value2.varId && value1.varvalue == value2.varvalue && value1.isIntValue() && value2.isIntValue())
return true;
return false;
}
/** set ValueFlow value and perform calculations if possible */
void setTokenValue(Token* tok,
Value value,
const Settings& settings,
SourceLocation loc)
{
// Skip setting values that are too big since its ambiguous
if (!value.isImpossible() && value.isIntValue() && value.intvalue < 0 && astIsUnsigned(tok) &&
getSizeOf(*tok->valueType(), settings) >= sizeof(MathLib::bigint))
return;
if (!value.isImpossible() && value.isIntValue())
value = truncateImplicitConversion(tok->astParent(), value, settings);
if (settings.debugnormal)
setSourceLocation(value, loc, tok);
if (!tok->addValue(value))
return;
if (value.path < 0)
return;
Token *parent = tok->astParent();
if (!parent)
return;
if (Token::simpleMatch(parent, ",") && !parent->isInitComma() && astIsRHS(tok)) {
const Token* callParent = findParent(parent, [](const Token* p) {
return !Token::simpleMatch(p, ",");
});
// Ensure that the comma isn't a function call
if (!callParent || (!Token::Match(callParent->previous(), "%name%|> (") && !Token::simpleMatch(callParent, "{") &&
(!Token::Match(callParent, "( %name%") || settings.library.isNotLibraryFunction(callParent->next())) &&
!(callParent->str() == "(" && (Token::simpleMatch(callParent->astOperand1(), "*") || Token::Match(callParent->astOperand1(), "%name%|("))))) {
setTokenValue(parent, std::move(value), settings);
return;
}
}
if (Token::simpleMatch(parent, "=") && astIsRHS(tok)) {
setTokenValue(parent, value, settings);
if (!value.isUninitValue())
return;
}
if (value.isContainerSizeValue() && astIsContainer(tok)) {
// .empty, .size, +"abc", +'a'
if (Token::Match(parent, "+|==|!=") && parent->astOperand1() && parent->astOperand2()) {
for (const Value &value1 : parent->astOperand1()->values()) {
if (value1.isImpossible())
continue;
for (const Value &value2 : parent->astOperand2()->values()) {
if (value2.isImpossible())
continue;
if (value1.path != value2.path)
continue;
Value result;
if (Token::Match(parent, "%comp%"))
result.valueType = Value::ValueType::INT;
else
result.valueType = Value::ValueType::CONTAINER_SIZE;
if (value1.isContainerSizeValue() && value2.isContainerSizeValue())
result.intvalue = calculate(parent->str(), value1.intvalue, value2.intvalue);
else if (value1.isContainerSizeValue() && value2.isTokValue() && value2.tokvalue->tokType() == Token::eString)
result.intvalue = calculate(parent->str(), value1.intvalue, MathLib::bigint(Token::getStrLength(value2.tokvalue)));
else if (value2.isContainerSizeValue() && value1.isTokValue() && value1.tokvalue->tokType() == Token::eString)
result.intvalue = calculate(parent->str(), MathLib::bigint(Token::getStrLength(value1.tokvalue)), value2.intvalue);
else
continue;
combineValueProperties(value1, value2, result);
if (Token::simpleMatch(parent, "==") && result.intvalue)
continue;
if (Token::simpleMatch(parent, "!=") && !result.intvalue)
continue;
setTokenValue(parent, std::move(result), settings);
}
}
}
Token* next = nullptr;
const Library::Container::Yield yields = getContainerYield(parent, settings, next);
if (yields == Library::Container::Yield::SIZE) {
Value v(value);
v.valueType = Value::ValueType::INT;
setTokenValue(next, std::move(v), settings);
} else if (yields == Library::Container::Yield::EMPTY) {
Value v(value);
v.valueType = Value::ValueType::INT;
v.bound = Value::Bound::Point;
if (value.isImpossible()) {
if (value.intvalue == 0)
v.setKnown();
else if ((value.bound == Value::Bound::Upper && value.intvalue > 0) ||
(value.bound == Value::Bound::Lower && value.intvalue < 0)) {
v.intvalue = 0;
v.setKnown();
} else
v.setPossible();
} else {
v.intvalue = !v.intvalue;
}
setTokenValue(next, std::move(v), settings);
}
return;
}
if (value.isLifetimeValue()) {
if (!isLifetimeBorrowed(parent, settings))
return;
if (value.lifetimeKind == Value::LifetimeKind::Iterator && astIsIterator(parent)) {
setTokenValue(parent,std::move(value),settings);
} else if (astIsPointer(tok) && astIsPointer(parent) && !parent->isUnaryOp("*") &&
(parent->isArithmeticalOp() || parent->isCast())) {
setTokenValue(parent,std::move(value),settings);
}
return;
}
if (value.isUninitValue()) {
if (Token::Match(tok, ". %var%"))
setTokenValue(tok->next(), value, settings);
if (parent->isCast()) {
setTokenValue(parent, std::move(value), settings);
return;
}
Value pvalue = value;
if (!value.subexpressions.empty() && Token::Match(parent, ". %var%")) {
if (contains(value.subexpressions, parent->strAt(1)))
pvalue.subexpressions.clear();
else
return;
}
if (parent->isUnaryOp("&")) {
pvalue.indirect++;
setTokenValue(parent, std::move(pvalue), settings);
} else if (Token::Match(parent, ". %var%") && parent->astOperand1() == tok && parent->astOperand2()) {
if (parent->originalName() == "->" && pvalue.indirect > 0)
pvalue.indirect--;
setTokenValue(parent->astOperand2(), std::move(pvalue), settings);
} else if (Token::Match(parent->astParent(), ". %var%") && parent->astParent()->astOperand1() == parent) {
if (parent->astParent()->originalName() == "->" && pvalue.indirect > 0)
pvalue.indirect--;
setTokenValue(parent->astParent()->astOperand2(), std::move(pvalue), settings);
} else if (parent->isUnaryOp("*") && pvalue.indirect > 0) {
pvalue.indirect--;
setTokenValue(parent, std::move(pvalue), settings);
}
return;
}
// cast..
if (const Token *castType = getCastTypeStartToken(parent, settings)) {
if (contains({Value::ValueType::INT, Value::ValueType::SYMBOLIC}, value.valueType) &&
Token::simpleMatch(parent->astOperand1(), "dynamic_cast"))
return;
const ValueType &valueType = ValueType::parseDecl(castType, settings);
if (value.isImpossible() && value.isIntValue() && value.intvalue < 0 && astIsUnsigned(tok) &&
valueType.sign == ValueType::SIGNED && tok->valueType() &&
getSizeOf(*tok->valueType(), settings) >= getSizeOf(valueType, settings))
return;
setTokenValueCast(parent, valueType, value, settings);
}
else if (parent->str() == ":") {
setTokenValue(parent,std::move(value),settings);
}
else if (parent->str() == "?" && tok->str() == ":" && tok == parent->astOperand2() && parent->astOperand1()) {
// is condition always true/false?
if (parent->astOperand1()->hasKnownValue()) {
const Value &condvalue = parent->astOperand1()->values().front();
const bool cond(condvalue.isTokValue() || (condvalue.isIntValue() && condvalue.intvalue != 0));
if (cond && !tok->astOperand1()) { // true condition, no second operator
setTokenValue(parent, condvalue, settings);
} else {
const Token *op = cond ? tok->astOperand1() : tok->astOperand2();
if (!op) // #7769 segmentation fault at setTokenValue()
return;
const std::list<Value> &values = op->values();
if (std::find(values.cbegin(), values.cend(), value) != values.cend())
setTokenValue(parent, std::move(value), settings);
}
} else if (!value.isImpossible()) {
// is condition only depending on 1 variable?
// cppcheck-suppress[variableScope] #8541
nonneg int varId = 0;
bool ret = false;
visitAstNodes(parent->astOperand1(),
[&](const Token *t) {
if (t->varId()) {
if (varId > 0 || value.varId != 0)
ret = true;
varId = t->varId();
} else if (t->str() == "(" && Token::Match(t->previous(), "%name%"))
ret = true; // function call
return ret ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
if (ret)
return;
Value v(std::move(value));
v.conditional = true;
v.changeKnownToPossible();
setTokenValue(parent, std::move(v), settings);
}
}
else if (parent->str() == "?" && value.isIntValue() && tok == parent->astOperand1() && value.isKnown() &&
parent->astOperand2() && parent->astOperand2()->astOperand1() && parent->astOperand2()->astOperand2()) {
const std::list<Value> &values = (value.intvalue == 0
? parent->astOperand2()->astOperand2()->values()
: parent->astOperand2()->astOperand1()->values());
for (const Value &v : values)
setTokenValue(parent, v, settings);
}
// Offset of non null pointer is not null also
else if (astIsPointer(tok) && Token::Match(parent, "+|-") &&
(parent->astOperand2() == nullptr || !astIsPointer(parent->astOperand2())) &&
value.isIntValue() && value.isImpossible() && value.intvalue == 0) {
setTokenValue(parent, std::move(value), settings);
}
// Calculations..
else if ((parent->isArithmeticalOp() || parent->isComparisonOp() || (parent->tokType() == Token::eBitOp) ||
(parent->tokType() == Token::eLogicalOp)) &&
parent->astOperand1() && parent->astOperand2()) {
const bool noninvertible = isNonInvertibleOperation(parent);
// Skip operators with impossible values that are not invertible
if (noninvertible && value.isImpossible())
return;
// known result when a operand is 0.
if (Token::Match(parent, "[&*]") && astIsIntegral(parent, true) && value.isKnown() && value.isIntValue() &&
value.intvalue == 0) {
setTokenValue(parent, std::move(value), settings);
return;
}
// known result when a operand is true.
if (Token::simpleMatch(parent, "&&") && value.isKnown() && value.isIntValue() && value.intvalue==0) {
setTokenValue(parent, std::move(value), settings);
return;
}
// known result when a operand is false.
if (Token::simpleMatch(parent, "||") && value.isKnown() && value.isIntValue() && value.intvalue!=0) {
setTokenValue(parent, std::move(value), settings);
return;
}
for (const Value &value1 : parent->astOperand1()->values()) {
if (!isComputableValue(parent, value1))
continue;
for (const Value &value2 : parent->astOperand2()->values()) {
if (value1.path != value2.path)
continue;
if (!isComputableValue(parent, value2))
continue;
if (value1.isIteratorValue() && value2.isIteratorValue())
continue;
if (!isCompatibleValues(value1, value2))
continue;
Value result(0);
combineValueProperties(value1, value2, result);
if (astIsFloat(parent, false)) {
if (!result.isIntValue() && !result.isFloatValue())
continue;
result.valueType = Value::ValueType::FLOAT;
}
const double floatValue1 = value1.isFloatValue() ? value1.floatValue : value1.intvalue;
const double floatValue2 = value2.isFloatValue() ? value2.floatValue : value2.intvalue;
const auto intValue1 = [&]() -> MathLib::bigint {
return value1.isFloatValue() ? static_cast<MathLib::bigint>(value1.floatValue) : value1.intvalue;
};
const auto intValue2 = [&]() -> MathLib::bigint {
return value2.isFloatValue() ? static_cast<MathLib::bigint>(value2.floatValue) : value2.intvalue;
};
if ((value1.isFloatValue() || value2.isFloatValue()) && Token::Match(parent, "&|^|%|<<|>>|==|!=|%or%"))
continue;
if (Token::Match(parent, "==|!=")) {
if ((value1.isIntValue() && value2.isTokValue()) || (value1.isTokValue() && value2.isIntValue())) {
if (parent->str() == "==")
result.intvalue = 0;
else if (parent->str() == "!=")
result.intvalue = 1;
} else if (value1.isIntValue() && value2.isIntValue()) {
bool error = false;
result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error);
if (error)
continue;
} else if (value1.isTokValue() && value2.isTokValue() &&
(astIsContainer(parent->astOperand1()) || astIsContainer(parent->astOperand2()))) {
const Token* tok1 = value1.tokvalue;
const Token* tok2 = value2.tokvalue;
bool equal = false;
if (Token::Match(tok1, "%str%") && Token::Match(tok2, "%str%")) {
equal = tok1->str() == tok2->str();
} else if (Token::simpleMatch(tok1, "{") && Token::simpleMatch(tok2, "{")) {
std::vector<const Token*> args1 = getArguments(tok1);
std::vector<const Token*> args2 = getArguments(tok2);
if (args1.size() == args2.size()) {
if (!std::all_of(args1.begin(), args1.end(), std::mem_fn(&Token::hasKnownIntValue)))
continue;
if (!std::all_of(args2.begin(), args2.end(), std::mem_fn(&Token::hasKnownIntValue)))
continue;
equal = std::equal(args1.begin(),
args1.end(),
args2.begin(),
[&](const Token* atok, const Token* btok) {
return atok->values().front().intvalue ==
btok->values().front().intvalue;
});
} else {
equal = false;
}
} else {
continue;
}
result.intvalue = parent->str() == "==" ? equal : !equal;
} else {
continue;
}
setTokenValue(parent, std::move(result), settings);
} else if (Token::Match(parent, "%op%")) {
if (Token::Match(parent, "%comp%")) {
if (!result.isFloatValue() && !value1.isIntValue() && !value2.isIntValue())
continue;
} else {
if (value1.isTokValue() || value2.isTokValue())
break;
}
bool error = false;
if (result.isFloatValue()) {
result.floatValue = calculate(parent->str(), floatValue1, floatValue2, &error);
} else {
result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error);
}
if (error)
continue;
// If the bound comes from the second value then invert the bound when subtracting
if (Token::simpleMatch(parent, "-") && value2.bound == result.bound &&
value2.bound != Value::Bound::Point)
result.invertBound();
setTokenValue(parent, std::move(result), settings);
}
}
}
}
// !
else if (parent->str() == "!") {
for (const Value &val : tok->values()) {
if (!val.isIntValue())
continue;
if (val.isImpossible() && val.intvalue != 0)
continue;
Value v(val);
if (val.isImpossible())
v.setKnown();
else
v.intvalue = !v.intvalue;
setTokenValue(parent, std::move(v), settings);
}
}
// ~
else if (parent->str() == "~") {
for (const Value &val : tok->values()) {
if (!val.isIntValue())
continue;
Value v(val);
v.intvalue = ~v.intvalue;
int bits = 0;
if (tok->valueType() &&
tok->valueType()->sign == ValueType::Sign::UNSIGNED &&
tok->valueType()->pointer == 0) {
if (tok->valueType()->type == ValueType::Type::INT)
bits = settings.platform.int_bit;
else if (tok->valueType()->type == ValueType::Type::LONG)
bits = settings.platform.long_bit;
}
if (bits > 0 && bits < MathLib::bigint_bits)
v.intvalue &= (((MathLib::biguint)1)<<bits) - 1;
setTokenValue(parent, std::move(v), settings);
}
}
// unary minus
else if (parent->isUnaryOp("-")) {
for (const Value &val : tok->values()) {
if (!val.isIntValue() && !val.isFloatValue())
continue;
Value v(val);
if (v.isIntValue()) {
if (v.intvalue == LLONG_MIN)
// Value can't be inverted
continue;
v.intvalue = -v.intvalue;
} else
v.floatValue = -v.floatValue;
v.invertBound();
setTokenValue(parent, std::move(v), settings);
}
}
// increment
else if (parent->str() == "++") {
for (const Value &val : tok->values()) {
if (!val.isIntValue() && !val.isFloatValue() && !val.isSymbolicValue())
continue;
Value v(val);
if (parent == tok->previous()) {
if (v.isIntValue() || v.isSymbolicValue()) {
const ValueType *dst = tok->valueType();
if (dst) {
const size_t sz = ValueFlow::getSizeOf(*dst, settings);
MathLib::bigint newvalue = ValueFlow::truncateIntValue(v.intvalue + 1, sz, dst->sign);
if (v.bound != ValueFlow::Value::Bound::Point) {
if (newvalue < v.intvalue) {
v.invertBound();
newvalue -= 2;
}
}
v.intvalue = newvalue;
} else {
v.intvalue = v.intvalue + 1;
}
}
else
v.floatValue = v.floatValue + 1.0;
}
setTokenValue(parent, std::move(v), settings);
}
}
// decrement
else if (parent->str() == "--") {
for (const Value &val : tok->values()) {
if (!val.isIntValue() && !val.isFloatValue() && !val.isSymbolicValue())
continue;
Value v(val);
if (parent == tok->previous()) {
if (v.isIntValue() || v.isSymbolicValue()) {
const ValueType *dst = tok->valueType();
if (dst) {
const size_t sz = ValueFlow::getSizeOf(*dst, settings);
MathLib::bigint newvalue = ValueFlow::truncateIntValue(v.intvalue - 1, sz, dst->sign);
if (v.bound != ValueFlow::Value::Bound::Point) {
if (newvalue > v.intvalue) {
v.invertBound();
newvalue += 2;
}
}
v.intvalue = newvalue;
} else {
v.intvalue = v.intvalue - 1;
}
}
else
v.floatValue = v.floatValue - 1.0;
}
setTokenValue(parent, std::move(v), settings);
}
}
// C++ init
else if (parent->str() == "{" && Token::simpleMatch(parent->previous(), "= {") &&
Token::simpleMatch(parent->link(), "} ;")) {
const Token* lhs = parent->previous()->astOperand1();
if (lhs && lhs->valueType()) {
if (lhs->valueType()->isIntegral() || lhs->valueType()->isFloat() || (lhs->valueType()->pointer > 0 && value.isIntValue())) {
setTokenValue(parent, std::move(value), settings);
}
}
}
else if (Token::Match(parent, ":: %name%") && parent->astOperand2() == tok) {
setTokenValue(parent, std::move(value), settings);
}
// Calling std::size or std::empty on an array
else if (value.isTokValue() && Token::simpleMatch(value.tokvalue, "{") && tok->variable() &&
tok->variable()->isArray() && Token::Match(parent->previous(), "%name% (") && astIsRHS(tok)) {
std::vector<const Token*> args = getArguments(value.tokvalue);
if (const Library::Function* f = settings.library.getFunction(parent->previous())) {
if (f->containerYield == Library::Container::Yield::SIZE) {
Value v(std::move(value));
v.valueType = Value::ValueType::INT;
v.intvalue = args.size();
setTokenValue(parent, std::move(v), settings);
} else if (f->containerYield == Library::Container::Yield::EMPTY) {
Value v(std::move(value));
v.intvalue = args.empty();
v.valueType = Value::ValueType::INT;
setTokenValue(parent, std::move(v), settings);
}
}
}
}
}
| null |
864 | cpp | cppcheck | keywords.cpp | lib/keywords.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "keywords.h"
#include "utils.h"
// see https://en.cppreference.com/w/c/keyword
#define C90_KEYWORDS \
"auto", "break", "case", "char", "const", "continue", "default", \
"do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", \
"register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", \
"union", "unsigned", "void", "volatile", "while"
#define C99_KEYWORDS \
"inline", "restrict", "_Bool", "_Complex", "_Imaginary"
#define C11_KEYWORDS \
"_Alignas", "_Alignof", "_Atomic", "_Generic", "_Noreturn", "_Static_assert", "_Thread_local"
#define C23_KEYWORDS \
"alignas", "alignof", "bool", "constexpr", "false", "nullptr", "static_assert", "thread_local", "true", "typeof", "typeof_unqual", \
"_BitInt", "_Decimal128", "_Decimal32", "_Decimal64"
static const std::unordered_set<std::string> c89_keywords_all = {
C90_KEYWORDS
};
static const std::unordered_set<std::string> c89_keywords = {
C90_KEYWORDS
};
static const std::unordered_set<std::string> c99_keywords_all = {
C90_KEYWORDS, C99_KEYWORDS
};
static const std::unordered_set<std::string> c99_keywords = {
C99_KEYWORDS
};
static const std::unordered_set<std::string> c11_keywords_all = {
C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS
};
static const std::unordered_set<std::string> c11_keywords = {
C11_KEYWORDS
};
static const std::unordered_set<std::string> c17_keywords_all = {
C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS
};
static const std::unordered_set<std::string> c17_keywords = {
};
static const std::unordered_set<std::string> c23_keywords_all = {
C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS, C23_KEYWORDS
};
static const std::unordered_set<std::string> c23_keywords = {
C23_KEYWORDS
};
// see https://en.cppreference.com/w/cpp/keyword
#define CPP03_KEYWORDS \
"and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", \
"class", "compl", "const", "const_cast", "continue", "default", \
"delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", \
"float", "for", "friend", "goto", "if", "inline", "int", "long", \
"mutable", "namespace", "new", "not", "not_eq", "operator", \
"or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", \
"return", "short", "signed", "sizeof", "static", \
"static_cast", "struct", "switch", "template", "this", "throw", \
"true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", \
"virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"
#define CPP11_KEYWORDS \
"alignas", "alignof", "char16_t", "char32_t", "constexpr", "decltype", \
"noexcept", "nullptr", "static_assert", "thread_local"
#define CPP20_KEYWORDS \
"char8_t", "concept", "consteval", "constinit", "co_await", \
"co_return", "co_yield", "requires"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-macros"
#endif
#define CPP_TMTS_KEYWORDS \
"atomic_cancel", "atomic_commit", "atomic_noexcept", "synchronized"
#define CPP_REFL_TS_KEYWORDS \
"reflexpr"
#ifdef __clang__
#pragma clang diagnostic pop
#endif
static const std::unordered_set<std::string> cpp03_keywords_all = {
CPP03_KEYWORDS
};
static const std::unordered_set<std::string> cpp03_keywords = {
CPP03_KEYWORDS
};
static const std::unordered_set<std::string> cpp11_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS
};
static const std::unordered_set<std::string> cpp11_keywords = {
CPP11_KEYWORDS
};
static const std::unordered_set<std::string> cpp14_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS
};
static const std::unordered_set<std::string> cpp14_keywords = {
};
static const std::unordered_set<std::string> cpp17_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS
};
static const std::unordered_set<std::string> cpp17_keywords = {
};
static const std::unordered_set<std::string> cpp20_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS
};
static const std::unordered_set<std::string> cpp20_keywords = {
CPP20_KEYWORDS
};
static const std::unordered_set<std::string> cpp23_keywords = {
};
static const std::unordered_set<std::string> cpp23_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS
};
static const std::unordered_set<std::string> cpp26_keywords = {
};
static const std::unordered_set<std::string> cpp26_keywords_all = {
CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS
};
// cppcheck-suppress unusedFunction
const std::unordered_set<std::string>& Keywords::getAll(Standards::cstd_t cStd)
{
// cppcheck-suppress missingReturn
switch (cStd) {
case Standards::cstd_t::C89:
return c89_keywords_all;
case Standards::cstd_t::C99:
return c99_keywords_all;
case Standards::cstd_t::C11:
return c11_keywords_all;
case Standards::cstd_t::C17:
return c17_keywords_all;
case Standards::cstd_t::C23:
return c23_keywords_all;
}
cppcheck::unreachable();
}
// cppcheck-suppress unusedFunction
const std::unordered_set<std::string>& Keywords::getAll(Standards::cppstd_t cppStd) {
// cppcheck-suppress missingReturn
switch (cppStd) {
case Standards::cppstd_t::CPP03:
return cpp03_keywords_all;
case Standards::cppstd_t::CPP11:
return cpp11_keywords_all;
case Standards::cppstd_t::CPP14:
return cpp14_keywords_all;
case Standards::cppstd_t::CPP17:
return cpp17_keywords_all;
case Standards::cppstd_t::CPP20:
return cpp20_keywords_all;
case Standards::cppstd_t::CPP23:
return cpp23_keywords_all;
case Standards::cppstd_t::CPP26:
return cpp26_keywords_all;
}
cppcheck::unreachable();
}
// cppcheck-suppress unusedFunction
const std::unordered_set<std::string>& Keywords::getOnly(Standards::cstd_t cStd)
{
// cppcheck-suppress missingReturn
switch (cStd) {
case Standards::cstd_t::C89:
return c89_keywords;
case Standards::cstd_t::C99:
return c99_keywords;
case Standards::cstd_t::C11:
return c11_keywords;
case Standards::cstd_t::C17:
return c17_keywords;
case Standards::cstd_t::C23:
return c23_keywords;
}
cppcheck::unreachable();
}
// cppcheck-suppress unusedFunction
const std::unordered_set<std::string>& Keywords::getOnly(Standards::cppstd_t cppStd)
{
// cppcheck-suppress missingReturn
switch (cppStd) {
case Standards::cppstd_t::CPP03:
return cpp03_keywords;
case Standards::cppstd_t::CPP11:
return cpp11_keywords;
case Standards::cppstd_t::CPP14:
return cpp14_keywords;
case Standards::cppstd_t::CPP17:
return cpp17_keywords;
case Standards::cppstd_t::CPP20:
return cpp20_keywords;
case Standards::cppstd_t::CPP23:
return cpp23_keywords;
case Standards::cppstd_t::CPP26:
return cpp26_keywords;
}
cppcheck::unreachable();
}
| null |
865 | cpp | cppcheck | checkunusedfunctions.h | lib/checkunusedfunctions.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkunusedfunctionsH
#define checkunusedfunctionsH
//---------------------------------------------------------------------------
#include "config.h"
#include <list>
#include <set>
#include <string>
#include <unordered_map>
class ErrorLogger;
class Function;
class Settings;
class Tokenizer;
/** @brief Check for functions never called */
/// @{
class CPPCHECKLIB CheckUnusedFunctions {
friend class TestSuppressions;
friend class TestSingleExecutorBase;
friend class TestProcessExecutorBase;
friend class TestThreadExecutorBase;
friend class TestUnusedFunctions;
public:
CheckUnusedFunctions() = default;
// Parse current tokens and determine..
// * Check what functions are used
// * What functions are declared
void parseTokens(const Tokenizer &tokenizer, const Settings &settings);
std::string analyzerInfo() const;
static void analyseWholeProgram(const Settings &settings, ErrorLogger& errorLogger, const std::string &buildDir);
static void getErrorMessages(ErrorLogger &errorLogger) {
unusedFunctionError(errorLogger, emptyString, 0, 0, "funcName");
}
// Return true if an error is reported.
bool check(const Settings& settings, ErrorLogger& errorLogger) const;
void updateFunctionData(const CheckUnusedFunctions& check);
private:
static void unusedFunctionError(ErrorLogger& errorLogger,
const std::string &filename, unsigned int fileIndex, unsigned int lineNumber,
const std::string &funcname);
struct CPPCHECKLIB FunctionUsage {
std::string filename;
unsigned int lineNumber{};
unsigned int fileIndex{};
bool usedSameFile{};
bool usedOtherFile{};
};
std::unordered_map<std::string, FunctionUsage> mFunctions;
class CPPCHECKLIB FunctionDecl {
public:
explicit FunctionDecl(const Function *f);
std::string functionName;
std::string fileName;
unsigned int lineNumber;
};
std::list<FunctionDecl> mFunctionDecl;
std::set<std::string> mFunctionCalls;
};
/// @}
//---------------------------------------------------------------------------
#endif // checkunusedfunctionsH
| null |
866 | cpp | cppcheck | templatesimplifier.h | lib/templatesimplifier.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef templatesimplifierH
#define templatesimplifierH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
class ErrorLogger;
class Settings;
class Token;
class Tokenizer;
class TokenList;
struct newInstantiation;
/// @addtogroup Core
/// @{
/** @brief Simplify templates from the preprocessed and partially simplified code. */
class CPPCHECKLIB TemplateSimplifier {
friend class TestSimplifyTemplate;
public:
explicit TemplateSimplifier(Tokenizer &tokenizer);
const std::string& dump() const {
return mDump;
}
/**
*/
void checkComplicatedSyntaxErrorsInTemplates();
/**
* is the token pointing at a template parameters block
* < int , 3 > => yes
* \param tok start token that must point at "<"
* \return number of parameters (invalid parameters => 0)
*/
static unsigned int templateParameters(const Token *tok);
/**
* Token and its full scopename
*/
class TokenAndName {
Token *mToken;
std::string mScope;
std::string mName;
std::string mFullName;
const Token *mNameToken;
const Token *mParamEnd;
unsigned int mFlags;
enum : std::uint16_t {
fIsClass = (1 << 0), // class template
fIsFunction = (1 << 1), // function template
fIsVariable = (1 << 2), // variable template
fIsAlias = (1 << 3), // alias template
fIsSpecialization = (1 << 4), // user specialized template
fIsPartialSpecialization = (1 << 5), // user partial specialized template
fIsForwardDeclaration = (1 << 6), // forward declaration
fIsVariadic = (1 << 7), // variadic template
fIsFriend = (1 << 8), // friend template
fFamilyMask = (fIsClass | fIsFunction | fIsVariable)
};
void isClass(bool state) {
setFlag(fIsClass, state);
}
void isFunction(bool state) {
setFlag(fIsFunction, state);
}
void isVariable(bool state) {
setFlag(fIsVariable, state);
}
void isAlias(bool state) {
setFlag(fIsAlias, state);
}
void isSpecialization(bool state) {
setFlag(fIsSpecialization, state);
}
void isPartialSpecialization(bool state) {
setFlag(fIsPartialSpecialization, state);
}
void isForwardDeclaration(bool state) {
setFlag(fIsForwardDeclaration, state);
}
void isVariadic(bool state) {
setFlag(fIsVariadic, state);
}
void isFriend(bool state) {
setFlag(fIsFriend, state);
}
/**
* Get specified flag state.
* @param flag flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag) const {
return ((mFlags & flag) != 0);
}
/**
* Set specified flag state.
* @param flag flag to set state
* @param state new state of flag
*/
void setFlag(unsigned int flag, bool state) {
mFlags = state ? mFlags | flag : mFlags & ~flag;
}
public:
/**
* Constructor used for instantiations.
* \param token template instantiation name token "name<...>"
* \param scope full qualification of template(scope)
*/
TokenAndName(Token *token, std::string scope);
/**
* Constructor used for declarations.
* \param token template declaration token "template < ... >"
* \param scope full qualification of template(scope)
* \param nameToken template name token "template < ... > class name"
* \param paramEnd template parameter end token ">"
*/
TokenAndName(Token *token, std::string scope, const Token *nameToken, const Token *paramEnd);
TokenAndName(const TokenAndName& other);
~TokenAndName();
bool operator == (const TokenAndName & rhs) const {
return mToken == rhs.mToken && mScope == rhs.mScope && mName == rhs.mName && mFullName == rhs.mFullName &&
mNameToken == rhs.mNameToken && mParamEnd == rhs.mParamEnd && mFlags == rhs.mFlags;
}
std::string dump(const std::vector<std::string>& fileNames) const;
// TODO: do not return non-const pointer from const object
Token * token() const {
return mToken;
}
void token(Token * token) {
mToken = token;
}
const std::string & scope() const {
return mScope;
}
const std::string & name() const {
return mName;
}
const std::string & fullName() const {
return mFullName;
}
const Token * nameToken() const {
return mNameToken;
}
const Token * paramEnd() const {
return mParamEnd;
}
void paramEnd(const Token *end) {
mParamEnd = end;
}
bool isClass() const {
return getFlag(fIsClass);
}
bool isFunction() const {
return getFlag(fIsFunction);
}
bool isVariable() const {
return getFlag(fIsVariable);
}
bool isAlias() const {
return getFlag(fIsAlias);
}
bool isSpecialization() const {
return getFlag(fIsSpecialization);
}
bool isPartialSpecialization() const {
return getFlag(fIsPartialSpecialization);
}
bool isForwardDeclaration() const {
return getFlag(fIsForwardDeclaration);
}
bool isVariadic() const {
return getFlag(fIsVariadic);
}
bool isFriend() const {
return getFlag(fIsFriend);
}
/**
* Get alias start token.
* template < ... > using X = foo < ... >;
* ^
* @return alias start token
*/
const Token * aliasStartToken() const;
/**
* Get alias end token.
* template < ... > using X = foo < ... >;
* ^
* @return alias end token
*/
const Token * aliasEndToken() const;
/**
* Is token an alias token?
* template < ... > using X = foo < ... >;
* ^
* @param tok token to check
* @return true if alias token, false if not
*/
bool isAliasToken(const Token *tok) const;
/**
* Is declaration the same family (class, function or variable).
*
* @param decl declaration to compare to
* @return true if same family, false if different family
*/
bool isSameFamily(const TemplateSimplifier::TokenAndName &decl) const {
// Make sure a family flag is set and matches.
// This works because at most only one flag will be set.
return ((mFlags & fFamilyMask) && (decl.mFlags & fFamilyMask));
}
};
/**
* Find last token of a template declaration.
* @param tok start token of declaration "template" or token after "template < ... >"
* @return last token of declaration or nullptr if syntax error
*/
static Token *findTemplateDeclarationEnd(Token *tok);
static const Token *findTemplateDeclarationEnd(const Token *tok);
/**
* Match template declaration/instantiation
* @param instance template instantiation
* @param numberOfArguments number of template arguments
* @param variadic last template argument is variadic
* @param patternAfter pattern that must match the tokens after the ">"
* @return match => true
*/
static bool instantiateMatch(const Token *instance, std::size_t numberOfArguments, bool variadic, const char patternAfter[]);
/**
* Match template declaration/instantiation
* @param tok The ">" token e.g. before "class"
* @return -1 to bail out or positive integer to identity the position
* of the template name.
*/
int getTemplateNamePosition(const Token *tok);
/**
* Get class template name position
* @param tok The ">" token e.g. before "class"
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateClass(const Token *tok, int &namepos);
/**
* Get function template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateFunction(const Token *tok, int &namepos);
/**
* Get variable template name position
* @param tok The ">" token
* @param namepos return offset to name
* @return true if name found, false if not
* */
static bool getTemplateNamePositionTemplateVariable(const Token *tok, int &namepos);
/**
* Simplify templates
* @param maxtime time when the simplification should be stopped
*/
void simplifyTemplates(std::time_t maxtime);
/**
* Simplify constant calculations such as "1+2" => "3"
* @param tok start token
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
static bool simplifyNumericCalculations(Token *tok, bool isTemplate = true);
/**
* Simplify constant calculations such as "1+2" => "3".
* This also performs simple cleanup of parentheses etc.
* @return true if modifications to token-list are done.
* false if no modifications are done.
*/
bool simplifyCalculations(Token* frontToken = nullptr, const Token *backToken = nullptr, bool isTemplate = true);
/** Simplify template instantiation arguments.
* @param start first token of arguments
* @param end token following last argument token
*/
void simplifyTemplateArgs(Token *start, const Token *end, std::vector<newInstantiation>* newInst = nullptr);
private:
/**
* Get template declarations
* @return true if code has templates.
*/
bool getTemplateDeclarations();
/** Add template instantiation.
* @param token first token of instantiation
* @param scope scope of instantiation
*/
void addInstantiation(Token *token, const std::string &scope);
/**
* Get template instantiations
*/
void getTemplateInstantiations();
/**
* Fix forward declared default argument values by copying them
* when they are not present in the declaration.
*/
void fixForwardDeclaredDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
*/
void useDefaultArgumentValues();
/**
* simplify template instantiations (use default argument values)
* @param declaration template declaration or forward declaration
*/
void useDefaultArgumentValues(TokenAndName &declaration);
/**
* Try to locate a matching declaration for each user defined
* specialization.
*/
void getSpecializations();
/**
* Try to locate a matching declaration for each user defined
* partial specialization.
*/
void getPartialSpecializations();
/**
* simplify template aliases
*/
void simplifyTemplateAliases();
/**
* Simplify templates : expand all instantiations for a template
* @todo It seems that inner templates should be instantiated recursively
* @param templateDeclaration template declaration
* @param specializations template specializations (list each template name token)
* @param maxtime time when the simplification will stop
* @param expandedtemplates all templates that has been expanded so far. The full names are stored.
* @return true if the template was instantiated
*/
bool simplifyTemplateInstantiations(
const TokenAndName &templateDeclaration,
const std::list<const Token *> &specializations,
std::time_t maxtime,
std::set<std::string> &expandedtemplates);
/**
* Simplify templates : add namespace to template name
* @param templateDeclaration template declaration
* @param tok place to insert namespace
*/
void addNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Simplify templates : check if namespace already present
* @param templateDeclaration template declaration
* @param tok place to start looking for namespace
* @return true if namespace already present
*/
static bool alreadyHasNamespace(const TokenAndName &templateDeclaration, const Token *tok);
/**
* Expand a template. Create "expanded" class/function at end of tokenlist.
* @param templateDeclaration Template declaration information
* @param templateInstantiation Full name of template
* @param typeParametersInDeclaration The type parameters of the template
* @param newName New name of class/function.
* @param copy copy or expand in place
*/
void expandTemplate(
const TokenAndName &templateDeclaration,
const TokenAndName &templateInstantiation,
const std::vector<const Token *> &typeParametersInDeclaration,
const std::string &newName,
bool copy);
/**
* Replace all matching template usages 'Foo < int >' => 'Foo<int>'
* @param instantiation Template instantiation information.
* @param typeStringsUsedInTemplateInstantiation template parameters. list of token strings.
* @param newName The new type name
*/
void replaceTemplateUsage(const TokenAndName &instantiation,
const std::list<std::string> &typeStringsUsedInTemplateInstantiation,
const std::string &newName);
/**
* @brief TemplateParametersInDeclaration
* @param tok template < typename T, typename S >
* ^ tok
* @param typeParametersInDeclaration template < typename T, typename S >
* ^ [0] ^ [1]
*/
static void getTemplateParametersInDeclaration(
const Token * tok,
std::vector<const Token *> & typeParametersInDeclaration);
/**
* Remove a specific "template < ..." template class/function
*/
static bool removeTemplate(Token *tok, std::map<Token*, Token*>* forwardDecls = nullptr);
/** Syntax error */
NORETURN static void syntaxError(const Token *tok);
static bool matchSpecialization(
const Token *templateDeclarationNameToken,
const Token *templateInstantiationNameToken,
const std::list<const Token *> & specializations);
/*
* Same as Token::eraseTokens() but tries to fix up lists with pointers to the deleted tokens.
* @param begin Tokens after this will be erased.
* @param end Tokens before this will be erased.
*/
static void eraseTokens(Token *begin, const Token *end);
/**
* Delete specified token without invalidating pointer to following token.
* tok will be invalidated.
* @param tok token to delete
*/
static void deleteToken(Token *tok);
/**
* Get the new token name.
* @param tok2 name token
* @param typeStringsUsedInTemplateInstantiation type strings use in template instantiation
* @return new token name
*/
std::string getNewName(
Token *tok2,
std::list<std::string> &typeStringsUsedInTemplateInstantiation);
void printOut(
const TokenAndName &tokenAndName,
const std::string &indent = " ") const;
void printOut(const std::string &text = emptyString) const;
Tokenizer &mTokenizer;
TokenList &mTokenList;
const Settings &mSettings;
ErrorLogger &mErrorLogger;
bool mChanged{};
std::list<TokenAndName> mTemplateDeclarations;
std::list<TokenAndName> mTemplateForwardDeclarations;
std::map<Token *, Token *> mTemplateForwardDeclarationsMap;
std::map<Token *, Token *> mTemplateSpecializationMap;
std::map<Token *, Token *> mTemplatePartialSpecializationMap;
std::list<TokenAndName> mTemplateInstantiations;
std::list<TokenAndName> mInstantiatedTemplates;
std::list<TokenAndName> mMemberFunctionsToDelete;
std::vector<TokenAndName> mExplicitInstantiationsToDelete;
std::vector<TokenAndName> mTypesUsedInTemplateInstantiation;
std::unordered_map<const Token*, int> mTemplateNamePos;
std::string mDump;
};
/// @}
//---------------------------------------------------------------------------
#endif // templatesimplifierH
| null |
867 | cpp | cppcheck | checknullpointer.cpp | lib/checknullpointer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checknullpointer.h"
#include "astutils.h"
#include "ctu.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "findtoken.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "valueflow.h"
#include <algorithm>
#include <cctype>
#include <map>
#include <set>
#include <vector>
//---------------------------------------------------------------------------
// CWE ids used:
static const CWE CWE_NULL_POINTER_DEREFERENCE(476U);
static const CWE CWE_INCORRECT_CALCULATION(682U);
// Register this check class (by creating a static instance of it)
namespace {
CheckNullPointer instance;
}
//---------------------------------------------------------------------------
static bool checkNullpointerFunctionCallPlausibility(const Function* func, unsigned int arg)
{
return !func || (func->argCount() >= arg && func->getArgumentVar(arg - 1) && func->getArgumentVar(arg - 1)->isPointer());
}
/**
* @brief parse a function call and extract information about variable usage
* @param tok first token
* @param var variables that the function read / write.
* @param library --library files data
* @param checkNullArg perform isnullargbad check for each argument?
*/
void CheckNullPointer::parseFunctionCall(const Token &tok, std::list<const Token *> &var, const Library &library, bool checkNullArg)
{
if (Token::Match(&tok, "%name% ( )") || !tok.tokAt(2))
return;
const std::vector<const Token *> args = getArguments(&tok);
for (int argnr = 1; argnr <= args.size(); ++argnr) {
const Token *param = args[argnr - 1];
if ((!checkNullArg || library.isnullargbad(&tok, argnr)) && checkNullpointerFunctionCallPlausibility(tok.function(), argnr))
var.push_back(param);
else if (tok.function()) {
const Variable* argVar = tok.function()->getArgumentVar(argnr-1);
if (argVar && argVar->isStlStringType() && !argVar->isArrayOrPointer())
var.push_back(param);
}
}
if (library.formatstr_function(&tok)) {
const int formatStringArgNr = library.formatstr_argno(&tok);
if (formatStringArgNr < 0 || formatStringArgNr >= args.size())
return;
// 1st parameter..
if (Token::Match(&tok, "snprintf|vsnprintf|fnprintf|vfnprintf") && args.size() > 1 && !(args[1] && args[1]->hasKnownIntValue() && args[1]->getKnownIntValue() == 0)) // Only if length (second parameter) is not zero
var.push_back(args[0]);
if (args[formatStringArgNr]->tokType() != Token::eString)
return;
const std::string &formatString = args[formatStringArgNr]->strValue();
int argnr = formatStringArgNr + 1;
const bool scan = library.formatstr_scan(&tok);
bool percent = false;
for (std::string::const_iterator i = formatString.cbegin(); i != formatString.cend(); ++i) {
if (*i == '%') {
percent = !percent;
} else if (percent) {
percent = false;
bool _continue = false;
while (!std::isalpha((unsigned char)*i)) {
if (*i == '*') {
if (scan)
_continue = true;
else
argnr++;
}
++i;
if (i == formatString.end())
return;
}
if (_continue)
continue;
if (argnr < args.size() && (*i == 'n' || *i == 's' || scan))
var.push_back(args[argnr]);
if (*i != 'm') // %m is a non-standard glibc extension that requires no parameter
argnr++;
}
}
}
}
namespace {
const std::set<std::string> stl_stream = {
"fstream", "ifstream", "iostream", "istream",
"istringstream", "ofstream", "ostream", "ostringstream",
"stringstream", "wistringstream", "wostringstream", "wstringstream"
};
}
/**
* Is there a pointer dereference? Everything that should result in
* a nullpointer dereference error message will result in a true
* return value. If it's unknown if the pointer is dereferenced false
* is returned.
* @param tok token for the pointer
* @param unknown it is not known if there is a pointer dereference (could be reported as a debug message)
* @return true => there is a dereference
*/
bool CheckNullPointer::isPointerDeRef(const Token *tok, bool &unknown) const
{
return isPointerDeRef(tok, unknown, *mSettings);
}
bool CheckNullPointer::isPointerDeRef(const Token *tok, bool &unknown, const Settings &settings, bool checkNullArg)
{
unknown = false;
// Is pointer used as function parameter?
if (Token::Match(tok->previous(), "[(,] %name% [,)]")) {
const Token *ftok = tok->previous();
while (ftok && ftok->str() != "(") {
if (ftok->str() == ")")
ftok = ftok->link();
ftok = ftok->previous();
}
if (ftok && ftok->previous()) {
std::list<const Token *> varlist;
parseFunctionCall(*ftok->previous(), varlist, settings.library, checkNullArg);
if (std::find(varlist.cbegin(), varlist.cend(), tok) != varlist.cend()) {
return true;
}
}
}
if (tok->str() == "(" && !tok->scope()->isExecutable())
return false;
const Token* parent = tok->astParent();
if (!parent)
return false;
const bool addressOf = parent->astParent() && parent->astParent()->str() == "&";
if (parent->str() == "." && astIsRHS(tok))
return isPointerDeRef(parent, unknown, settings);
const bool firstOperand = parent->astOperand1() == tok;
parent = astParentSkipParens(tok);
if (!parent)
return false;
// Dereferencing pointer..
const Token* grandParent = parent->astParent();
if (parent->isUnaryOp("*") && !(grandParent && isUnevaluated(grandParent->previous()))) {
// declaration of function pointer
if (tok->variable() && tok->variable()->nameToken() == tok)
return false;
if (!addressOf)
return true;
}
// array access
if (firstOperand && parent->str() == "[" && !addressOf)
return true;
// address of member variable / array element
const Token *parent2 = parent;
while (Token::Match(parent2, "[|."))
parent2 = parent2->astParent();
if (parent2 != parent && parent2 && parent2->isUnaryOp("&"))
return false;
// read/write member variable
if (firstOperand && parent->originalName() == "->" && !addressOf)
return true;
// If its a function pointer then check if its called
if (tok->variable() && tok->variable()->isPointer() && Token::Match(tok->variable()->nameToken(), "%name% ) (") &&
Token::Match(tok, "%name% ("))
return true;
if (Token::Match(tok, "%var% = %var% .") &&
tok->varId() == tok->tokAt(2)->varId())
return true;
// std::string dereferences nullpointers
if (Token::Match(parent->tokAt(-3), "std :: string|wstring (|{ %name% )|}"))
return true;
if (Token::Match(parent->previous(), "%name% (|{ %name% )|}")) {
const Variable* var = tok->tokAt(-2)->variable();
if (var && !var->isPointer() && !var->isArray() && var->isStlStringType())
return true;
}
// streams dereference nullpointers
if (Token::Match(parent, "<<|>>") && !firstOperand) {
const Variable* var = tok->variable();
if (var && var->isPointer() && Token::Match(var->typeStartToken(), "char|wchar_t")) { // Only outputting or reading to char* can cause problems
const Token* tok2 = parent; // Find start of statement
for (; tok2; tok2 = tok2->previous()) {
if (Token::Match(tok2->previous(), ";|{|}|:"))
break;
}
if (Token::Match(tok2, "std :: cout|cin|cerr"))
return true;
if (tok2 && tok2->varId() != 0) {
const Variable* var2 = tok2->variable();
if (var2 && var2->isStlType(stl_stream))
return true;
}
}
}
const Variable *ovar = nullptr;
if (Token::Match(parent, "+|==|!=") || (parent->str() == "=" && !firstOperand)) {
if (parent->astOperand1() == tok && parent->astOperand2())
ovar = parent->astOperand2()->variable();
else if (parent->astOperand1() && parent->astOperand2() == tok)
ovar = parent->astOperand1()->variable();
}
if (ovar && !ovar->isPointer() && !ovar->isArray() && ovar->isStlStringType())
return true;
// assume that it's not a dereference (no false positives)
return false;
}
static bool isNullablePointer(const Token* tok)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "new") && tok->varId() == 0)
return false;
if (astIsPointer(tok))
return true;
if (astIsSmartPointer(tok))
return true;
if (Token::simpleMatch(tok, "."))
return isNullablePointer(tok->astOperand2());
if (const Variable* var = tok->variable()) {
return (var->isPointer() || var->isSmartPointer());
}
return false;
}
void CheckNullPointer::nullPointerByDeRefAndCheck()
{
const bool printInconclusive = (mSettings->certainty.isEnabled(Certainty::inconclusive));
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
auto pred = [printInconclusive](const Token* tok) -> bool {
if (!tok)
return false;
if (Token::Match(tok, "%num%|%char%|%str%"))
return false;
if (!isNullablePointer(tok) ||
(tok->str() == "." && isNullablePointer(tok->astOperand2()) && tok->astOperand2()->getValue(0))) // avoid duplicate warning
return false;
// Can pointer be NULL?
const ValueFlow::Value *value = tok->getValue(0);
if (!value)
return false;
if (!printInconclusive && value->isInconclusive())
return false;
return true;
};
std::vector<const Token *> tokens = findTokensSkipDeadAndUnevaluatedCode(mSettings->library, scope->bodyStart, scope->bodyEnd, pred);
for (const Token *tok : tokens) {
const ValueFlow::Value *value = tok->getValue(0);
// Pointer dereference.
bool unknown = false;
if (!isPointerDeRef(tok, unknown)) {
if (unknown)
nullPointerError(tok, tok->expressionString(), value, true);
continue;
}
nullPointerError(tok, tok->expressionString(), value, value->isInconclusive());
}
}
}
void CheckNullPointer::nullPointer()
{
logChecker("CheckNullPointer::nullPointer");
nullPointerByDeRefAndCheck();
}
namespace {
const std::set<std::string> stl_istream = {
"fstream", "ifstream", "iostream", "istream",
"istringstream", "stringstream", "wistringstream", "wstringstream"
};
}
/** Dereferencing null constant (simplified token list) */
void CheckNullPointer::nullConstantDereference()
{
logChecker("CheckNullPointer::nullConstantDereference");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body
continue;
const Token *tok = scope->bodyStart;
if (scope->function->isConstructor())
tok = scope->function->token; // Check initialization list
for (; tok != scope->bodyEnd; tok = tok->next()) {
if (isUnevaluated(tok))
tok = tok->linkAt(1);
else if (Token::simpleMatch(tok, "* 0")) {
if (Token::Match(tok->previous(), "return|throw|;|{|}|:|[|(|,") || tok->previous()->isOp()) {
nullPointerError(tok);
}
}
else if (Token::Match(tok, "0 [") && (tok->strAt(-1) != "&" || !Token::Match(tok->linkAt(1)->next(), "[.(]")))
nullPointerError(tok);
else if (Token::Match(tok->previous(), "!!. %name% (|{") && (tok->strAt(-1) != "::" || tok->strAt(-2) == "std")) {
if (Token::Match(tok->tokAt(2), "0|NULL|nullptr )|}") && tok->varId()) { // constructor call
const Variable *var = tok->variable();
if (var && !var->isPointer() && !var->isArray() && var->isStlStringType())
nullPointerError(tok);
} else { // function call
std::list<const Token *> var;
parseFunctionCall(*tok, var, mSettings->library);
// is one of the var items a NULL pointer?
for (const Token *vartok : var) {
if (vartok->hasKnownIntValue() && vartok->getKnownIntValue() == 0)
nullPointerError(vartok);
}
}
} else if (Token::Match(tok, "std :: string|wstring ( 0|NULL|nullptr )"))
nullPointerError(tok);
else if (Token::Match(tok->previous(), "::|. %name% (")) {
const std::vector<const Token *> &args = getArguments(tok);
for (int argnr = 0; argnr < args.size(); ++argnr) {
const Token *argtok = args[argnr];
if (!argtok->hasKnownIntValue())
continue;
if (argtok->values().front().intvalue != 0)
continue;
if (mSettings->library.isnullargbad(tok, argnr+1))
nullPointerError(argtok);
}
}
else if (Token::Match(tok->previous(), ">> 0|NULL|nullptr")) { // Only checking input stream operations is safe here, because otherwise 0 can be an integer as well
const Token* tok2 = tok->previous(); // Find start of statement
for (; tok2; tok2 = tok2->previous()) {
if (Token::Match(tok2->previous(), ";|{|}|:|("))
break;
}
if (tok2 && tok2->previous() && tok2->strAt(-1)=="(")
continue;
if (Token::simpleMatch(tok2, "std :: cin"))
nullPointerError(tok);
if (tok2 && tok2->varId() != 0) {
const Variable *var = tok2->variable();
if (var && var->isStlType(stl_istream))
nullPointerError(tok);
}
}
const Variable *ovar = nullptr;
const Token *tokNull = nullptr;
if (Token::Match(tok, "0|NULL|nullptr ==|!=|>|>=|<|<= %var%")) {
if (!Token::Match(tok->tokAt(3),".|[")) {
ovar = tok->tokAt(2)->variable();
tokNull = tok;
}
} else if (Token::Match(tok, "%var% ==|!=|>|>=|<|<= 0|NULL|nullptr") ||
Token::Match(tok, "%var% =|+ 0|NULL|nullptr )|]|,|;|+")) {
ovar = tok->variable();
tokNull = tok->tokAt(2);
}
if (ovar && !ovar->isPointer() && !ovar->isArray() && ovar->isStlStringType() && tokNull && tokNull->originalName() != "'\\0'")
nullPointerError(tokNull);
}
}
}
void CheckNullPointer::nullPointerError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive)
{
const std::string errmsgcond("$symbol:" + varname + '\n' + ValueFlow::eitherTheConditionIsRedundant(value ? value->condition : nullptr) + " or there is possible null pointer dereference: $symbol.");
const std::string errmsgdefarg("$symbol:" + varname + "\nPossible null pointer dereference if the default parameter value is used: $symbol");
if (!tok) {
reportError(tok, Severity::error, "nullPointer", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
reportError(tok, Severity::warning, "nullPointerDefaultArg", errmsgdefarg, CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
reportError(tok, Severity::warning, "nullPointerRedundantCheck", errmsgcond, CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
reportError(tok, Severity::warning, "nullPointerOutOfMemory", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
reportError(tok, Severity::warning, "nullPointerOutOfResources", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
return;
}
if (!value) {
reportError(tok, Severity::error, "nullPointer", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, inconclusive ? Certainty::inconclusive : Certainty::normal);
return;
}
if (!mSettings->isEnabled(value, inconclusive) && !mSettings->isPremiumEnabled("nullPointer"))
return;
const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer dereference");
if (value->condition) {
reportError(errorPath, Severity::warning, "nullPointerRedundantCheck", errmsgcond, CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
} else if (value->defaultArg) {
reportError(errorPath, Severity::warning, "nullPointerDefaultArg", errmsgdefarg, CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
} else {
std::string errmsg = std::string(value->isKnown() ? "Null" : "Possible null") + " pointer dereference";
std::string id = "nullPointer";
if (value->unknownFunctionReturn == ValueFlow::Value::UnknownFunctionReturn::outOfMemory) {
errmsg = "If memory allocation fails, then there is a " + ((char)std::tolower(errmsg[0]) + errmsg.substr(1));
id += "OutOfMemory";
}
else if (value->unknownFunctionReturn == ValueFlow::Value::UnknownFunctionReturn::outOfResources) {
errmsg = "If resource allocation fails, then there is a " + ((char)std::tolower(errmsg[0]) + errmsg.substr(1));
id += "OutOfResources";
}
if (!varname.empty())
errmsg = "$symbol:" + varname + '\n' + errmsg + ": $symbol";
reportError(errorPath,
value->isKnown() ? Severity::error : Severity::warning,
id.c_str(),
errmsg,
CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
}
void CheckNullPointer::arithmetic()
{
logChecker("CheckNullPointer::arithmetic");
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "-|+|+=|-=|++|--"))
continue;
const Token *pointerOperand;
const Token *numericOperand;
if (tok->astOperand1() && tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->pointer != 0) {
pointerOperand = tok->astOperand1();
numericOperand = tok->astOperand2();
} else if (tok->astOperand2() && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->pointer != 0) {
pointerOperand = tok->astOperand2();
numericOperand = tok->astOperand1();
} else
continue;
if (numericOperand && numericOperand->valueType() && !numericOperand->valueType()->isIntegral())
continue;
const ValueFlow::Value* numValue = numericOperand ? numericOperand->getValue(0) : nullptr;
if (numValue && numValue->intvalue == 0) // don't warn for arithmetic with 0
continue;
const ValueFlow::Value* value = pointerOperand->getValue(0);
if (!value)
continue;
if (!mSettings->certainty.isEnabled(Certainty::inconclusive) && value->isInconclusive())
continue;
if (value->condition && !mSettings->severity.isEnabled(Severity::warning))
continue;
if (value->condition)
redundantConditionWarning(tok, value, value->condition, value->isInconclusive());
else
pointerArithmeticError(tok, value, value->isInconclusive());
}
}
}
static std::string arithmeticTypeString(const Token *tok)
{
if (tok && tok->str()[0] == '-')
return "subtraction";
if (tok && tok->str()[0] == '+')
return "addition";
return "arithmetic";
}
void CheckNullPointer::pointerArithmeticError(const Token* tok, const ValueFlow::Value *value, bool inconclusive)
{
// cppcheck-suppress shadowFunction - TODO: fix this
std::string arithmetic = arithmeticTypeString(tok);
std::string errmsg;
if (tok && tok->str()[0] == '-') {
errmsg = "Overflow in pointer arithmetic, NULL pointer is subtracted.";
} else {
errmsg = "Pointer " + arithmetic + " with NULL pointer.";
}
std::string id = "nullPointerArithmetic";
if (value && value->unknownFunctionReturn == ValueFlow::Value::UnknownFunctionReturn::outOfMemory) {
errmsg = "If memory allocation fail: " + ((char)std::tolower(errmsg[0]) + errmsg.substr(1));
id += "OutOfMemory";
}
else if (value && value->unknownFunctionReturn == ValueFlow::Value::UnknownFunctionReturn::outOfResources) {
errmsg = "If resource allocation fail: " + ((char)std::tolower(errmsg[0]) + errmsg.substr(1));
id += "OutOfResources";
}
const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer " + arithmetic);
reportError(errorPath,
Severity::error,
id.c_str(),
errmsg,
CWE_INCORRECT_CALCULATION,
inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckNullPointer::redundantConditionWarning(const Token* tok, const ValueFlow::Value *value, const Token *condition, bool inconclusive)
{
// cppcheck-suppress shadowFunction - TODO: fix this
std::string arithmetic = arithmeticTypeString(tok);
std::string errmsg;
if (tok && tok->str()[0] == '-') {
errmsg = ValueFlow::eitherTheConditionIsRedundant(condition) + " or there is overflow in pointer " + arithmetic + ".";
} else {
errmsg = ValueFlow::eitherTheConditionIsRedundant(condition) + " or there is pointer arithmetic with NULL pointer.";
}
const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer " + arithmetic);
reportError(errorPath,
Severity::warning,
"nullPointerArithmeticRedundantCheck",
errmsg,
CWE_INCORRECT_CALCULATION,
inconclusive ? Certainty::inconclusive : Certainty::normal);
}
// NOLINTNEXTLINE(readability-non-const-parameter) - used as callback so we need to preserve the signature
static bool isUnsafeUsage(const Settings &settings, const Token *vartok, MathLib::bigint *value)
{
(void)value;
bool unknown = false;
return CheckNullPointer::isPointerDeRef(vartok, unknown, settings);
}
// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now
// see https://trac.cppcheck.net/ticket/12108 for more details
#ifdef __clang__
inline namespace CheckNullPointer_internal
#else
namespace
#endif
{
/* data for multifile checking */
class MyFileInfo : public Check::FileInfo {
public:
/** function arguments that are dereferenced without checking if they are null */
std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage;
/** Convert data into xml string */
std::string toString() const override
{
return CTU::toString(unsafeUsage);
}
};
}
Check::FileInfo *CheckNullPointer::getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const
{
const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::getUnsafeUsage(tokenizer, settings, isUnsafeUsage);
if (unsafeUsage.empty())
return nullptr;
auto *fileInfo = new MyFileInfo;
fileInfo->unsafeUsage = unsafeUsage;
return fileInfo;
}
Check::FileInfo * CheckNullPointer::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const
{
const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::loadUnsafeUsageListFromXml(xmlElement);
if (unsafeUsage.empty())
return nullptr;
auto *fileInfo = new MyFileInfo;
fileInfo->unsafeUsage = unsafeUsage;
return fileInfo;
}
bool CheckNullPointer::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger)
{
if (!ctu)
return false;
bool foundErrors = false;
(void)settings; // This argument is unused
CheckNullPointer dummy(nullptr, &settings, &errorLogger);
dummy.
logChecker("CheckNullPointer::analyseWholeProgram"); // unusedfunctions
const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap();
for (const Check::FileInfo* fi1 : fileInfo) {
const auto *fi = dynamic_cast<const MyFileInfo*>(fi1);
if (!fi)
continue;
for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) {
for (int warning = 0; warning <= 1; warning++) {
if (warning == 1 && !settings.severity.isEnabled(Severity::warning))
break;
const std::list<ErrorMessage::FileLocation> &locationList =
CTU::FileInfo::getErrorPath(CTU::FileInfo::InvalidValueType::null,
unsafeUsage,
callsMap,
"Dereferencing argument ARG that is null",
nullptr,
warning,
settings.maxCtuDepth);
if (locationList.empty())
continue;
const ErrorMessage errmsg(locationList,
emptyString,
warning ? Severity::warning : Severity::error,
"Null pointer dereference: " + unsafeUsage.myArgumentName,
"ctunullpointer",
CWE_NULL_POINTER_DEREFERENCE, Certainty::normal);
errorLogger.reportErr(errmsg);
foundErrors = true;
break;
}
}
}
return foundErrors;
}
| null |
868 | cpp | cppcheck | suppressions.h | lib/suppressions.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef suppressionsH
#define suppressionsH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstddef>
#include <cstdint>
#include <istream>
#include <list>
#include <set>
#include <string>
#include <utility>
#include <vector>
/// @addtogroup Core
/// @{
class Tokenizer;
class ErrorMessage;
class ErrorLogger;
enum class Certainty : std::uint8_t;
class FileWithDetails;
/** @brief class for handling suppressions */
class CPPCHECKLIB SuppressionList {
public:
enum class Type : std::uint8_t {
unique, file, block, blockBegin, blockEnd, macro
};
struct CPPCHECKLIB ErrorMessage {
std::size_t hash;
std::string errorId;
void setFileName(std::string s);
const std::string &getFileName() const {
return mFileName;
}
int lineNumber;
Certainty certainty;
std::string symbolNames;
std::set<std::string> macroNames;
static SuppressionList::ErrorMessage fromErrorMessage(const ::ErrorMessage &msg, const std::set<std::string> ¯oNames);
private:
std::string mFileName;
};
struct CPPCHECKLIB Suppression {
Suppression() = default;
Suppression(std::string id, std::string file, int line=NO_LINE) : errorId(std::move(id)), fileName(std::move(file)), lineNumber(line) {}
bool operator<(const Suppression &other) const {
if (errorId != other.errorId)
return errorId < other.errorId;
if (lineNumber < other.lineNumber)
return true;
if (fileName != other.fileName)
return fileName < other.fileName;
if (symbolName != other.symbolName)
return symbolName < other.symbolName;
if (macroName != other.macroName)
return macroName < other.macroName;
if (hash != other.hash)
return hash < other.hash;
if (thisAndNextLine != other.thisAndNextLine)
return thisAndNextLine;
return false;
}
bool operator==(const Suppression &other) const {
if (errorId != other.errorId)
return false;
if (lineNumber < other.lineNumber)
return false;
if (fileName != other.fileName)
return false;
if (symbolName != other.symbolName)
return false;
if (macroName != other.macroName)
return false;
if (hash != other.hash)
return false;
if (type != other.type)
return false;
if (lineBegin != other.lineBegin)
return false;
if (lineEnd != other.lineEnd)
return false;
return true;
}
/**
* Parse inline suppression in comment
* @param comment the full comment text
* @param errorMessage output parameter for error message (wrong suppression attribute)
* @return true if it is a inline comment.
*/
bool parseComment(std::string comment, std::string *errorMessage);
bool isSuppressed(const ErrorMessage &errmsg) const;
bool isMatch(const ErrorMessage &errmsg);
std::string getText() const;
bool isLocal() const {
return !fileName.empty() && fileName.find_first_of("?*") == std::string::npos;
}
bool isSameParameters(const Suppression &other) const {
return errorId == other.errorId &&
fileName == other.fileName &&
lineNumber == other.lineNumber &&
symbolName == other.symbolName &&
hash == other.hash &&
thisAndNextLine == other.thisAndNextLine;
}
std::string errorId;
std::string fileName;
int lineNumber = NO_LINE;
int lineBegin = NO_LINE;
int lineEnd = NO_LINE;
Type type = Type::unique;
std::string symbolName;
std::string macroName;
std::size_t hash{};
bool thisAndNextLine{}; // Special case for backwards compatibility: { // cppcheck-suppress something
bool matched{};
bool checked{}; // for inline suppressions, checked or not
enum : std::int8_t { NO_LINE = -1 };
};
/**
* @brief Don't show errors listed in the file.
* @param istr Open file stream where errors can be read.
* @return error message. empty upon success
*/
std::string parseFile(std::istream &istr);
/**
* @brief Don't show errors listed in the file.
* @param filename file name
* @return error message. empty upon success
*/
std::string parseXmlFile(const char *filename);
/**
* Parse multi inline suppression in comment
* @param comment the full comment text
* @param errorMessage output parameter for error message (wrong suppression attribute)
* @return empty vector if something wrong.
*/
static std::vector<Suppression> parseMultiSuppressComment(const std::string &comment, std::string *errorMessage);
/**
* @brief Don't show the given error.
* @param line Description of error to suppress (in id:file:line format).
* @return error message. empty upon success
*/
std::string addSuppressionLine(const std::string &line);
/**
* @brief Don't show this error. File and/or line are optional. In which case
* the errorId alone is used for filtering.
* @param suppression suppression details
* @return error message. empty upon success
*/
std::string addSuppression(Suppression suppression);
/**
* @brief Combine list of suppressions into the current suppressions.
* @param suppressions list of suppression details
* @return error message. empty upon success
*/
std::string addSuppressions(std::list<Suppression> suppressions);
/**
* @brief Returns true if this message should not be shown to the user.
* @param errmsg error message
* @param global use global suppressions
* @return true if this error is suppressed.
*/
bool isSuppressed(const ErrorMessage &errmsg, bool global = true);
/**
* @brief Returns true if this message is "explicitly" suppressed. The suppression "id" must match textually exactly.
* @param errmsg error message
* @param global use global suppressions
* @return true if this error is explicitly suppressed.
*/
bool isSuppressedExplicitly(const ErrorMessage &errmsg, bool global = true);
/**
* @brief Returns true if this message should not be shown to the user.
* @param errmsg error message
* @return true if this error is suppressed.
*/
bool isSuppressed(const ::ErrorMessage &errmsg, const std::set<std::string>& macroNames);
/**
* @brief Create an xml dump of suppressions
* @param out stream to write XML to
*/
void dump(std::ostream &out) const;
/**
* @brief Returns list of unmatched local (per-file) suppressions.
* @return list of unmatched suppressions
*/
std::list<Suppression> getUnmatchedLocalSuppressions(const FileWithDetails &file, bool unusedFunctionChecking) const;
/**
* @brief Returns list of unmatched global (glob pattern) suppressions.
* @return list of unmatched suppressions
*/
std::list<Suppression> getUnmatchedGlobalSuppressions(bool unusedFunctionChecking) const;
/**
* @brief Returns list of all suppressions.
* @return list of suppressions
*/
const std::list<Suppression> &getSuppressions() const;
/**
* @brief Marks Inline Suppressions as checked if source line is in the token stream
*/
void markUnmatchedInlineSuppressionsAsChecked(const Tokenizer &tokenizer);
/**
* Report unmatched suppressions
* @param unmatched list of unmatched suppressions (from Settings::Suppressions::getUnmatched(Local|Global)Suppressions)
* @return true is returned if errors are reported
*/
static bool reportUnmatchedSuppressions(const std::list<SuppressionList::Suppression> &unmatched, ErrorLogger &errorLogger);
private:
/** @brief List of error which the user doesn't want to see. */
std::list<Suppression> mSuppressions;
};
struct Suppressions
{
/** @brief suppress message (--suppressions) */
SuppressionList nomsg;
/** @brief suppress exitcode */
SuppressionList nofail;
};
/// @}
//---------------------------------------------------------------------------
#endif // suppressionsH
| null |
869 | cpp | cppcheck | checkpostfixoperator.h | lib/checkpostfixoperator.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkpostfixoperatorH
#define checkpostfixoperatorH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Using postfix operators ++ or -- rather than postfix operator.
*/
class CPPCHECKLIB CheckPostfixOperator : public Check {
friend class TestPostfixOperator;
public:
/** This constructor is used when registering the CheckPostfixOperator */
CheckPostfixOperator() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckPostfixOperator(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
if (tokenizer.isC())
return;
CheckPostfixOperator checkPostfixOperator(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkPostfixOperator.postfixOperator();
}
/** Check postfix operators */
void postfixOperator();
/** Report Error */
void postfixOperatorError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckPostfixOperator c(nullptr, settings, errorLogger);
c.postfixOperatorError(nullptr);
}
static std::string myName() {
return "Using postfix operators";
}
std::string classInfo() const override {
return "Warn if using postfix operators ++ or -- rather than prefix operator\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkpostfixoperatorH
| null |
870 | cpp | cppcheck | checkcondition.cpp | lib/checkcondition.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Check for condition mismatches
//---------------------------------------------------------------------------
#include "checkcondition.h"
#include "astutils.h"
#include "library.h"
#include "platform.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "utils.h"
#include "vfvalue.h"
#include "checkother.h" // comparisonNonZeroExpressionLessThanZero and testIfNonZeroExpressionIsPositive
#include <algorithm>
#include <cstdint>
#include <limits>
#include <list>
#include <set>
#include <sstream>
#include <utility>
#include <vector>
// CWE ids used
static const CWE uncheckedErrorConditionCWE(391U);
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE570(570U); // Expression is Always False
static const CWE CWE571(571U); // Expression is Always True
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckCondition instance;
}
bool CheckCondition::diag(const Token* tok, bool insert)
{
if (!tok)
return false;
const Token* parent = tok->astParent();
bool hasParent = false;
while (Token::Match(parent, "!|&&|%oror%")) {
if (mCondDiags.count(parent) != 0) {
hasParent = true;
break;
}
parent = parent->astParent();
}
if (mCondDiags.count(tok) == 0 && !hasParent) {
if (insert)
mCondDiags.insert(tok);
return false;
}
return true;
}
bool CheckCondition::isAliased(const std::set<int> &vars) const
{
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "= & %var% ;") && vars.find(tok->tokAt(2)->varId()) != vars.end())
return true;
}
return false;
}
void CheckCondition::assignIf()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("assignIfError"))
return;
logChecker("CheckCondition::assignIf"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=")
continue;
if (Token::Match(tok->tokAt(-2), "[;{}] %var% =")) {
const Variable *var = tok->previous()->variable();
if (var == nullptr)
continue;
char bitop = '\0';
MathLib::bigint num = 0;
if (Token::Match(tok->next(), "%num% [&|]")) {
bitop = tok->strAt(2).at(0);
num = MathLib::toBigNumber(tok->strAt(1));
} else {
const Token *endToken = Token::findsimplematch(tok, ";");
// Casting address
if (endToken && Token::Match(endToken->tokAt(-4), "* ) & %any% ;"))
endToken = nullptr;
if (endToken && Token::Match(endToken->tokAt(-2), "[&|] %num% ;")) {
bitop = endToken->strAt(-2).at(0);
num = MathLib::toBigNumber(endToken->strAt(-1));
}
}
if (bitop == '\0')
continue;
if (num < 0 && bitop == '|')
continue;
assignIfParseScope(tok, tok->tokAt(4), var->declarationId(), var->isLocal(), bitop, num);
}
}
}
static bool isParameterChanged(const Token *partok)
{
bool addressOf = Token::Match(partok, "[(,] &");
int argumentNumber = 0;
const Token *ftok;
for (ftok = partok; ftok && ftok->str() != "("; ftok = ftok->previous()) {
if (ftok->str() == ")")
ftok = ftok->link();
else if (argumentNumber == 0U && ftok->str() == "&")
addressOf = true;
else if (ftok->str() == ",")
argumentNumber++;
}
ftok = ftok ? ftok->previous() : nullptr;
if (!(ftok && ftok->function()))
return true;
const Variable *par = ftok->function()->getArgumentVar(argumentNumber);
if (!par)
return true;
if (par->isConst())
return false;
if (addressOf || par->isReference() || par->isPointer())
return true;
return false;
}
/** parse scopes recursively */
bool CheckCondition::assignIfParseScope(const Token * const assignTok,
const Token * const startTok,
const nonneg int varid,
const bool islocal,
const char bitop,
const MathLib::bigint num)
{
bool ret = false;
for (const Token *tok2 = startTok; tok2; tok2 = tok2->next()) {
if ((bitop == '&') && Token::Match(tok2->tokAt(2), "%varid% %cop% %num% ;", varid) && tok2->strAt(3) == std::string(1U, bitop)) {
const MathLib::bigint num2 = MathLib::toBigNumber(tok2->strAt(4));
if (0 == (num & num2))
mismatchingBitAndError(assignTok, num, tok2, num2);
}
if (Token::Match(tok2, "%varid% =", varid)) {
return true;
}
if (bitop == '&' && Token::Match(tok2, "%varid% &= %num% ;", varid)) {
const MathLib::bigint num2 = MathLib::toBigNumber(tok2->strAt(2));
if (0 == (num & num2))
mismatchingBitAndError(assignTok, num, tok2, num2);
}
if (Token::Match(tok2, "++|-- %varid%", varid) || Token::Match(tok2, "%varid% ++|--", varid))
return true;
if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid) && isParameterChanged(tok2))
return true;
if (tok2->str() == "}")
return false;
if (Token::Match(tok2, "break|continue|return"))
ret = true;
if (ret && tok2->str() == ";")
return false;
if (!islocal && Token::Match(tok2, "%name% (") && !Token::simpleMatch(tok2->linkAt(1), ") {"))
return true;
if (Token::Match(tok2, "if|while (")) {
if (!islocal && tok2->str() == "while")
continue;
if (tok2->str() == "while") {
// is variable changed in loop?
const Token *bodyStart = tok2->linkAt(1)->next();
const Token *bodyEnd = bodyStart ? bodyStart->link() : nullptr;
if (!bodyEnd || bodyEnd->str() != "}" || isVariableChanged(bodyStart, bodyEnd, varid, !islocal, *mSettings))
continue;
}
// parse condition
const Token * const end = tok2->linkAt(1);
for (; tok2 != end; tok2 = tok2->next()) {
if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid)) {
return true;
}
if (Token::Match(tok2,"&&|%oror%|( %varid% ==|!= %num% &&|%oror%|)", varid)) {
const Token *vartok = tok2->next();
const MathLib::bigint num2 = MathLib::toBigNumber(vartok->strAt(2));
if ((num & num2) != ((bitop=='&') ? num2 : num)) {
const std::string& op(vartok->strAt(1));
const bool alwaysTrue = op == "!=";
const std::string condition(vartok->str() + op + vartok->strAt(2));
assignIfError(assignTok, tok2, condition, alwaysTrue);
}
}
if (Token::Match(tok2, "%varid% %op%", varid) && tok2->next()->isAssignmentOp()) {
return true;
}
}
const bool ret1 = assignIfParseScope(assignTok, end->tokAt(2), varid, islocal, bitop, num);
bool ret2 = false;
if (Token::simpleMatch(end->linkAt(1), "} else {"))
ret2 = assignIfParseScope(assignTok, end->linkAt(1)->tokAt(3), varid, islocal, bitop, num);
if (ret1 || ret2)
return true;
}
}
return false;
}
void CheckCondition::assignIfError(const Token *tok1, const Token *tok2, const std::string &condition, bool result)
{
if (tok2 && diag(tok2->tokAt(2)))
return;
std::list<const Token *> locations = { tok1, tok2 };
reportError(locations,
Severity::style,
"assignIfError",
"Mismatching assignment and comparison, comparison '" + condition + "' is always " + std::string(bool_to_string(result)) + ".", CWE398, Certainty::normal);
}
void CheckCondition::mismatchingBitAndError(const Token *tok1, const MathLib::bigint num1, const Token *tok2, const MathLib::bigint num2)
{
std::list<const Token *> locations = { tok1, tok2 };
std::ostringstream msg;
msg << "Mismatching bitmasks. Result is always 0 ("
<< "X = Y & 0x" << std::hex << num1 << "; Z = X & 0x" << std::hex << num2 << "; => Z=0).";
reportError(locations,
Severity::style,
"mismatchingBitAnd",
msg.str(), CWE398, Certainty::normal);
}
static void getnumchildren(const Token *tok, std::list<MathLib::bigint> &numchildren)
{
if (tok->astOperand1() && tok->astOperand1()->isNumber())
numchildren.push_back(MathLib::toBigNumber(tok->astOperand1()->str()));
else if (tok->astOperand1() && tok->str() == tok->astOperand1()->str())
getnumchildren(tok->astOperand1(), numchildren);
if (tok->astOperand2() && tok->astOperand2()->isNumber())
numchildren.push_back(MathLib::toBigNumber(tok->astOperand2()->str()));
else if (tok->astOperand2() && tok->str() == tok->astOperand2()->str())
getnumchildren(tok->astOperand2(), numchildren);
}
/* Return whether tok is in the body for a function returning a boolean. */
static bool inBooleanFunction(const Token *tok)
{
const Scope *scope = tok ? tok->scope() : nullptr;
while (scope && scope->isLocal())
scope = scope->nestedIn;
if (scope && scope->type == Scope::eFunction) {
const Function *func = scope->function;
if (func) {
const Token *ret = func->retDef;
while (Token::Match(ret, "static|const"))
ret = ret->next();
return Token::Match(ret, "bool|_Bool");
}
}
return false;
}
static bool isOperandExpanded(const Token *tok)
{
if (tok->isExpandedMacro() || tok->isEnumerator())
return true;
if (tok->astOperand1() && isOperandExpanded(tok->astOperand1()))
return true;
if (tok->astOperand2() && isOperandExpanded(tok->astOperand2()))
return true;
return false;
}
void CheckCondition::checkBadBitmaskCheck()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("badBitmaskCheck"))
return;
logChecker("CheckCondition::checkBadBitmaskCheck"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() == "|" && tok->astOperand1() && tok->astOperand2() && tok->astParent()) {
const Token* parent = tok->astParent();
const bool isBoolean = Token::Match(parent, "&&|%oror%") ||
(parent->str() == "?" && parent->astOperand1() == tok) ||
(parent->str() == "=" && parent->astOperand2() == tok && parent->astOperand1() && parent->astOperand1()->variable() && Token::Match(parent->astOperand1()->variable()->typeStartToken(), "bool|_Bool")) ||
(parent->str() == "(" && Token::Match(parent->astOperand1(), "if|while")) ||
(parent->str() == "return" && parent->astOperand1() == tok && inBooleanFunction(tok));
const bool isTrue = (tok->astOperand1()->hasKnownIntValue() && tok->astOperand1()->values().front().intvalue != 0) ||
(tok->astOperand2()->hasKnownIntValue() && tok->astOperand2()->values().front().intvalue != 0);
if (isBoolean && isTrue)
badBitmaskCheckError(tok);
// If there are #ifdef in the expression don't warn about redundant | to avoid FP
const auto& startStop = tok->findExpressionStartEndTokens();
if (mTokenizer->hasIfdef(startStop.first, startStop.second))
continue;
const bool isZero1 = (tok->astOperand1()->hasKnownIntValue() && tok->astOperand1()->values().front().intvalue == 0);
const bool isZero2 = (tok->astOperand2()->hasKnownIntValue() && tok->astOperand2()->values().front().intvalue == 0);
if (!isZero1 && !isZero2)
continue;
if (!tok->isExpandedMacro() &&
!(isZero1 && isOperandExpanded(tok->astOperand1())) &&
!(isZero2 && isOperandExpanded(tok->astOperand2())))
badBitmaskCheckError(tok, /*isNoOp*/ true);
}
}
}
void CheckCondition::badBitmaskCheckError(const Token *tok, bool isNoOp)
{
if (isNoOp)
reportError(tok, Severity::style, "badBitmaskCheck", "Operator '|' with one operand equal to zero is redundant.", CWE571, Certainty::normal);
else
reportError(tok, Severity::warning, "badBitmaskCheck", "Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?", CWE571, Certainty::normal);
}
void CheckCondition::comparison()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("comparisonError"))
return;
logChecker("CheckCondition::comparison"); // style
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isComparisonOp())
continue;
const Token *expr1 = tok->astOperand1();
const Token *expr2 = tok->astOperand2();
if (!expr1 || !expr2)
continue;
if (expr1->hasKnownIntValue())
std::swap(expr1,expr2);
if (!expr2->hasKnownIntValue())
continue;
if (!compareTokenFlags(expr1, expr2, /*macro*/ true))
continue;
const MathLib::bigint num2 = expr2->getKnownIntValue();
if (num2 < 0)
continue;
if (!Token::Match(expr1,"[&|]"))
continue;
std::list<MathLib::bigint> numbers;
getnumchildren(expr1, numbers);
for (const MathLib::bigint num1 : numbers) {
if (num1 < 0)
continue;
if (Token::Match(tok, "==|!=")) {
if ((expr1->str() == "&" && (num1 & num2) != num2) ||
(expr1->str() == "|" && (num1 | num2) != num2)) {
const std::string& op(tok->str());
comparisonError(expr1, expr1->str(), num1, op, num2, op != "==");
}
} else if (expr1->str() == "&") {
const bool or_equal = Token::Match(tok, ">=|<=");
const std::string& op(tok->str());
if ((Token::Match(tok, ">=|<")) && (num1 < num2)) {
comparisonError(expr1, expr1->str(), num1, op, num2, !or_equal);
} else if ((Token::Match(tok, "<=|>")) && (num1 <= num2)) {
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal);
}
} else if (expr1->str() == "|") {
if ((expr1->astOperand1()->valueType()) &&
(expr1->astOperand1()->valueType()->sign == ValueType::Sign::UNSIGNED)) {
const bool or_equal = Token::Match(tok, ">=|<=");
const std::string& op(tok->str());
if ((Token::Match(tok, ">=|<")) && (num1 >= num2)) {
//"(a | 0x07) >= 7U" is always true for unsigned a
//"(a | 0x07) < 7U" is always false for unsigned a
comparisonError(expr1, expr1->str(), num1, op, num2, or_equal);
} else if ((Token::Match(tok, "<=|>")) && (num1 > num2)) {
//"(a | 0x08) <= 7U" is always false for unsigned a
//"(a | 0x07) > 6U" is always true for unsigned a
comparisonError(expr1, expr1->str(), num1, op, num2, !or_equal);
}
}
}
}
}
}
void CheckCondition::comparisonError(const Token *tok, const std::string &bitop, MathLib::bigint value1, const std::string &op, MathLib::bigint value2, bool result)
{
std::ostringstream expression;
expression << std::hex << "(X " << bitop << " 0x" << value1 << ") " << op << " 0x" << value2;
const std::string errmsg("Expression '" + expression.str() + "' is always " + bool_to_string(result) + ".\n"
"The expression '" + expression.str() + "' is always " + bool_to_string(result) +
". Check carefully constants and operators used, these errors might be hard to "
"spot sometimes. In case of complex expression it might help to split it to "
"separate expressions.");
reportError(tok, Severity::style, "comparisonError", errmsg, CWE398, Certainty::normal);
}
bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token * const cond2, bool pure) const
{
if (!cond1 || !cond2)
return false;
// same expressions
if (isSameExpression(true, cond1, cond2, *mSettings, pure, false))
return true;
// bitwise overlap for example 'x&7' and 'x==1'
if (cond1->str() == "&" && cond1->astOperand1() && cond2->astOperand2()) {
const Token *expr1 = cond1->astOperand1();
const Token *num1 = cond1->astOperand2();
if (!num1) // unary operator&
return false;
if (!num1->isNumber())
std::swap(expr1,num1);
if (!num1->isNumber() || MathLib::isNegative(num1->str()))
return false;
if (!Token::Match(cond2, "&|==") || !cond2->astOperand1() || !cond2->astOperand2())
return false;
const Token *expr2 = cond2->astOperand1();
const Token *num2 = cond2->astOperand2();
if (!num2->isNumber())
std::swap(expr2,num2);
if (!num2->isNumber() || MathLib::isNegative(num2->str()))
return false;
if (!isSameExpression(true, expr1, expr2, *mSettings, pure, false))
return false;
const MathLib::bigint value1 = MathLib::toBigNumber(num1->str());
const MathLib::bigint value2 = MathLib::toBigNumber(num2->str());
if (cond2->str() == "&")
return ((value1 & value2) == value2);
return ((value1 & value2) > 0);
}
return false;
}
void CheckCondition::duplicateCondition()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateCondition"))
return;
logChecker("CheckCondition::duplicateCondition"); // style
const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
const Token* tok2 = scope.classDef->next();
if (!tok2)
continue;
const Token* cond1 = tok2->astOperand2();
if (!cond1)
continue;
if (cond1->hasKnownIntValue())
continue;
tok2 = tok2->link();
if (!Token::simpleMatch(tok2, ") {"))
continue;
tok2 = tok2->linkAt(1);
if (!Token::simpleMatch(tok2, "} if ("))
continue;
const Token *cond2 = tok2->tokAt(2)->astOperand2();
if (!cond2)
continue;
ErrorPath errorPath;
if (!findExpressionChanged(cond1, scope.classDef->next(), cond2, *mSettings) &&
isSameExpression(true, cond1, cond2, *mSettings, true, true, &errorPath))
duplicateConditionError(cond1, cond2, std::move(errorPath));
}
}
void CheckCondition::duplicateConditionError(const Token *tok1, const Token *tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
errorPath.emplace_back(tok1, "First condition");
errorPath.emplace_back(tok2, "Second condition");
std::string msg = "The if condition is the same as the previous if condition";
reportError(errorPath, Severity::style, "duplicateCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::multiCondition()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("multiCondition"))
return;
logChecker("CheckCondition::multiCondition"); // style
const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
if (scope.type != Scope::eIf)
continue;
const Token * const cond1 = scope.classDef->next()->astOperand2();
if (!cond1)
continue;
const Token * tok2 = scope.classDef->next();
// Check each 'else if'
for (;;) {
tok2 = tok2->link();
if (!Token::simpleMatch(tok2, ") {"))
break;
tok2 = tok2->linkAt(1);
if (!Token::simpleMatch(tok2, "} else { if ("))
break;
tok2 = tok2->tokAt(4);
if (tok2->astOperand2()) {
ErrorPath errorPath;
if (isOverlappingCond(cond1, tok2->astOperand2(), true) &&
!findExpressionChanged(cond1, cond1, tok2->astOperand2(), *mSettings))
overlappingElseIfConditionError(tok2->astOperand2(), cond1->linenr());
else if (isOppositeCond(
true, cond1, tok2->astOperand2(), *mSettings, true, true, &errorPath) &&
!findExpressionChanged(cond1, cond1, tok2->astOperand2(), *mSettings))
oppositeElseIfConditionError(cond1, tok2->astOperand2(), std::move(errorPath));
}
}
}
}
void CheckCondition::overlappingElseIfConditionError(const Token *tok, nonneg int line1)
{
if (diag(tok))
return;
std::ostringstream errmsg;
errmsg << "Expression is always false because 'else if' condition matches previous condition at line "
<< line1 << ".";
reportError(tok, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal);
}
void CheckCondition::oppositeElseIfConditionError(const Token *ifCond, const Token *elseIfCond, ErrorPath errorPath)
{
if (diag(ifCond) & diag(elseIfCond))
return;
std::ostringstream errmsg;
errmsg << "Expression is always true because 'else if' condition is opposite to previous condition at line "
<< ifCond->linenr() << ".";
errorPath.emplace_back(ifCond, "first condition");
errorPath.emplace_back(elseIfCond, "else if condition is opposite to first condition");
reportError(errorPath, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// - Opposite inner conditions => always false
// - (TODO) Same/Overlapping inner condition => always true
// - same condition after early exit => always false
//---------------------------------------------------------------------------
static bool isNonConstFunctionCall(const Token *ftok, const Library &library)
{
if (library.isFunctionConst(ftok))
return false;
const Token *obj = ftok->next()->astOperand1();
while (obj && obj->str() == ".")
obj = obj->astOperand1();
if (!obj)
return true;
if (obj->variable() && obj->variable()->isConst())
return false;
if (ftok->function() && ftok->function()->isConst())
return false;
return true;
}
void CheckCondition::multiCondition2()
{
if (!mSettings->severity.isEnabled(Severity::warning) &&
!mSettings->isPremiumEnabled("identicalConditionAfterEarlyExit") &&
!mSettings->isPremiumEnabled("identicalInnerCondition"))
return;
logChecker("CheckCondition::multiCondition2"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope &scope : symbolDatabase->scopeList) {
const Token *condTok = nullptr;
if (scope.type == Scope::eIf || scope.type == Scope::eWhile)
condTok = scope.classDef->next()->astOperand2();
else if (scope.type == Scope::eFor) {
condTok = scope.classDef->next()->astOperand2();
if (!condTok || condTok->str() != ";")
continue;
condTok = condTok->astOperand2();
if (!condTok || condTok->str() != ";")
continue;
condTok = condTok->astOperand1();
}
if (!condTok)
continue;
const Token * const cond1 = condTok;
if (!Token::simpleMatch(scope.classDef->linkAt(1), ") {"))
continue;
bool functionCall = false;
bool nonConstFunctionCall = false;
bool nonlocal = false; // nonlocal variable used in condition
std::set<int> vars; // variables used in condition
visitAstNodes(condTok,
[&](const Token *cond) {
if (Token::Match(cond, "%name% (")) {
functionCall = true;
nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library);
if (nonConstFunctionCall)
return ChildrenToVisit::done;
}
if (cond->varId()) {
vars.insert(cond->varId());
const Variable *var = cond->variable();
if (!nonlocal && var) {
if (!(var->isLocal() || var->isArgument()))
nonlocal = true;
else if ((var->isPointer() || var->isReference()) && !Token::Match(cond->astParent(), "%oror%|&&|!"))
// TODO: if var is pointer check what it points at
nonlocal = true;
}
} else if (!nonlocal && cond->isName()) {
// varid is 0. this is possibly a nonlocal variable..
nonlocal = Token::Match(cond->astParent(), "%cop%|(|[") || Token::Match(cond, "%name% .") || (cond->isCpp() && cond->str() == "this");
} else {
return ChildrenToVisit::op1_and_op2;
}
return ChildrenToVisit::none;
});
if (nonConstFunctionCall)
continue;
std::vector<const Variable*> varsInCond;
visitAstNodes(condTok,
[&varsInCond](const Token *cond) {
if (cond->variable()) {
const Variable *var = cond->variable();
if (std::find(varsInCond.cbegin(), varsInCond.cend(), var) == varsInCond.cend())
varsInCond.push_back(var);
}
return ChildrenToVisit::op1_and_op2;
});
// parse until second condition is reached..
enum MULTICONDITIONTYPE : std::uint8_t { INNER, AFTER };
const Token *tok;
// Parse inner condition first and then early return condition
std::vector<MULTICONDITIONTYPE> types = {MULTICONDITIONTYPE::INNER};
if (Token::Match(scope.bodyStart, "{ return|throw|continue|break"))
types.push_back(MULTICONDITIONTYPE::AFTER);
for (const MULTICONDITIONTYPE type:types) {
if (type == MULTICONDITIONTYPE::AFTER) {
tok = scope.bodyEnd->next();
} else {
tok = scope.bodyStart;
}
const Token * const endToken = tok->scope()->bodyEnd;
for (; tok && tok != endToken; tok = tok->next()) {
if (isExpressionChangedAt(cond1, tok, 0, false, *mSettings))
break;
if (Token::Match(tok, "if|return")) {
const Token * condStartToken = tok->str() == "if" ? tok->next() : tok;
const Token * condEndToken = tok->str() == "if" ? condStartToken->link() : Token::findsimplematch(condStartToken, ";");
// Does condition modify tracked variables?
if (findExpressionChanged(cond1, condStartToken, condEndToken, *mSettings))
break;
// Condition..
const Token *cond2 = tok->str() == "if" ? condStartToken->astOperand2() : condStartToken->astOperand1();
const bool isReturnVar = (tok->str() == "return" && (!Token::Match(cond2, "%cop%") || (cond2 && cond2->isUnaryOp("!"))));
ErrorPath errorPath;
if (type == MULTICONDITIONTYPE::INNER) {
visitAstNodes(cond1, [&](const Token* firstCondition) {
if (!firstCondition)
return ChildrenToVisit::none;
if (firstCondition->str() == "&&") {
if (!isOppositeCond(false, firstCondition, cond2, *mSettings, true, true))
return ChildrenToVisit::op1_and_op2;
}
if (!firstCondition->hasKnownIntValue()) {
if (!isReturnVar && isOppositeCond(false, firstCondition, cond2, *mSettings, true, true, &errorPath)) {
if (!isAliased(vars))
oppositeInnerConditionError(firstCondition, cond2, errorPath);
} else if (!isReturnVar && isSameExpression(true, firstCondition, cond2, *mSettings, true, true, &errorPath)) {
identicalInnerConditionError(firstCondition, cond2, errorPath);
}
}
return ChildrenToVisit::none;
});
} else {
visitAstNodes(cond2, [&](const Token *secondCondition) {
if (secondCondition->str() == "||" || secondCondition->str() == "&&")
return ChildrenToVisit::op1_and_op2;
if ((!cond1->hasKnownIntValue() || !secondCondition->hasKnownIntValue()) &&
isSameExpression(true, cond1, secondCondition, *mSettings, true, true, &errorPath)) {
if (!isAliased(vars) && !mTokenizer->hasIfdef(cond1, secondCondition)) {
identicalConditionAfterEarlyExitError(cond1, secondCondition, errorPath);
return ChildrenToVisit::done;
}
}
return ChildrenToVisit::none;
});
}
}
if (Token::Match(tok, "%name% (") &&
isVariablesChanged(tok, tok->linkAt(1), 0, varsInCond, *mSettings)) {
break;
}
if (Token::Match(tok, "%type% (") && nonlocal && isNonConstFunctionCall(tok, mSettings->library)) // non const function call -> bailout if there are nonlocal variables
break;
if (Token::Match(tok, "case|break|continue|return|throw") && tok->scope() == endToken->scope())
break;
if (Token::Match(tok, "[;{}] %name% :"))
break;
// bailout if loop is seen.
// TODO: handle loops better.
if (Token::Match(tok, "for|while|do")) {
const Token *tok1 = tok->next();
const Token *tok2;
if (Token::simpleMatch(tok, "do {")) {
if (!Token::simpleMatch(tok->linkAt(1), "} while ("))
break;
tok2 = tok->linkAt(1)->linkAt(2);
} else if (Token::Match(tok, "if|while (")) {
tok2 = tok->linkAt(1);
if (Token::simpleMatch(tok2, ") {"))
tok2 = tok2->linkAt(1);
if (!tok2)
break;
} else {
// Incomplete code
break;
}
const bool changed = std::any_of(vars.cbegin(), vars.cend(), [&](int varid) {
return isVariableChanged(tok1, tok2, varid, nonlocal, *mSettings);
});
if (changed)
break;
}
if ((tok->varId() && vars.find(tok->varId()) != vars.end()) ||
(!tok->varId() && nonlocal) ||
(functionCall && tok->variable() && !tok->variable()->isLocal())) {
if (Token::Match(tok, "%name% %assign%|++|--"))
break;
if (Token::Match(tok->astParent(), "*|.|[")) {
const Token *parent = tok;
while (Token::Match(parent->astParent(), ".|[") || (parent->astParent() && parent->astParent()->isUnaryOp("*")))
parent = parent->astParent();
if (Token::Match(parent->astParent(), "%assign%|++|--"))
break;
}
if (tok->isCpp() && Token::Match(tok, "%name% <<") && (!tok->valueType() || !tok->valueType()->isIntegral()))
break;
if (isLikelyStreamRead(tok->next()) || isLikelyStreamRead(tok->previous()))
break;
if (Token::Match(tok, "%name% [")) {
const Token *tok2 = tok->linkAt(1);
while (Token::simpleMatch(tok2, "] ["))
tok2 = tok2->linkAt(1);
if (Token::Match(tok2, "] %assign%|++|--"))
break;
}
if (Token::Match(tok->previous(), "++|--|& %name%"))
break;
if (tok->variable() &&
!tok->variable()->isConst() &&
Token::Match(tok, "%name% . %name% (")) {
const Function* function = tok->tokAt(2)->function();
if (!function || !function->isConst())
break;
}
if (Token::Match(tok->previous(), "[(,] *|& %name% [,)]") && isParameterChanged(tok))
break;
}
}
}
}
}
static std::string innerSmtString(const Token * tok)
{
if (!tok)
return "if";
const Token * top = tok->astTop();
if (top->str() == "(" && top->astOperand1())
return top->astOperand1()->str();
return top->str();
}
void CheckCondition::oppositeInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
const std::string s1(tok1 ? tok1->expressionString() : "x");
const std::string s2(tok2 ? tok2->expressionString() : "!x");
const std::string innerSmt = innerSmtString(tok2);
errorPath.emplace_back(tok1, "outer condition: " + s1);
errorPath.emplace_back(tok2, "opposite inner condition: " + s2);
const std::string msg("Opposite inner '" + innerSmt + "' condition leads to a dead code block.\n"
"Opposite inner '" + innerSmt + "' condition leads to a dead code block (outer condition is '" + s1 + "' and inner condition is '" + s2 + "').");
reportError(errorPath, Severity::warning, "oppositeInnerCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::identicalInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath)
{
if (diag(tok1) & diag(tok2))
return;
const std::string s1(tok1 ? tok1->expressionString() : "x");
const std::string s2(tok2 ? tok2->expressionString() : "x");
const std::string innerSmt = innerSmtString(tok2);
errorPath.emplace_back(tok1, "outer condition: " + s1);
errorPath.emplace_back(tok2, "identical inner condition: " + s2);
const std::string msg("Identical inner '" + innerSmt + "' condition is always true.\n"
"Identical inner '" + innerSmt + "' condition is always true (outer condition is '" + s1 + "' and inner condition is '" + s2 + "').");
reportError(errorPath, Severity::warning, "identicalInnerCondition", msg, CWE398, Certainty::normal);
}
void CheckCondition::identicalConditionAfterEarlyExitError(const Token *cond1, const Token* cond2, ErrorPath errorPath)
{
if (diag(cond1) & diag(cond2))
return;
const bool isReturnValue = cond2 && Token::simpleMatch(cond2->astParent(), "return");
const std::string cond(cond1 ? cond1->expressionString() : "x");
const std::string value = (cond2 && cond2->valueType() && cond2->valueType()->type == ValueType::Type::BOOL) ? "false" : "0";
errorPath.emplace_back(cond1, "If condition '" + cond + "' is true, the function will return/exit");
errorPath.emplace_back(cond2, (isReturnValue ? "Returning identical expression '" : "Testing identical condition '") + cond + "'");
reportError(errorPath,
Severity::warning,
"identicalConditionAfterEarlyExit",
isReturnValue
? ("Identical condition and return expression '" + cond + "', return value is always " + value)
: ("Identical condition '" + cond + "', second condition is always false"),
CWE398,
Certainty::normal);
}
//---------------------------------------------------------------------------
// if ((x != 1) || (x != 3)) // expression always true
// if ((x == 1) && (x == 3)) // expression always false
// if ((x < 1) && (x > 3)) // expression always false
// if ((x > 3) || (x < 10)) // expression always true
// if ((x > 5) && (x != 1)) // second comparison always true
//
// Check for suspect logic for an expression consisting of 2 comparison
// expressions with a shared variable and constants and a logical operator
// between them.
//
// Suggest a different logical operator when the logical operator between
// the comparisons is probably wrong.
//
// Inform that second comparison is always true when first comparison is true.
//---------------------------------------------------------------------------
static std::string invertOperatorForOperandSwap(std::string s)
{
if (s[0] == '<')
s[0] = '>';
else if (s[0] == '>')
s[0] = '<';
return s;
}
template<typename T>
static int sign(const T v) {
return static_cast<int>(v > 0) - static_cast<int>(v < 0);
}
// returns 1 (-1) if the first (second) condition is sufficient, 0 if indeterminate
template<typename T>
static int sufficientCondition(std::string op1, const bool not1, const T value1, std::string op2, const bool not2, const T value2, const bool isAnd) {
auto transformOp = [](std::string& op, const bool invert) {
if (invert) {
if (op == "==")
op = "!=";
else if (op == "!=")
op = "==";
else if (op == "<")
op = ">=";
else if (op == ">")
op = "<=";
else if (op == "<=")
op = ">";
else if (op == ">=")
op = "<";
}
};
transformOp(op1, not1);
transformOp(op2, not2);
int res = 0;
bool equal = false;
if (op1 == op2) {
equal = true;
if (op1 == ">" || op1 == ">=")
res = sign(value1 - value2);
else if (op1 == "<" || op1 == "<=")
res = -sign(value1 - value2);
} else { // not equal
if (op1 == "!=")
res = 1;
else if (op2 == "!=")
res = -1;
else if (op1 == "==")
res = -1;
else if (op2 == "==")
res = 1;
else if (op1 == ">" && op2 == ">=")
res = sign(value1 - (value2 - 1));
else if (op1 == ">=" && op2 == ">")
res = sign((value1 - 1) - value2);
else if (op1 == "<" && op2 == "<=")
res = -sign(value1 - (value2 + 1));
else if (op1 == "<=" && op2 == "<")
res = -sign((value1 + 1) - value2);
}
return res * (isAnd == equal ? 1 : -1);
}
template<typename T>
static bool checkIntRelation(const std::string &op, const T value1, const T value2)
{
return (op == "==" && value1 == value2) ||
(op == "!=" && value1 != value2) ||
(op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2);
}
static bool checkFloatRelation(const std::string &op, const double value1, const double value2)
{
return (op == ">" && value1 > value2) ||
(op == ">=" && value1 >= value2) ||
(op == "<" && value1 < value2) ||
(op == "<=" && value1 <= value2);
}
template<class T>
static T getvalue3(const T value1, const T value2)
{
const T min = std::min(value1, value2);
if (min== std::numeric_limits<T>::max())
return min;
return min + 1; // see #5895
}
template<>
double getvalue3(const double value1, const double value2)
{
return (value1 + value2) / 2.0;
}
template<class T>
static inline T getvalue(const int test, const T value1, const T value2)
{
// test:
// 1 => return value that is less than both value1 and value2
// 2 => return value1
// 3 => return value that is between value1 and value2
// 4 => return value2
// 5 => return value that is larger than both value1 and value2
switch (test) {
case 1:
return std::numeric_limits<T>::lowest();
case 2:
return value1;
case 3:
return getvalue3<T>(value1, value2);
case 4:
return value2;
case 5:
return std::numeric_limits<T>::max();
}
return 0;
}
static bool parseComparison(const Token *comp, bool ¬1, std::string &op, std::string &value, const Token *&expr, bool &inconclusive)
{
not1 = false;
while (comp && comp->str() == "!") {
not1 = !(not1);
comp = comp->astOperand1();
}
if (!comp)
return false;
const Token* op1 = comp->astOperand1();
const Token* op2 = comp->astOperand2();
if (!comp->isComparisonOp() || !op1 || !op2) {
op = "!=";
value = "0";
expr = comp;
} else if (op1->isLiteral()) {
if (op1->isExpandedMacro())
return false;
op = invertOperatorForOperandSwap(comp->str());
if (op1->enumerator() && op1->enumerator()->value_known)
value = std::to_string(op1->enumerator()->value);
else
value = op1->str();
expr = op2;
} else if (comp->astOperand2()->isLiteral()) {
if (op2->isExpandedMacro())
return false;
op = comp->str();
if (op2->enumerator() && op2->enumerator()->value_known)
value = std::to_string(op2->enumerator()->value);
else
value = op2->str();
expr = op1;
} else {
op = "!=";
value = "0";
expr = comp;
}
inconclusive = inconclusive || ((value)[0] == '\'' && !(op == "!=" || op == "=="));
// Only float and int values are currently handled
return MathLib::isInt(value) || MathLib::isFloat(value) || (value[0] == '\'');
}
static std::string conditionString(bool not1, const Token *expr1, const std::string &op, const std::string &value1)
{
if (expr1->astParent()->isComparisonOp())
return std::string(not1 ? "!(" : "") + expr1->expressionString() +
" " +
op +
" " +
value1 +
(not1 ? ")" : "");
return std::string(not1 ? "!" : "") + expr1->expressionString();
}
static std::string conditionString(const Token * tok)
{
if (!tok)
return "";
if (tok->isComparisonOp()) {
bool inconclusive = false;
bool not_;
std::string op, value;
const Token *expr;
if (parseComparison(tok, not_, op, value, expr, inconclusive) && expr->isName()) {
return conditionString(not_, expr, op, value);
}
}
if (Token::Match(tok, "%cop%|&&|%oror%")) {
if (tok->astOperand2())
return conditionString(tok->astOperand1()) + " " + tok->str() + " " + conditionString(tok->astOperand2());
return tok->str() + "(" + conditionString(tok->astOperand1()) + ")";
}
return tok->expressionString();
}
static bool isIfConstexpr(const Token* tok) {
const Token* const top = tok->astTop();
return Token::simpleMatch(top->astOperand1(), "if") && top->astOperand1()->isConstexpr();
}
void CheckCondition::checkIncorrectLogicOperator()
{
const bool printStyle = mSettings->severity.isEnabled(Severity::style);
const bool printWarning = mSettings->severity.isEnabled(Severity::warning);
if (!printWarning && !printStyle && !mSettings->isPremiumEnabled("incorrectLogicOperator"))
return;
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
logChecker("CheckCondition::checkIncorrectLogicOperator"); // style,warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::Match(tok, "%oror%|&&") || !tok->astOperand1() || !tok->astOperand2())
continue;
// 'A && (!A || B)' is equivalent to 'A && B'
// 'A || (!A && B)' is equivalent to 'A || B'
// 'A && (A || B)' is equivalent to 'A'
// 'A || (A && B)' is equivalent to 'A'
if (printStyle &&
((tok->str() == "||" && tok->astOperand2()->str() == "&&") ||
(tok->str() == "&&" && tok->astOperand2()->str() == "||"))) {
const Token* tok2 = tok->astOperand2()->astOperand1();
if (isOppositeCond(true, tok->astOperand1(), tok2, *mSettings, true, false)) {
std::string expr1(tok->astOperand1()->expressionString());
std::string expr2(tok->astOperand2()->astOperand1()->expressionString());
std::string expr3(tok->astOperand2()->astOperand2()->expressionString());
// make copy for later because the original string might get overwritten
const std::string expr1VerboseMsg = expr1;
const std::string expr2VerboseMsg = expr2;
const std::string expr3VerboseMsg = expr3;
if (expr1.length() + expr2.length() + expr3.length() > 50U) {
if (expr1[0] == '!' && expr2[0] != '!') {
expr1 = "!A";
expr2 = "A";
} else {
expr1 = "A";
expr2 = "!A";
}
expr3 = "B";
}
const std::string cond1 = expr1 + " " + tok->str() + " (" + expr2 + " " + tok->astOperand2()->str() + " " + expr3 + ")";
const std::string cond2 = expr1 + " " + tok->str() + " " + expr3;
const std::string cond1VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr2VerboseMsg + " " + tok->astOperand2()->str() + " " + expr3VerboseMsg;
const std::string cond2VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr3VerboseMsg;
// for the --verbose message, transform the actual condition and print it
const std::string msg = tok2->expressionString() + ". '" + cond1 + "' is equivalent to '" + cond2 + "'\n"
"The condition '" + cond1VerboseMsg + "' is equivalent to '" + cond2VerboseMsg + "'.";
redundantConditionError(tok, msg, false);
continue;
}
if (isSameExpression(false, tok->astOperand1(), tok2, *mSettings, true, true)) {
std::string expr1(tok->astOperand1()->expressionString());
std::string expr2(tok->astOperand2()->astOperand1()->expressionString());
std::string expr3(tok->astOperand2()->astOperand2()->expressionString());
// make copy for later because the original string might get overwritten
const std::string expr1VerboseMsg = expr1;
const std::string expr2VerboseMsg = expr2;
const std::string expr3VerboseMsg = expr3;
if (expr1.length() + expr2.length() + expr3.length() > 50U) {
expr1 = "A";
expr2 = "A";
expr3 = "B";
}
const std::string cond1 = expr1 + " " + tok->str() + " (" + expr2 + " " + tok->astOperand2()->str() + " " + expr3 + ")";
const std::string cond2 = std::move(expr1);
const std::string cond1VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr2VerboseMsg + " " + tok->astOperand2()->str() + " " + expr3VerboseMsg;
const std::string& cond2VerboseMsg = expr1VerboseMsg;
// for the --verbose message, transform the actual condition and print it
const std::string msg = tok2->expressionString() + ". '" + cond1 + "' is equivalent to '" + cond2 + "'\n"
"The condition '" + cond1VerboseMsg + "' is equivalent to '" + cond2VerboseMsg + "'.";
redundantConditionError(tok, msg, false);
continue;
}
}
// Comparison #1 (LHS)
const Token *comp1 = tok->astOperand1();
if (comp1->str() == tok->str())
comp1 = comp1->astOperand2();
// Comparison #2 (RHS)
const Token *comp2 = tok->astOperand2();
bool inconclusive = false;
bool parseable = true;
// Parse LHS
bool not1;
std::string op1, value1;
const Token *expr1 = nullptr;
parseable &= (parseComparison(comp1, not1, op1, value1, expr1, inconclusive));
// Parse RHS
bool not2;
std::string op2, value2;
const Token *expr2 = nullptr;
parseable &= (parseComparison(comp2, not2, op2, value2, expr2, inconclusive));
if (inconclusive && !printInconclusive)
continue;
const bool isUnknown = (expr1 && expr1->valueType() && expr1->valueType()->type == ValueType::UNKNOWN_TYPE) ||
(expr2 && expr2->valueType() && expr2->valueType()->type == ValueType::UNKNOWN_TYPE);
if (isUnknown)
continue;
const bool isfloat = astIsFloat(expr1, true) || MathLib::isFloat(value1) || astIsFloat(expr2, true) || MathLib::isFloat(value2);
ErrorPath errorPath;
// Opposite comparisons around || or && => always true or always false
const bool isLogicalOr(tok->str() == "||");
if (!isfloat && isOppositeCond(isLogicalOr, tok->astOperand1(), tok->astOperand2(), *mSettings, true, true, &errorPath)) {
if (!isIfConstexpr(tok)) {
const bool alwaysTrue(isLogicalOr);
incorrectLogicOperatorError(tok, conditionString(tok), alwaysTrue, inconclusive, errorPath);
}
continue;
}
if (!parseable)
continue;
if (isSameExpression(true, comp1, comp2, *mSettings, true, true))
continue; // same expressions => only report that there are same expressions
if (!isSameExpression(true, expr1, expr2, *mSettings, true, true))
continue;
// don't check floating point equality comparisons. that is bad
// and deserves different warnings.
if (isfloat && (op1 == "==" || op1 == "!=" || op2 == "==" || op2 == "!="))
continue;
const double d1 = (isfloat) ? MathLib::toDoubleNumber(value1) : 0;
const double d2 = (isfloat) ? MathLib::toDoubleNumber(value2) : 0;
const MathLib::bigint i1 = (isfloat) ? 0 : MathLib::toBigNumber(value1);
const MathLib::bigint i2 = (isfloat) ? 0 : MathLib::toBigNumber(value2);
const bool useUnsignedInt = (std::numeric_limits<MathLib::bigint>::max()==i1) || (std::numeric_limits<MathLib::bigint>::max()==i2);
const MathLib::biguint u1 = (useUnsignedInt) ? MathLib::toBigUNumber(value1) : 0;
const MathLib::biguint u2 = (useUnsignedInt) ? MathLib::toBigUNumber(value2) : 0;
// evaluate if expression is always true/false
bool alwaysTrue = true, alwaysFalse = true;
bool firstTrue = true, secondTrue = true;
const bool isAnd = tok->str() == "&&";
for (int test = 1; test <= 5; ++test) {
// test:
// 1 => testvalue is less than both value1 and value2
// 2 => testvalue is value1
// 3 => testvalue is between value1 and value2
// 4 => testvalue value2
// 5 => testvalue is larger than both value1 and value2
bool result1, result2;
if (isfloat) {
const auto testvalue = getvalue<double>(test, d1, d2);
result1 = checkFloatRelation(op1, testvalue, d1);
result2 = checkFloatRelation(op2, testvalue, d2);
} else if (useUnsignedInt) {
const auto testvalue = getvalue<MathLib::biguint>(test, u1, u2);
result1 = checkIntRelation(op1, testvalue, u1);
result2 = checkIntRelation(op2, testvalue, u2);
} else {
const auto testvalue = getvalue<MathLib::bigint>(test, i1, i2);
result1 = checkIntRelation(op1, testvalue, i1);
result2 = checkIntRelation(op2, testvalue, i2);
}
if (not1)
result1 = !result1;
if (not2)
result2 = !result2;
if (isAnd) {
alwaysTrue &= (result1 && result2);
alwaysFalse &= !(result1 && result2);
} else {
alwaysTrue &= (result1 || result2);
alwaysFalse &= !(result1 || result2);
}
firstTrue &= !(!result1 && result2);
secondTrue &= !(result1 && !result2);
}
const std::string cond1str = conditionString(not1, expr1, op1, value1);
const std::string cond2str = conditionString(not2, expr2, op2, value2);
if (printWarning && (alwaysTrue || alwaysFalse)) {
const std::string text = cond1str + " " + tok->str() + " " + cond2str;
incorrectLogicOperatorError(tok, text, alwaysTrue, inconclusive, std::move(errorPath));
} else if (printStyle && (firstTrue || secondTrue)) {
// cppcheck-suppress accessMoved - TODO: FP - see #12174
const int which = isfloat ? sufficientCondition(std::move(op1), not1, d1, std::move(op2), not2, d2, isAnd) : sufficientCondition(std::move(op1), not1, i1, std::move(op2), not2, i2, isAnd);
std::string text;
if (which != 0) {
text = "The condition '" + (which == 1 ? cond2str : cond1str) + "' is redundant since '" + (which == 1 ? cond1str : cond2str) + "' is sufficient.";
} else
text = "If '" + (secondTrue ? cond1str : cond2str) + "', the comparison '" + (secondTrue ? cond2str : cond1str) + "' is always true.";
redundantConditionError(tok, text, inconclusive);
}
}
}
}
void CheckCondition::incorrectLogicOperatorError(const Token *tok, const std::string &condition, bool always, bool inconclusive, ErrorPath errors)
{
if (diag(tok))
return;
errors.emplace_back(tok, "");
if (always)
reportError(errors, Severity::warning, "incorrectLogicOperator",
"Logical disjunction always evaluates to true: " + condition + ".\n"
"Logical disjunction always evaluates to true: " + condition + ". "
"Are these conditions necessary? Did you intend to use && instead? Are the numbers correct? Are you comparing the correct variables?", CWE571, inconclusive ? Certainty::inconclusive : Certainty::normal);
else
reportError(errors, Severity::warning, "incorrectLogicOperator",
"Logical conjunction always evaluates to false: " + condition + ".\n"
"Logical conjunction always evaluates to false: " + condition + ". "
"Are these conditions necessary? Did you intend to use || instead? Are the numbers correct? Are you comparing the correct variables?", CWE570, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckCondition::redundantConditionError(const Token *tok, const std::string &text, bool inconclusive)
{
if (diag(tok))
return;
reportError(tok, Severity::style, "redundantCondition", "Redundant condition: " + text, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
//-----------------------------------------------------------------------------
// Detect "(var % val1) > val2" where val2 is >= val1.
//-----------------------------------------------------------------------------
void CheckCondition::checkModuloAlwaysTrueFalse()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckCondition::checkModuloAlwaysTrueFalse"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp())
continue;
const Token *num, *modulo;
if (Token::simpleMatch(tok->astOperand1(), "%") && Token::Match(tok->astOperand2(), "%num%")) {
modulo = tok->astOperand1();
num = tok->astOperand2();
} else if (Token::Match(tok->astOperand1(), "%num%") && Token::simpleMatch(tok->astOperand2(), "%")) {
num = tok->astOperand1();
modulo = tok->astOperand2();
} else {
continue;
}
if (Token::Match(modulo->astOperand2(), "%num%") &&
MathLib::isLessEqual(modulo->astOperand2()->str(), num->str()))
moduloAlwaysTrueFalseError(tok, modulo->astOperand2()->str());
}
}
}
void CheckCondition::moduloAlwaysTrueFalseError(const Token* tok, const std::string& maxVal)
{
if (diag(tok))
return;
reportError(tok, Severity::warning, "moduloAlwaysTrueFalse",
"Comparison of modulo result is predetermined, because it is always less than " + maxVal + ".", CWE398, Certainty::normal);
}
static int countPar(const Token *tok1, const Token *tok2)
{
int par = 0;
for (const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) {
if (tok->str() == "(")
++par;
else if (tok->str() == ")")
--par;
else if (tok->str() == ";")
return -1;
}
return par;
}
//---------------------------------------------------------------------------
// Clarify condition '(x = a < 0)' into '((x = a) < 0)' or '(x = (a < 0))'
// Clarify condition '(a & b == c)' into '((a & b) == c)' or '(a & (b == c))'
//---------------------------------------------------------------------------
void CheckCondition::clarifyCondition()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("clarifyCondition"))
return;
logChecker("CheckCondition::clarifyCondition"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "( %name% [=&|^]")) {
for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) {
if (tok2->str() == "(" || tok2->str() == "[")
tok2 = tok2->link();
else if (tok2->isComparisonOp()) {
// This might be a template
if (!tok2->isC() && tok2->link())
break;
if (Token::simpleMatch(tok2->astParent(), "?"))
break;
clarifyConditionError(tok, tok->strAt(2) == "=", false);
break;
} else if (!tok2->isName() && !tok2->isNumber() && tok2->str() != ".")
break;
}
} else if (tok->tokType() == Token::eBitOp && !tok->isUnaryOp("&")) {
if (tok->astOperand2() && tok->astOperand2()->variable() && tok->astOperand2()->variable()->nameToken() == tok->astOperand2())
continue;
// using boolean result in bitwise operation ! x [&|^]
const ValueType* vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType* vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr;
if (vt1 && vt1->type == ValueType::BOOL && !Token::Match(tok->astOperand1(), "%name%|(|[|::|.") && countPar(tok->astOperand1(), tok) == 0)
clarifyConditionError(tok, false, true);
else if (vt2 && vt2->type == ValueType::BOOL && !Token::Match(tok->astOperand2(), "%name%|(|[|::|.") && countPar(tok, tok->astOperand2()) == 0)
clarifyConditionError(tok, false, true);
}
}
}
}
void CheckCondition::clarifyConditionError(const Token *tok, bool assign, bool boolop)
{
std::string errmsg;
if (assign)
errmsg = "Suspicious condition (assignment + comparison); Clarify expression with parentheses.";
else if (boolop)
errmsg = "Boolean result is used in bitwise operation. Clarify expression with parentheses.\n"
"Suspicious expression. Boolean result is used in bitwise operation. The operator '!' "
"and the comparison operators have higher precedence than bitwise operators. "
"It is recommended that the expression is clarified with parentheses.";
else
errmsg = "Suspicious condition (bitwise operator + comparison); Clarify expression with parentheses.\n"
"Suspicious condition. Comparison operators have higher precedence than bitwise operators. "
"Please clarify the condition with parentheses.";
reportError(tok,
Severity::style,
"clarifyCondition",
errmsg, CWE398, Certainty::normal);
}
void CheckCondition::alwaysTrueFalse()
{
if (!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("alwaysTrue") &&
!mSettings->isPremiumEnabled("alwaysFalse") &&
!mSettings->isPremiumEnabled("knownConditionTrueFalse"))
return;
logChecker("CheckCondition::alwaysTrueFalse"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// don't write false positives when templates are used or inside of asserts or non-evaluated contexts
if (tok->link() && (Token::simpleMatch(tok, "<") ||
Token::Match(tok->previous(), "static_assert|assert|ASSERT|sizeof|decltype ("))) {
tok = tok->link();
continue;
}
if (!tok->hasKnownIntValue())
continue;
if (Token::Match(tok->previous(), "%name% (") && tok->previous()->function()) {
const Function* f = tok->previous()->function();
if (f->functionScope && Token::Match(f->functionScope->bodyStart, "{ return true|false ;"))
continue;
}
const Token* condition = nullptr;
{
// is this a condition..
const Token *parent = tok->astParent();
while (Token::Match(parent, "%oror%|&&"))
parent = parent->astParent();
if (!parent)
continue;
if (parent->str() == "?" && precedes(tok, parent))
condition = parent;
else if (Token::Match(parent->previous(), "if|while ("))
condition = parent->previous();
else if (Token::simpleMatch(parent, "return"))
condition = parent;
else if (parent->str() == ";" && parent->astParent() && parent->astParent()->astParent() &&
Token::simpleMatch(parent->astParent()->astParent()->previous(), "for ("))
condition = parent->astParent()->astParent()->previous();
else if (Token::Match(tok, "%comp%"))
condition = tok;
else
continue;
}
// Skip already diagnosed values
if (diag(tok, false))
continue;
if (condition->isConstexpr())
continue;
if (!isUsedAsBool(tok, *mSettings))
continue;
if (Token::simpleMatch(condition, "return") && Token::Match(tok, "%assign%"))
continue;
if (Token::simpleMatch(tok->astParent(), "return") && Token::Match(tok, ".|%var%"))
continue;
if (Token::Match(tok, "%num%|%bool%|%char%"))
continue;
if (Token::Match(tok, "! %num%|%bool%|%char%"))
continue;
if (Token::Match(tok, "%oror%|&&")) {
bool bail = false;
for (const Token* op : { tok->astOperand1(), tok->astOperand2() }) {
if (op->hasKnownIntValue() && (!op->isLiteral() || op->isBoolean())) {
bail = true;
break;
}
}
if (bail)
continue;
}
if (Token::simpleMatch(tok, ":"))
continue;
if (Token::Match(tok->astOperand1(), "%name% (") && Token::simpleMatch(tok->astParent(), "return"))
continue;
if (tok->isComparisonOp() && isWithoutSideEffects(tok->astOperand1()) &&
isSameExpression(true,
tok->astOperand1(),
tok->astOperand2(),
*mSettings,
true,
true))
continue;
if (isConstVarExpression(tok, [](const Token* tok) {
return Token::Match(tok, "[|(|&|+|-|*|/|%|^|>>|<<") && !Token::simpleMatch(tok, "( )");
}))
continue;
// there are specific warnings about nonzero expressions (pointer/unsigned)
// do not write alwaysTrueFalse for these comparisons.
{
const ValueFlow::Value *zeroValue = nullptr;
const Token *nonZeroExpr = nullptr;
if (CheckOther::comparisonNonZeroExpressionLessThanZero(tok, zeroValue, nonZeroExpr, /*suppress*/ true) ||
CheckOther::testIfNonZeroExpressionIsPositive(tok, zeroValue, nonZeroExpr))
continue;
}
// Don't warn when there are expanded macros..
bool isExpandedMacro = false;
visitAstNodes(tok, [&](const Token * tok2) {
if (!tok2)
return ChildrenToVisit::none;
if (tok2->isExpandedMacro()) {
isExpandedMacro = true;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
if (isExpandedMacro)
continue;
for (const Token *parent = tok; parent; parent = parent->astParent()) {
if (parent->isExpandedMacro()) {
isExpandedMacro = true;
break;
}
}
if (isExpandedMacro)
continue;
// don't warn when condition checks sizeof result
bool hasSizeof = false;
visitAstNodes(tok, [&](const Token * tok2) {
if (!tok2)
return ChildrenToVisit::none;
if (tok2->isNumber())
return ChildrenToVisit::none;
if (Token::simpleMatch(tok2->previous(), "sizeof (")) {
hasSizeof = true;
return ChildrenToVisit::none;
}
if (tok2->isComparisonOp() || tok2->isArithmeticalOp()) {
return ChildrenToVisit::op1_and_op2;
}
return ChildrenToVisit::none;
});
if (hasSizeof)
continue;
alwaysTrueFalseError(tok, condition, &tok->values().front());
}
}
}
void CheckCondition::alwaysTrueFalseError(const Token* tok, const Token* condition, const ValueFlow::Value* value)
{
const bool alwaysTrue = value && (value->intvalue != 0 || value->isImpossible());
const std::string expr = tok ? tok->expressionString() : std::string("x");
const std::string conditionStr = (Token::simpleMatch(condition, "return") ? "Return value" : "Condition");
const std::string errmsg = conditionStr + " '" + expr + "' is always " + bool_to_string(alwaysTrue);
const ErrorPath errorPath = getErrorPath(tok, value, errmsg);
reportError(errorPath,
Severity::style,
"knownConditionTrueFalse",
errmsg,
(alwaysTrue ? CWE571 : CWE570), Certainty::normal);
}
void CheckCondition::checkInvalidTestForOverflow()
{
// Interesting blogs:
// https://www.airs.com/blog/archives/120
// https://kristerw.blogspot.com/2016/02/how-undefined-signed-overflow-enables.html
// https://research.checkpoint.com/2020/optout-compiler-undefined-behavior-optimizations/
// x + c < x -> false
// x + c <= x -> false
// x + c > x -> true
// x + c >= x -> true
// x + y < x -> y < 0
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckCondition::checkInvalidTestForOverflow"); // warning
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "<|<=|>=|>") || !tok->isBinaryOp())
continue;
const Token *lhsTokens[2] = {tok->astOperand1(), tok->astOperand2()};
for (const Token *lhs: lhsTokens) {
std::string cmp = tok->str();
if (lhs == tok->astOperand2())
cmp[0] = (cmp[0] == '<') ? '>' : '<';
if (!Token::Match(lhs, "[+-]") || !lhs->isBinaryOp())
continue;
const bool isSignedInteger = lhs->valueType() && lhs->valueType()->isIntegral() && lhs->valueType()->sign == ValueType::Sign::SIGNED;
const bool isPointer = lhs->valueType() && lhs->valueType()->pointer > 0;
if (!isSignedInteger && !isPointer)
continue;
const Token *exprTokens[2] = {lhs->astOperand1(), lhs->astOperand2()};
for (const Token *expr: exprTokens) {
if (lhs->str() == "-" && expr == lhs->astOperand2())
continue; // TODO?
if (expr->hasKnownIntValue())
continue;
if (!isSameExpression(true,
expr,
lhs->astSibling(),
*mSettings,
true,
false))
continue;
const Token * const other = expr->astSibling();
// x [+-] c cmp x
if ((other->isNumber() && other->getKnownIntValue() > 0) ||
(!other->isNumber() && other->valueType() && other->valueType()->isIntegral() && other->valueType()->sign == ValueType::Sign::UNSIGNED)) {
bool result;
if (lhs->str() == "+")
result = (cmp == ">" || cmp == ">=");
else
result = (cmp == "<" || cmp == "<=");
invalidTestForOverflow(tok, lhs->valueType(), bool_to_string(result));
continue;
}
// x + y cmp x
if (lhs->str() == "+" && other->varId() > 0) {
const std::string result = other->str() + cmp + "0";
invalidTestForOverflow(tok, lhs->valueType(), result);
continue;
}
// x - y cmp x
if (lhs->str() == "-" && other->varId() > 0) {
std::string cmp2 = cmp;
cmp2[0] = (cmp[0] == '<') ? '>' : '<';
const std::string result = other->str() + cmp2 + "0";
invalidTestForOverflow(tok, lhs->valueType(), result);
continue;
}
}
}
}
}
void CheckCondition::invalidTestForOverflow(const Token* tok, const ValueType *valueType, const std::string &replace)
{
const std::string expr = (tok ? tok->expressionString() : std::string("x + c < x"));
const std::string overflow = (valueType && valueType->pointer) ? "pointer overflow" : "signed integer overflow";
std::string errmsg =
"Invalid test for overflow '" + expr + "'; " + overflow + " is undefined behavior.";
if (replace == "false" || replace == "true")
errmsg += " Some mainstream compilers remove such overflow tests when optimising the code and assume it's always " + replace + ".";
else
errmsg += " Some mainstream compilers removes handling of overflows when optimising the code and change the code to '" + replace + "'.";
reportError(tok, Severity::warning, "invalidTestForOverflow", errmsg, uncheckedErrorConditionCWE, Certainty::normal);
}
void CheckCondition::checkPointerAdditionResultNotNull()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckCondition::checkPointerAdditionResultNotNull"); // warning
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2())
continue;
// Macros might have pointless safety checks
if (tok->isExpandedMacro())
continue;
const Token *calcToken, *exprToken;
if (tok->astOperand1()->str() == "+") {
calcToken = tok->astOperand1();
exprToken = tok->astOperand2();
} else if (tok->astOperand2()->str() == "+") {
calcToken = tok->astOperand2();
exprToken = tok->astOperand1();
} else
continue;
// pointer comparison against NULL (ptr+12==0)
if (calcToken->hasKnownIntValue())
continue;
if (!calcToken->valueType() || calcToken->valueType()->pointer==0)
continue;
if (!exprToken->hasKnownIntValue() || !exprToken->getValue(0))
continue;
pointerAdditionResultNotNullError(tok, calcToken);
}
}
}
void CheckCondition::pointerAdditionResultNotNullError(const Token *tok, const Token *calc)
{
const std::string s = calc ? calc->expressionString() : "ptr+1";
reportError(tok, Severity::warning, "pointerAdditionResultNotNull", "Comparison is wrong. Result of '" + s + "' can't be 0 unless there is pointer overflow, and pointer overflow is undefined behaviour.");
}
void CheckCondition::checkDuplicateConditionalAssign()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateConditionalAssign"))
return;
logChecker("CheckCondition::checkDuplicateConditionalAssign"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope *scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!Token::simpleMatch(tok, "if ("))
continue;
if (!Token::simpleMatch(tok->linkAt(1), ") {"))
continue;
const Token *blockTok = tok->linkAt(1)->next();
const Token *condTok = tok->next()->astOperand2();
const bool isBoolVar = Token::Match(condTok, "!| %var%");
if (!isBoolVar && !Token::Match(condTok, "==|!="))
continue;
if ((isBoolVar || condTok->str() == "!=") && Token::simpleMatch(blockTok->link(), "} else {"))
continue;
if (!blockTok->next())
continue;
const Token *assignTok = blockTok->next()->astTop();
if (!Token::simpleMatch(assignTok, "="))
continue;
if (nextAfterAstRightmostLeaf(assignTok) != blockTok->link()->previous())
continue;
bool isRedundant = false;
if (isBoolVar) {
const bool isNegation = condTok->str() == "!";
const Token* const varTok = isNegation ? condTok->next() : condTok;
const ValueType* vt = varTok->variable() ? varTok->variable()->valueType() : nullptr;
if (!(vt && vt->type == ValueType::Type::BOOL && !vt->pointer))
continue;
if (!(assignTok->astOperand1() && assignTok->astOperand1()->varId() == varTok->varId()))
continue;
if (!(assignTok->astOperand2() && assignTok->astOperand2()->hasKnownIntValue()))
continue;
const MathLib::bigint val = assignTok->astOperand2()->getKnownIntValue();
if (val < 0 || val > 1)
continue;
isRedundant = (isNegation && val == 0) || (!isNegation && val == 1);
} else { // comparison
if (!isSameExpression(
true, condTok->astOperand1(), assignTok->astOperand1(), *mSettings, true, true))
continue;
if (!isSameExpression(
true, condTok->astOperand2(), assignTok->astOperand2(), *mSettings, true, true))
continue;
}
duplicateConditionalAssignError(condTok, assignTok, isRedundant);
}
}
}
void CheckCondition::duplicateConditionalAssignError(const Token *condTok, const Token* assignTok, bool isRedundant)
{
ErrorPath errors;
std::string msg = "Duplicate expression for the condition and assignment.";
if (condTok && assignTok) {
if (condTok->str() == "==") {
msg = "Assignment '" + assignTok->expressionString() + "' is redundant with condition '" + condTok->expressionString() + "'.";
errors.emplace_back(condTok, "Condition '" + condTok->expressionString() + "'");
errors.emplace_back(assignTok, "Assignment '" + assignTok->expressionString() + "' is redundant");
} else {
msg = "The statement 'if (" + condTok->expressionString() + ") " + assignTok->expressionString();
msg += isRedundant ? "' is redundant." : "' is logically equivalent to '" + assignTok->expressionString() + "'.";
errors.emplace_back(assignTok, "Assignment '" + assignTok->expressionString() + "'");
errors.emplace_back(condTok, "Condition '" + condTok->expressionString() + "' is redundant");
}
}
reportError(
errors, Severity::style, "duplicateConditionalAssign", msg, CWE398, Certainty::normal);
}
void CheckCondition::checkAssignmentInCondition()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("assignmentInCondition"))
return;
logChecker("CheckCondition::checkAssignmentInCondition"); // style
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() != "=")
continue;
if (!tok->astParent())
continue;
// Is this assignment of container/iterator?
if (!tok->valueType())
continue;
if (tok->valueType()->pointer > 0)
continue;
if (tok->valueType()->type != ValueType::Type::CONTAINER && tok->valueType()->type != ValueType::Type::ITERATOR)
continue;
// warn if this is a conditional expression..
if (Token::Match(tok->astParent()->previous(), "if|while ("))
assignmentInCondition(tok);
else if (Token::Match(tok->astParent(), "%oror%|&&"))
assignmentInCondition(tok);
else if (Token::simpleMatch(tok->astParent(), "?") && tok == tok->astParent()->astOperand1())
assignmentInCondition(tok);
}
}
}
void CheckCondition::assignmentInCondition(const Token *eq)
{
std::string expr = eq ? eq->expressionString() : "x=y";
reportError(
eq,
Severity::style,
"assignmentInCondition",
"Suspicious assignment in condition. Condition '" + expr + "' is always true.",
CWE571,
Certainty::normal);
}
void CheckCondition::checkCompareValueOutOfTypeRange()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("compareValueOutOfTypeRangeError"))
return;
if (mSettings->platform.type == Platform::Type::Native ||
mSettings->platform.type == Platform::Type::Unspecified)
return;
logChecker("CheckCondition::checkCompareValueOutOfTypeRange"); // style,platform
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (!tok->isComparisonOp() || !tok->isBinaryOp())
continue;
for (int i = 0; i < 2; ++i) {
const Token * const valueTok = (i == 0) ? tok->astOperand1() : tok->astOperand2();
const Token * const typeTok = valueTok->astSibling();
if (!valueTok->hasKnownIntValue() || !typeTok->valueType() || typeTok->valueType()->pointer)
continue;
if (valueTok->getKnownIntValue() < 0 && valueTok->valueType() && valueTok->valueType()->sign != ValueType::Sign::SIGNED)
continue;
if (valueTok->valueType() && valueTok->valueType()->isTypeEqual(typeTok->valueType()))
continue;
int bits = 0;
switch (typeTok->valueType()->type) {
case ValueType::Type::BOOL:
bits = 1;
break;
case ValueType::Type::CHAR:
bits = mSettings->platform.char_bit;
break;
case ValueType::Type::SHORT:
bits = mSettings->platform.short_bit;
break;
case ValueType::Type::INT:
bits = mSettings->platform.int_bit;
break;
case ValueType::Type::LONG:
bits = mSettings->platform.long_bit;
break;
case ValueType::Type::LONGLONG:
bits = mSettings->platform.long_long_bit;
break;
default:
break;
}
if (bits == 0 || bits >= 64)
continue;
const auto typeMinValue = (typeTok->valueType()->sign == ValueType::Sign::UNSIGNED) ? 0 : (-(1LL << (bits-1)));
const auto unsignedTypeMaxValue = (1LL << bits) - 1LL;
long long typeMaxValue;
if (typeTok->valueType()->sign != ValueType::Sign::SIGNED)
typeMaxValue = unsignedTypeMaxValue;
else if (bits >= mSettings->platform.int_bit && (!valueTok->valueType() || valueTok->valueType()->sign != ValueType::Sign::SIGNED))
typeMaxValue = unsignedTypeMaxValue;
else
typeMaxValue = unsignedTypeMaxValue / 2;
bool result{};
const auto kiv = valueTok->getKnownIntValue();
if (tok->str() == "==")
result = false;
else if (tok->str() == "!=")
result = true;
else if (tok->str()[0] == '>' && i == 0)
// num > var
result = (kiv > 0);
else if (tok->str()[0] == '>' && i == 1)
// var > num
result = (kiv < 0);
else if (tok->str()[0] == '<' && i == 0)
// num < var
result = (kiv < 0);
else if (tok->str()[0] == '<' && i == 1)
// var < num
result = (kiv > 0);
bool error = false;
if (kiv < typeMinValue || kiv > typeMaxValue) {
error = true;
} else {
switch (i) {
case 0: // num cmp var
if (kiv == typeMinValue) {
if (tok->str() == "<=") {
result = true;
error = true;
} else if (tok->str() == ">")
error = true;
}
else if (kiv == typeMaxValue && (tok->str() == ">=" || tok->str() == "<")) {
error = true;
}
break;
case 1: // var cmp num
if (kiv == typeMinValue) {
if (tok->str() == ">=") {
result = true;
error = true;
} else if (tok->str() == "<")
error = true;
}
else if (kiv == typeMaxValue && (tok->str() == "<=" || tok->str() == ">")) {
error = true;
}
break;
}
}
if (error)
compareValueOutOfTypeRangeError(valueTok, typeTok->valueType()->str(), kiv, result);
}
}
}
}
void CheckCondition::compareValueOutOfTypeRangeError(const Token *comparison, const std::string &type, MathLib::bigint value, bool result)
{
reportError(
comparison,
Severity::style,
"compareValueOutOfTypeRangeError",
"Comparing expression of type '" + type + "' against value " + std::to_string(value) + ". Condition is always " + bool_to_string(result) + ".",
CWE398,
Certainty::normal);
}
| null |
871 | cpp | cppcheck | keywords.h | lib/keywords.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef keywordsH
#define keywordsH
#include "standards.h"
#include <string>
#include <unordered_set>
class Keywords
{
public:
static const std::unordered_set<std::string>& getAll(Standards::cstd_t cStd);
static const std::unordered_set<std::string>& getAll(Standards::cppstd_t cppStd);
static const std::unordered_set<std::string>& getOnly(Standards::cstd_t cStd);
static const std::unordered_set<std::string>& getOnly(Standards::cppstd_t cppStd);
};
#endif
| null |
872 | cpp | cppcheck | tokenize.cpp | lib/tokenize.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "tokenize.h"
#include "astutils.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "path.h"
#include "platform.h"
#include "preprocessor.h"
#include "settings.h"
#include "standards.h"
#include "summaries.h"
#include "symboldatabase.h"
#include "templatesimplifier.h"
#include "timer.h"
#include "token.h"
#include "utils.h"
#include "valueflow.h"
#include "vfvalue.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <iterator>
#include <exception>
#include <memory>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <simplecpp.h>
//---------------------------------------------------------------------------
namespace {
// local struct used in setVarId
// in order to store information about the scope
struct VarIdScopeInfo {
VarIdScopeInfo() = default;
VarIdScopeInfo(bool isExecutable, bool isStructInit, bool isEnum, nonneg int startVarid)
: isExecutable(isExecutable), isStructInit(isStructInit), isEnum(isEnum), startVarid(startVarid) {}
const bool isExecutable{};
const bool isStructInit{};
const bool isEnum{};
const nonneg int startVarid{};
};
}
/** Return whether tok is the "{" that starts an enumerator list */
static bool isEnumStart(const Token* tok)
{
if (!Token::simpleMatch(tok, "{"))
return false;
tok = tok->previous();
while (tok && (!tok->isKeyword() || Token::isStandardType(tok->str())) && Token::Match(tok, "%name%|::|:"))
tok = tok->previous();
if (Token::simpleMatch(tok, "class"))
tok = tok->previous();
return Token::simpleMatch(tok, "enum");
}
template<typename T>
static void skipEnumBody(T *&tok)
{
T *defStart = tok;
while (Token::Match(defStart, "%name%|::|:"))
defStart = defStart->next();
if (defStart && defStart->str() == "{")
tok = defStart->link()->next();
}
const Token * Tokenizer::isFunctionHead(const Token *tok, const std::string &endsWith)
{
if (!tok)
return nullptr;
if (tok->str() == "(")
tok = tok->link();
if (tok->str() != ")")
return nullptr;
if (!tok->isCpp() && !Token::Match(tok->link()->previous(), "%name%|(|)"))
return nullptr;
if (Token::Match(tok, ") ;|{|[")) {
tok = tok->next();
while (tok && tok->str() == "[" && tok->link()) {
if (endsWith.find(tok->str()) != std::string::npos)
return tok;
tok = tok->link()->next();
}
return (tok && endsWith.find(tok->str()) != std::string::npos) ? tok : nullptr;
}
if (tok->isCpp() && tok->str() == ")") {
tok = tok->next();
while (Token::Match(tok, "const|noexcept|override|final|volatile|mutable|&|&& !!(") ||
(Token::Match(tok, "%name% !!(") && tok->isUpperCaseName()))
tok = tok->next();
if (tok && tok->str() == ")")
tok = tok->next();
while (tok && tok->str() == "[")
tok = tok->link()->next();
if (Token::Match(tok, "throw|noexcept ("))
tok = tok->linkAt(1)->next();
if (Token::Match(tok, "%name% (") && tok->isUpperCaseName())
tok = tok->linkAt(1)->next();
if (tok && tok->originalName() == "->") { // trailing return type
for (tok = tok->next(); tok && !Token::Match(tok, ";|{|override|final|}|)|]"); tok = tok->next())
if (tok->link() && Token::Match(tok, "<|[|("))
tok = tok->link();
}
while (Token::Match(tok, "override|final !!(") ||
(Token::Match(tok, "%name% !!(") && tok->isUpperCaseName()))
tok = tok->next();
if (Token::Match(tok, "= 0|default|delete ;"))
tok = tok->tokAt(2);
if (Token::simpleMatch(tok, "requires")) {
for (tok = tok->next(); tok && !Token::Match(tok, ";|{|}|)|]"); tok = tok->next()) {
if (tok->link() && Token::Match(tok, "<|[|("))
tok = tok->link();
if (Token::simpleMatch(tok, "bool {"))
tok = tok->linkAt(1);
}
}
if (tok && tok->str() == ":" && !Token::Match(tok->next(), "%name%|::"))
return nullptr;
return (tok && endsWith.find(tok->str()) != std::string::npos) ? tok : nullptr;
}
return nullptr;
}
/**
* is tok the start brace { of a class, struct, union, or enum
*/
static bool isClassStructUnionEnumStart(const Token * tok)
{
if (!Token::Match(tok->previous(), "class|struct|union|enum|%name%|>|>> {"))
return false;
const Token * tok2 = tok->previous();
while (tok2 && !Token::Match(tok2, "class|struct|union|enum|{|}|;"))
tok2 = tok2->previous();
return Token::Match(tok2, "class|struct|union|enum");
}
//---------------------------------------------------------------------------
Tokenizer::Tokenizer(const Settings &settings, ErrorLogger &errorLogger) :
list(&settings),
mSettings(settings),
mErrorLogger(errorLogger),
mTemplateSimplifier(new TemplateSimplifier(*this))
{}
Tokenizer::~Tokenizer()
{
delete mSymbolDatabase;
delete mTemplateSimplifier;
}
//---------------------------------------------------------------------------
// SizeOfType - gives the size of a type
//---------------------------------------------------------------------------
nonneg int Tokenizer::sizeOfType(const std::string& type) const
{
const std::map<std::string, int>::const_iterator it = mTypeSize.find(type);
if (it == mTypeSize.end()) {
const Library::PodType* podtype = mSettings.library.podtype(type);
if (!podtype)
return 0;
return podtype->size;
}
return it->second;
}
nonneg int Tokenizer::sizeOfType(const Token *type) const
{
if (!type || type->str().empty())
return 0;
if (type->tokType() == Token::eString)
return Token::getStrLength(type) + 1U;
const std::map<std::string, int>::const_iterator it = mTypeSize.find(type->str());
if (it == mTypeSize.end()) {
const Library::PodType* podtype = mSettings.library.podtype(type->str());
if (!podtype)
return 0;
return podtype->size;
}
if (type->isLong()) {
if (type->str() == "double")
return mSettings.platform.sizeof_long_double;
if (type->str() == "long")
return mSettings.platform.sizeof_long_long;
}
return it->second;
}
//---------------------------------------------------------------------------
// check if this statement is a duplicate definition
bool Tokenizer::duplicateTypedef(Token *&tokPtr, const Token *name, const Token *typeDef) const
{
// check for an end of definition
Token * tok = tokPtr;
if (tok && Token::Match(tok->next(), ";|,|[|=|)|>|(|{")) {
Token * end = tok->next();
if (end->str() == "[") {
if (!end->link())
syntaxError(end); // invalid code
end = end->link()->next();
} else if (end->str() == ",") {
// check for derived class
if (Token::Match(tok->previous(), "public|private|protected"))
return false;
// find end of definition
while (end && end->next() && !Token::Match(end->next(), ";|)|>")) {
if (end->strAt(1) == "(")
end = end->linkAt(1);
end = (end)?end->next():nullptr;
}
if (end)
end = end->next();
} else if (end->str() == "(") {
if (startsWith(tok->strAt(-1), "operator"))
// conversion operator
return false;
if (tok->strAt(-1) == "typedef")
// typedef of function returning this type
return false;
if (Token::Match(tok->previous(), "public:|private:|protected:"))
return false;
if (tok->strAt(-1) == ">") {
if (!Token::Match(tok->tokAt(-2), "%type%"))
return false;
if (!Token::Match(tok->tokAt(-3), ",|<"))
return false;
tokPtr = end->link();
return true;
}
}
if (end) {
if (Token::simpleMatch(end, ") {")) { // function parameter ?
// look backwards
if (Token::Match(tok->previous(), "%type%") &&
!Token::Match(tok->previous(), "return|new|const|struct")) {
// duplicate definition so skip entire function
tokPtr = end->linkAt(1);
return true;
}
} else if (end->str() == ">") { // template parameter ?
// look backwards
if (Token::Match(tok->previous(), "%type%") &&
!Token::Match(tok->previous(), "return|new|const|volatile")) {
// duplicate definition so skip entire template
while (end && end->str() != "{")
end = end->next();
if (end) {
tokPtr = end->link();
return true;
}
}
} else {
// look backwards
if (Token::Match(tok->previous(), "typedef|}|>") ||
(end->str() == ";" && tok->strAt(-1) == ",") ||
(tok->strAt(-1) == "*" && tok->strAt(1) != "(") ||
(Token::Match(tok->previous(), "%type%") &&
(!Token::Match(tok->previous(), "return|new|const|friend|public|private|protected|throw|extern") &&
!Token::simpleMatch(tok->tokAt(-2), "friend class")))) {
// scan backwards for the end of the previous statement
while (tok && tok->previous() && !Token::Match(tok->previous(), ";|{")) {
if (tok->strAt(-1) == "}") {
tok = tok->linkAt(-1);
} else if (tok->strAt(-1) == "typedef") {
return true;
} else if (tok->strAt(-1) == "enum") {
return true;
} else if (tok->strAt(-1) == "struct") {
if (tok->strAt(-2) == "typedef" &&
tok->strAt(1) == "{" &&
typeDef->strAt(3) != "{") {
// declaration after forward declaration
return true;
}
if (tok->strAt(1) == "{")
return true;
if (Token::Match(tok->next(), ")|*"))
return true;
if (tok->strAt(1) == name->str())
return true;
if (tok->strAt(1) != ";")
return true;
return false;
} else if (tok->strAt(-1) == "union") {
return tok->strAt(1) != ";";
} else if (tok->isCpp() && tok->strAt(-1) == "class") {
return tok->strAt(1) != ";";
}
if (tok)
tok = tok->previous();
}
if (tokPtr->strAt(1) != "(" || !Token::Match(tokPtr->linkAt(1), ") .|(|["))
return true;
}
}
}
}
return false;
}
void Tokenizer::unsupportedTypedef(const Token *tok) const
{
if (!mSettings.debugwarnings)
return;
std::ostringstream str;
const Token *tok1 = tok;
int level = 0;
while (tok) {
if (level == 0 && tok->str() == ";")
break;
if (tok->str() == "{")
++level;
else if (tok->str() == "}") {
if (level == 0)
break;
--level;
}
if (tok != tok1)
str << " ";
str << tok->str();
tok = tok->next();
}
if (tok)
str << " ;";
reportError(tok1, Severity::debug, "simplifyTypedef",
"Failed to parse \'" + str.str() + "\'. The checking continues anyway.");
}
Token * Tokenizer::deleteInvalidTypedef(Token *typeDef)
{
Token *tok = nullptr;
// remove typedef but leave ;
while (typeDef->next()) {
if (typeDef->strAt(1) == ";") {
typeDef->deleteNext();
break;
}
if (typeDef->strAt(1) == "{")
Token::eraseTokens(typeDef, typeDef->linkAt(1));
else if (typeDef->strAt(1) == "}")
break;
typeDef->deleteNext();
}
if (typeDef != list.front()) {
tok = typeDef->previous();
tok->deleteNext();
} else {
list.front()->deleteThis();
tok = list.front();
}
return tok;
}
namespace {
struct Space {
std::string className;
const Token* bodyEnd{}; // for body contains typedef define
const Token* bodyEnd2{}; // for body contains typedef using
bool isNamespace{};
std::set<std::string> recordTypes;
};
}
static Token *splitDefinitionFromTypedef(Token *tok, nonneg int *unnamedCount)
{
std::string name;
std::set<std::string> qualifiers;
while (Token::Match(tok->next(), "const|volatile")) {
qualifiers.insert(tok->strAt(1));
tok->deleteNext();
}
// skip "class|struct|union|enum"
Token *tok1 = tok->tokAt(2);
const bool hasName = Token::Match(tok1, "%name%");
// skip name
if (hasName) {
name = tok1->str();
tok1 = tok1->next();
}
// skip base classes if present
if (tok1->str() == ":") {
tok1 = tok1->next();
while (tok1 && tok1->str() != "{")
tok1 = tok1->next();
if (!tok1)
return nullptr;
}
// skip to end
tok1 = tok1->link();
if (!hasName) { // unnamed
if (tok1->next()) {
// use typedef name if available
if (Token::Match(tok1->next(), "%type%"))
name = tok1->strAt(1);
else // create a unique name
name = "Unnamed" + std::to_string((*unnamedCount)++);
tok->next()->insertToken(name);
} else
return nullptr;
}
tok1->insertToken(";");
tok1 = tok1->next();
if (tok1->next() && tok1->strAt(1) == ";" && tok1->strAt(-1) == "}") {
tok->deleteThis();
tok1->deleteThis();
return nullptr;
}
tok1->insertToken("typedef");
tok1 = tok1->next();
Token * tok3 = tok1;
for (const std::string &qualifier : qualifiers) {
tok1->insertToken(qualifier);
tok1 = tok1->next();
}
tok1->insertToken(tok->strAt(1)); // struct, union or enum
tok1 = tok1->next();
tok1->insertToken(name);
tok->deleteThis();
tok = tok3;
return tok;
}
/* This function is called when processing function related typedefs.
* If simplifyTypedef generates an "Internal Error" message and the
* code that generated it deals in some way with functions, then this
* function will probably need to be extended to handle a new function
* related pattern */
const Token *Tokenizer::processFunc(const Token *tok2, bool inOperator) const
{
if (tok2->next() && tok2->strAt(1) != ")" &&
tok2->strAt(1) != ",") {
// skip over tokens for some types of canonicalization
if (Token::Match(tok2->next(), "( * %type% ) ("))
tok2 = tok2->linkAt(5);
else if (Token::Match(tok2->next(), "* ( * %type% ) ("))
tok2 = tok2->linkAt(6);
else if (Token::Match(tok2->next(), "* ( * %type% ) ;"))
tok2 = tok2->tokAt(5);
else if (Token::Match(tok2->next(), "* ( %type% [") &&
Token::Match(tok2->linkAt(4), "] ) ;|="))
tok2 = tok2->linkAt(4)->next();
else if (Token::Match(tok2->next(), "* ( * %type% ("))
tok2 = tok2->linkAt(5)->next();
else if (Token::simpleMatch(tok2->next(), "* [") &&
Token::simpleMatch(tok2->linkAt(2), "] ;"))
tok2 = tok2->next();
else {
if (tok2->strAt(1) == "(")
tok2 = tok2->linkAt(1);
else if (!inOperator && !Token::Match(tok2->next(), "[|>|;")) {
tok2 = tok2->next();
while (Token::Match(tok2, "*|&") &&
!Token::Match(tok2->next(), "[)>,]"))
tok2 = tok2->next();
// skip over namespace
while (Token::Match(tok2, "%name% ::"))
tok2 = tok2->tokAt(2);
if (!tok2)
return nullptr;
if (tok2->str() == "(" &&
tok2->link()->next() &&
tok2->link()->strAt(1) == "(") {
tok2 = tok2->link();
if (tok2->strAt(1) == "(")
tok2 = tok2->linkAt(1);
}
// skip over typedef parameter
if (tok2->next() && tok2->strAt(1) == "(") {
tok2 = tok2->linkAt(1);
if (!tok2->next())
syntaxError(tok2);
if (tok2->strAt(1) == "(")
tok2 = tok2->linkAt(1);
}
}
}
}
return tok2;
}
Token *Tokenizer::processFunc(Token *tok2, bool inOperator)
{
return const_cast<Token*>(processFunc(const_cast<const Token*>(tok2), inOperator));
}
void Tokenizer::simplifyUsingToTypedef()
{
if (!isCPP() || mSettings.standards.cpp < Standards::CPP11)
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
// using a::b; => typedef a::b b;
if ((Token::Match(tok, "[;{}] using %name% :: %name% ::|;") && !tok->tokAt(2)->isKeyword()) ||
(Token::Match(tok, "[;{}] using :: %name% :: %name% ::|;") && !tok->tokAt(3)->isKeyword())) {
Token *endtok = tok->tokAt(5);
if (Token::Match(endtok, "%name%"))
endtok = endtok->next();
while (Token::Match(endtok, ":: %name%"))
endtok = endtok->tokAt(2);
if (endtok && endtok->str() == ";") {
if (endtok->strAt(-1) == endtok->strAt(-3))
continue;
tok->next()->str("typedef");
endtok = endtok->previous();
endtok->insertToken(endtok->str());
}
}
}
}
void Tokenizer::simplifyTypedefLHS()
{
if (!list.front())
return;
for (Token* tok = list.front()->next(); tok; tok = tok->next()) {
if (tok->str() == "typedef") {
bool doSimplify = !Token::Match(tok->previous(), ";|{|}|:|public:|private:|protected:");
if (doSimplify && Token::simpleMatch(tok->previous(), ")") && Token::Match(tok->linkAt(-1)->previous(), "if|for|while"))
doSimplify = false;
bool haveStart = false;
Token* start{};
if (!doSimplify && Token::simpleMatch(tok->previous(), "}")) {
start = tok->linkAt(-1)->previous();
while (Token::Match(start, "%name%")) {
if (Token::Match(start, "class|struct|union|enum")) {
start = start->previous();
doSimplify = true;
haveStart = true;
break;
}
start = start->previous();
}
}
if (doSimplify) {
if (!haveStart) {
start = tok;
while (start && !Token::Match(start, "[;{}]"))
start = start->previous();
}
if (start)
start = start->next();
else
start = list.front();
start->insertTokenBefore(tok->str());
tok->deleteThis();
}
}
}
}
namespace {
class TypedefSimplifier {
private:
Token* mTypedefToken; // The "typedef" token
Token* mEndToken{nullptr}; // Semicolon
std::pair<Token*, Token*> mRangeType;
std::pair<Token*, Token*> mRangeTypeQualifiers;
std::pair<Token*, Token*> mRangeAfterVar;
Token* mNameToken{nullptr};
bool mFail = false;
bool mReplaceFailed = false;
bool mUsed = false;
public:
explicit TypedefSimplifier(Token* typedefToken) : mTypedefToken(typedefToken) {
Token* start = typedefToken->next();
if (Token::simpleMatch(start, "typename"))
start = start->next();
// TODO handle unnamed structs etc
if (Token::Match(start, "const| enum|struct|union|class %name%| {")) {
const std::pair<Token*, Token*> rangeBefore(start, Token::findsimplematch(start, "{"));
// find typedef name token
Token* nameToken = rangeBefore.second->link()->next();
while (Token::Match(nameToken, "%name%|* %name%|*"))
nameToken = nameToken->next();
const std::pair<Token*, Token*> rangeQualifiers(rangeBefore.second->link()->next(), nameToken);
if (Token::Match(nameToken, "%name% ;")) {
if (Token::Match(rangeBefore.second->previous(), "enum|struct|union|class {"))
rangeBefore.second->previous()->insertToken(nameToken->str());
mRangeType = rangeBefore;
mRangeTypeQualifiers = rangeQualifiers;
Token* typeName = rangeBefore.second->previous();
if (typeName->isKeyword()) {
// TODO typeName->insertToken("T:" + std::to_string(num++));
typeName->insertToken(nameToken->str());
}
mNameToken = nameToken;
mEndToken = nameToken->next();
return;
}
}
for (Token* type = start; Token::Match(type, "%name%|*|&|&&"); type = type->next()) {
if (type != start && Token::Match(type, "%name% ;") && !type->isStandardType()) {
mRangeType.first = start;
mRangeType.second = type;
mNameToken = type;
mEndToken = mNameToken->next();
return;
}
if (type != start && Token::Match(type, "%name% [")) {
Token* end = type->linkAt(1);
while (Token::simpleMatch(end, "] ["))
end = end->linkAt(1);
if (!Token::simpleMatch(end, "] ;"))
break;
mRangeType.first = start;
mRangeType.second = type;
mNameToken = type;
mEndToken = end->next();
mRangeAfterVar.first = mNameToken->next();
mRangeAfterVar.second = mEndToken;
return;
}
if (Token::Match(type->next(), "( * const| %name% ) (") && Token::simpleMatch(type->linkAt(1)->linkAt(1), ") ;")) {
mNameToken = type->linkAt(1)->previous();
mEndToken = type->linkAt(1)->linkAt(1)->next();
mRangeType.first = start;
mRangeType.second = mNameToken;
mRangeAfterVar.first = mNameToken->next();
mRangeAfterVar.second = mEndToken;
return;
}
if (type != start && Token::Match(type, "%name% ( !!(") && Token::simpleMatch(type->linkAt(1), ") ;") && !type->isStandardType()) {
mNameToken = type;
mEndToken = type->linkAt(1)->next();
mRangeType.first = start;
mRangeType.second = type;
mRangeAfterVar.first = mNameToken->next();
mRangeAfterVar.second = mEndToken;
return;
}
}
// TODO: handle all typedefs
if ((false))
printTypedef(typedefToken, std::cout);
mFail = true;
}
const Token* getTypedefToken() const {
return mTypedefToken;
}
bool isUsed() const {
return mUsed;
}
bool isInvalidConstFunctionType(const std::map<std::string, TypedefSimplifier>& m) const {
if (!Token::Match(mTypedefToken, "typedef const %name% %name% ;"))
return false;
const auto it = m.find(mTypedefToken->strAt(2));
if (it == m.end())
return false;
return Token::Match(it->second.mNameToken, "%name% (");
}
bool fail() const {
return mFail;
}
bool replaceFailed() const {
return mReplaceFailed;
}
bool isStructEtc() const {
return mRangeType.second && mRangeType.second->str() == "{";
}
std::string name() const {
return mNameToken ? mNameToken->str() : "";
}
void replace(Token* tok) {
if (tok == mNameToken)
return;
mUsed = true;
const bool isFunctionPointer = Token::Match(mNameToken, "%name% )");
// Special handling for T(...) when T is a pointer
if (Token::Match(tok, "%name% [({]") && !isFunctionPointer && !Token::simpleMatch(tok->linkAt(1), ") (")) {
bool pointerType = false;
for (const Token* type = mRangeType.first; type != mRangeType.second; type = type->next()) {
if (type->str() == "*" || type->str() == "&") {
pointerType = true;
break;
}
}
for (const Token* type = mRangeTypeQualifiers.first; type != mRangeTypeQualifiers.second; type = type->next()) {
if (type->str() == "*" || type->str() == "&") {
pointerType = true;
break;
}
}
if (pointerType) {
tok->tokAt(1)->str("(");
tok->linkAt(1)->str(")");
if (tok->linkAt(1) == tok->tokAt(2)) { // T() or T{}
tok->deleteThis();
tok->next()->insertToken("0");
Token* tok2 = insertTokens(tok, mRangeType);
insertTokens(tok2, mRangeTypeQualifiers);
}
else { // functional-style cast
tok->originalName(tok->str());
tok->isSimplifiedTypedef(true);
tok->str("(");
Token* tok2 = insertTokens(tok, mRangeType);
tok2 = insertTokens(tok2, mRangeTypeQualifiers);
Token* tok3 = tok2->insertToken(")");
Token::createMutualLinks(tok, tok3);
tok->insertTokenBefore("(");
tok3 = tok3->linkAt(1);
tok3 = tok3->insertToken(")");
Token::createMutualLinks(tok->tokAt(-1), tok3);
}
return;
}
}
// Special handling of function pointer cast
if (isFunctionPointer && isCast(tok->previous())) {
tok->insertToken("*");
Token* const tok_1 = insertTokens(tok, std::pair<Token*, Token*>(mRangeType.first, mNameToken->linkAt(1)));
tok_1->originalName(tok->str());
tok->deleteThis();
return;
}
// Inherited type => skip "struct" / "class"
if (Token::Match(mRangeType.first, "const| struct|class %name% {") && Token::Match(tok->previous(), "public|protected|private|<")) {
tok->originalName(tok->str());
tok->str(mRangeType.second->strAt(-1));
return;
}
if (Token::Match(tok, "%name% ::")) {
if (Token::Match(mRangeType.first, "const| struct|class|union|enum %name% %name%|{") ||
Token::Match(mRangeType.first, "%name% %name% ;")) {
tok->originalName(tok->str());
tok->str(mRangeType.second->strAt(-1));
} else {
mReplaceFailed = true;
}
return;
}
// pointer => move "const"
if (Token::simpleMatch(tok->previous(), "const")) {
bool pointerType = false;
for (const Token* type = mRangeType.first; type != mRangeType.second; type = type->next()) {
if (type->str() == "*") {
pointerType = true;
break;
}
}
if (pointerType) {
tok->insertToken("const");
tok->next()->column(tok->column());
tok->next()->setMacroName(tok->previous()->getMacroName());
tok->deletePrevious();
}
}
// Do not duplicate class/struct/enum/union
if (Token::Match(tok->previous(), "enum|union|struct|class")) {
bool found = false;
const std::string &kw = tok->strAt(-1);
for (const Token* type = mRangeType.first; type != mRangeType.second; type = type->next()) {
if (type->str() == kw) {
found = true;
break;
}
}
if (found)
tok->deletePrevious();
else {
mReplaceFailed = true;
return;
}
}
// don't add class|struct|union in inheritance list
auto rangeType = mRangeType;
if (Token::Match(tok->previous(), "public|private|protected")) {
while (Token::Match(rangeType.first, "const|class|struct|union"))
rangeType.first = rangeType.first->next();
}
Token* const tok2 = insertTokens(tok, rangeType);
Token* const tok3 = insertTokens(tok2, mRangeTypeQualifiers);
tok2->originalName(tok->str());
tok3->originalName(tok->str());
Token *after = tok3;
while (Token::Match(after, "%name%|*|&|&&|::"))
after = after->next();
if (Token::Match(mNameToken, "%name% (") && Token::simpleMatch(tok3->next(), "*")) {
while (Token::Match(after, "(|["))
after = after->link()->next();
if (after) {
tok3->insertToken("(");
after->previous()->insertToken(")");
Token::createMutualLinks(tok3->next(), after->previous());
}
}
if (!after) {
mReplaceFailed = true;
return;
}
bool useAfterVarRange = true;
if (Token::simpleMatch(mRangeAfterVar.first, "[")) {
if (Token::Match(after->previous(), "%name% ( !!*")) {
useAfterVarRange = false;
// Function return type => replace array with "*"
for (const Token* a = mRangeAfterVar.first; Token::simpleMatch(a, "["); a = a->link()->next())
tok3->insertToken("*");
} else if (Token::Match(after->previous(), "%name% ( * %name% ) [")) {
after = after->linkAt(4)->next();
} else {
Token* prev = after->previous();
if (prev->isName() && prev != tok3)
prev = prev->previous();
if (Token::Match(prev, "*|&|&&") && prev != tok3) {
while (Token::Match(prev, "*|&|&&") && prev != tok3)
prev = prev->previous();
prev->insertToken("(");
after->previous()->insertToken(")");
}
}
}
if (isFunctionPointer) {
if (Token::Match(after, "( * %name% ) ("))
after = after->link()->linkAt(1)->next();
else if (after->str() == "(") {
useAfterVarRange = false;
if (Token::simpleMatch(tok3->previous(), "( *"))
tok3->deletePrevious();
}
else if (after->str() == "[") {
while (after && after->str() == "[")
after = after->link()->next();
}
}
else {
while (Token::simpleMatch(after, "["))
after = after->link()->next();
}
if (!after)
throw InternalError(tok, "Failed to simplify typedef. Is the code valid?");
Token* const tok4 = useAfterVarRange ? insertTokens(after->previous(), mRangeAfterVar)->next() : tok3->next();
if (tok->next() == tok4)
throw InternalError(tok, "Failed to simplify typedef. Is the code valid?");
tok->deleteThis();
// Unsplit variable declarations
if (tok4 && tok4->isSplittedVarDeclEq() &&
((tok4->isCpp() && Token::Match(tok4->tokAt(-2), "&|&& %name% ;")) || Token::Match(tok4->previous(), "] ; %name% = {"))) {
tok4->deleteNext();
tok4->deleteThis();
}
// Set links
std::stack<Token*> brackets;
for (; tok != tok4; tok = tok->next()) {
if (Token::Match(tok, "[{([]"))
brackets.push(tok);
else if (Token::Match(tok, "[})]]")) {
Token::createMutualLinks(brackets.top(), tok);
brackets.pop();
}
}
}
void removeDeclaration() {
if (Token::simpleMatch(mRangeType.second, "{")) {
while (Token::Match(mTypedefToken, "typedef|const"))
mTypedefToken->deleteThis();
Token::eraseTokens(mRangeType.second->link(), mEndToken);
} else {
Token::eraseTokens(mTypedefToken, mEndToken);
mTypedefToken->deleteThis();
}
}
static int canReplaceStatic(const Token* tok) {
if (!Token::Match(tok, "%name% %name%|*|&|&&|;|(|)|,|::")) {
if (Token::Match(tok->previous(), "( %name% =") && Token::Match(tok->linkAt(-1), ") %name%|{") && !tok->tokAt(-2)->isKeyword())
return true;
if (Token::Match(tok->previous(), ", %name% ="))
return true;
if (Token::Match(tok->previous(), "new %name% ["))
return true;
if (Token::Match(tok->previous(), "< %name%") && tok->previous()->findClosingBracket())
return true;
if (Token::Match(tok->previous(), ", %name% >|>>")) {
for (const Token* prev = tok->previous(); prev; prev = prev->previous()) {
if (Token::Match(prev, "[;{}(]"))
break;
if (prev->str() == "<" && prev->findClosingBracket() == tok->next())
return true;
if (prev->str() == ")")
prev = prev->link();
}
return true;
}
if (Token::Match(tok->previous(), "public|protected|private"))
return true;
if (Token::Match(tok->previous(), ", %name% :")) {
bool isGeneric = false;
for (; tok; tok = tok->previous()) {
if (Token::Match(tok, ")|]"))
tok = tok->link();
else if (Token::Match(tok, "[;{}(]")) {
isGeneric = Token::simpleMatch(tok->previous(), "_Generic (");
break;
}
}
return isGeneric;
}
return false;
}
return -1;
}
bool canReplace(const Token* tok) {
if (mNameToken == tok)
return false;
if (!Token::Match(tok->previous(), "%name%|;|{|}|(|,|<") && !Token::Match(tok->previous(), "!!. %name% ("))
return false;
{
const int res = canReplaceStatic(tok);
if (res == 0 || res == 1)
return res != 0;
}
if (Token::Match(tok->previous(), "%name%") && !tok->previous()->isKeyword())
return false;
if (Token::simpleMatch(tok->next(), "(") && Token::Match(tok->linkAt(1), ") %name%|{"))
return false;
if (Token::Match(tok->previous(), "struct|union|class|enum %name% %name%") &&
Token::simpleMatch(mRangeType.second, "{") &&
tok->str() != mRangeType.second->strAt(-1))
return true;
if (Token::Match(tok->previous(), "; %name% ;"))
return false;
if (Token::Match(tok->previous(), "<|, %name% * ,|>"))
return true;
for (const Token* after = tok->next(); after; after = after->next()) {
if (Token::Match(after, "%name%|::|&|*|&&"))
continue;
if (after->str() == "<" && after->link())
break;
if (after->isNumber())
return false;
if (after->isComparisonOp() || after->isArithmeticalOp())
return false;
break;
}
for (const Token* before = tok->previous(); before; before = before->previous()) {
if (Token::Match(before, "[+-*/&|~!]"))
return false;
if (Token::Match(before, "struct|union|class|enum") || before->isStandardType())
return false;
if (before->str() == "::")
return false;
if (before->isName())
continue;
break;
}
return true;
}
Token* endToken() const {
return mEndToken;
}
Token* nameToken() const {
return mNameToken;
}
private:
static bool isCast(const Token* tok) {
if (Token::Match(tok, "( %name% ) (|%name%|%num%"))
return !tok->tokAt(3)->isKeyword();
if (Token::Match(tok, "< %name% > (") && tok->previous() && endsWith(tok->strAt(-1), "_cast", 5))
return true;
return false;
}
static Token* insertTokens(Token* to, std::pair<Token*,Token*> range) {
for (const Token* from = range.first; from != range.second; from = from->next()) {
to->insertToken(from->str());
to->next()->column(to->column());
to = to->next();
to->isSimplifiedTypedef(true);
to->isExternC(from->isExternC());
}
return to;
}
static void printTypedef(const Token *tok, std::ostream& out) {
int indent = 0;
while (tok && (indent > 0 || tok->str() != ";")) {
if (tok->str() == "{")
++indent;
else if (tok->str() == "}")
--indent;
out << " " << tok->str();
tok = tok->next();
}
out << "\n";
}
};
}
void Tokenizer::simplifyTypedef()
{
// Simplify global typedefs that are not redefined with the fast 1-pass simplification.
// Then use the slower old typedef simplification.
std::map<std::string, int> numberOfTypedefs;
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "typedef") {
TypedefSimplifier ts(tok);
if (!ts.fail())
numberOfTypedefs[ts.name()]++;
continue;
}
}
int indentlevel = 0;
std::map<std::string, TypedefSimplifier> typedefs;
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName()) {
if (tok->str()[0] == '{')
++indentlevel;
else if (tok->str()[0] == '}')
--indentlevel;
continue;
}
if (indentlevel == 0 && tok->str() == "typedef") {
TypedefSimplifier ts(tok);
if (!ts.fail() && numberOfTypedefs[ts.name()] == 1 &&
(numberOfTypedefs.find(ts.getTypedefToken()->strAt(1)) == numberOfTypedefs.end() || ts.getTypedefToken()->strAt(2) == "(")) {
if (mSettings.severity.isEnabled(Severity::portability) && ts.isInvalidConstFunctionType(typedefs))
reportError(tok->next(), Severity::portability, "invalidConstFunctionType",
"It is unspecified behavior to const qualify a function type.");
typedefs.emplace(ts.name(), ts);
if (!ts.isStructEtc())
tok = ts.endToken();
}
continue;
}
auto it = typedefs.find(tok->str());
if (it != typedefs.end() && it->second.canReplace(tok)) {
std::set<std::string> r;
while (it != typedefs.end() && r.insert(tok->str()).second) {
it->second.replace(tok);
it = typedefs.find(tok->str());
}
} else if (tok->str() == "enum") {
while (Token::Match(tok, "%name%|:|::"))
tok = tok->next();
if (!tok)
break;
if (tok->str() == "{")
tok = tok->link();
}
}
if (!typedefs.empty())
{
// remove typedefs
for (auto &t: typedefs) {
if (t.second.replaceFailed()) {
syntaxError(t.second.getTypedefToken());
} else {
const Token* const typedefToken = t.second.getTypedefToken();
TypedefInfo typedefInfo;
typedefInfo.name = t.second.name();
typedefInfo.filename = list.file(typedefToken);
typedefInfo.lineNumber = typedefToken->linenr();
typedefInfo.column = typedefToken->column();
typedefInfo.used = t.second.isUsed();
typedefInfo.isFunctionPointer = Token::Match(t.second.nameToken(), "%name% ) (");
mTypedefInfo.push_back(std::move(typedefInfo));
t.second.removeDeclaration();
}
}
while (Token::Match(list.front(), "; %any%"))
list.front()->deleteThis();
}
simplifyTypedefCpp();
}
static Token* simplifyTypedefCopyTokens(Token* to, const Token* fromStart, const Token* toEnd, const Token* location) {
Token* ret = TokenList::copyTokens(to, fromStart, toEnd);
for (Token* tok = to->next(); tok != ret->next(); tok = tok->next()) {
tok->linenr(location->linenr());
tok->column(location->column());
tok->isSimplifiedTypedef(true);
}
return ret;
}
static Token* simplifyTypedefInsertToken(Token* tok, const std::string& str, const Token* location) {
tok = tok->insertToken(str);
tok->linenr(location->linenr());
tok->column(location->column());
tok->isSimplifiedTypedef(true);
return tok;
}
// TODO: rename - it is not C++ specific
void Tokenizer::simplifyTypedefCpp()
{
const bool cpp = isCPP();
bool isNamespace = false;
std::string className, fullClassName;
bool hasClass = false;
bool goback = false;
// add global namespace
std::vector<Space> spaceInfo(1);
// Convert "using a::b;" to corresponding typedef statements
simplifyUsingToTypedef();
const std::time_t maxTime = mSettings.typedefMaxTime > 0 ? std::time(nullptr) + mSettings.typedefMaxTime: 0;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!list.getFiles().empty())
mErrorLogger.reportProgress(list.getFiles()[0], "Tokenize (typedef)", tok->progressValue());
if (Settings::terminated())
return;
if (maxTime > 0 && std::time(nullptr) > maxTime) {
if (mSettings.debugwarnings) {
ErrorMessage::FileLocation loc(list.getFiles()[0], 0, 0);
ErrorMessage errmsg({std::move(loc)},
emptyString,
Severity::debug,
"Typedef simplification instantiation maximum time exceeded",
"typedefMaxTime",
Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
return;
}
if (goback) {
//jump back once, see the comment at the end of the function
goback = false;
tok = tok->previous();
}
if (tok->str() != "typedef") {
if (Token::simpleMatch(tok, "( typedef")) {
// Skip typedefs inside parentheses (#2453 and #4002)
tok = tok->next();
} else if (Token::Match(tok, "class|struct|namespace %any%") &&
(!tok->previous() || tok->strAt(-1) != "enum")) {
isNamespace = (tok->str() == "namespace");
hasClass = true;
className = tok->strAt(1);
const Token *tok1 = tok->next();
fullClassName = className;
while (Token::Match(tok1, "%name% :: %name%")) {
tok1 = tok1->tokAt(2);
fullClassName += " :: " + tok1->str();
}
} else if (hasClass && tok->str() == ";") {
hasClass = false;
} else if (hasClass && tok->str() == "{") {
if (!isNamespace)
spaceInfo.back().recordTypes.insert(fullClassName);
Space info;
info.isNamespace = isNamespace;
info.className = className;
info.bodyEnd = tok->link();
info.bodyEnd2 = tok->link();
spaceInfo.push_back(std::move(info));
hasClass = false;
} else if (spaceInfo.size() > 1 && tok->str() == "}" && spaceInfo.back().bodyEnd == tok) {
spaceInfo.pop_back();
}
continue;
}
// pull struct, union, enum or class definition out of typedef
// use typedef name for unnamed struct, union, enum or class
const Token* tokClass = tok->next();
while (Token::Match(tokClass, "const|volatile"))
tokClass = tokClass->next();
if (Token::Match(tokClass, "struct|enum|union|class %type%| {|:")) {
Token *tok1 = splitDefinitionFromTypedef(tok, &mUnnamedCount);
if (!tok1)
continue;
tok = tok1;
}
/** @todo add support for union */
if (Token::Match(tok->next(), "enum %type% %type% ;") && tok->strAt(2) == tok->strAt(3)) {
tok->deleteNext(3);
tok->deleteThis();
if (tok->next())
tok->deleteThis();
//now the next token to process is 'tok', not 'tok->next()';
goback = true;
continue;
}
Token *typeName;
Token *typeStart = nullptr;
Token *typeEnd = nullptr;
Token *argStart = nullptr;
Token *argEnd = nullptr;
Token *arrayStart = nullptr;
Token *arrayEnd = nullptr;
Token *specStart = nullptr;
Token *specEnd = nullptr;
Token *typeDef = tok;
Token *argFuncRetStart = nullptr;
Token *argFuncRetEnd = nullptr;
Token *funcStart = nullptr;
Token *funcEnd = nullptr;
Token *tokOffset = tok->next();
bool function = false;
bool functionPtr = false;
bool functionRetFuncPtr = false;
bool functionPtrRetFuncPtr = false;
bool ptrToArray = false;
bool refToArray = false;
bool ptrMember = false;
bool typeOf = false;
Token *namespaceStart = nullptr;
Token *namespaceEnd = nullptr;
// check for invalid input
if (!tokOffset || tokOffset->isControlFlowKeyword())
syntaxError(tok);
if (tokOffset->str() == "::") {
typeStart = tokOffset;
tokOffset = tokOffset->next();
while (Token::Match(tokOffset, "%type% ::"))
tokOffset = tokOffset->tokAt(2);
typeEnd = tokOffset;
if (Token::Match(tokOffset, "%type%"))
tokOffset = tokOffset->next();
} else if (Token::Match(tokOffset, "%type% ::")) {
typeStart = tokOffset;
do {
tokOffset = tokOffset->tokAt(2);
} while (Token::Match(tokOffset, "%type% ::"));
typeEnd = tokOffset;
if (Token::Match(tokOffset, "%type%"))
tokOffset = tokOffset->next();
} else if (Token::Match(tokOffset, "%type%")) {
typeStart = tokOffset;
while (Token::Match(tokOffset, "const|struct|enum %type%") ||
(tokOffset->next() && tokOffset->next()->isStandardType() && !Token::Match(tokOffset->next(), "%name% ;")))
tokOffset = tokOffset->next();
typeEnd = tokOffset;
if (!Token::Match(tokOffset->next(), "%name% ;"))
tokOffset = tokOffset->next();
while (Token::Match(tokOffset, "%type%") &&
(tokOffset->isStandardType() || Token::Match(tokOffset, "unsigned|signed")) &&
!Token::Match(tokOffset->next(), "%name% ;")) {
typeEnd = tokOffset;
tokOffset = tokOffset->next();
}
bool atEnd = false;
while (!atEnd) {
if (tokOffset && tokOffset->str() == "::") {
typeEnd = tokOffset;
tokOffset = tokOffset->next();
}
if (Token::Match(tokOffset, "%type%") &&
tokOffset->next() && !Token::Match(tokOffset->next(), "[|;|,|(")) {
typeEnd = tokOffset;
tokOffset = tokOffset->next();
} else if (Token::simpleMatch(tokOffset, "const (")) {
typeEnd = tokOffset;
tokOffset = tokOffset->next();
atEnd = true;
} else
atEnd = true;
}
} else
continue; // invalid input
// check for invalid input
if (!tokOffset)
syntaxError(tok);
// check for template
if (!isC() && tokOffset->str() == "<") {
typeEnd = tokOffset->findClosingBracket();
while (typeEnd && Token::Match(typeEnd->next(), ":: %type%"))
typeEnd = typeEnd->tokAt(2);
if (!typeEnd) {
// internal error
return;
}
while (Token::Match(typeEnd->next(), "const|volatile"))
typeEnd = typeEnd->next();
tok = typeEnd;
tokOffset = tok->next();
}
std::list<std::string> pointers;
// check for pointers and references
while (Token::Match(tokOffset, "*|&|&&|const")) {
pointers.push_back(tokOffset->str());
tokOffset = tokOffset->next();
}
// check for invalid input
if (!tokOffset)
syntaxError(tok);
if (tokOffset->isName() && !tokOffset->isKeyword()) {
// found the type name
typeName = tokOffset;
tokOffset = tokOffset->next();
// check for array
while (tokOffset && tokOffset->str() == "[") {
if (!arrayStart)
arrayStart = tokOffset;
arrayEnd = tokOffset->link();
tokOffset = arrayEnd->next();
}
// check for end or another
if (Token::Match(tokOffset, ";|,"))
tok = tokOffset;
// or a function typedef
else if (tokOffset && tokOffset->str() == "(") {
Token *tokOffset2 = nullptr;
if (Token::Match(tokOffset, "( *|%name%")) {
tokOffset2 = tokOffset->next();
if (tokOffset2->str() == "typename")
tokOffset2 = tokOffset2->next();
while (Token::Match(tokOffset2, "%type% ::"))
tokOffset2 = tokOffset2->tokAt(2);
}
// unhandled typedef, skip it and continue
if (typeName->str() == "void") {
unsupportedTypedef(typeDef);
tok = deleteInvalidTypedef(typeDef);
if (tok == list.front())
//now the next token to process is 'tok', not 'tok->next()';
goback = true;
continue;
}
// function pointer
if (Token::Match(tokOffset2, "* %name% ) (")) {
// name token wasn't a name, it was part of the type
typeEnd = typeEnd->next();
functionPtr = true;
funcStart = funcEnd = tokOffset2; // *
tokOffset = tokOffset2->tokAt(3); // (
typeName = tokOffset->tokAt(-2);
argStart = tokOffset;
argEnd = tokOffset->link();
tok = argEnd->next();
}
// function
else if (isFunctionHead(tokOffset->link(), ";,")) {
function = true;
if (tokOffset->link()->strAt(1) == "const") {
specStart = tokOffset->link()->next();
specEnd = specStart;
}
argStart = tokOffset;
argEnd = tokOffset->link();
tok = argEnd->next();
if (specStart)
tok = tok->next();
}
// syntax error
else
syntaxError(tok);
}
// unhandled typedef, skip it and continue
else {
unsupportedTypedef(typeDef);
tok = deleteInvalidTypedef(typeDef);
if (tok == list.front())
//now the next token to process is 'tok', not 'tok->next()';
goback = true;
continue;
}
}
// typeof: typedef typeof ( ... ) type;
else if (Token::simpleMatch(tokOffset->previous(), "typeof (") &&
Token::Match(tokOffset->link(), ") %type% ;")) {
argStart = tokOffset;
argEnd = tokOffset->link();
typeName = tokOffset->link()->next();
tok = typeName->next();
typeOf = true;
}
// function: typedef ... ( ... type )( ... );
// typedef ... (( ... type )( ... ));
// typedef ... ( * ( ... type )( ... ));
else if (tokOffset->str() == "(" && (
(tokOffset->link() && Token::Match(tokOffset->link()->previous(), "%type% ) (") &&
Token::Match(tokOffset->link()->linkAt(1), ") const|volatile|;")) ||
(Token::simpleMatch(tokOffset, "( (") &&
tokOffset->next() && Token::Match(tokOffset->linkAt(1)->previous(), "%type% ) (") &&
Token::Match(tokOffset->linkAt(1)->linkAt(1), ") const|volatile| ) ;|,")) ||
(Token::simpleMatch(tokOffset, "( * (") &&
tokOffset->linkAt(2) && Token::Match(tokOffset->linkAt(2)->previous(), "%type% ) (") &&
Token::Match(tokOffset->linkAt(2)->linkAt(1), ") const|volatile| ) ;|,")))) {
if (tokOffset->strAt(1) == "(")
tokOffset = tokOffset->next();
else if (Token::simpleMatch(tokOffset, "( * (")) {
pointers.emplace_back("*");
tokOffset = tokOffset->tokAt(2);
}
if (tokOffset->link()->strAt(-2) == "*")
functionPtr = true;
else
function = true;
funcStart = tokOffset->next();
tokOffset = tokOffset->link();
funcEnd = tokOffset->tokAt(-2);
typeName = tokOffset->previous();
argStart = tokOffset->next();
argEnd = tokOffset->linkAt(1);
if (!argEnd)
syntaxError(argStart);
const Token* tok2 = argEnd->next();
while (tok2 && (tok2->isKeyword() || tok2->str() == ")"))
tok2 = tok2->next();
if (!Token::simpleMatch(tok2, ";"))
syntaxError(tok2);
tok = argEnd->next();
Token *spec = tok;
if (Token::Match(spec, "const|volatile")) {
specStart = spec;
specEnd = spec;
while (Token::Match(spec->next(), "const|volatile")) {
specEnd = spec->next();
spec = specEnd;
}
tok = specEnd->next();
}
if (!tok)
syntaxError(specEnd);
if (tok->str() == ")")
tok = tok->next();
}
else if (Token::Match(tokOffset, "( %type% (")) {
function = true;
if (tokOffset->link()->next()) {
tok = tokOffset->link()->next();
tokOffset = tokOffset->tokAt(2);
typeName = tokOffset->previous();
argStart = tokOffset;
argEnd = tokOffset->link();
} else {
// internal error
continue;
}
}
// pointer to function returning pointer to function
else if (Token::Match(tokOffset, "( * ( * %type% ) (") &&
Token::simpleMatch(tokOffset->linkAt(6), ") ) (") &&
Token::Match(tokOffset->linkAt(6)->linkAt(2), ") ;|,")) {
functionPtrRetFuncPtr = true;
tokOffset = tokOffset->tokAt(6);
typeName = tokOffset->tokAt(-2);
argStart = tokOffset;
argEnd = tokOffset->link();
if (!argEnd)
syntaxError(arrayStart);
argFuncRetStart = argEnd->tokAt(2);
argFuncRetEnd = argFuncRetStart->link();
if (!argFuncRetEnd)
syntaxError(argFuncRetStart);
tok = argFuncRetEnd->next();
}
// function returning pointer to function
else if (Token::Match(tokOffset, "( * %type% (") &&
Token::simpleMatch(tokOffset->linkAt(3), ") ) (") &&
Token::Match(tokOffset->linkAt(3)->linkAt(2), ") ;|,")) {
functionRetFuncPtr = true;
tokOffset = tokOffset->tokAt(3);
typeName = tokOffset->previous();
argStart = tokOffset;
argEnd = tokOffset->link();
argFuncRetStart = argEnd->tokAt(2);
if (!argFuncRetStart)
syntaxError(tokOffset);
argFuncRetEnd = argFuncRetStart->link();
if (!argFuncRetEnd)
syntaxError(tokOffset);
tok = argFuncRetEnd->next();
} else if (Token::Match(tokOffset, "( * ( %type% ) (")) {
functionRetFuncPtr = true;
tokOffset = tokOffset->tokAt(5);
typeName = tokOffset->tokAt(-2);
argStart = tokOffset;
argEnd = tokOffset->link();
if (!argEnd)
syntaxError(arrayStart);
argFuncRetStart = argEnd->tokAt(2);
if (!argFuncRetStart)
syntaxError(tokOffset);
argFuncRetEnd = argFuncRetStart->link();
if (!argFuncRetEnd)
syntaxError(tokOffset);
tok = argFuncRetEnd->next();
}
// pointer/reference to array
else if (Token::Match(tokOffset, "( *|& %type% ) [")) {
ptrToArray = (tokOffset->strAt(1) == "*");
refToArray = !ptrToArray;
tokOffset = tokOffset->tokAt(2);
typeName = tokOffset;
arrayStart = tokOffset->tokAt(2);
arrayEnd = arrayStart->link();
if (!arrayEnd)
syntaxError(arrayStart);
tok = arrayEnd->next();
}
// pointer to class member
else if (Token::Match(tokOffset, "( %type% :: * %type% ) ;")) {
tokOffset = tokOffset->tokAt(2);
namespaceStart = tokOffset->previous();
namespaceEnd = tokOffset;
ptrMember = true;
tokOffset = tokOffset->tokAt(2);
typeName = tokOffset;
tok = tokOffset->tokAt(2);
}
// unhandled typedef, skip it and continue
else {
unsupportedTypedef(typeDef);
tok = deleteInvalidTypedef(typeDef);
if (tok == list.front())
//now the next token to process is 'tok', not 'tok->next()';
goback = true;
continue;
}
bool done = false;
bool ok = true;
TypedefInfo typedefInfo;
typedefInfo.name = typeName->str();
typedefInfo.filename = list.file(typeName);
typedefInfo.lineNumber = typeName->linenr();
typedefInfo.column = typeName->column();
typedefInfo.used = false;
typedefInfo.isFunctionPointer = Token::Match(typeName, "%name% ) (");
mTypedefInfo.push_back(std::move(typedefInfo));
while (!done) {
std::string pattern = typeName->str();
int scope = 0;
bool simplifyType = false;
bool inMemberFunc = false;
int memberScope = 0;
bool globalScope = false;
int classLevel = spaceInfo.size();
bool inTypeDef = false;
bool inEnum = false;
std::string removed;
std::string classPath;
for (size_t i = 1; i < spaceInfo.size(); ++i) {
if (!classPath.empty())
classPath += " :: ";
classPath += spaceInfo[i].className;
}
for (Token *tok2 = tok; tok2; tok2 = tok2->next()) {
if (Settings::terminated())
return;
removed.clear();
if (Token::simpleMatch(tok2, "typedef"))
inTypeDef = true;
if (inTypeDef && Token::simpleMatch(tok2, ";"))
inTypeDef = false;
// Check for variable declared with the same name
if (!inTypeDef && spaceInfo.size() == 1 && Token::Match(tok2->previous(), "%name%") &&
!tok2->previous()->isKeyword()) {
Token* varDecl = tok2;
while (Token::Match(varDecl, "*|&|&&|const"))
varDecl = varDecl->next();
if (Token::Match(varDecl, "%name% ;|,|)|=") && varDecl->str() == typeName->str()) {
// Skip to the next closing brace
if (Token::Match(varDecl, "%name% ) {")) { // is argument variable
tok2 = varDecl->linkAt(2)->next();
} else {
tok2 = varDecl;
while (tok2 && !Token::simpleMatch(tok2, "}")) {
if (Token::Match(tok2, "(|{|["))
tok2 = tok2->link();
tok2 = tok2->next();
}
}
if (!tok2)
break;
continue;
}
}
if (tok2->link()) { // Pre-check for performance
// check for end of scope
if (tok2->str() == "}") {
// check for end of member function
if (inMemberFunc) {
--memberScope;
if (memberScope == 0)
inMemberFunc = false;
}
inEnum = false;
if (classLevel > 1 && tok2 == spaceInfo[classLevel - 1].bodyEnd2) {
--classLevel;
pattern.clear();
for (std::size_t i = classLevel; i < spaceInfo.size(); ++i)
pattern += (spaceInfo[i].className + " :: ");
pattern += typeName->str();
} else {
if (scope == 0 && !(classLevel > 1 && tok2 == spaceInfo[classLevel - 1].bodyEnd))
break;
scope = std::max(scope - 1, 0);
}
}
// check for member functions
else if (cpp && tok2->str() == "(" && isFunctionHead(tok2, "{:")) {
const Token *func = tok2->previous();
/** @todo add support for multi-token operators */
if (func->strAt(-1) == "operator")
func = func->previous();
if (!func->previous())
syntaxError(func);
// check for qualifier
if (Token::Match(func->tokAt(-2), "%name% ::")) {
int offset = -2;
while (Token::Match(func->tokAt(offset - 2), "%name% ::"))
offset -= 2;
// check for available and matching class name
if (spaceInfo.size() > 1 && classLevel < spaceInfo.size() &&
func->strAt(offset) == spaceInfo[classLevel].className) {
memberScope = 0;
inMemberFunc = true;
}
}
}
// check for entering a new scope
else if (tok2->str() == "{") {
// check for entering a new namespace
if (cpp) {
if (tok2->strAt(-2) == "namespace") {
if (classLevel < spaceInfo.size() &&
spaceInfo[classLevel].isNamespace &&
spaceInfo[classLevel].className == tok2->strAt(-1)) {
spaceInfo[classLevel].bodyEnd2 = tok2->link();
++classLevel;
pattern.clear();
for (std::size_t i = classLevel; i < spaceInfo.size(); ++i)
pattern += spaceInfo[i].className + " :: ";
pattern += typeName->str();
}
++scope;
}
if (isEnumStart(tok2))
inEnum = true;
}
// keep track of scopes within member function
if (inMemberFunc)
++memberScope;
++scope;
}
}
// check for operator typedef
/** @todo add support for multi-token operators */
else if (cpp &&
tok2->str() == "operator" &&
tok2->next() &&
tok2->strAt(1) == typeName->str() &&
tok2->linkAt(2) &&
tok2->strAt(2) == "(" &&
Token::Match(tok2->linkAt(2), ") const| {")) {
// check for qualifier
if (tok2->strAt(-1) == "::") {
// check for available and matching class name
if (spaceInfo.size() > 1 && classLevel < spaceInfo.size() &&
tok2->strAt(-2) == spaceInfo[classLevel].className) {
tok2 = tok2->next();
simplifyType = true;
}
}
}
else if (Token::Match(tok2->previous(), "class|struct %name% [:{]")) {
// don't replace names in struct/class definition
}
// check for typedef that can be substituted
else if ((tok2->isNameOnly() || (tok2->isName() && (tok2->isExpandedMacro() || tok2->isInline() || tok2->isExternC()))) &&
(Token::simpleMatch(tok2, pattern.c_str(), pattern.size()) ||
(inMemberFunc && tok2->str() == typeName->str()))) {
// member function class variables don't need qualification
if (!(inMemberFunc && tok2->str() == typeName->str()) && pattern.find("::") != std::string::npos) { // has a "something ::"
Token *start = tok2;
int count = 0;
int back = classLevel - 1;
bool good = true;
// check for extra qualification
while (back >= 1) {
Token *qualificationTok = start->tokAt(-2);
if (!Token::Match(qualificationTok, "%type% ::"))
break;
if (qualificationTok->str() == spaceInfo[back].className) {
start = qualificationTok;
back--;
count++;
} else {
good = false;
break;
}
}
// check global namespace
if (good && back == 1 && start->strAt(-1) == "::")
good = false;
if (good) {
// remove any extra qualification if present
while (count) {
if (!removed.empty())
removed.insert(0, " ");
removed.insert(0, tok2->strAt(-2) + " " + tok2->strAt(-1));
tok2->tokAt(-3)->deleteNext(2);
--count;
}
// remove global namespace if present
if (tok2->strAt(-1) == "::") {
removed.insert(0, ":: ");
tok2->tokAt(-2)->deleteNext();
globalScope = true;
}
// remove qualification if present
for (std::size_t i = classLevel; i < spaceInfo.size(); ++i) {
if (!removed.empty())
removed += " ";
removed += (tok2->str() + " " + tok2->strAt(1));
tok2->deleteThis();
tok2->deleteThis();
}
simplifyType = true;
}
} else {
if (tok2->strAt(-1) == "::") {
int relativeSpaceInfoSize = spaceInfo.size();
Token * tokBeforeType = tok2->previous();
while (relativeSpaceInfoSize > 1 &&
tokBeforeType && tokBeforeType->str() == "::" &&
tokBeforeType->strAt(-1) == spaceInfo[relativeSpaceInfoSize-1].className) {
tokBeforeType = tokBeforeType->tokAt(-2);
--relativeSpaceInfoSize;
}
if (tokBeforeType && tokBeforeType->str() != "::") {
Token::eraseTokens(tokBeforeType, tok2);
simplifyType = true;
}
} else if (Token::Match(tok2->previous(), "case|;|{|} %type% :")) {
tok2 = tok2->next();
} else if (duplicateTypedef(tok2, typeName, typeDef)) {
// skip to end of scope if not already there
if (tok2->str() != "}") {
while (tok2->next()) {
if (tok2->strAt(1) == "{")
tok2 = tok2->linkAt(1)->previous();
else if (tok2->strAt(1) == "}")
break;
tok2 = tok2->next();
}
}
} else if (Token::Match(tok2->tokAt(-2), "%type% *|&")) {
// Ticket #5868: Don't substitute variable names
} else if (tok2->strAt(-1) != ".") {
simplifyType = (TypedefSimplifier::canReplaceStatic(tok2) != 0);
}
}
}
simplifyType = simplifyType && (!inEnum || !Token::simpleMatch(tok2->next(), "="));
simplifyType = simplifyType && !(Token::simpleMatch(tok2->next(), "<") && Token::simpleMatch(typeEnd, ">"));
if (simplifyType) {
mTypedefInfo.back().used = true;
// can't simplify 'operator functionPtr ()' and 'functionPtr operator ... ()'
if (functionPtr && (tok2->strAt(-1) == "operator" ||
(tok2->next() && tok2->strAt(1) == "operator"))) {
simplifyType = false;
tok2 = tok2->next();
continue;
}
// There are 2 categories of typedef substitutions:
// 1. variable declarations that preserve the variable name like
// global, local, and function parameters
// 2. not variable declarations that have no name like derived
// classes, casts, operators, and template parameters
// try to determine which category this substitution is
bool inCast = false;
bool inTemplate = false;
bool inOperator = false;
bool inSizeof = false;
const bool sameStartEnd = (typeStart == typeEnd);
// check for derived class: class A : some_typedef {
const bool isDerived = Token::Match(tok2->previous(), "public|protected|private|: %type% {|,");
// check for cast: (some_typedef) A or static_cast<some_typedef>(A)
// todo: check for more complicated casts like: (const some_typedef *)A
if ((tok2->strAt(-1) == "(" && tok2->strAt(1) == ")" && tok2->strAt(-2) != "sizeof") ||
(tok2->strAt(-1) == "<" && Token::simpleMatch(tok2->next(), "> (")) ||
Token::Match(tok2->tokAt(-2), "( const %name% )"))
inCast = true;
// check for template parameters: t<some_typedef> t1
else if (Token::Match(tok2->previous(), "<|,") &&
Token::Match(tok2->next(), "&|*| &|*| >|,"))
inTemplate = true;
else if (Token::Match(tok2->tokAt(-2), "sizeof ( %type% )"))
inSizeof = true;
// check for operator
if (tok2->strAt(-1) == "operator" ||
Token::simpleMatch(tok2->tokAt(-2), "operator const"))
inOperator = true;
if (typeStart->str() == "typename" && tok2->strAt(-1)=="typename") {
// Remove one typename if it is already contained in the goal
typeStart = typeStart->next();
}
// skip over class or struct in derived class declaration
bool structRemoved = false;
if ((isDerived || inTemplate) && Token::Match(typeStart, "class|struct")) {
if (typeStart->str() == "struct")
structRemoved = true;
typeStart = typeStart->next();
}
if (Token::Match(typeStart, "struct|class|union") && Token::Match(tok2, "%name% ::"))
typeStart = typeStart->next();
if (sameStartEnd)
typeEnd = typeStart;
// Is this a "T()" expression where T is a pointer type?
const bool isPointerTypeCall = !inOperator && Token::Match(tok2, "%name% ( )") && !pointers.empty();
// start substituting at the typedef name by replacing it with the type
const Token * const location = tok2;
for (Token* tok3 = typeStart; tok3 && (tok3->str() != ";"); tok3 = tok3->next())
tok3->isSimplifiedTypedef(true);
if (isPointerTypeCall) {
tok2->deleteThis();
tok2 = simplifyTypedefInsertToken(tok2, "0", location);
simplifyTypedefInsertToken(tok2->next(), "0", location);
}
if (Token::Match(tok2->tokAt(-1), "class|struct|union") && tok2->strAt(-1) == typeStart->str())
tok2->deletePrevious();
tok2->str(typeStart->str());
// restore qualification if it was removed
if (Token::Match(typeStart, "class|struct|union") || structRemoved) {
if (structRemoved)
tok2 = tok2->previous();
if (globalScope) {
tok2 = simplifyTypedefInsertToken(tok2, "::", location);
}
for (std::size_t i = classLevel; i < spaceInfo.size(); ++i) {
tok2 = simplifyTypedefInsertToken(tok2, spaceInfo[i].className, location);
tok2 = simplifyTypedefInsertToken(tok2, "::", location);
}
}
// add some qualification back if needed
Token *start = tok2;
std::string removed1 = removed;
std::string::size_type idx = removed1.rfind(" ::");
if (idx != std::string::npos)
removed1.resize(idx);
if (removed1 == classPath && !removed1.empty()) {
for (std::vector<Space>::const_reverse_iterator it = spaceInfo.crbegin(); it != spaceInfo.crend(); ++it) {
if (it->recordTypes.find(start->str()) != it->recordTypes.end()) {
std::string::size_type spaceIdx = 0;
std::string::size_type startIdx = 0;
while ((spaceIdx = removed1.find(' ', startIdx)) != std::string::npos) {
simplifyTypedefInsertToken(tok2->previous(), removed1.substr(startIdx, spaceIdx - startIdx), location);
startIdx = spaceIdx + 1;
}
simplifyTypedefInsertToken(tok2->previous(), removed1.substr(startIdx), location);
simplifyTypedefInsertToken(tok2->previous(), "::", location);
break;
}
idx = removed1.rfind(" ::");
if (idx == std::string::npos)
break;
removed1.resize(idx);
}
}
Token* constTok = Token::simpleMatch(tok2->previous(), "const") ? tok2->previous() : nullptr;
// add remainder of type
tok2 = simplifyTypedefCopyTokens(tok2, typeStart->next(), typeEnd, location);
if (!pointers.empty()) {
for (const std::string &p : pointers)
// cppcheck-suppress useStlAlgorithm
tok2 = simplifyTypedefInsertToken(tok2, p, location);
if (constTok && !functionPtr) {
tok2 = simplifyTypedefInsertToken(tok2, "const", location);
constTok->deleteThis();
}
}
if (funcStart && funcEnd) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
Token *paren = tok2;
tok2 = simplifyTypedefCopyTokens(tok2, funcStart, funcEnd, location);
if (!inCast)
tok2 = processFunc(tok2, inOperator);
if (!tok2)
break;
while (Token::Match(tok2, "%name%|] ["))
tok2 = tok2->linkAt(1);
tok2 = simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2, paren);
tok2 = simplifyTypedefCopyTokens(tok2, argStart, argEnd, location);
if (specStart) {
Token *spec = specStart;
tok2 = simplifyTypedefInsertToken(tok2, spec->str(), location);
while (spec != specEnd) {
spec = spec->next();
tok2 = simplifyTypedefInsertToken(tok2, spec->str(), location);
}
}
}
else if (functionPtr || function) {
// don't add parentheses around function names because it
// confuses other simplifications
bool needParen = true;
if (!inTemplate && function && tok2->next() && tok2->strAt(1) != "*")
needParen = false;
if (needParen) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
}
Token *tok3 = tok2;
if (namespaceStart) {
const Token *tok4 = namespaceStart;
while (tok4 != namespaceEnd) {
tok2 = simplifyTypedefInsertToken(tok2, tok4->str(), location);
tok4 = tok4->next();
}
tok2 = simplifyTypedefInsertToken(tok2, namespaceEnd->str(), location);
}
if (functionPtr) {
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
}
if (!inCast)
tok2 = processFunc(tok2, inOperator);
if (needParen) {
if (!tok2)
syntaxError(nullptr);
tok2 = simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2, tok3);
}
if (!tok2)
syntaxError(nullptr);
tok2 = simplifyTypedefCopyTokens(tok2, argStart, argEnd, location);
if (inTemplate) {
tok2 = tok2->next();
}
if (specStart) {
Token *spec = specStart;
tok2 = simplifyTypedefInsertToken(tok2, spec->str(), location);
while (spec != specEnd) {
spec = spec->next();
tok2 = simplifyTypedefInsertToken(tok2, spec->str(), location);
}
}
} else if (functionRetFuncPtr || functionPtrRetFuncPtr) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
Token *tok3 = tok2;
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
Token * tok4 = nullptr;
if (functionPtrRetFuncPtr) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
tok4 = tok2;
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
}
// skip over variable name if there
if (!inCast) {
if (!tok2 || !tok2->next())
syntaxError(nullptr);
if (tok2->strAt(1) != ")")
tok2 = tok2->next();
}
if (tok4 && functionPtrRetFuncPtr) {
tok2 = simplifyTypedefInsertToken(tok2,")", location);
Token::createMutualLinks(tok2, tok4);
}
tok2 = simplifyTypedefCopyTokens(tok2, argStart, argEnd, location);
tok2 = simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2, tok3);
tok2 = simplifyTypedefCopyTokens(tok2, argFuncRetStart, argFuncRetEnd, location);
} else if (ptrToArray || refToArray) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
Token *tok3 = tok2;
if (ptrToArray)
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
else
tok2 = simplifyTypedefInsertToken(tok2, "&", location);
bool hasName = false;
// skip over name
if (tok2->next() && tok2->strAt(1) != ")" && tok2->strAt(1) != "," &&
tok2->strAt(1) != ">") {
hasName = true;
if (tok2->strAt(1) != "(")
tok2 = tok2->next();
// check for function and skip over args
if (tok2 && tok2->next() && tok2->strAt(1) == "(")
tok2 = tok2->linkAt(1);
// check for array
if (tok2 && tok2->next() && tok2->strAt(1) == "[")
tok2 = tok2->linkAt(1);
}
simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2->next(), tok3);
if (!hasName)
tok2 = tok2->next();
} else if (ptrMember) {
if (Token::simpleMatch(tok2, "* (")) {
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
} else {
// This is the case of casting operator.
// Name is not available, and () should not be
// inserted
const bool castOperator = inOperator && Token::Match(tok2, "%type% (");
Token *openParenthesis = nullptr;
if (!castOperator) {
tok2 = simplifyTypedefInsertToken(tok2, "(", location);
openParenthesis = tok2;
}
const Token *tok4 = namespaceStart;
while (tok4 != namespaceEnd) {
tok2 = simplifyTypedefInsertToken(tok2, tok4->str(), location);
tok4 = tok4->next();
}
tok2 = simplifyTypedefInsertToken(tok2, namespaceEnd->str(), location);
tok2 = simplifyTypedefInsertToken(tok2, "*", location);
if (openParenthesis) {
// Skip over name, if any
if (Token::Match(tok2->next(), "%name%"))
tok2 = tok2->next();
tok2 = simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2, openParenthesis);
}
}
} else if (typeOf) {
tok2 = simplifyTypedefCopyTokens(tok2, argStart, argEnd, location);
} else if (Token::Match(tok2, "%name% [")) {
while (Token::Match(tok2, "%name%|] [")) {
tok2 = tok2->linkAt(1);
}
tok2 = tok2->previous();
}
if (arrayStart && arrayEnd) {
do {
if (!tok2->next())
syntaxError(tok2); // can't recover so quit
if (!inCast && !inSizeof && !inTemplate)
tok2 = tok2->next();
if (tok2->str() == "const")
tok2 = tok2->next();
// reference or pointer to array?
if (Token::Match(tok2, "&|*|&&")) {
tok2 = tok2->previous();
Token *tok3 = simplifyTypedefInsertToken(tok2, "(", location);
// handle missing variable name
if (Token::Match(tok3, "( *|&|&& *|&|&& %name%"))
tok2 = tok3->tokAt(3);
else if (Token::Match(tok2->tokAt(3), "[(),;]"))
tok2 = tok2->tokAt(2);
else if (Token::simpleMatch(tok2->tokAt(3), ">"))
tok2 = tok2->tokAt(2);
else
tok2 = tok2->tokAt(3);
if (!tok2)
syntaxError(nullptr);
while (tok2->strAt(1) == "::")
tok2 = tok2->tokAt(2);
// skip over function parameters
if (tok2->str() == "(")
tok2 = tok2->link();
if (tok2->strAt(1) == "(")
tok2 = tok2->linkAt(1);
// skip over const/noexcept
while (Token::Match(tok2->next(), "const|noexcept")) {
tok2 = tok2->next();
if (Token::Match(tok2->next(), "( true|false )"))
tok2 = tok2->tokAt(3);
}
tok2 = simplifyTypedefInsertToken(tok2, ")", location);
Token::createMutualLinks(tok2, tok3);
}
if (!tok2->next())
syntaxError(tok2); // can't recover so quit
// skip over array dimensions
while (tok2->strAt(1) == "[")
tok2 = tok2->linkAt(1);
tok2 = simplifyTypedefCopyTokens(tok2, arrayStart, arrayEnd, location);
if (!tok2->next())
syntaxError(tok2);
if (tok2->str() == "=") {
if (tok2->strAt(1) == "{")
tok2 = tok2->linkAt(1)->next();
else if (tok2->strAt(1).at(0) == '\"')
tok2 = tok2->tokAt(2);
}
} while (Token::Match(tok2, ", %name% ;|=|,"));
}
simplifyType = false;
}
if (!tok2)
break;
}
if (!tok)
syntaxError(nullptr);
if (tok->str() == ";")
done = true;
else if (tok->str() == ",") {
arrayStart = nullptr;
arrayEnd = nullptr;
tokOffset = tok->next();
pointers.clear();
while (Token::Match(tokOffset, "*|&")) {
pointers.push_back(tokOffset->str());
tokOffset = tokOffset->next();
}
if (Token::Match(tokOffset, "%type%")) {
typeName = tokOffset;
tokOffset = tokOffset->next();
if (tokOffset && tokOffset->str() == "[") {
arrayStart = tokOffset;
for (;;) {
while (tokOffset->next() && !Token::Match(tokOffset->next(), ";|,"))
tokOffset = tokOffset->next();
if (!tokOffset->next())
return; // invalid input
if (tokOffset->strAt(1) == ";")
break;
if (tokOffset->str() == "]")
break;
tokOffset = tokOffset->next();
}
arrayEnd = tokOffset;
tokOffset = tokOffset->next();
}
if (Token::Match(tokOffset, ";|,"))
tok = tokOffset;
else {
// we encountered a typedef we don't support yet so just continue
done = true;
ok = false;
}
} else {
// we encountered a typedef we don't support yet so just continue
done = true;
ok = false;
}
} else {
// something is really wrong (internal error)
done = true;
ok = false;
}
}
if (ok) {
// remove typedef
Token::eraseTokens(typeDef, tok);
if (typeDef != list.front()) {
tok = typeDef->previous();
tok->deleteNext();
//no need to remove last token in the list
if (tok->tokAt(2))
tok->deleteNext();
} else {
list.front()->deleteThis();
//no need to remove last token in the list
if (list.front()->next())
list.front()->deleteThis();
tok = list.front();
//now the next token to process is 'tok', not 'tok->next()';
goback = true;
}
}
}
}
namespace {
struct ScopeInfo3 {
enum Type : std::uint8_t { Global, Namespace, Record, MemberFunction, Other };
ScopeInfo3() : parent(nullptr), type(Global), bodyStart(nullptr), bodyEnd(nullptr) {}
ScopeInfo3(ScopeInfo3 *parent_, Type type_, std::string name_, const Token *bodyStart_, const Token *bodyEnd_)
: parent(parent_), type(type_), name(std::move(name_)), bodyStart(bodyStart_), bodyEnd(bodyEnd_) {
if (name.empty())
return;
fullName = name;
ScopeInfo3 *scope = parent;
while (scope && scope->parent) {
if (scope->name.empty())
break;
fullName = scope->name + " :: " + fullName;
scope = scope->parent;
}
}
ScopeInfo3 *parent;
std::list<ScopeInfo3> children;
Type type;
std::string fullName;
std::string name;
const Token * bodyStart;
const Token * bodyEnd;
std::set<std::string> usingNamespaces;
std::set<std::string> recordTypes;
std::set<std::string> baseTypes;
ScopeInfo3 *addChild(Type scopeType, const std::string &scopeName, const Token *bodyStartToken, const Token *bodyEndToken) {
children.emplace_back(this, scopeType, scopeName, bodyStartToken, bodyEndToken);
return &children.back();
}
bool hasChild(const std::string &childName) const {
return std::any_of(children.cbegin(), children.cend(), [&](const ScopeInfo3& child) {
return child.name == childName;
});
}
const ScopeInfo3 * findInChildren(const std::string & scope) const {
for (const auto & child : children) {
if (child.type == Record && (child.name == scope || child.fullName == scope))
return &child;
const ScopeInfo3 * temp = child.findInChildren(scope);
if (temp)
return temp;
}
return nullptr;
}
const ScopeInfo3 * findScope(const std::string & scope) const {
const ScopeInfo3 * tempScope = this;
while (tempScope) {
// check children
auto it = std::find_if(tempScope->children.cbegin(), tempScope->children.cend(), [&](const ScopeInfo3& child) {
return &child != this && child.type == Record && (child.name == scope || child.fullName == scope);
});
if (it != tempScope->children.end())
return &*it;
// check siblings for same name
if (tempScope->parent) {
for (const auto &sibling : tempScope->parent->children) {
if (sibling.name == tempScope->name && &sibling != this) {
const ScopeInfo3 * temp = sibling.findInChildren(scope);
if (temp)
return temp;
}
}
}
tempScope = tempScope->parent;
}
return nullptr;
}
bool findTypeInBase(const std::string &scope) const {
if (scope.empty())
return false;
// check in base types first
if (baseTypes.find(scope) != baseTypes.end())
return true;
// check in base types base types
for (const std::string & base : baseTypes) {
const ScopeInfo3 * baseScope = findScope(base);
// bail on uninstantiated recursive template
if (baseScope == this)
return false;
if (baseScope && baseScope->fullName == scope)
return true;
if (baseScope && baseScope->findTypeInBase(scope))
return true;
}
return false;
}
ScopeInfo3 * findScope(const ScopeInfo3 * scope) {
if (scope->bodyStart == bodyStart)
return this;
for (auto & child : children) {
ScopeInfo3 * temp = child.findScope(scope);
if (temp)
return temp;
}
return nullptr;
}
};
void setScopeInfo(Token *tok, ScopeInfo3 *&scopeInfo, bool debug=false)
{
if (!tok)
return;
if (tok->str() == "{" && scopeInfo->parent && tok == scopeInfo->bodyStart)
return;
if (tok->str() == "}") {
if (scopeInfo->parent && tok == scopeInfo->bodyEnd)
scopeInfo = scopeInfo->parent;
else {
// Try to find parent scope
ScopeInfo3 *parent = scopeInfo->parent;
while (parent && parent->bodyEnd != tok)
parent = parent->parent;
if (parent) {
scopeInfo = parent;
if (debug)
throw std::runtime_error("Internal error: unmatched }");
}
}
return;
}
if (!Token::Match(tok, "namespace|class|struct|union %name% {|:|::|<")) {
// check for using namespace
if (Token::Match(tok, "using namespace %name% ;|::")) {
const Token * tok1 = tok->tokAt(2);
std::string nameSpace;
while (tok1 && tok1->str() != ";") {
if (!nameSpace.empty())
nameSpace += " ";
nameSpace += tok1->str();
tok1 = tok1->next();
}
scopeInfo->usingNamespaces.insert(std::move(nameSpace));
}
// check for member function
else if (tok->str() == "{") {
bool added = false;
Token *tok1 = tok;
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->previous() && (tok1->strAt(-1) == ")" || tok->strAt(-1) == "}")) {
tok1 = tok1->linkAt(-1);
if (Token::Match(tok1->previous(), "throw|noexcept (")) {
tok1 = tok1->previous();
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->strAt(-1) != ")")
return;
tok1 = tok1->linkAt(-1);
} else {
while (Token::Match(tok1->tokAt(-2), ":|, %name%")) {
tok1 = tok1->tokAt(-2);
if (tok1->strAt(-1) != ")" && tok1->strAt(-1) != "}")
return;
tok1 = tok1->linkAt(-1);
}
}
if (tok1->strAt(-1) == ">")
tok1 = tok1->previous()->findOpeningBracket();
if (tok1 && (Token::Match(tok1->tokAt(-3), "%name% :: %name%") ||
Token::Match(tok1->tokAt(-4), "%name% :: ~ %name%"))) {
tok1 = tok1->tokAt(-2);
if (tok1->str() == "~")
tok1 = tok1->previous();
std::string scope = tok1->strAt(-1);
while (Token::Match(tok1->tokAt(-2), ":: %name%")) {
scope = tok1->strAt(-3) + " :: " + scope;
tok1 = tok1->tokAt(-2);
}
scopeInfo = scopeInfo->addChild(ScopeInfo3::MemberFunction, scope, tok, tok->link());
added = true;
}
// inline member function
else if ((scopeInfo->type == ScopeInfo3::Record || scopeInfo->type == ScopeInfo3::Namespace) && tok1 && Token::Match(tok1->tokAt(-1), "%name% (")) {
const std::string scope = scopeInfo->name + "::" + tok1->strAt(-1);
scopeInfo = scopeInfo->addChild(ScopeInfo3::MemberFunction, scope, tok, tok->link());
added = true;
}
}
if (!added)
scopeInfo = scopeInfo->addChild(ScopeInfo3::Other, emptyString, tok, tok->link());
}
return;
}
const bool record = Token::Match(tok, "class|struct|union %name%");
tok = tok->next();
std::string classname = tok->str();
while (Token::Match(tok, "%name% :: %name%")) {
tok = tok->tokAt(2);
classname += " :: " + tok->str();
}
// add record type to scope info
if (record)
scopeInfo->recordTypes.insert(classname);
tok = tok->next();
// skip template parameters
if (tok && tok->str() == "<") {
tok = tok->findClosingBracket();
if (tok)
tok = tok->next();
}
// get base class types
std::set<std::string> baseTypes;
if (tok && tok->str() == ":") {
do {
tok = tok->next();
while (Token::Match(tok, "public|protected|private|virtual"))
tok = tok->next();
std::string base;
while (tok && !Token::Match(tok, ";|,|{")) {
if (!base.empty())
base += ' ';
base += tok->str();
tok = tok->next();
// add template parameters
if (tok && tok->str() == "<") {
const Token* endTok = tok->findClosingBracket();
if (endTok) {
endTok = endTok->next();
while (tok != endTok) {
base += tok->str();
tok = tok->next();
}
}
}
}
baseTypes.insert(std::move(base));
} while (tok && !Token::Match(tok, ";|{"));
}
if (tok && tok->str() == "{") {
scopeInfo = scopeInfo->addChild(record ? ScopeInfo3::Record : ScopeInfo3::Namespace, classname, tok, tok->link());
scopeInfo->baseTypes = std::move(baseTypes);
}
}
Token *findSemicolon(Token *tok)
{
int level = 0;
for (; tok && (level > 0 || tok->str() != ";"); tok = tok->next()) {
if (tok->str() == "{")
++level;
else if (level > 0 && tok->str() == "}")
--level;
}
return tok;
}
bool usingMatch(
const Token *nameToken,
const std::string &scope,
Token *&tok,
const std::string &scope1,
const ScopeInfo3 *currentScope,
const ScopeInfo3 *memberClassScope)
{
Token *tok1 = tok;
if (tok1 && tok1->str() != nameToken->str())
return false;
// skip this using
if (tok1 == nameToken) {
tok = findSemicolon(tok1);
return false;
}
// skip other using with this name
if (tok1->strAt(-1) == "using") {
// fixme: this is wrong
// skip to end of scope
if (currentScope->bodyEnd)
tok = const_cast<Token*>(currentScope->bodyEnd->previous());
return false;
}
if (Token::Match(tok1->tokAt(-1), "class|struct|union|enum|namespace")) {
// fixme
return false;
}
// get qualification
std::string qualification;
const Token* tok2 = tok1;
std::string::size_type index = scope.size();
std::string::size_type new_index = std::string::npos;
bool match = true;
while (Token::Match(tok2->tokAt(-2), "%name% ::") && !tok2->tokAt(-2)->isKeyword()) {
std::string last;
if (match && !scope1.empty()) {
new_index = scope1.rfind(' ', index - 1);
if (new_index != std::string::npos)
last = scope1.substr(new_index, index - new_index);
else if (!qualification.empty())
last.clear();
else
last = scope1;
} else
match = false;
if (match && tok2->strAt(-2) == last)
index = new_index;
else {
if (!qualification.empty())
qualification = " :: " + qualification;
qualification = tok2->strAt(-2) + qualification;
}
tok2 = tok2->tokAt(-2);
}
std::string fullScope1 = scope1;
if (!scope1.empty() && !qualification.empty())
fullScope1 += " :: ";
fullScope1 += qualification;
if (scope == fullScope1)
return true;
const ScopeInfo3 *scopeInfo = memberClassScope ? memberClassScope : currentScope;
// check in base types
if (qualification.empty() && scopeInfo->findTypeInBase(scope))
return true;
// check using namespace
const ScopeInfo3 * tempScope = scopeInfo;
while (tempScope) {
//if (!tempScope->parent->usingNamespaces.empty()) {
const std::set<std::string>& usingNS = tempScope->usingNamespaces;
if (!usingNS.empty()) {
if (qualification.empty()) {
if (usingNS.find(scope) != usingNS.end())
return true;
} else {
const std::string suffix = " :: " + qualification;
if (std::any_of(usingNS.cbegin(), usingNS.cend(), [&](const std::string& ns) {
return scope == ns + suffix;
}))
return true;
}
}
tempScope = tempScope->parent;
}
std::string newScope1 = scope1;
// scopes didn't match so try higher scopes
index = newScope1.size();
while (!newScope1.empty()) {
const std::string::size_type separator = newScope1.rfind(" :: ", index - 1);
if (separator != std::string::npos)
newScope1.resize(separator);
else
newScope1.clear();
std::string newFullScope1 = newScope1;
if (!newScope1.empty() && !qualification.empty())
newFullScope1 += " :: ";
newFullScope1 += qualification;
if (scope == newFullScope1)
return true;
}
return false;
}
std::string memberFunctionScope(const Token *tok)
{
std::string qualification;
const Token *qualTok = tok->strAt(-2) == "~" ? tok->tokAt(-4) : tok->tokAt(-3);
while (Token::Match(qualTok, "%type% ::")) {
if (!qualification.empty())
qualification = " :: " + qualification;
qualification = qualTok->str() + qualification;
qualTok = qualTok->tokAt(-2);
}
return qualification;
}
const Token * memberFunctionEnd(const Token *tok)
{
if (tok->str() != "(")
return nullptr;
const Token *end = tok->link()->next();
while (end) {
if (end->str() == "{" && !Token::Match(end->tokAt(-2), ":|, %name%"))
return end;
if (end->str() == ";")
break;
end = end->next();
}
return nullptr;
}
} // namespace
bool Tokenizer::isMemberFunction(const Token *openParen)
{
return (Token::Match(openParen->tokAt(-2), ":: %name% (") ||
Token::Match(openParen->tokAt(-3), ":: ~ %name% (")) &&
isFunctionHead(openParen, "{|:");
}
static bool scopesMatch(const std::string &scope1, const std::string &scope2, const ScopeInfo3 *globalScope)
{
if (scope1.empty() || scope2.empty())
return false;
// check if scopes match
if (scope1 == scope2)
return true;
// check if scopes only differ by global qualification
if (scope1 == (":: " + scope2)) {
std::string::size_type end = scope2.find_first_of(' ');
if (end == std::string::npos)
end = scope2.size();
if (globalScope->hasChild(scope2.substr(0, end)))
return true;
} else if (scope2 == (":: " + scope1)) {
std::string::size_type end = scope1.find_first_of(' ');
if (end == std::string::npos)
end = scope1.size();
if (globalScope->hasChild(scope1.substr(0, end)))
return true;
}
return false;
}
static unsigned int tokDistance(const Token* tok1, const Token* tok2) {
unsigned int dist = 0;
const Token* tok = tok1;
while (tok != tok2) {
++dist;
tok = tok->next();
}
return dist;
}
bool Tokenizer::simplifyUsing()
{
if (!isCPP() || mSettings.standards.cpp < Standards::CPP11)
return false;
// simplify using N::x; to using x = N::x;
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "using ::| %name% ::"))
continue;
const Token* ns = tok->tokAt(tok->strAt(1) == "::" ? 2 : 1);
if (ns->isKeyword())
continue;
Token* end = tok->tokAt(3);
while (end && !Token::Match(end, "[;,]")) {
if (end->str() == "<") // skip template args
end = end->findClosingBracket();
else
end = end->next();
}
if (!end)
continue;
if (!end->tokAt(-1)->isNameOnly() || end->tokAt(-2)->isLiteral()) // e.g. operator=, operator""sv
continue;
tok->insertToken(end->strAt(-1))->insertToken("=")->isSimplifiedTypedef(true);
if (end->str() == ",") { // comma-separated list
end->str(";");
end->insertToken("using");
}
tok = end;
}
const unsigned int maxReplacementTokens = 1000; // limit the number of tokens we replace
bool substitute = false;
ScopeInfo3 scopeInfo;
ScopeInfo3 *currentScope = &scopeInfo;
struct Using {
Using(Token *start, Token *end) : startTok(start), endTok(end) {}
Token *startTok;
Token *endTok;
};
std::list<Using> usingList;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!list.getFiles().empty())
mErrorLogger.reportProgress(list.getFiles()[0], "Tokenize (using)", tok->progressValue());
if (Settings::terminated())
return substitute;
if (Token::Match(tok, "enum class|struct")) {
Token *bodyStart = tok;
while (Token::Match(bodyStart, "%name%|:|::|<")) {
if (bodyStart->str() == "<")
bodyStart = bodyStart->findClosingBracket();
bodyStart = bodyStart ? bodyStart->next() : nullptr;
}
if (Token::simpleMatch(bodyStart, "{"))
tok = bodyStart->link();
continue;
}
if (Token::Match(tok, "{|}|namespace|class|struct|union") ||
Token::Match(tok, "using namespace %name% ;|::")) {
try {
setScopeInfo(tok, currentScope, mSettings.debugwarnings);
} catch (const std::runtime_error &) {
reportError(tok, Severity::debug, "simplifyUsingUnmatchedBodyEnd",
"simplifyUsing: unmatched body end");
}
continue;
}
// skip template declarations
if (Token::Match(tok, "template < !!>")) {
// add template record type to scope info
const Token *end = tok->next()->findClosingBracket();
if (end && Token::Match(end->next(), "class|struct|union %name%"))
currentScope->recordTypes.insert(end->strAt(2));
Token *declEndToken = TemplateSimplifier::findTemplateDeclarationEnd(tok);
if (declEndToken)
tok = declEndToken;
continue;
}
// look for non-template type aliases
if (!(tok->strAt(-1) != ">" &&
(Token::Match(tok, "using %name% = ::| %name%") ||
(Token::Match(tok, "using %name% [ [") &&
Token::Match(tok->linkAt(2), "] ] = ::| %name%")))))
continue;
const std::string& name = tok->strAt(1);
const Token *nameToken = tok->next();
std::string scope = currentScope->fullName;
Token *usingStart = tok;
Token *start;
if (tok->strAt(2) == "=") {
if (currentScope->type == ScopeInfo3::Record && tok->tokAt(2)->isSimplifiedTypedef()) // don't simplify within class definition
continue;
start = tok->tokAt(3);
}
else
start = tok->linkAt(2)->tokAt(3);
Token *usingEnd = findSemicolon(start);
if (!usingEnd)
continue;
// Move struct defined in using out of using.
// using T = struct t { }; => struct t { }; using T = struct t;
// fixme: this doesn't handle attributes
if (Token::Match(start, "class|struct|union|enum %name%| {|:")) {
Token *structEnd = start->tokAt(1);
const bool hasName = Token::Match(structEnd, "%name%");
// skip over name if present
if (hasName)
structEnd = structEnd->next();
// skip over base class information
if (structEnd->str() == ":") {
structEnd = structEnd->next(); // skip over ":"
while (structEnd && structEnd->str() != "{")
structEnd = structEnd->next();
if (!structEnd)
continue;
}
// use link to go to end
structEnd = structEnd->link();
// add ';' after end of struct
structEnd->insertToken(";", emptyString);
// add name for anonymous struct
if (!hasName) {
std::string newName;
if (structEnd->strAt(2) == ";")
newName = name;
else
newName = "Unnamed" + std::to_string(mUnnamedCount++);
TokenList::copyTokens(structEnd->next(), tok, start);
structEnd->tokAt(5)->insertToken(newName, emptyString);
start->insertToken(newName, emptyString);
} else
TokenList::copyTokens(structEnd->next(), tok, start->next());
// add using after end of struct
usingStart = structEnd->tokAt(2);
nameToken = usingStart->next();
if (usingStart->strAt(2) == "=")
start = usingStart->tokAt(3);
else
start = usingStart->linkAt(2)->tokAt(3);
usingEnd = findSemicolon(start);
// delete original using before struct
tok->deleteThis();
tok->deleteThis();
tok->deleteThis();
tok = usingStart;
}
// remove 'typename' and 'template'
else if (start->str() == "typename") {
start->deleteThis();
Token *temp = start;
while (Token::Match(temp, "%name% ::"))
temp = temp->tokAt(2);
if (Token::Match(temp, "template %name%"))
temp->deleteThis();
}
if (usingEnd)
tok = usingEnd;
if (Token::Match(start, "class|struct|union|enum"))
start = start->next();
// Unfortunately we have to start searching from the beginning
// of the token stream because templates are instantiated at
// the end of the token stream and it may be used before then.
ScopeInfo3 scopeInfo1;
ScopeInfo3 *currentScope1 = &scopeInfo1;
Token *startToken = list.front();
Token *endToken = nullptr;
bool inMemberFunc = false;
const ScopeInfo3 * memberFuncScope = nullptr;
const Token * memberFuncEnd = nullptr;
// We can limit the search to the current function when the type alias
// is defined in that function.
if (currentScope->type == ScopeInfo3::Other ||
currentScope->type == ScopeInfo3::MemberFunction) {
scopeInfo1 = scopeInfo;
currentScope1 = scopeInfo1.findScope(currentScope);
if (!currentScope1)
return substitute; // something bad happened
startToken = usingEnd->next();
endToken = const_cast<Token*>(currentScope->bodyEnd->next());
if (currentScope->type == ScopeInfo3::MemberFunction) {
const ScopeInfo3 * temp = currentScope->findScope(currentScope->fullName);
if (temp) {
inMemberFunc = true;
memberFuncScope = temp;
memberFuncEnd = endToken;
}
}
}
std::string scope1 = currentScope1->fullName;
bool skip = false; // don't erase type aliases we can't parse
Token *enumOpenBrace = nullptr;
for (Token* tok1 = startToken; !skip && tok1 && tok1 != endToken; tok1 = tok1->next()) {
// skip enum body
if (tok1 && tok1 == enumOpenBrace) {
tok1 = tok1->link();
enumOpenBrace = nullptr;
continue;
}
if ((Token::Match(tok1, "{|}|namespace|class|struct|union") && tok1->strAt(-1) != "using") ||
Token::Match(tok1, "using namespace %name% ;|::")) {
try {
setScopeInfo(tok1, currentScope1, mSettings.debugwarnings);
} catch (const std::runtime_error &) {
reportError(tok1, Severity::debug, "simplifyUsingUnmatchedBodyEnd",
"simplifyUsing: unmatched body end");
}
scope1 = currentScope1->fullName;
if (inMemberFunc && memberFuncEnd && tok1 == memberFuncEnd) {
inMemberFunc = false;
memberFuncScope = nullptr;
memberFuncEnd = nullptr;
}
continue;
}
// skip template definitions
if (Token::Match(tok1, "template < !!>")) {
Token *declEndToken = TemplateSimplifier::findTemplateDeclarationEnd(tok1);
if (declEndToken)
tok1 = declEndToken;
continue;
}
// check for enum with body
if (tok1->str() == "enum") {
if (Token::Match(tok1, "enum class|struct"))
tok1 = tok1->next();
Token *defStart = tok1;
while (Token::Match(defStart, "%name%|::|:"))
defStart = defStart->next();
if (Token::simpleMatch(defStart, "{"))
enumOpenBrace = defStart;
continue;
}
// check for member function and adjust scope
if (isMemberFunction(tok1)) {
if (!scope1.empty())
scope1 += " :: ";
scope1 += memberFunctionScope(tok1);
const ScopeInfo3 * temp = currentScope1->findScope(scope1);
if (temp) {
const Token *end = memberFunctionEnd(tok1);
if (end) {
inMemberFunc = true;
memberFuncScope = temp;
memberFuncEnd = end;
}
}
continue;
}
if (inMemberFunc && memberFuncScope) {
if (!usingMatch(nameToken, scope, tok1, scope1, currentScope1, memberFuncScope))
continue;
} else if (!usingMatch(nameToken, scope, tok1, scope1, currentScope1, nullptr))
continue;
const auto nReplace = tokDistance(start, usingEnd);
if (nReplace > maxReplacementTokens) {
simplifyUsingError(usingStart, usingEnd);
continue;
}
// remove the qualification
std::string fullScope = scope;
std::string removed;
while (Token::Match(tok1->tokAt(-2), "%name% ::") && !tok1->tokAt(-2)->isKeyword()) {
removed = (tok1->strAt(-2) + " :: ") + removed;
if (fullScope == tok1->strAt(-2)) {
tok1->deletePrevious();
tok1->deletePrevious();
break;
}
const std::string::size_type idx = fullScope.rfind("::");
if (idx == std::string::npos)
break;
if (tok1->strAt(-2) == fullScope.substr(idx + 3)) {
tok1->deletePrevious();
tok1->deletePrevious();
fullScope.resize(idx - 1);
} else
break;
}
// remove global namespace if present
if (tok1->strAt(-1) == "::") {
removed.insert(0, ":: ");
tok1->deletePrevious();
}
Token * arrayStart = nullptr;
// parse the type
Token *type = start;
if (type->str() == "::") {
type = type->next();
while (Token::Match(type, "%type% ::"))
type = type->tokAt(2);
if (Token::Match(type, "%type%"))
type = type->next();
} else if (Token::Match(type, "%type% ::")) {
do {
type = type->tokAt(2);
} while (Token::Match(type, "%type% ::"));
if (Token::Match(type, "%type%"))
type = type->next();
} else if (Token::Match(type, "%type%")) {
while (Token::Match(type, "const|class|struct|union|enum %type%") ||
(type->next() && type->next()->isStandardType()))
type = type->next();
type = type->next();
while (Token::Match(type, "%type%") &&
(type->isStandardType() || Token::Match(type, "unsigned|signed"))) {
type = type->next();
}
bool atEnd = false;
while (!atEnd) {
if (type && type->str() == "::") {
type = type->next();
}
if (Token::Match(type, "%type%") &&
type->next() && !Token::Match(type->next(), "[|,|(")) {
type = type->next();
} else if (Token::simpleMatch(type, "const (")) {
type = type->next();
atEnd = true;
} else
atEnd = true;
}
} else
syntaxError(type);
// check for invalid input
if (!type)
syntaxError(tok1);
// check for template
if (type->str() == "<") {
type = type->findClosingBracket();
while (type && Token::Match(type->next(), ":: %type%"))
type = type->tokAt(2);
if (!type) {
syntaxError(tok1);
}
while (Token::Match(type->next(), "const|volatile"))
type = type->next();
type = type->next();
}
// check for pointers and references
std::list<std::string> pointers;
while (Token::Match(type, "*|&|&&|const")) {
pointers.push_back(type->str());
type = type->next();
}
// check for array
if (type && type->str() == "[") {
do {
if (!arrayStart)
arrayStart = type;
bool atEnd = false;
while (!atEnd) {
while (type->next() && !Token::Match(type->next(), ";|,")) {
type = type->next();
}
if (!type->next())
syntaxError(type); // invalid input
else if (type->strAt(1) == ";")
atEnd = true;
else if (type->str() == "]")
atEnd = true;
else
type = type->next();
}
type = type->next();
} while (type && type->str() == "[");
}
// make sure we are in a good state
if (!tok1 || !tok1->next())
break; // bail
Token* after = tok1->next();
// check if type was parsed
if (type && type == usingEnd) {
// check for array syntax and add type around variable
if (arrayStart) {
if (Token::Match(tok1->next(), "%name%")) {
TokenList::copyTokens(tok1->next(), arrayStart, usingEnd->previous());
TokenList::copyTokens(tok1, start, arrayStart->previous());
tok1->deleteThis();
substitute = true;
}
} else {
// add some qualification back if needed
std::string removed1 = std::move(removed);
std::string::size_type idx = removed1.rfind(" ::");
if (idx != std::string::npos)
removed1.resize(idx);
if (scopesMatch(removed1, scope, &scopeInfo1)) {
ScopeInfo3 * tempScope = currentScope;
while (tempScope->parent) {
if (tempScope->recordTypes.find(start->str()) != tempScope->recordTypes.end()) {
std::string::size_type spaceIdx = 0;
std::string::size_type startIdx = 0;
while ((spaceIdx = removed1.find(' ', startIdx)) != std::string::npos) {
tok1->previous()->insertToken(removed1.substr(startIdx, spaceIdx - startIdx));
startIdx = spaceIdx + 1;
}
tok1->previous()->insertToken(removed1.substr(startIdx));
tok1->previous()->insertToken("::");
break;
}
idx = removed1.rfind(" ::");
if (idx == std::string::npos)
break;
removed1.resize(idx);
tempScope = tempScope->parent;
}
}
// Is this a "T(...)" expression where T is a pointer type?
if (Token::Match(tok1, "%name% [({]") && !pointers.empty() && !Token::simpleMatch(tok1->tokAt(-1), ".")) {
tok1->tokAt(1)->str("(");
tok1->linkAt(1)->str(")");
if (tok1->linkAt(1) == tok1->tokAt(2)) { // T() or T{}
Token* tok2 = tok1->linkAt(1);
tok1->deleteThis();
TokenList::copyTokens(tok1, start, usingEnd->previous());
tok2->insertToken("0");
after = tok2->next();
}
else { // functional-style cast
Token* tok2 = tok1->linkAt(1);
tok1->originalName(tok1->str());
tok1->isSimplifiedTypedef(true);
tok1->str("(");
Token* tok3 = TokenList::copyTokens(tok1, start, usingEnd->previous());
tok3->insertToken(")");
Token::createMutualLinks(tok1, tok3->next());
after = tok2->next();
}
}
else { // just replace simple type aliases
TokenList::copyTokens(tok1, start, usingEnd->previous());
tok1->deleteThis();
}
substitute = true;
}
} else {
skip = true;
simplifyUsingError(usingStart, usingEnd);
}
tok1 = after->previous();
}
if (!skip)
usingList.emplace_back(usingStart, usingEnd);
}
// delete all used type alias definitions
for (std::list<Using>::reverse_iterator it = usingList.rbegin(); it != usingList.rend(); ++it) {
Token *usingStart = it->startTok;
Token *usingEnd = it->endTok;
if (usingStart->previous()) {
if (usingEnd->next())
Token::eraseTokens(usingStart->previous(), usingEnd->next());
else {
Token::eraseTokens(usingStart->previous(), usingEnd);
usingEnd->deleteThis();
}
} else {
if (usingEnd->next()) {
Token::eraseTokens(usingStart, usingEnd->next());
usingStart->deleteThis();
} else {
// this is the only code being checked so leave ';'
Token::eraseTokens(usingStart, usingEnd);
usingStart->deleteThis();
}
}
}
return substitute;
}
void Tokenizer::simplifyUsingError(const Token* usingStart, const Token* usingEnd)
{
if (mSettings.debugwarnings) {
std::string str;
for (const Token *tok = usingStart; tok && tok != usingEnd; tok = tok->next()) {
if (!str.empty())
str += ' ';
str += tok->str();
}
str += " ;";
std::list<const Token *> callstack(1, usingStart);
mErrorLogger.reportErr(ErrorMessage(callstack, &list, Severity::debug, "simplifyUsing",
"Failed to parse \'" + str + "\'. The checking continues anyway.", Certainty::normal));
}
}
bool Tokenizer::simplifyTokens1(const std::string &configuration)
{
// Fill the map mTypeSize..
fillTypeSizes();
mConfiguration = configuration;
if (mTimerResults) {
Timer t("Tokenizer::simplifyTokens1::simplifyTokenList1", mSettings.showtime, mTimerResults);
if (!simplifyTokenList1(list.getFiles().front().c_str()))
return false;
} else {
if (!simplifyTokenList1(list.getFiles().front().c_str()))
return false;
}
const SHOWTIME_MODES showTime = mTimerResults ? mSettings.showtime : SHOWTIME_MODES::SHOWTIME_NONE;
Timer::run("Tokenizer::simplifyTokens1::createAst", showTime, mTimerResults, [&]() {
list.createAst();
list.validateAst(mSettings.debugnormal);
});
Timer::run("Tokenizer::simplifyTokens1::createSymbolDatabase", showTime, mTimerResults, [&]() {
createSymbolDatabase();
});
Timer::run("Tokenizer::simplifyTokens1::setValueType", showTime, mTimerResults, [&]() {
mSymbolDatabase->setValueTypeInTokenList(false);
mSymbolDatabase->setValueTypeInTokenList(true);
});
if (!mSettings.buildDir.empty())
Summaries::create(*this, configuration);
// TODO: apply this through Settings::ValueFlowOptions
// TODO: do not run valueflow if no checks are being performed at all - e.g. unusedFunctions only
// TODO: log message when this is active?
const char* disableValueflowEnv = std::getenv("DISABLE_VALUEFLOW");
const bool doValueFlow = !disableValueflowEnv || (std::strcmp(disableValueflowEnv, "1") != 0);
if (doValueFlow) {
Timer::run("Tokenizer::simplifyTokens1::ValueFlow", showTime, mTimerResults, [&]() {
ValueFlow::setValues(list, *mSymbolDatabase, mErrorLogger, mSettings, mTimerResults);
});
arraySizeAfterValueFlow();
}
// Warn about unhandled character literals
if (mSettings.severity.isEnabled(Severity::portability)) {
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (tok->tokType() == Token::eChar && tok->values().empty()) {
try {
simplecpp::characterLiteralToLL(tok->str());
} catch (const std::exception &e) {
unhandledCharLiteral(tok, e.what());
}
}
}
}
if (doValueFlow) {
mSymbolDatabase->setArrayDimensionsUsingValueFlow();
}
printDebugOutput(1, std::cout);
return true;
}
//---------------------------------------------------------------------------
void Tokenizer::findComplicatedSyntaxErrorsInTemplates()
{
validate();
mTemplateSimplifier->checkComplicatedSyntaxErrorsInTemplates();
}
void Tokenizer::checkForEnumsWithTypedef()
{
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "enum %name% {")) {
tok = tok->tokAt(2);
const Token *tok2 = Token::findsimplematch(tok, "typedef", tok->link());
if (tok2)
syntaxError(tok2);
tok = tok->link();
}
}
}
void Tokenizer::fillTypeSizes()
{
mTypeSize.clear();
mTypeSize["char"] = 1;
mTypeSize["_Bool"] = mSettings.platform.sizeof_bool;
mTypeSize["bool"] = mSettings.platform.sizeof_bool;
mTypeSize["short"] = mSettings.platform.sizeof_short;
mTypeSize["int"] = mSettings.platform.sizeof_int;
mTypeSize["long"] = mSettings.platform.sizeof_long;
mTypeSize["long long"] = mSettings.platform.sizeof_long_long;
mTypeSize["float"] = mSettings.platform.sizeof_float;
mTypeSize["double"] = mSettings.platform.sizeof_double;
mTypeSize["long double"] = mSettings.platform.sizeof_long_double;
mTypeSize["wchar_t"] = mSettings.platform.sizeof_wchar_t;
mTypeSize["size_t"] = mSettings.platform.sizeof_size_t;
mTypeSize["*"] = mSettings.platform.sizeof_pointer;
}
void Tokenizer::combineOperators()
{
const bool cpp = isCPP();
// Combine tokens..
for (Token *tok = list.front(); tok && tok->next(); tok = tok->next()) {
const char c1 = tok->str()[0];
if (tok->str().length() == 1 && tok->strAt(1).length() == 1) {
const char c2 = tok->strAt(1)[0];
// combine +-*/ and =
if (c2 == '=' && (std::strchr("+-*/%|^=!<>", c1)) && !Token::Match(tok->previous(), "%type% *")) {
// skip templates
if (cpp && (tok->str() == ">" || Token::simpleMatch(tok->previous(), "> *"))) {
const Token* opening =
tok->str() == ">" ? tok->findOpeningBracket() : tok->previous()->findOpeningBracket();
if (opening && Token::Match(opening->previous(), "%name%"))
continue;
}
tok->str(tok->str() + c2);
tok->deleteNext();
continue;
}
} else if (tok->strAt(1) == "=") {
if (tok->str() == ">>") {
tok->str(">>=");
tok->deleteNext();
} else if (tok->str() == "<<") {
tok->str("<<=");
tok->deleteNext();
}
} else if (cpp && (c1 == 'p' || c1 == '_') &&
Token::Match(tok, "private|protected|public|__published : !!:")) {
bool simplify = false;
int par = 0;
for (const Token *prev = tok->previous(); prev; prev = prev->previous()) {
if (prev->str() == ")") {
++par;
} else if (prev->str() == "(") {
if (par == 0U)
break;
--par;
}
if (par != 0U || prev->str() == "(")
continue;
if (Token::Match(prev, "[;{}]")) {
simplify = true;
break;
}
if (prev->isName() && prev->isUpperCaseName())
continue;
if (prev->isName() && endsWith(prev->str(), ':'))
simplify = true;
break;
}
if (simplify) {
tok->str(tok->str() + ":");
tok->deleteNext();
}
} else if (tok->str() == "->") {
tok->str(".");
tok->originalName("->");
}
}
}
void Tokenizer::combineStringAndCharLiterals()
{
// Combine strings
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!isStringLiteral(tok->str()))
continue;
tok->str(simplifyString(tok->str()));
while (Token::Match(tok->next(), "%str%") || Token::Match(tok->next(), "_T|_TEXT|TEXT ( %str% )")) {
if (tok->next()->isName()) {
if (!mSettings.platform.isWindows())
break;
tok->deleteNext(2);
tok->next()->deleteNext();
}
// Two strings after each other, combine them
tok->concatStr(simplifyString(tok->strAt(1)));
tok->deleteNext();
}
}
}
void Tokenizer::concatenateNegativeNumberAndAnyPositive()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "?|:|,|(|[|{|return|case|sizeof|%op% +|-") || tok->tokType() == Token::eIncDecOp)
continue;
while (tok->str() != ">" && tok->next() && tok->strAt(1) == "+" && (!Token::Match(tok->tokAt(2), "%name% (|;") || Token::Match(tok, "%op%")))
tok->deleteNext();
if (Token::Match(tok->next(), "- %num%")) {
tok->deleteNext();
tok->next()->str("-" + tok->strAt(1));
}
}
}
void Tokenizer::simplifyExternC()
{
if (isC())
return;
// Add attributes to all tokens within `extern "C"` inlines and blocks, and remove the `extern "C"` tokens.
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "extern \"C\"|\"C++\"")) {
Token *tok2 = tok->next();
const bool isExtC = tok->strAt(1).size() == 3;
if (tok->strAt(2) == "{") {
tok2 = tok2->next(); // skip {
while ((tok2 = tok2->next()) && tok2 != tok->linkAt(2))
tok2->isExternC(isExtC);
tok->linkAt(2)->deleteThis(); // }
tok->deleteNext(2); // "C" {
} else {
while ((tok2 = tok2->next()) && !Token::Match(tok2, "[;{]"))
tok2->isExternC(isExtC);
tok->deleteNext(); // "C"
}
tok->deleteThis(); // extern
}
}
}
void Tokenizer::simplifyCompoundStatements()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (Token::Match(tok, "[;{}:] ( {") &&
Token::simpleMatch(tok->linkAt(2), "} ) ;")) {
if (tok->str() == ":" && !Token::Match(tok->tokAt(-2),"[;{}] %type% :"))
break;
Token *end = tok->linkAt(2)->tokAt(-3);
if (Token::Match(end, "[;{}] %num%|%str% ;"))
end->deleteNext(2);
tok->linkAt(2)->previous()->deleteNext(3);
tok->deleteNext(2);
}
if (Token::Match(tok, "( { %bool%|%char%|%num%|%str%|%name% ; } )")) {
tok->deleteNext();
tok->deleteThis();
tok->deleteNext(3);
}
else if (tok->str() == "(")
tok = tok->link();
}
}
void Tokenizer::simplifySQL()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "__CPPCHECK_EMBEDDED_SQL_EXEC__ SQL"))
continue;
const Token *end = findSQLBlockEnd(tok);
if (end == nullptr)
syntaxError(nullptr);
const std::string instruction = tok->stringifyList(end);
// delete all tokens until the embedded SQL block end
Token::eraseTokens(tok, end);
// insert "asm ( "instruction" ) ;"
tok->str("asm");
// it can happen that 'end' is NULL when wrong code is inserted
if (!tok->next())
tok->insertToken(";");
tok->insertToken(")");
tok->insertToken("\"" + instruction + "\"");
tok->insertToken("(");
// jump to ';' and continue
tok = tok->tokAt(3);
}
}
void Tokenizer::simplifyArrayAccessSyntax()
{
// 0[a] -> a[0]
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->isNumber() && Token::Match(tok, "%num% [ %name% ]")) {
const std::string number(tok->str());
Token* indexTok = tok->tokAt(2);
tok->str(indexTok->str());
tok->varId(indexTok->varId());
indexTok->str(number);
}
}
}
void Tokenizer::simplifyParameterVoid()
{
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% ( void )") && !Token::Match(tok, "sizeof|decltype|typeof|return")) {
tok->next()->deleteNext();
tok->next()->setRemovedVoidParameter(true);
}
}
}
void Tokenizer::simplifyRedundantConsecutiveBraces()
{
// Remove redundant consecutive braces, i.e. '.. { { .. } } ..' -> '.. { .. } ..'.
for (Token *tok = list.front(); tok;) {
if (Token::simpleMatch(tok, "= {")) {
tok = tok->linkAt(1);
} else if (Token::simpleMatch(tok, "{ {") && Token::simpleMatch(tok->linkAt(1), "} }")) {
//remove internal parentheses
tok->linkAt(1)->deleteThis();
tok->deleteNext();
} else
tok = tok->next();
}
}
void Tokenizer::simplifyDoublePlusAndDoubleMinus()
{
// Convert - - into + and + - into -
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (tok->next()) {
if (tok->str() == "+") {
if (tok->strAt(1)[0] == '-') {
tok = tok->next();
if (tok->str().size() == 1) {
tok = tok->previous();
tok->str("-");
tok->deleteNext();
} else if (tok->isNumber()) {
tok->str(tok->str().substr(1));
tok = tok->previous();
tok->str("-");
}
continue;
}
} else if (tok->str() == "-") {
if (tok->strAt(1)[0] == '-') {
tok = tok->next();
if (tok->str().size() == 1) {
tok = tok->previous();
tok->str("+");
tok->deleteNext();
} else if (tok->isNumber()) {
tok->str(tok->str().substr(1));
tok = tok->previous();
tok->str("+");
}
continue;
}
}
break;
}
}
}
/** Specify array size if it hasn't been given */
void Tokenizer::arraySize()
{
auto getStrTok = [](Token* tok, bool addLength, Token*& endStmt) -> Token* {
if (addLength) {
endStmt = tok->tokAt(5);
return tok->tokAt(4);
}
if (Token::Match(tok, "%var% [ ] =")) {
tok = tok->tokAt(4);
int parCount = 0;
while (Token::simpleMatch(tok, "(")) {
++parCount;
tok = tok->next();
}
if (Token::Match(tok, "%str%")) {
endStmt = tok->tokAt(parCount + 1);
return tok;
}
}
return nullptr;
};
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName() || !Token::Match(tok, "%var% [ ] ="))
continue;
bool addlength = false;
if (Token::Match(tok->previous(), "!!* %var% [ ] = { %str% } ;")) {
Token *t = tok->tokAt(3);
t->deleteNext();
t->next()->deleteNext();
addlength = true;
}
Token* endStmt{};
if (const Token* strTok = getStrTok(tok, addlength, endStmt)) {
const int sz = Token::getStrArraySize(strTok);
tok->next()->insertToken(std::to_string(sz));
tok = endStmt;
}
else if (Token::Match(tok, "%var% [ ] = {")) {
MathLib::biguint sz = 1;
tok = tok->next();
Token *end = tok->linkAt(3);
for (Token *tok2 = tok->tokAt(4); tok2 && tok2 != end; tok2 = tok2->next()) {
if (tok2->link() && Token::Match(tok2, "{|(|[|<")) {
if (tok2->str() == "[" && tok2->link()->strAt(1) == "=") { // designated initializer
if (Token::Match(tok2, "[ %num% ]"))
sz = std::max(sz, MathLib::toBigUNumber(tok2->strAt(1)) + 1U);
else {
sz = 0;
break;
}
}
tok2 = tok2->link();
} else if (tok2->str() == ",") {
if (!Token::Match(tok2->next(), "[},]"))
++sz;
else {
tok2 = tok2->previous();
tok2->deleteNext();
}
}
}
if (sz != 0)
tok->insertToken(std::to_string(sz));
tok = end->next() ? end->next() : end;
}
}
}
void Tokenizer::arraySizeAfterValueFlow()
{
// After ValueFlow, adjust array sizes.
for (const Variable* var: mSymbolDatabase->variableList()) {
if (!var || !var->isArray())
continue;
if (!Token::Match(var->nameToken(), "%name% [ ] = { ["))
continue;
MathLib::bigint maxIndex = -1;
const Token* const startToken = var->nameToken()->tokAt(4);
const Token* const endToken = startToken->link();
for (const Token* tok = startToken; tok != endToken; tok = tok->next()) {
if (!Token::Match(tok, "[{,] [") || !Token::simpleMatch(tok->linkAt(1), "] ="))
continue;
const Token* expr = tok->next()->astOperand1();
if (expr && expr->hasKnownIntValue())
maxIndex = std::max(maxIndex, expr->getKnownIntValue());
}
if (maxIndex >= 0) {
// insert array size
auto* tok = const_cast<Token*>(var->nameToken()->next());
tok->insertToken(std::to_string(maxIndex + 1));
// ast
tok->astOperand2(tok->next());
// Token::scope
tok->next()->scope(tok->scope());
// Value flow
ValueFlow::Value value(maxIndex + 1);
value.setKnown();
tok->next()->addValue(value);
// Set array dimensions
Dimension d;
d.num = maxIndex + 1;
std::vector<Dimension> dimensions{d};
const_cast<Variable*>(var)->setDimensions(dimensions);
}
}
}
static Token *skipTernaryOp(Token *tok)
{
int colonLevel = 1;
while (nullptr != (tok = tok->next())) {
if (tok->str() == "?") {
++colonLevel;
} else if (tok->str() == ":") {
--colonLevel;
if (colonLevel == 0) {
tok = tok->next();
break;
}
}
if (tok->link() && Token::Match(tok, "[(<]"))
tok = tok->link();
else if (Token::Match(tok->next(), "[{};)]"))
break;
}
if (colonLevel > 0) // Ticket #5214: Make sure the ':' matches the proper '?'
return nullptr;
return tok;
}
// Skips until the colon at the end of the case label, the argument must point to the "case" token.
// In case of success returns the colon token.
// In case of failure returns the token that caused the error.
static Token *skipCaseLabel(Token *tok)
{
assert(tok->str() == "case");
while (nullptr != (tok = tok->next())) {
if (Token::Match(tok, "(|["))
tok = tok->link();
else if (tok->str() == "?") {
Token * tok1 = skipTernaryOp(tok);
if (!tok1)
return tok;
tok = tok1;
}
if (Token::Match(tok, "[:{};]"))
return tok;
}
return nullptr;
}
const Token * Tokenizer::startOfExecutableScope(const Token * tok)
{
if (tok->str() != ")")
return nullptr;
tok = Tokenizer::isFunctionHead(tok, ":{");
if (Token::Match(tok, ": %name% [({]")) {
while (Token::Match(tok, "[:,] %name% [({]"))
tok = tok->linkAt(2)->next();
}
return (tok && tok->str() == "{") ? tok : nullptr;
}
/** simplify labels and case|default in the code: add a ";" if not already in.*/
void Tokenizer::simplifyLabelsCaseDefault()
{
const bool cpp = isCPP();
bool executablescope = false;
int indentLevel = 0;
for (Token *tok = list.front(); tok; tok = tok->next()) {
// Simplify labels in the executable scope..
auto *start = const_cast<Token *>(startOfExecutableScope(tok));
if (start) {
tok = start;
executablescope = true;
}
if (!executablescope)
continue;
if (tok->str() == "{") {
if (tok->strAt(-1) == "=")
tok = tok->link();
else
++indentLevel;
} else if (tok->str() == "}") {
--indentLevel;
if (indentLevel == 0) {
executablescope = false;
continue;
}
} else if (Token::Match(tok, "(|["))
tok = tok->link();
if (Token::Match(tok, "[;{}:] case")) {
tok = skipCaseLabel(tok->next());
if (!tok)
break;
if (tok->str() != ":" || tok->strAt(-1) == "case" || !tok->next())
syntaxError(tok);
if (tok->strAt(1) != ";" && tok->strAt(1) != "case")
tok->insertToken(";");
else
tok = tok->previous();
} else if (Token::Match(tok, "[;{}] %name% : !!;")) {
if (!cpp || !Token::Match(tok->next(), "class|struct|enum")) {
tok = tok->tokAt(2);
tok->insertToken(";");
}
}
}
}
void Tokenizer::simplifyCaseRange()
{
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "case %num%|%char% ... %num%|%char% :")) {
const MathLib::bigint start = MathLib::toBigNumber(tok->strAt(1));
MathLib::bigint end = MathLib::toBigNumber(tok->strAt(3));
end = std::min(start + 50, end); // Simplify it 50 times at maximum
if (start < end) {
tok = tok->tokAt(2);
tok->str(":");
tok->insertToken("case");
for (MathLib::bigint i = end-1; i > start; i--) {
tok->insertToken(":");
tok->insertToken(std::to_string(i));
tok->insertToken("case");
}
}
}
}
}
void Tokenizer::calculateScopes()
{
for (auto *tok = list.front(); tok; tok = tok->next())
tok->scopeInfo(nullptr);
std::string nextScopeNameAddition;
std::shared_ptr<ScopeInfo2> primaryScope = std::make_shared<ScopeInfo2>("", nullptr);
list.front()->scopeInfo(std::move(primaryScope));
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (tok == list.front() || !tok->scopeInfo()) {
if (tok != list.front())
tok->scopeInfo(tok->previous()->scopeInfo());
if (Token::Match(tok, "using namespace %name% ::|<|;")) {
std::string usingNamespaceName;
for (const Token* namespaceNameToken = tok->tokAt(2);
namespaceNameToken && namespaceNameToken->str() != ";";
namespaceNameToken = namespaceNameToken->next()) {
usingNamespaceName += namespaceNameToken->str();
usingNamespaceName += " ";
}
if (!usingNamespaceName.empty())
usingNamespaceName.pop_back();
tok->scopeInfo()->usingNamespaces.insert(std::move(usingNamespaceName));
} else if (Token::Match(tok, "namespace|class|struct|union %name% {|::|:|<")) {
for (Token* nameTok = tok->next(); nameTok && !Token::Match(nameTok, "{|:"); nameTok = nameTok->next()) {
if (Token::Match(nameTok, ";|<")) {
nextScopeNameAddition = "";
break;
}
nextScopeNameAddition.append(nameTok->str());
nextScopeNameAddition.append(" ");
}
if (!nextScopeNameAddition.empty())
nextScopeNameAddition.pop_back();
}
if (Token::simpleMatch(tok, "{")) {
// This might be the opening of a member function
Token *tok1 = tok;
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->previous() && tok1->strAt(-1) == ")") {
bool member = true;
tok1 = tok1->linkAt(-1);
if (Token::Match(tok1->previous(), "throw|noexcept")) {
tok1 = tok1->previous();
while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept"))
tok1 = tok1->previous();
if (tok1->strAt(-1) != ")")
member = false;
} else if (Token::Match(tok->tokAt(-2), ":|, %name%")) {
tok1 = tok1->tokAt(-2);
if (tok1->strAt(-1) != ")")
member = false;
}
if (member) {
if (tok1->strAt(-1) == ">")
tok1 = tok1->previous()->findOpeningBracket();
if (tok1 && Token::Match(tok1->tokAt(-3), "%name% :: %name%")) {
tok1 = tok1->tokAt(-2);
std::string scope = tok1->strAt(-1);
while (Token::Match(tok1->tokAt(-2), ":: %name%")) {
scope = tok1->strAt(-3) + " :: " + scope;
tok1 = tok1->tokAt(-2);
}
if (!nextScopeNameAddition.empty() && !scope.empty())
nextScopeNameAddition += " :: ";
nextScopeNameAddition += scope;
}
}
}
// New scope is opening, record it here
std::shared_ptr<ScopeInfo2> newScopeInfo = std::make_shared<ScopeInfo2>(tok->scopeInfo()->name, tok->link(), tok->scopeInfo()->usingNamespaces);
if (!newScopeInfo->name.empty() && !nextScopeNameAddition.empty())
newScopeInfo->name.append(" :: ");
newScopeInfo->name.append(nextScopeNameAddition);
nextScopeNameAddition = "";
if (tok->link())
tok->link()->scopeInfo(tok->scopeInfo());
tok->scopeInfo(std::move(newScopeInfo));
}
}
}
}
void Tokenizer::simplifyTemplates()
{
if (isC())
return;
const std::time_t maxTime = mSettings.templateMaxTime > 0 ? std::time(nullptr) + mSettings.templateMaxTime : 0;
mTemplateSimplifier->simplifyTemplates(
maxTime);
}
//---------------------------------------------------------------------------
namespace {
/** Class used in Tokenizer::setVarIdPass1 */
class VariableMap {
private:
std::unordered_map<std::string, nonneg int> mVariableId;
std::unordered_map<std::string, nonneg int> mVariableId_global;
std::stack<std::vector<std::pair<std::string, nonneg int>>> mScopeInfo;
mutable nonneg int mVarId{};
public:
VariableMap() = default;
void enterScope();
bool leaveScope();
void addVariable(const std::string& varname, bool globalNamespace);
bool hasVariable(const std::string& varname) const {
return mVariableId.find(varname) != mVariableId.end();
}
const std::unordered_map<std::string, nonneg int>& map(bool global) const {
return global ? mVariableId_global : mVariableId;
}
nonneg int& getVarId() {
return mVarId;
}
};
}
void VariableMap::enterScope()
{
mScopeInfo.emplace(/*std::vector<std::pair<std::string, nonneg int>>()*/);
}
bool VariableMap::leaveScope()
{
if (mScopeInfo.empty())
return false;
for (const std::pair<std::string, nonneg int>& outerVariable : mScopeInfo.top()) {
if (outerVariable.second != 0)
mVariableId[outerVariable.first] = outerVariable.second;
else
mVariableId.erase(outerVariable.first);
}
mScopeInfo.pop();
return true;
}
void VariableMap::addVariable(const std::string& varname, bool globalNamespace)
{
if (mScopeInfo.empty()) {
mVariableId[varname] = ++mVarId;
if (globalNamespace)
mVariableId_global[varname] = mVariableId[varname];
return;
}
std::unordered_map<std::string, nonneg int>::iterator it = mVariableId.find(varname);
if (it == mVariableId.end()) {
mScopeInfo.top().emplace_back(varname, 0);
mVariableId[varname] = ++mVarId;
if (globalNamespace)
mVariableId_global[varname] = mVariableId[varname];
return;
}
mScopeInfo.top().emplace_back(varname, it->second);
it->second = ++mVarId;
}
static bool setVarIdParseDeclaration(Token*& tok, const VariableMap& variableMap, bool executableScope)
{
const Token* const tok1 = tok;
Token* tok2 = tok;
if (!tok2->isName())
return false;
nonneg int typeCount = 0;
nonneg int singleNameCount = 0;
bool hasstruct = false; // Is there a "struct" or "class"?
bool bracket = false;
bool ref = false;
while (tok2) {
if (tok2->isName()) {
if (Token::simpleMatch(tok2, "alignas (")) {
tok2 = tok2->linkAt(1)->next();
continue;
}
if (tok2->isCpp() && Token::Match(tok2, "namespace|public|private|protected"))
return false;
if (tok2->isCpp() && Token::simpleMatch(tok2, "decltype (")) {
typeCount = 1;
tok2 = tok2->linkAt(1)->next();
continue;
}
if (Token::Match(tok2, "struct|union|enum") || (tok2->isCpp() && Token::Match(tok2, "class|typename"))) {
hasstruct = true;
typeCount = 0;
singleNameCount = 0;
} else if (Token::Match(tok2, "const|extern")) {
// just skip "const", "extern"
} else if (!hasstruct && variableMap.map(false).count(tok2->str()) && tok2->strAt(-1) != "::") {
++typeCount;
tok2 = tok2->next();
if (!tok2 || tok2->str() != "::")
break;
} else {
if (tok2->str() != "void" || Token::Match(tok2, "void const| *|(")) // just "void" cannot be a variable type
++typeCount;
++singleNameCount;
}
} else if (tok2->isCpp() && ((TemplateSimplifier::templateParameters(tok2) > 0) ||
Token::simpleMatch(tok2, "< >") /* Ticket #4764 */)) {
const Token *start = tok;
if (Token::Match(start->previous(), "%or%|%oror%|&&|&|^|+|-|*|/"))
return false;
Token* const closingBracket = tok2->findClosingBracket();
if (closingBracket == nullptr) { /* Ticket #8151 */
throw tok2;
}
tok2 = closingBracket;
if (tok2->str() != ">")
break;
singleNameCount = 1;
if (Token::Match(tok2, "> %name% %or%|%oror%|&&|&|^|+|-|*|/") && !Token::Match(tok2, "> const [*&]"))
return false;
if (Token::Match(tok2, "> %name% )")) {
if (Token::Match(tok2->linkAt(2)->previous(), "if|for|while ("))
return false;
if (!Token::Match(tok2->linkAt(2)->previous(), "%name%|] ("))
return false;
}
} else if (Token::Match(tok2, "&|&&")) {
ref = !bracket;
} else if (singleNameCount >= 1 && Token::Match(tok2, "( [*&]") && Token::Match(tok2->link(), ") (|[")) {
for (const Token* tok3 = tok2->tokAt(2); Token::Match(tok3, "!!)"); tok3 = tok3->next()) {
if (Token::Match(tok3, "(|["))
tok3 = tok3->link();
if (tok3->str() == ",")
return false;
}
bracket = true; // Skip: Seems to be valid pointer to array or function pointer
} else if (singleNameCount >= 1 && Token::Match(tok2, "( * %name% [") && Token::Match(tok2->linkAt(3), "] ) [;,]") && !variableMap.map(false).count(tok2->strAt(2))) {
bracket = true;
} else if (singleNameCount >= 1 && tok2->previous() && tok2->previous()->isStandardType() && Token::Match(tok2, "( *|&| %name% ) ;")) {
bracket = true;
} else if (tok2->str() == "::") {
singleNameCount = 0;
} else if (tok2->str() != "*" && tok2->str() != "...") {
break;
}
tok2 = tok2->next();
}
if (tok2) {
bool isLambdaArg = false;
{
const Token *tok3 = tok->previous();
if (tok3 && tok3->str() == ",") {
while (tok3 && !Token::Match(tok3,";|(|[|{")) {
if (Token::Match(tok3, ")|]"))
tok3 = tok3->link();
tok3 = tok3->previous();
}
if (tok3 && executableScope && Token::Match(tok3->previous(), "%name% (")) {
const Token *fdecl = tok3->previous();
int count = 0;
while (Token::Match(fdecl, "%name%|*")) {
fdecl = fdecl->previous();
count++;
}
if (!Token::Match(fdecl, "[;{}] %name%") || count <= 1)
return false;
}
}
if (tok3 && tok3->isCpp() && Token::simpleMatch(tok3->previous(), "] (") &&
(Token::simpleMatch(tok3->link(), ") {") || Token::Match(tok3->link(), ") . %name%")))
isLambdaArg = true;
}
tok = tok2;
// In executable scopes, references must be assigned
// Catching by reference is an exception
if (executableScope && ref && !isLambdaArg) {
if (Token::Match(tok2, "(|=|{|:"))
; // reference is assigned => ok
else if (tok2->str() != ")" || tok2->link()->strAt(-1) != "catch")
return false; // not catching by reference => not declaration
}
}
// Check if array declaration is valid (#2638)
// invalid declaration: AAA a[4] = 0;
if (typeCount >= 2 && executableScope && Token::Match(tok2, ")| [")) {
const Token *tok3 = tok2->str() == ")" ? tok2->next() : tok2;
while (tok3 && tok3->str() == "[") {
tok3 = tok3->link()->next();
}
if (Token::Match(tok3, "= %num%"))
return false;
if (bracket && Token::Match(tok1->previous(), "[(,]") && Token::Match(tok3, ",|)|%cop%"))
return false;
}
return (typeCount >= 2 && tok2 && Token::Match(tok2->tokAt(-2), "!!:: %type%"));
}
static void setVarIdStructMembers(Token *&tok1,
std::map<nonneg int, std::map<std::string, nonneg int>>& structMembers,
nonneg int &varId)
{
Token *tok = tok1;
if (Token::Match(tok, "%name% = { . %name% =|{")) {
const nonneg int struct_varid = tok->varId();
if (struct_varid == 0)
return;
std::map<std::string, nonneg int>& members = structMembers[struct_varid];
tok = tok->tokAt(3);
while (tok->str() != "}") {
if (Token::Match(tok, "{|[|("))
tok = tok->link();
if (Token::Match(tok->previous(), "[,{] . %name% =|{")) {
tok = tok->next();
const std::map<std::string, nonneg int>::const_iterator it = members.find(tok->str());
if (it == members.cend()) {
members[tok->str()] = ++varId;
tok->varId(varId);
} else {
tok->varId(it->second);
}
}
tok = tok->next();
}
return;
}
while (Token::Match(tok->next(), ")| . %name% !!(")) {
// Don't set varid for trailing return type
if (tok->strAt(1) == ")" && Token::Match(tok->linkAt(1)->tokAt(-1), "%name%|]") &&
Tokenizer::isFunctionHead(tok->linkAt(1), "{|;")) {
tok = tok->tokAt(3);
continue;
}
const nonneg int struct_varid = tok->varId();
tok = tok->tokAt(2);
if (struct_varid == 0)
continue;
if (tok->str() == ".")
tok = tok->next();
// Don't set varid for template function
if (TemplateSimplifier::templateParameters(tok->next()) > 0)
break;
std::map<std::string, nonneg int>& members = structMembers[struct_varid];
const std::map<std::string, nonneg int>::const_iterator it = members.find(tok->str());
if (it == members.cend()) {
members[tok->str()] = ++varId;
tok->varId(varId);
} else {
tok->varId(it->second);
}
}
// tok can't be null
tok1 = tok;
}
static bool setVarIdClassDeclaration(Token* const startToken,
VariableMap& variableMap,
const nonneg int scopeStartVarId,
std::map<nonneg int, std::map<std::string, nonneg int>>& structMembers)
{
// end of scope
const Token* const endToken = startToken->link();
// determine class name
std::string className;
for (const Token *tok = startToken->previous(); tok; tok = tok->previous()) {
if (!tok->isName() && tok->str() != ":")
break;
if (Token::Match(tok, "class|struct|enum %type% [:{]")) {
className = tok->strAt(1);
break;
}
}
// replace varids..
int indentlevel = 0;
bool initList = false;
bool inEnum = false;
const Token *initListArgLastToken = nullptr;
for (Token *tok = startToken->next(); tok != endToken; tok = tok->next()) {
if (!tok)
return false;
if (initList) {
if (tok == initListArgLastToken)
initListArgLastToken = nullptr;
else if (!initListArgLastToken &&
Token::Match(tok->previous(), "%name%|>|>> {|(") &&
Token::Match(tok->link(), "}|) ,|{"))
initListArgLastToken = tok->link();
}
if (tok->str() == "{") {
inEnum = isEnumStart(tok);
if (initList && !initListArgLastToken)
initList = false;
++indentlevel;
} else if (tok->str() == "}") {
--indentlevel;
inEnum = false;
} else if (initList && indentlevel == 0 && Token::Match(tok->previous(), "[,:] %name% [({]")) {
const std::unordered_map<std::string, nonneg int>::const_iterator it = variableMap.map(false).find(tok->str());
if (it != variableMap.map(false).end()) {
tok->varId(it->second);
}
} else if (tok->isName() && tok->varId() <= scopeStartVarId) {
if (indentlevel > 0 || initList) {
if (Token::Match(tok->previous(), "::|.") && tok->strAt(-2) != "this" && !Token::simpleMatch(tok->tokAt(-5), "( * this ) ."))
continue;
if (!tok->next())
return false;
if (tok->strAt(1) == "::") {
if (tok->str() == className)
tok = tok->tokAt(2);
else
continue;
}
if (!inEnum) {
const std::unordered_map<std::string, nonneg int>::const_iterator it = variableMap.map(false).find(tok->str());
if (it != variableMap.map(false).end()) {
tok->varId(it->second);
setVarIdStructMembers(tok, structMembers, variableMap.getVarId());
}
}
}
} else if (indentlevel == 0 && tok->str() == ":" && !initListArgLastToken)
initList = true;
}
return true;
}
// Update the variable ids..
// Parse each function..
void Tokenizer::setVarIdClassFunction(const std::string &classname,
Token * const startToken,
const Token * const endToken,
const std::map<std::string, nonneg int> &varlist,
std::map<nonneg int, std::map<std::string, nonneg int>>& structMembers,
nonneg int &varId_)
{
const auto pos = classname.rfind(' '); // TODO handle multiple scopes
const std::string lastScope = classname.substr(pos == std::string::npos ? 0 : pos + 1);
for (Token *tok2 = startToken; tok2 && tok2 != endToken; tok2 = tok2->next()) {
if (tok2->varId() != 0 || !tok2->isName())
continue;
if (Token::Match(tok2->tokAt(-2), ("!!" + lastScope + " ::").c_str()))
continue;
if (Token::Match(tok2->tokAt(-4), "%name% :: %name% ::")) // Currently unsupported
continue;
if (Token::Match(tok2->tokAt(-2), "!!this .") && !Token::simpleMatch(tok2->tokAt(-5), "( * this ) ."))
continue;
if (Token::Match(tok2, "%name% ::"))
continue;
const std::map<std::string, nonneg int>::const_iterator it = varlist.find(tok2->str());
if (it != varlist.end()) {
tok2->varId(it->second);
setVarIdStructMembers(tok2, structMembers, varId_);
}
}
}
void Tokenizer::setVarId()
{
// Clear all variable ids
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->isName())
tok->varId(0);
}
setVarIdPass1();
setPodTypes();
setVarIdPass2();
}
// Variable declarations can't start with "return" etc.
#define NOTSTART_C "NOT", "case", "default", "goto", "not", "return", "sizeof", "typedef"
static const std::unordered_set<std::string> notstart_c = { NOTSTART_C };
static const std::unordered_set<std::string> notstart_cpp = { NOTSTART_C,
"delete", "friend", "new", "throw", "using", "virtual", "explicit", "const_cast", "dynamic_cast", "reinterpret_cast", "static_cast", "template"
};
void Tokenizer::setVarIdPass1()
{
const bool cpp = isCPP();
// Variable declarations can't start with "return" etc.
const std::unordered_set<std::string>& notstart = (isC()) ? notstart_c : notstart_cpp;
VariableMap variableMap;
std::map<nonneg int, std::map<std::string, nonneg int>> structMembers;
std::stack<VarIdScopeInfo> scopeStack;
scopeStack.emplace(/*VarIdScopeInfo()*/);
std::stack<const Token *> functionDeclEndStack;
const Token *functionDeclEndToken = nullptr;
bool initlist = false;
bool inlineFunction = false;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->isOp())
continue;
if (cpp && Token::simpleMatch(tok, "template <")) {
Token* closingBracket = tok->next()->findClosingBracket();
if (closingBracket)
tok = closingBracket;
continue;
}
if (tok == functionDeclEndToken) {
functionDeclEndStack.pop();
functionDeclEndToken = functionDeclEndStack.empty() ? nullptr : functionDeclEndStack.top();
if (tok->str() == ":")
initlist = true;
else if (tok->str() == ";") {
if (!variableMap.leaveScope())
cppcheckError(tok);
} else if (tok->str() == "{") {
scopeStack.emplace(true, scopeStack.top().isStructInit || tok->strAt(-1) == "=", /*isEnum=*/ false, variableMap.getVarId());
// check if this '{' is a start of an "if" body
const Token * ifToken = tok->previous();
if (ifToken && ifToken->str() == ")")
ifToken = ifToken->link();
else
ifToken = nullptr;
if (ifToken)
ifToken = ifToken->previous();
if (ifToken && ifToken->str() == "if") {
// open another scope to differentiate between variables declared in the "if" condition and in the "if" body
variableMap.enterScope();
}
}
} else if (!initlist && tok->str()=="(") {
const Token * newFunctionDeclEnd = nullptr;
if (!scopeStack.top().isExecutable)
newFunctionDeclEnd = isFunctionHead(tok, "{:;");
else {
const Token* tokenLinkNext = tok->link()->next();
if (Token::simpleMatch(tokenLinkNext, ".")) { // skip trailing return type
tokenLinkNext = tokenLinkNext->next();
while (Token::Match(tokenLinkNext, "%name%|::")) {
tokenLinkNext = tokenLinkNext->next();
if (Token::simpleMatch(tokenLinkNext, "<") && tokenLinkNext->link())
tokenLinkNext = tokenLinkNext->link()->next();
}
}
if (tokenLinkNext && tokenLinkNext->str() == "{") // might be for- or while-loop or if-statement
newFunctionDeclEnd = tokenLinkNext;
}
if (newFunctionDeclEnd && newFunctionDeclEnd != functionDeclEndToken) {
functionDeclEndStack.push(newFunctionDeclEnd);
functionDeclEndToken = newFunctionDeclEnd;
variableMap.enterScope();
}
} else if (Token::Match(tok, "{|}")) {
inlineFunction = false;
const Token * const startToken = (tok->str() == "{") ? tok : tok->link();
// parse anonymous namespaces as part of the current scope
if (!Token::Match(startToken->previous(), "union|struct|enum|namespace {") &&
!(initlist && Token::Match(startToken->previous(), "%name%|>|>>|(") && Token::Match(startToken->link(), "} ,|{|)|..."))) {
if (tok->str() == "{") {
bool isExecutable;
const Token *prev = tok->previous();
while (Token::Match(prev, "%name%|."))
prev = prev->previous();
const bool isLambda = prev && prev->str() == ")" && Token::simpleMatch(prev->link()->previous(), "] (");
if ((!isLambda && (tok->strAt(-1) == ")" || Token::Match(tok->tokAt(-2), ") %type%"))) ||
(initlist && tok->strAt(-1) == "}")) {
isExecutable = true;
} else {
isExecutable = ((scopeStack.top().isExecutable || initlist || tok->strAt(-1) == "else") &&
!isClassStructUnionEnumStart(tok));
if (!(scopeStack.top().isStructInit || tok->strAt(-1) == "="))
variableMap.enterScope();
}
const bool isStructInit = scopeStack.top().isStructInit || tok->strAt(-1) == "=" || (initlist && !Token::Match(tok->tokAt(-1), ")|}|..."));
scopeStack.emplace(isExecutable, isStructInit, isEnumStart(tok), variableMap.getVarId());
initlist = false;
} else { /* if (tok->str() == "}") */
bool isNamespace = false;
for (const Token *tok1 = tok->link()->previous(); tok1 && tok1->isName(); tok1 = tok1->previous()) {
if (tok1->str() == "namespace") {
isNamespace = true;
break;
}
}
// Set variable ids in class declaration..
if (!initlist && !isC() && !scopeStack.top().isExecutable && tok->link() && !isNamespace) {
if (!setVarIdClassDeclaration(tok->link(),
variableMap,
scopeStack.top().startVarid,
structMembers)) {
syntaxError(nullptr);
}
}
if (!scopeStack.top().isStructInit) {
variableMap.leaveScope();
// check if this '}' is an end of an "else" body or an "if" body without an "else" part
const Token * ifToken = startToken->previous();
if (ifToken && ifToken->str() == ")")
ifToken = ifToken->link()->previous();
else
ifToken = nullptr;
if (startToken->strAt(-1) == "else" || (ifToken && ifToken->str() == "if" && tok->strAt(1) != "else")) {
// leave the extra scope used to differentiate between variables declared in the "if" condition and in the "if" body
variableMap.leaveScope();
}
}
scopeStack.pop();
if (scopeStack.empty()) { // should be impossible
scopeStack.emplace(/*VarIdScopeInfo()*/);
}
}
}
}
if ((!scopeStack.top().isStructInit &&
(tok == list.front() ||
Token::Match(tok, "[;{}]") ||
(tok->str() == "(" && !scopeStack.top().isExecutable && isFunctionHead(tok,";:")) ||
(tok->str() == "," && (!scopeStack.top().isExecutable || inlineFunction || !tok->previous()->varId())) ||
(tok->isName() && endsWith(tok->str(), ':')))) ||
(tok->str() == "(" && isFunctionHead(tok, "{"))) {
// No variable declarations in sizeof
if (Token::simpleMatch(tok->previous(), "sizeof (")) {
continue;
}
if (Settings::terminated())
return;
// locate the variable name..
Token* tok2 = (tok->isName()) ? tok : tok->next();
// private: protected: public: etc
while (tok2 && endsWith(tok2->str(), ':')) {
tok2 = tok2->next();
}
if (!tok2)
break;
// Variable declaration can't start with "return", etc
if (notstart.find(tok2->str()) != notstart.end())
continue;
if (!isC() && Token::simpleMatch(tok2, "const new"))
continue;
bool decl;
if (cpp && mSettings.standards.cpp >= Standards::CPP17 && Token::Match(tok, "[(;{}] const| auto &|&&| [")) {
// Structured bindings
tok2 = Token::findsimplematch(tok, "[");
if ((Token::simpleMatch(tok->previous(), "for (") && Token::simpleMatch(tok2->link(), "] :")) ||
Token::simpleMatch(tok2->link(), "] =")) {
while (tok2 && tok2->str() != "]") {
if (Token::Match(tok2, "%name% [,]]"))
variableMap.addVariable(tok2->str(), false);
tok2 = tok2->next();
}
continue;
}
}
try { /* Ticket #8151 */
decl = setVarIdParseDeclaration(tok2, variableMap, scopeStack.top().isExecutable);
} catch (const Token * errTok) {
syntaxError(errTok);
}
if (tok->str() == "(" && isFunctionHead(tok, "{") && scopeStack.top().isExecutable)
inlineFunction = true;
if (decl) {
if (cpp) {
if (Token *declTypeTok = Token::findsimplematch(tok, "decltype (", tok2)) {
for (Token *declTok = declTypeTok->linkAt(1); declTok != declTypeTok; declTok = declTok->previous()) {
if (declTok->isName() && !Token::Match(declTok->previous(), "::|.") && variableMap.hasVariable(declTok->str()))
declTok->varId(variableMap.map(false).find(declTok->str())->second);
}
}
}
const Token* prev2 = tok2->previous();
if (Token::Match(prev2, "%type% [;[=,)]") && tok2->strAt(-1) != "const")
;
else if (Token::Match(prev2, "%type% :") && tok->strAt(-1) == "for")
;
else if (Token::Match(prev2, "%type% ( !!)") && Token::simpleMatch(tok2->link(), ") ;")) {
// In C++ , a variable can't be called operator+ or something like that.
if (cpp &&
prev2->isOperatorKeyword())
continue;
const Token *tok3 = tok2->next();
if (!tok3->isStandardType() && tok3->str() != "void" && !Token::Match(tok3, "struct|union|class %type%") && tok3->str() != "." && !Token::Match(tok2->link()->previous(), "[&*]")) {
if (!scopeStack.top().isExecutable) {
// Detecting initializations with () in non-executable scope is hard and often impossible to be done safely. Thus, only treat code as a variable that definitely is one.
decl = false;
bool rhs = false;
for (; tok3; tok3 = tok3->nextArgumentBeforeCreateLinks2()) {
if (tok3->str() == "=") {
rhs = true;
continue;
}
if (tok3->str() == ",") {
rhs = false;
continue;
}
if (rhs)
continue;
if (tok3->isLiteral() ||
(tok3->isName() && (variableMap.hasVariable(tok3->str()) ||
(tok3->strAt(-1) == "(" && Token::simpleMatch(tok3->next(), "(") && !Token::simpleMatch(tok3->linkAt(1)->next(), "(")))) ||
tok3->isOp() ||
tok3->str() == "(" ||
notstart.find(tok3->str()) != notstart.end()) {
decl = true;
break;
}
}
}
} else
decl = false;
} else if (cpp && Token::Match(prev2, "%type% {") && Token::simpleMatch(tok2->link(), "} ;")) { // C++11 initialization style
if (tok2->link() != tok2->next() && // add value-initialized variable T x{};
(Token::Match(prev2, "do|try|else") || Token::Match(prev2->tokAt(-2), "struct|class|:")))
continue;
} else
decl = false;
if (decl) {
if (isC() && Token::Match(prev2->previous(), "&|&&"))
syntaxErrorC(prev2, prev2->strAt(-2) + prev2->strAt(-1) + " " + prev2->str());
variableMap.addVariable(prev2->str(), scopeStack.size() <= 1);
if (Token::simpleMatch(tok->previous(), "for (") && Token::Match(prev2, "%name% [=,]")) {
for (const Token *tok3 = prev2->next(); tok3 && tok3->str() != ";"; tok3 = tok3->next()) {
if (Token::Match(tok3, "[([]"))
tok3 = tok3->link();
if (Token::Match(tok3, ", %name% [,=;]"))
variableMap.addVariable(tok3->strAt(1), false);
}
}
// set varid for template parameters..
tok = tok->next();
while (Token::Match(tok, "%name%|::"))
tok = tok->next();
if (tok && tok->str() == "<") {
const Token *end = tok->findClosingBracket();
while (tok != end) {
if (tok->isName() && !(Token::simpleMatch(tok->next(), "<") &&
Token::Match(tok->tokAt(-1), ":: %name%"))) {
const std::unordered_map<std::string, nonneg int>::const_iterator it = variableMap.map(false).find(tok->str());
if (it != variableMap.map(false).end())
tok->varId(it->second);
}
tok = tok->next();
}
}
tok = tok2->previous();
}
}
}
if (tok->isName() && !tok->isKeyword() && !tok->isStandardType()) {
// don't set variable id after a struct|enum|union
if (Token::Match(tok->previous(), "struct|enum|union") || (cpp && tok->strAt(-1) == "class"))
continue;
bool globalNamespace = false;
if (!isC()) {
if (tok->previous() && tok->strAt(-1) == "::") {
if (Token::Match(tok->tokAt(-2), ")|]|%name%"))
continue;
globalNamespace = true;
}
if (tok->next() && tok->strAt(1) == "::")
continue;
if (Token::simpleMatch(tok->tokAt(-2), ":: template"))
continue;
}
// function declaration inside executable scope? Function declaration is of form: type name "(" args ")"
if (scopeStack.top().isExecutable && !scopeStack.top().isStructInit && Token::Match(tok, "%name% [,)[]")) {
bool par = false;
const Token* start;
Token* end;
// search begin of function declaration
for (start = tok; Token::Match(start, "%name%|*|&|,|("); start = start->previous()) {
if (start->str() == "(") {
if (par)
break;
par = true;
}
if (Token::Match(start, "[(,]")) {
if (!Token::Match(start, "[(,] %type% %name%|*|&"))
break;
}
if (start->varId() > 0)
break;
}
// search end of function declaration
for (end = tok->next(); Token::Match(end, "%name%|*|&|,|[|]|%num%"); end = end->next()) {}
// there are tokens which can't appear at the begin of a function declaration such as "return"
const bool isNotstartKeyword = start->next() && notstart.find(start->strAt(1)) != notstart.end();
// now check if it is a function declaration
if (Token::Match(start, "[;{}] %type% %name%|*") && par && Token::simpleMatch(end, ") ;") && !isNotstartKeyword) {
// function declaration => don't set varid
tok = end;
continue;
}
}
if (tok->varId() == 0 && (!scopeStack.top().isEnum || !(Token::Match(tok->previous(), "{|,") && Token::Match(tok->next(), ",|=|}"))) &&
!Token::simpleMatch(tok->next(), ": ;") && !(tok->tokAt(-1) && Token::Match(tok->tokAt(-2), "{|, ."))) {
const std::unordered_map<std::string, nonneg int>::const_iterator it = variableMap.map(globalNamespace).find(tok->str());
if (it != variableMap.map(globalNamespace).end()) {
tok->varId(it->second);
setVarIdStructMembers(tok, structMembers, variableMap.getVarId());
}
}
} else if (Token::Match(tok, "::|. %name%") && Token::Match(tok->previous(), ")|]|>|%name%")) {
// Don't set varid after a :: or . token
tok = tok->next();
} else if (tok->str() == ":" && Token::Match(tok->tokAt(-2), "class %type%")) {
do {
tok = tok->next();
} while (tok && (tok->isName() || tok->str() == ","));
if (!tok)
break;
tok = tok->previous();
}
}
mVarId = variableMap.getVarId();
}
namespace {
struct Member {
Member(std::list<std::string> s, std::list<const Token *> ns, Token *t) : usingnamespaces(std::move(ns)), scope(std::move(s)), tok(t) {}
std::list<const Token *> usingnamespaces;
std::list<std::string> scope;
Token *tok;
};
}
static std::string getScopeName(const std::list<ScopeInfo2> &scopeInfo)
{
std::string ret;
for (const ScopeInfo2 &si : scopeInfo)
ret += (ret.empty() ? "" : " :: ") + (si.name);
return ret;
}
static Token * matchMemberName(const std::list<std::string> &scope, const Token *nsToken, Token *memberToken, const std::list<ScopeInfo2> &scopeInfo)
{
std::list<ScopeInfo2>::const_iterator scopeIt = scopeInfo.cbegin();
// Current scope..
for (std::list<std::string>::const_iterator it = scope.cbegin(); it != scope.cend(); ++it) {
if (scopeIt == scopeInfo.cend() || scopeIt->name != *it)
return nullptr;
++scopeIt;
}
// using namespace..
if (nsToken) {
while (Token::Match(nsToken, "%name% ::")) {
if (scopeIt != scopeInfo.end() && nsToken->str() == scopeIt->name) {
nsToken = nsToken->tokAt(2);
++scopeIt;
} else {
return nullptr;
}
}
if (!Token::Match(nsToken, "%name% ;"))
return nullptr;
if (scopeIt == scopeInfo.end() || nsToken->str() != scopeIt->name)
return nullptr;
++scopeIt;
}
// Parse member tokens..
while (scopeIt != scopeInfo.end()) {
if (!Token::Match(memberToken, "%name% ::|<"))
return nullptr;
if (memberToken->str() != scopeIt->name)
return nullptr;
if (memberToken->strAt(1) == "<") {
memberToken = memberToken->next()->findClosingBracket();
if (!Token::simpleMatch(memberToken, "> ::"))
return nullptr;
}
memberToken = memberToken->tokAt(2);
++scopeIt;
}
return Token::Match(memberToken, "~| %name%") ? memberToken : nullptr;
}
static Token * matchMemberName(const Member &member, const std::list<ScopeInfo2> &scopeInfo)
{
if (scopeInfo.empty())
return nullptr;
// Does this member match without "using namespace"..
Token *ret = matchMemberName(member.scope, nullptr, member.tok, scopeInfo);
if (ret)
return ret;
// Try to match member using the "using namespace ..." namespaces..
for (const Token *ns : member.usingnamespaces) {
ret = matchMemberName(member.scope, ns, member.tok, scopeInfo);
if (ret)
return ret;
}
return nullptr;
}
static Token * matchMemberVarName(const Member &var, const std::list<ScopeInfo2> &scopeInfo)
{
Token *tok = matchMemberName(var, scopeInfo);
if (Token::Match(tok, "%name%")) {
if (!tok->next() || tok->strAt(1) != "(" || (tok->tokAt(2) && tok->tokAt(2)->isLiteral()))
return tok;
}
return nullptr;
}
static Token * matchMemberFunctionName(const Member &func, const std::list<ScopeInfo2> &scopeInfo)
{
Token *tok = matchMemberName(func, scopeInfo);
return Token::Match(tok, "~| %name% (") ? tok : nullptr;
}
template<typename T>
static T* skipInitializerList(T* tok)
{
T* const start = tok;
while (Token::Match(tok, "[:,] ::| %name%")) {
tok = tok->tokAt(tok->strAt(1) == "::" ? 1 : 2);
while (Token::Match(tok, ":: %name%"))
tok = tok->tokAt(2);
if (!Token::Match(tok, "[({<]") || !tok->link())
return start;
const bool isTemplate = tok->str() == "<";
tok = tok->link()->next();
if (isTemplate && tok && tok->link())
tok = tok->link()->next();
}
return tok;
}
void Tokenizer::setVarIdPass2()
{
std::map<nonneg int, std::map<std::string, nonneg int>> structMembers;
// Member functions and variables in this source
std::list<Member> allMemberFunctions;
std::list<Member> allMemberVars;
if (!isC()) {
std::map<const Token *, std::string> endOfScope;
std::list<std::string> scope;
std::list<const Token *> usingnamespaces;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->previous() || Token::Match(tok->previous(), "[;{}]")) {
if (Token::Match(tok, "using namespace %name% ::|;")) {
Token *endtok = tok->tokAt(2);
while (Token::Match(endtok, "%name% ::"))
endtok = endtok->tokAt(2);
if (Token::Match(endtok, "%name% ;"))
usingnamespaces.push_back(tok->tokAt(2));
tok = endtok;
continue;
}
if (Token::Match(tok, "namespace %name% {")) {
scope.push_back(tok->strAt(1));
endOfScope[tok->linkAt(2)] = tok->strAt(1);
}
}
if (tok->str() == "}") {
const std::map<const Token *, std::string>::const_iterator it = endOfScope.find(tok);
if (it != endOfScope.cend())
scope.remove(it->second);
}
Token* const tok1 = tok;
if (Token::Match(tok, "%name% :: ~| %name%"))
tok = tok->next();
else if (Token::Match(tok, "%name% <") && Token::Match(tok->next()->findClosingBracket(),"> :: ~| %name%"))
tok = tok->next()->findClosingBracket()->next();
else if (usingnamespaces.empty() || tok->varId() || !tok->isName() || tok->isStandardType() || tok->tokType() == Token::eKeyword || tok->tokType() == Token::eBoolean ||
Token::Match(tok->previous(), ".|namespace|class|struct|&|&&|*|> %name%") || Token::Match(tok->previous(), "%type%| %name% ( %type%|)") || Token::Match(tok, "public:|private:|protected:") ||
(!tok->next() && Token::Match(tok->previous(), "}|; %name%")))
continue;
if (tok->strAt(-1) == "::" && tok->tokAt(-2) && tok->tokAt(-2)->isName())
continue;
while (Token::Match(tok, ":: ~| %name%")) {
tok = tok->next();
if (tok->str() == "~")
tok = tok->next();
else if (Token::Match(tok, "%name% <") && Token::Match(tok->next()->findClosingBracket(),"> :: ~| %name%"))
tok = tok->next()->findClosingBracket()->next();
else if (Token::Match(tok, "%name% ::"))
tok = tok->next();
else
break;
}
if (!tok->next())
syntaxError(tok);
if (Token::Match(tok, "%name% (") && !(tok->tokAt(2) && tok->tokAt(2)->isLiteral()))
allMemberFunctions.emplace_back(scope, usingnamespaces, tok1);
else
allMemberVars.emplace_back(scope, usingnamespaces, tok1);
}
}
std::list<ScopeInfo2> scopeInfo;
// class members..
std::map<std::string, std::map<std::string, nonneg int>> varsByClass;
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (tok->str() == "}" && !scopeInfo.empty() && tok == scopeInfo.back().bodyEnd)
scopeInfo.pop_back();
if (!Token::Match(tok, "namespace|class|struct %name% {|:|::|<"))
continue;
const std::string &scopeName(getScopeName(scopeInfo));
const std::string scopeName2(scopeName.empty() ? std::string() : (scopeName + " :: "));
std::list<const Token*> classnameTokens{ tok->next() };
Token* tokStart = tok->tokAt(2);
while (Token::Match(tokStart, ":: %name%") || tokStart->str() == "<") {
if (tokStart->str() == "<") {
// skip the template part
Token* closeTok = tokStart->findClosingBracket();
if (!closeTok)
syntaxError(tok);
tokStart = closeTok->next();
} else {
classnameTokens.push_back(tokStart->next());
tokStart = tokStart->tokAt(2);
}
if (!tokStart)
syntaxError(tok);
}
std::string classname;
for (const Token *it : classnameTokens)
classname += (classname.empty() ? "" : " :: ") + it->str();
std::map<std::string, nonneg int> &thisClassVars = varsByClass[scopeName2 + classname];
while (Token::Match(tokStart, ":|::|,|%name%")) {
if (Token::Match(tokStart, "%name% <")) { // TODO: why skip templates?
tokStart = tokStart->next()->findClosingBracket();
if (tokStart)
tokStart = tokStart->next();
continue;
}
if (Token::Match(tokStart, "%name% ,|{")) {
std::string baseClassName = tokStart->str();
const Token* baseStart = tokStart;
while (Token::Match(baseStart->tokAt(-2), "%name% ::")) { // build base class name
baseClassName.insert(0, baseStart->strAt(-2) + " :: ");
baseStart = baseStart->tokAt(-2);
}
std::string scopeName3(scopeName2);
while (!scopeName3.empty()) {
const std::string name = scopeName3 + baseClassName;
if (varsByClass.find(name) != varsByClass.end()) {
baseClassName = name;
break;
}
// Remove last scope name
if (scopeName3.size() <= 8)
break;
scopeName3.erase(scopeName3.size() - 4);
const std::string::size_type pos = scopeName3.rfind(" :: ");
if (pos == std::string::npos)
break;
scopeName3.erase(pos + 4);
}
const std::map<std::string, nonneg int>& baseClassVars = varsByClass[baseClassName];
thisClassVars.insert(baseClassVars.cbegin(), baseClassVars.cend());
}
tokStart = tokStart->next();
}
if (!Token::simpleMatch(tokStart, "{"))
continue;
// What member variables are there in this class?
std::transform(classnameTokens.cbegin(), classnameTokens.cend(), std::back_inserter(scopeInfo), [&](const Token* tok) {
return ScopeInfo2(tok->str(), tokStart->link());
});
for (Token *tok2 = tokStart->next(); tok2 && tok2 != tokStart->link(); tok2 = tok2->next()) {
// skip parentheses..
if (tok2->link()) {
if (tok2->str() == "(") {
Token *funcstart = const_cast<Token*>(isFunctionHead(tok2, "{"));
if (funcstart) {
setVarIdClassFunction(scopeName2 + classname, funcstart, funcstart->link(), thisClassVars, structMembers, mVarId);
tok2 = funcstart->link();
continue;
}
}
if (tok2->str() == "{" && !Token::simpleMatch(tok2->previous(), "union")) {
if (tok2->strAt(-1) == ")")
setVarIdClassFunction(scopeName2 + classname, tok2, tok2->link(), thisClassVars, structMembers, mVarId);
tok2 = tok2->link();
} else if (Token::Match(tok2, "( %name%|)")) {
tok2 = tok2->link();
// Skip initialization list
if (Token::simpleMatch(tok2, ") :")) {
tok2 = skipInitializerList(tok2->next());
if (Token::simpleMatch(tok2, "{"))
tok2 = tok2->link();
}
}
}
// Found a member variable..
else if (tok2->varId() > 0)
thisClassVars[tok2->str()] = tok2->varId();
}
// Are there any member variables in this class?
if (thisClassVars.empty())
continue;
// Member variables
for (const Member &var : allMemberVars) {
Token *tok2 = matchMemberVarName(var, scopeInfo);
if (!tok2)
continue;
if (tok2->varId() == 0)
tok2->varId(thisClassVars[tok2->str()]);
}
if (isC() || tok->str() == "namespace")
continue;
// Set variable ids in member functions for this class..
for (const Member &func : allMemberFunctions) {
Token *tok2 = matchMemberFunctionName(func, scopeInfo);
if (!tok2)
continue;
if (tok2->str() == "~")
tok2 = tok2->linkAt(2);
else
tok2 = tok2->linkAt(1);
// If this is a function implementation.. add it to funclist
Token * start = const_cast<Token *>(isFunctionHead(tok2, "{"));
if (start) {
setVarIdClassFunction(classname, start, start->link(), thisClassVars, structMembers, mVarId);
}
if (Token::Match(tok2, ") %name% ("))
tok2 = tok2->linkAt(2);
// constructor with initializer list
if (!Token::Match(tok2, ") : ::| %name%"))
continue;
Token *tok3 = tok2;
while (Token::Match(tok3, "[)}] [,:]")) {
tok3 = tok3->tokAt(2);
if (Token::Match(tok3, ":: %name%"))
tok3 = tok3->next();
while (Token::Match(tok3, "%name% :: %name%"))
tok3 = tok3->tokAt(2);
if (!Token::Match(tok3, "%name% (|{|<"))
break;
// set varid
const std::map<std::string, nonneg int>::const_iterator varpos = thisClassVars.find(tok3->str());
if (varpos != thisClassVars.end())
tok3->varId(varpos->second);
// goto end of var
if (tok3->strAt(1) == "<") {
tok3 = tok3->next()->findClosingBracket();
if (tok3 && tok3->next() && tok3->linkAt(1))
tok3 = tok3->linkAt(1);
} else
tok3 = tok3->linkAt(1);
}
if (Token::Match(tok3, ")|} {")) {
setVarIdClassFunction(classname, tok2, tok3->linkAt(1), thisClassVars, structMembers, mVarId);
}
}
}
}
static void linkBrackets(const Tokenizer & tokenizer, std::stack<const Token*>& type, std::stack<Token*>& links, Token * const token, const char open, const char close)
{
if (token->str()[0] == open) {
links.push(token);
type.push(token);
} else if (token->str()[0] == close) {
if (links.empty()) {
// Error, { and } don't match.
tokenizer.unmatchedToken(token);
}
if (type.top()->str()[0] != open) {
tokenizer.unmatchedToken(type.top());
}
type.pop();
Token::createMutualLinks(links.top(), token);
links.pop();
}
}
void Tokenizer::createLinks()
{
std::stack<const Token*> type;
std::stack<Token*> links1;
std::stack<Token*> links2;
std::stack<Token*> links3;
for (Token *token = list.front(); token; token = token->next()) {
if (token->link()) {
token->link(nullptr);
}
linkBrackets(*this, type, links1, token, '{', '}');
linkBrackets(*this, type, links2, token, '(', ')');
linkBrackets(*this, type, links3, token, '[', ']');
}
if (!links1.empty()) {
// Error, { and } don't match.
unmatchedToken(links1.top());
}
if (!links2.empty()) {
// Error, ( and ) don't match.
unmatchedToken(links2.top());
}
if (!links3.empty()) {
// Error, [ and ] don't match.
unmatchedToken(links3.top());
}
}
void Tokenizer::createLinks2()
{
if (isC())
return;
bool isStruct = false;
std::stack<Token*> type;
std::stack<Token*> templateTokens;
for (Token *token = list.front(); token; token = token->next()) {
if (Token::Match(token, "%name%|> %name% [:<]"))
isStruct = true;
else if (Token::Match(token, "[;{}]"))
isStruct = false;
if (token->link()) {
if (Token::Match(token, "{|[|("))
type.push(token);
else if (!type.empty() && Token::Match(token, "}|]|)")) {
while (type.top()->str() == "<") {
if (!templateTokens.empty() && templateTokens.top()->next() == type.top())
templateTokens.pop();
type.pop();
}
type.pop();
}
} else if (templateTokens.empty() && !isStruct && Token::Match(token, "%oror%|&&|;")) {
if (Token::Match(token, "&& [,>]"))
continue;
// If there is some such code: A<B||C>..
// Then this is probably a template instantiation if either "B" or "C" has comparisons
if (token->tokType() == Token::eLogicalOp && !type.empty() && type.top()->str() == "<") {
const Token *prev = token->previous();
bool foundComparison = false;
while (Token::Match(prev, "%name%|%num%|%str%|%cop%|)|]") && prev != type.top()) {
if (prev->str() == ")" || prev->str() == "]")
prev = prev->link();
else if (prev->tokType() == Token::eLogicalOp)
break;
else if (prev->isComparisonOp())
foundComparison = true;
prev = prev->previous();
}
if (prev == type.top() && foundComparison)
continue;
const Token *next = token->next();
foundComparison = false;
while (Token::Match(next, "%name%|%num%|%str%|%cop%|(|[") && next->str() != ">") {
if (next->str() == "(" || next->str() == "[")
next = next->link();
else if (next->tokType() == Token::eLogicalOp)
break;
else if (next->isComparisonOp())
foundComparison = true;
next = next->next();
}
if (next && next->str() == ">" && foundComparison)
continue;
}
while (!type.empty() && type.top()->str() == "<") {
const Token* end = type.top()->findClosingBracket();
if (Token::Match(end, "> %comp%|;|.|=|{|(|::"))
break;
// Variable declaration
if (Token::Match(end, "> %var% ;") && (type.top()->tokAt(-2) == nullptr || Token::Match(type.top()->tokAt(-2), ";|}|{")))
break;
type.pop();
}
} else if (token->str() == "<" &&
((token->previous() && (token->previous()->isTemplate() ||
(token->previous()->isName() && !token->previous()->varId()) ||
(token->strAt(-1) == "]" && (!Token::Match(token->linkAt(-1)->previous(), "%name%|)") || token->linkAt(-1)->previous()->isKeyword())) ||
(token->strAt(-1) == ")" && token->linkAt(-1)->strAt(-1) == "operator"))) ||
Token::Match(token->next(), ">|>>"))) {
type.push(token);
if (token->strAt(-1) == "template")
templateTokens.push(token);
} else if (token->str() == ">" || token->str() == ">>") {
if (type.empty() || type.top()->str() != "<") // < and > don't match.
continue;
Token * const top1 = type.top();
type.pop();
Token * const top2 = type.empty() ? nullptr : type.top();
type.push(top1);
if (!top2 || top2->str() != "<") {
if (token->str() == ">>")
continue;
if (!Token::Match(token->next(), "%name%|%cop%|%assign%|::|,|(|)|{|}|;|[|]|:|.|=|?|...") &&
!Token::Match(token->next(), "&& %name% ="))
continue;
}
if (token->str() == ">>" && top1 && top2) {
type.pop();
type.pop();
// Split the angle brackets
token->str(">");
Token::createMutualLinks(top1, token->insertTokenBefore(">"));
Token::createMutualLinks(top2, token);
if (templateTokens.size() == 2 && (top1 == templateTokens.top() || top2 == templateTokens.top())) {
templateTokens.pop();
templateTokens.pop();
}
} else {
type.pop();
if (Token::Match(token, "> %name%") && !token->next()->isKeyword() &&
Token::Match(top1->tokAt(-2), "%op% %name% <") && top1->strAt(-2) != "<" &&
(templateTokens.empty() || top1 != templateTokens.top()))
continue;
Token::createMutualLinks(top1, token);
if (!templateTokens.empty() && top1 == templateTokens.top())
templateTokens.pop();
}
}
}
}
void Tokenizer::markCppCasts()
{
if (isC())
return;
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "const_cast|dynamic_cast|reinterpret_cast|static_cast")) {
if (!Token::simpleMatch(tok->next(), "<") || !Token::simpleMatch(tok->linkAt(1), "> ("))
syntaxError(tok);
tok = tok->linkAt(1)->next();
tok->isCast(true);
}
}
}
void Tokenizer::sizeofAddParentheses()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "sizeof !!("))
continue;
if (tok->next()->isLiteral() || Token::Match(tok->next(), "%name%|*|~|!|&")) {
Token *endToken = tok->next();
while (Token::simpleMatch(endToken, "* *"))
endToken = endToken->next();
while (Token::Match(endToken->next(), "%name%|%num%|%str%|[|(|.|::|++|--|!|~") || (Token::Match(endToken, "%type% * %op%|?|:|const|;|,"))) {
if (Token::Match(endToken->next(), "(|["))
endToken = endToken->linkAt(1);
else
endToken = endToken->next();
}
// Add ( after sizeof and ) behind endToken
tok->insertToken("(");
endToken->insertToken(")");
Token::createMutualLinks(tok->next(), endToken->next());
}
}
}
bool Tokenizer::simplifyTokenList1(const char FileName[])
{
if (Settings::terminated())
return false;
// if MACRO
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "if|for|while|BOOST_FOREACH %name% (")) {
if (Token::simpleMatch(tok, "for each")) {
// 'for each ( )' -> 'asm ( )'
tok->str("asm");
tok->deleteNext();
} else if (tok->strAt(1) == "constexpr") {
tok->deleteNext();
tok->isConstexpr(true);
} else {
syntaxError(tok);
}
}
}
// Is there C++ code in C file?
validateC();
// Combine strings and character literals, e.g. L"string", L'c', "string1" "string2"
combineStringAndCharLiterals();
// replace inline SQL with "asm()" (Oracle PRO*C). Ticket: #1959
simplifySQL();
createLinks();
// Simplify debug intrinsics
simplifyDebug();
removePragma();
// Simplify the C alternative tokens (and, or, etc.)
simplifyCAlternativeTokens();
simplifyFunctionTryCatch();
simplifyHeadersAndUnusedTemplates();
// Remove __asm..
simplifyAsm();
// foo < bar < >> => foo < bar < > >
if (isCPP() || mSettings.daca)
splitTemplateRightAngleBrackets(!isCPP());
// Remove extra "template" tokens that are not used by cppcheck
removeExtraTemplateKeywords();
simplifySpaceshipOperator();
// @..
simplifyAt();
// Remove __declspec()
simplifyDeclspec();
// Remove "inline", "register", and "restrict"
simplifyKeyword();
// Remove [[attribute]]
simplifyCPPAttribute();
// remove __attribute__((?))
simplifyAttribute();
validate();
const SHOWTIME_MODES showTime = mTimerResults ? mSettings.showtime : SHOWTIME_MODES::SHOWTIME_NONE;
// Bail out if code is garbage
Timer::run("Tokenizer::simplifyTokens1::simplifyTokenList1::findGarbageCode", showTime, mTimerResults, [&]() {
findGarbageCode();
});
checkConfiguration();
// if (x) MACRO() ..
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "if (")) {
tok = tok->linkAt(1);
if (Token::Match(tok, ") %name% (") &&
tok->next()->isUpperCaseName() &&
Token::Match(tok->linkAt(2), ") {|else")) {
syntaxError(tok->next());
}
}
}
if (Settings::terminated())
return false;
// convert C++17 style nested namespaces to old style namespaces
simplifyNestedNamespace();
// convert c++20 coroutines
simplifyCoroutines();
// simplify namespace aliases
simplifyNamespaceAliases();
// simplify cppcheck attributes __cppcheck_?__(?)
simplifyCppcheckAttribute();
// Combine tokens..
combineOperators();
// combine "- %num%"
concatenateNegativeNumberAndAnyPositive();
// remove extern "C" and extern "C" {}
if (isCPP())
simplifyExternC();
// simplify compound statements: "[;{}] ( { code; } ) ;"->"[;{}] code;"
simplifyCompoundStatements();
// check for simple syntax errors..
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "> struct {") &&
Token::simpleMatch(tok->linkAt(2), "} ;")) {
syntaxError(tok);
}
}
if (!simplifyAddBraces())
return false;
sizeofAddParentheses();
// Simplify: 0[foo] -> *(foo)
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "0 [") && tok->linkAt(1)) {
tok->str("*");
tok->next()->str("(");
tok->linkAt(1)->str(")");
}
}
if (Settings::terminated())
return false;
validate();
// simplify simple calculations inside <..>
if (isCPP()) {
Token *lt = nullptr;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "[;{}]"))
lt = nullptr;
else if (Token::Match(tok, "%type% <"))
lt = tok->next();
else if (lt && Token::Match(tok, ">|>> %name%|::|(")) {
const Token * const end = tok;
for (tok = lt; tok != end; tok = tok->next()) {
if (tok->isNumber())
TemplateSimplifier::simplifyNumericCalculations(tok);
}
lt = tok->next();
}
}
}
// Convert K&R function declarations to modern C
simplifyVarDecl(true);
simplifyFunctionParameters();
// simplify case ranges (gcc extension)
simplifyCaseRange();
// simplify labels and 'case|default'-like syntaxes
simplifyLabelsCaseDefault();
if (!isC() && !mSettings.library.markupFile(FileName)) {
findComplicatedSyntaxErrorsInTemplates();
}
if (Settings::terminated())
return false;
// remove calling conventions __cdecl, __stdcall..
simplifyCallingConvention();
addSemicolonAfterUnknownMacro();
// remove some unhandled macros in global scope
removeMacrosInGlobalScope();
// remove undefined macro in class definition:
// class DLLEXPORT Fred { };
// class Fred FINAL : Base { };
removeMacroInClassDef();
// That call here fixes #7190
validate();
// remove unnecessary member qualification..
removeUnnecessaryQualification();
// convert Microsoft memory functions
simplifyMicrosoftMemoryFunctions();
// convert Microsoft string functions
simplifyMicrosoftStringFunctions();
if (Settings::terminated())
return false;
// remove Borland stuff..
simplifyBorland();
// syntax error: enum with typedef in it
checkForEnumsWithTypedef();
// Add parentheses to ternary operator where necessary
prepareTernaryOpForAST();
// Change initialisation of variable to assignment
simplifyInitVar();
// Split up variable declarations.
simplifyVarDecl(false);
reportUnknownMacros();
simplifyTypedefLHS();
// typedef..
Timer::run("Tokenizer::simplifyTokens1::simplifyTokenList1::simplifyTypedef", showTime, mTimerResults, [&]() {
simplifyTypedef();
});
// using A = B;
while (simplifyUsing())
;
// Add parentheses to ternary operator where necessary
// TODO: this is only necessary if one typedef simplification had a comma and was used within ?:
// If typedef handling is refactored and moved to symboldatabase someday we can remove this
prepareTernaryOpForAST();
// class x y {
if (isCPP() && mSettings.severity.isEnabled(Severity::information)) {
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "class %type% %type% [:{]")) {
unhandled_macro_class_x_y(tok);
}
}
}
// catch bad typedef canonicalization
//
// to reproduce bad typedef, download upx-ucl from:
// http://packages.debian.org/sid/upx-ucl
// analyse the file src/stub/src/i386-linux.elf.interp-main.c
validate();
// The simplify enum have inner loops
if (Settings::terminated())
return false;
// Put ^{} statements in asm()
simplifyAsm2();
// When the assembly code has been cleaned up, no @ is allowed
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "(") {
const Token *tok1 = tok;
tok = tok->link();
if (!tok)
syntaxError(tok1);
} else if (tok->str() == "@") {
syntaxError(tok);
}
}
// Order keywords "static" and "const"
simplifyStaticConst();
// convert platform dependent types to standard types
// 32 bits: size_t -> unsigned long
// 64 bits: size_t -> unsigned long long
list.simplifyPlatformTypes();
// collapse compound standard types into a single token
// unsigned long long int => long (with _isUnsigned=true,_isLong=true)
list.simplifyStdType();
if (Settings::terminated())
return false;
// simplify bit fields..
simplifyBitfields();
if (Settings::terminated())
return false;
// struct simplification "struct S {} s; => struct S { } ; S s ;
simplifyStructDecl();
if (Settings::terminated())
return false;
// x = ({ 123; }); => { x = 123; }
simplifyAssignmentBlock();
if (Settings::terminated())
return false;
simplifyVariableMultipleAssign();
// Collapse operator name tokens into single token
// operator = => operator=
simplifyOperatorName();
// Remove redundant parentheses
simplifyRedundantParentheses();
if (isCPP()) {
simplifyTypeIntrinsics();
// Handle templates..
Timer::run("Tokenizer::simplifyTokens1::simplifyTokenList1::simplifyTemplates", showTime, mTimerResults, [&]() {
simplifyTemplates();
});
// The simplifyTemplates have inner loops
if (Settings::terminated())
return false;
validate(); // #6847 - invalid code
}
// Simplify pointer to standard types (C only)
simplifyPointerToStandardType();
// simplify function pointers
simplifyFunctionPointers();
// Change initialisation of variable to assignment
simplifyInitVar();
// Split up variable declarations.
simplifyVarDecl(false);
elseif();
validate(); // #6772 "segmentation fault (invalid code) in Tokenizer::setVarId"
Timer::run("Tokenizer::simplifyTokens1::simplifyTokenList1::setVarId", showTime, mTimerResults, [&](){
setVarId();
});
// Link < with >
createLinks2();
// Mark C++ casts
markCppCasts();
// specify array size
arraySize();
// The simplify enum might have inner loops
if (Settings::terminated())
return false;
// Add std:: in front of std classes, when using namespace std; was given
simplifyNamespaceStd();
// Change initialisation of variable to assignment
simplifyInitVar();
simplifyDoublePlusAndDoubleMinus();
simplifyArrayAccessSyntax();
Token::assignProgressValues(list.front());
removeRedundantSemicolons();
simplifyParameterVoid();
simplifyRedundantConsecutiveBraces();
simplifyEmptyNamespaces();
simplifyIfSwitchForInit();
simplifyOverloadedOperators();
validate();
list.front()->assignIndexes();
return true;
}
//---------------------------------------------------------------------------
void Tokenizer::printDebugOutput(int simplification, std::ostream &out) const
{
const bool debug = (simplification != 1U && mSettings.debugSimplified) ||
(simplification != 2U && mSettings.debugnormal);
if (debug && list.front()) {
list.front()->printOut(out, nullptr, list.getFiles());
if (mSettings.xml)
out << "<debug>" << std::endl;
if (mSymbolDatabase) {
if (mSettings.xml)
mSymbolDatabase->printXml(out);
else if (mSettings.verbose) {
mSymbolDatabase->printOut("Symbol database");
}
}
if (mSettings.verbose)
list.front()->printAst(mSettings.verbose, mSettings.xml, list.getFiles(), out);
list.front()->printValueFlow(mSettings.xml, out);
if (mSettings.xml)
out << "</debug>" << std::endl;
}
if (mSymbolDatabase && simplification == 2U && mSettings.debugwarnings) {
printUnknownTypes();
// the typeStartToken() should come before typeEndToken()
for (const Variable *var : mSymbolDatabase->variableList()) {
if (!var)
continue;
const Token * typetok = var->typeStartToken();
while (typetok && typetok != var->typeEndToken())
typetok = typetok->next();
if (typetok != var->typeEndToken()) {
reportError(var->typeStartToken(),
Severity::debug,
"debug",
"Variable::typeStartToken() of variable '" + var->name() + "' is not located before Variable::typeEndToken(). The location of the typeStartToken() is '" + var->typeStartToken()->str() + "' at line " + std::to_string(var->typeStartToken()->linenr()));
}
}
}
}
void Tokenizer::dump(std::ostream &out) const
{
// Create a xml data dump.
// The idea is not that this will be readable for humans. It's a
// data dump that 3rd party tools could load and get useful info from.
std::string outs;
std::set<const Library::Container*> containers;
outs += " <directivelist>";
outs += '\n';
for (const Directive &dir : mDirectives) {
outs += " <directive ";
outs += "file=\"";
outs += ErrorLogger::toxml(Path::getRelativePath(dir.file, mSettings.basePaths));
outs += "\" ";
outs += "linenr=\"";
outs += std::to_string(dir.linenr);
outs += "\" ";
// str might contain characters such as '"', '<' or '>' which
// could result in invalid XML, so run it through toxml().
outs += "str=\"";
outs += ErrorLogger::toxml(dir.str);
outs +="\">";
outs += '\n';
for (const auto & strToken : dir.strTokens) {
outs += " <token ";
outs += "column=\"";
outs += std::to_string(strToken.column);
outs += "\" ";
outs += "str=\"";
outs += ErrorLogger::toxml(strToken.tokStr);
outs +="\"/>";
outs += '\n';
}
outs += " </directive>";
outs += '\n';
}
outs += " </directivelist>";
outs += '\n';
// tokens..
outs += " <tokenlist>";
outs += '\n';
for (const Token *tok = list.front(); tok; tok = tok->next()) {
outs += " <token id=\"";
outs += id_string(tok);
outs += "\" file=\"";
outs += ErrorLogger::toxml(list.file(tok));
outs += "\" linenr=\"";
outs += std::to_string(tok->linenr());
outs += "\" column=\"";
outs += std::to_string(tok->column());
outs += "\"";
outs += " str=\"";
outs += ErrorLogger::toxml(tok->str());
outs += '\"';
outs += " scope=\"";
outs += id_string(tok->scope());
outs += '\"';
if (tok->isName()) {
outs += " type=\"name\"";
if (tok->isUnsigned())
outs += " isUnsigned=\"true\"";
else if (tok->isSigned())
outs += " isSigned=\"true\"";
} else if (tok->isNumber()) {
outs += " type=\"number\"";
if (MathLib::isInt(tok->str()))
outs += " isInt=\"true\"";
if (MathLib::isFloat(tok->str()))
outs += " isFloat=\"true\"";
} else if (tok->tokType() == Token::eString) {
outs += " type=\"string\" strlen=\"";
outs += std::to_string(Token::getStrLength(tok));
outs += '\"';
}
else if (tok->tokType() == Token::eChar)
outs += " type=\"char\"";
else if (tok->isBoolean())
outs += " type=\"boolean\"";
else if (tok->isOp()) {
outs += " type=\"op\"";
if (tok->isArithmeticalOp())
outs += " isArithmeticalOp=\"true\"";
else if (tok->isAssignmentOp())
outs += " isAssignmentOp=\"true\"";
else if (tok->isComparisonOp())
outs += " isComparisonOp=\"true\"";
else if (tok->tokType() == Token::eLogicalOp)
outs += " isLogicalOp=\"true\"";
}
if (tok->isCast())
outs += " isCast=\"true\"";
if (tok->isExternC())
outs += " externLang=\"C\"";
if (tok->isExpandedMacro())
outs += " macroName=\"" + tok->getMacroName() + "\"";
if (tok->isTemplateArg())
outs += " isTemplateArg=\"true\"";
if (tok->isRemovedVoidParameter())
outs += " isRemovedVoidParameter=\"true\"";
if (tok->isSplittedVarDeclComma())
outs += " isSplittedVarDeclComma=\"true\"";
if (tok->isSplittedVarDeclEq())
outs += " isSplittedVarDeclEq=\"true\"";
if (tok->isImplicitInt())
outs += " isImplicitInt=\"true\"";
if (tok->isComplex())
outs += " isComplex=\"true\"";
if (tok->isRestrict())
outs += " isRestrict=\"true\"";
if (tok->isAtomic())
outs += " isAtomic=\"true\"";
if (tok->isAttributeExport())
outs += " isAttributeExport=\"true\"";
if (tok->isAttributeMaybeUnused())
outs += " isAttributeMaybeUnused=\"true\"";
if (tok->isAttributeUnused())
outs += " isAttributeUnused=\"true\"";
if (tok->hasAttributeAlignas()) {
const std::vector<std::string>& a = tok->getAttributeAlignas();
outs += " alignas=\"" + ErrorLogger::toxml(a[0]) + "\"";
if (a.size() > 1)
// we could write all alignas expressions but currently we only need 2
outs += " alignas2=\"" + ErrorLogger::toxml(a[1]) + "\"";
}
if (tok->link()) {
outs += " link=\"";
outs += id_string(tok->link());
outs += '\"';
}
if (tok->varId() > 0) {
outs += " varId=\"";
outs += std::to_string(tok->varId());
outs += '\"';
}
if (tok->exprId() > 0) {
outs += " exprId=\"";
outs += std::to_string(tok->exprId());
outs += '\"';
}
if (tok->variable()) {
outs += " variable=\"";
outs += id_string(tok->variable());
outs += '\"';
}
if (tok->function()) {
outs += " function=\"";
outs += id_string(tok->function());
outs += '\"';
}
if (!tok->values().empty()) {
outs += " values=\"";
outs += id_string(&tok->values());
outs += '\"';
}
if (tok->type()) {
outs += " type-scope=\"";
outs += id_string(tok->type()->classScope);
outs += '\"';
}
if (tok->astParent()) {
outs += " astParent=\"";
outs += id_string(tok->astParent());
outs += '\"';
}
if (tok->astOperand1()) {
outs += " astOperand1=\"";
outs += id_string(tok->astOperand1());
outs += '\"';
}
if (tok->astOperand2()) {
outs += " astOperand2=\"";
outs += id_string(tok->astOperand2());
outs += '\"';
}
if (!tok->originalName().empty()) {
outs += " originalName=\"";
outs += tok->originalName();
outs += '\"';
}
if (tok->valueType()) {
const std::string vt = tok->valueType()->dump();
if (!vt.empty()) {
outs += ' ';
outs += vt;
}
containers.insert(tok->valueType()->container);
}
if (!tok->varId() && tok->scope()->isExecutable() && Token::Match(tok, "%name% (")) {
if (mSettings.library.isnoreturn(tok))
outs += " noreturn=\"true\"";
}
outs += "/>";
outs += '\n';
}
outs += " </tokenlist>";
outs += '\n';
out << outs;
outs.clear();
if (mSymbolDatabase)
mSymbolDatabase->printXml(out);
containers.erase(nullptr);
if (!containers.empty()) {
outs += " <containers>";
outs += '\n';
for (const Library::Container* c: containers) {
outs += " <container id=\"";
outs += id_string(c);
outs += "\" array-like-index-op=\"";
outs += bool_to_string(c->arrayLike_indexOp);
outs += "\" ";
outs += "std-string-like=\"";
outs += bool_to_string(c->stdStringLike);
outs += "\"/>";
outs += '\n';
}
outs += " </containers>";
outs += '\n';
}
if (list.front())
list.front()->printValueFlow(true, out);
outs += dumpTypedefInfo();
outs += mTemplateSimplifier->dump();
out << outs;
}
std::string Tokenizer::dumpTypedefInfo() const
{
if (mTypedefInfo.empty())
return "";
std::string outs = " <typedef-info>";
outs += '\n';
for (const TypedefInfo &typedefInfo: mTypedefInfo) {
outs += " <info";
outs += " name=\"";
outs += typedefInfo.name;
outs += "\"";
outs += " file=\"";
outs += ErrorLogger::toxml(typedefInfo.filename);
outs += "\"";
outs += " line=\"";
outs += std::to_string(typedefInfo.lineNumber);
outs += "\"";
outs += " column=\"";
outs += std::to_string(typedefInfo.column);
outs += "\"";
outs += " used=\"";
outs += std::to_string(typedefInfo.used?1:0);
outs += "\"";
outs += " isFunctionPointer=\"";
outs += std::to_string(typedefInfo.isFunctionPointer);
outs += "\"";
outs += "/>";
outs += '\n';
}
outs += " </typedef-info>";
outs += '\n';
return outs;
}
void Tokenizer::simplifyHeadersAndUnusedTemplates()
{
if (mSettings.checkHeaders && mSettings.checkUnusedTemplates)
// Full analysis. All information in the headers are kept.
return;
const bool checkHeaders = mSettings.checkHeaders;
const bool removeUnusedIncludedFunctions = !mSettings.checkHeaders;
const bool removeUnusedIncludedClasses = !mSettings.checkHeaders;
const bool removeUnusedIncludedTemplates = !mSettings.checkUnusedTemplates || !mSettings.checkHeaders;
const bool removeUnusedTemplates = !mSettings.checkUnusedTemplates;
// checkHeaders:
//
// If it is true then keep all code in the headers. It's possible
// to remove unused types/variables if false positives / false
// negatives can be avoided.
//
// If it is false, then we want to remove selected stuff from the
// headers but not *everything*. The intention here is to not damage
// the analysis of the source file. You should get all warnings in
// the source file. You should not get false positives.
// functions and types to keep
std::set<std::string> keep;
for (const Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->isCpp() && Token::simpleMatch(tok, "template <")) {
const Token *closingBracket = tok->next()->findClosingBracket();
if (Token::Match(closingBracket, "> class|struct %name% {"))
tok = closingBracket->linkAt(3);
}
if (!tok->isName() || tok->isKeyword())
continue;
if (!checkHeaders && tok->fileIndex() != 0)
continue;
if (Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) {
keep.insert(tok->str());
continue;
}
if (Token::Match(tok, "%name% %name%|::|*|&|<")) {
keep.insert(tok->str());
}
}
const std::set<std::string> functionStart{"static", "const", "unsigned", "signed", "void", "bool", "char", "short", "int", "long", "float", "*"};
for (Token *tok = list.front(); tok; tok = tok->next()) {
const bool isIncluded = (tok->fileIndex() != 0);
// Remove executable code
if (isIncluded && !mSettings.checkHeaders && tok->str() == "{") {
// TODO: We probably need to keep the executable code if this function is called from the source file.
const Token *prev = tok->previous();
while (prev && prev->isName())
prev = prev->previous();
if (Token::simpleMatch(prev, ")")) {
// Replace all tokens from { to } with a ";".
Token::eraseTokens(tok,tok->link()->next());
tok->str(";");
tok->link(nullptr);
}
}
if (!tok->previous() || Token::Match(tok->previous(), "[;{}]")) {
// Remove unused function declarations
if (isIncluded && removeUnusedIncludedFunctions) {
while (true) {
Token *start = tok;
while (start && functionStart.find(start->str()) != functionStart.end())
start = start->next();
if (Token::Match(start, "%name% (") && Token::Match(start->linkAt(1), ") const| ;") && keep.find(start->str()) == keep.end()) {
Token::eraseTokens(tok, start->linkAt(1)->tokAt(2));
tok->deleteThis();
} else
break;
}
}
if (isIncluded && removeUnusedIncludedClasses) {
if (Token::Match(tok, "class|struct %name% [:{]") && keep.find(tok->strAt(1)) == keep.end()) {
// Remove this class/struct
const Token *endToken = tok->tokAt(2);
if (endToken->str() == ":") {
endToken = endToken->next();
while (Token::Match(endToken, "%name%|,"))
endToken = endToken->next();
}
if (endToken && endToken->str() == "{" && Token::simpleMatch(endToken->link(), "} ;")) {
Token::eraseTokens(tok, endToken->link()->next());
tok->deleteThis();
}
}
}
if (removeUnusedTemplates || (isIncluded && removeUnusedIncludedTemplates)) {
if (Token::Match(tok, "template < %name%")) {
const Token *closingBracket = tok->next()->findClosingBracket();
if (Token::Match(closingBracket, "> class|struct %name% [;:{]") && keep.find(closingBracket->strAt(2)) == keep.end()) {
const Token *endToken = closingBracket->tokAt(3);
if (endToken->str() == ":") {
endToken = endToken->next();
while (Token::Match(endToken, "%name%|,"))
endToken = endToken->next();
}
if (endToken && endToken->str() == "{")
endToken = endToken->link()->next();
if (endToken && endToken->str() == ";") {
Token::eraseTokens(tok, endToken);
tok->deleteThis();
}
} else if (Token::Match(closingBracket, "> %type% %name% (") && Token::simpleMatch(closingBracket->linkAt(3), ") {") && keep.find(closingBracket->strAt(2)) == keep.end()) {
const Token *endToken = closingBracket->linkAt(3)->linkAt(1)->next();
Token::eraseTokens(tok, endToken);
tok->deleteThis();
}
}
}
}
}
}
void Tokenizer::removeExtraTemplateKeywords()
{
if (isCPP()) {
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name%|>|) .|:: template %name%")) {
tok->next()->deleteNext();
Token* templateName = tok->tokAt(2);
while (Token::Match(templateName, "%name%|::")) {
templateName->isTemplate(true);
templateName = templateName->next();
}
if (!templateName)
syntaxError(tok);
if (Token::Match(templateName->previous(), "operator %op%|(")) {
templateName->isTemplate(true);
if (templateName->str() == "(" && templateName->link())
templateName->link()->isTemplate(true);
}
}
}
}
}
static std::string getExpression(const Token *tok)
{
std::string line;
for (const Token *prev = tok->previous(); prev && !Token::Match(prev, "[;{}]"); prev = prev->previous())
line = prev->str() + " " + line;
line += "!!!" + tok->str() + "!!!";
for (const Token *next = tok->next(); next && !Token::Match(next, "[;{}]"); next = next->next())
line += " " + next->str();
return line;
}
void Tokenizer::splitTemplateRightAngleBrackets(bool check)
{
std::vector<std::pair<std::string, int>> vars;
int scopeLevel = 0;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "{")
++scopeLevel;
else if (tok->str() == "}") {
vars.erase(std::remove_if(vars.begin(), vars.end(), [scopeLevel](const std::pair<std::string, int>& v) {
return v.second == scopeLevel;
}), vars.end());
--scopeLevel;
}
if (Token::Match(tok, "[;{}] %type% %type% [;,=]") && tok->next()->isStandardType())
vars.emplace_back(tok->strAt(2), scopeLevel);
// Ticket #6181: normalize C++11 template parameter list closing syntax
if (tok->previous() && tok->str() == "<" && TemplateSimplifier::templateParameters(tok) && std::none_of(vars.begin(), vars.end(), [&](const std::pair<std::string, int>& v) {
return v.first == tok->strAt(-1);
})) {
Token *endTok = tok->findClosingBracket();
if (check) {
if (Token::Match(endTok, ">>|>>="))
reportError(tok, Severity::debug, "dacaWrongSplitTemplateRightAngleBrackets", "bad closing bracket for !!!<!!!: " + getExpression(tok), false);
continue;
}
if (endTok && endTok->str() == ">>") {
endTok->str(">");
endTok->insertToken(">");
} else if (endTok && endTok->str() == ">>=") {
endTok->str(">");
endTok->insertToken("=");
endTok->insertToken(">");
}
} else if (Token::Match(tok, "class|struct|union|=|:|public|protected|private %name% <") && std::none_of(vars.begin(), vars.end(), [&](const std::pair<std::string, int>& v) {
return v.first == tok->strAt(1);
})) {
Token *endTok = tok->tokAt(2)->findClosingBracket();
if (check) {
if (Token::simpleMatch(endTok, ">>"))
reportError(tok, Severity::debug, "dacaWrongSplitTemplateRightAngleBrackets", "bad closing bracket for !!!<!!!: " + getExpression(tok), false);
continue;
}
if (Token::Match(endTok, ">> ;|{|%type%")) {
endTok->str(">");
endTok->insertToken(">");
}
}
}
}
void Tokenizer::removeMacrosInGlobalScope()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "(") {
tok = tok->link();
if (Token::Match(tok, ") %type% {") &&
!tok->next()->isStandardType() &&
!tok->next()->isKeyword() &&
!Token::Match(tok->next(), "override|final") &&
tok->next()->isUpperCaseName())
tok->deleteNext();
}
if (Token::Match(tok, "%type%") && tok->isUpperCaseName() &&
(!tok->previous() || Token::Match(tok->previous(), "[;{}]") || (tok->previous()->isName() && endsWith(tok->strAt(-1), ':')))) {
const Token *tok2 = tok->next();
if (tok2 && tok2->str() == "(")
tok2 = tok2->link()->next();
// Several unknown macros...
while (Token::Match(tok2, "%type% (") && tok2->isUpperCaseName())
tok2 = tok2->linkAt(1)->next();
if (Token::Match(tok, "%name% (") && Token::Match(tok2, "%name% *|&|::|<| %name%") &&
!Token::Match(tok2, "requires|namespace|class|struct|union|private:|protected:|public:"))
unknownMacroError(tok);
if (Token::Match(tok, "%type% (") && Token::Match(tok2, "%type% (") && !Token::Match(tok2, "noexcept|throw") && isFunctionHead(tok2->next(), ":;{"))
unknownMacroError(tok);
// remove unknown macros before namespace|class|struct|union
if (Token::Match(tok2, "namespace|class|struct|union")) {
// is there a "{" for?
const Token *tok3 = tok2;
while (tok3 && !Token::Match(tok3,"[;{}()]"))
tok3 = tok3->next();
if (tok3 && tok3->str() == "{") {
Token::eraseTokens(tok, tok2);
tok->deleteThis();
}
continue;
}
// replace unknown macros before foo(
/*
if (Token::Match(tok2, "%type% (") && isFunctionHead(tok2->next(), "{")) {
std::string typeName;
for (const Token* tok3 = tok; tok3 != tok2; tok3 = tok3->next())
typeName += tok3->str();
Token::eraseTokens(tok, tok2);
tok->str(typeName);
}
*/
// remove unknown macros before foo::foo(
if (Token::Match(tok2, "%type% :: %type%")) {
const Token *tok3 = tok2;
while (Token::Match(tok3, "%type% :: %type% ::"))
tok3 = tok3->tokAt(2);
if (Token::Match(tok3, "%type% :: %type% (") && tok3->str() == tok3->strAt(2)) {
Token::eraseTokens(tok, tok2);
tok->deleteThis();
}
continue;
}
}
// Skip executable scopes
if (tok->str() == "{") {
const Token *prev = tok->previous();
while (prev && prev->isName())
prev = prev->previous();
if (prev && prev->str() == ")")
tok = tok->link();
}
}
}
//---------------------------------------------------------------------------
void Tokenizer::removePragma()
{
if (isC() && mSettings.standards.c == Standards::C89)
return;
if (isCPP() && mSettings.standards.cpp == Standards::CPP03)
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (Token::simpleMatch(tok, "_Pragma (")) {
Token::eraseTokens(tok, tok->linkAt(1)->next());
tok->deleteThis();
}
}
}
//---------------------------------------------------------------------------
void Tokenizer::removeMacroInClassDef()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "class|struct %name% %name% final| {|:"))
continue;
const bool nextIsUppercase = tok->next()->isUpperCaseName();
const bool afterNextIsUppercase = tok->tokAt(2)->isUpperCaseName();
if (nextIsUppercase && !afterNextIsUppercase)
tok->deleteNext();
else if (!nextIsUppercase && afterNextIsUppercase)
tok->next()->deleteNext();
}
}
//---------------------------------------------------------------------------
void Tokenizer::addSemicolonAfterUnknownMacro()
{
if (!isCPP())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() != ")")
continue;
const Token *macro = tok->link() ? tok->link()->previous() : nullptr;
if (!macro || !macro->isName())
continue;
if (Token::simpleMatch(tok, ") try") && !Token::Match(macro, "if|for|while"))
tok->insertToken(";");
else if (Token::simpleMatch(tok, ") using"))
tok->insertToken(";");
}
}
//---------------------------------------------------------------------------
void Tokenizer::simplifyEmptyNamespaces()
{
if (isC())
return;
bool goback = false;
for (Token *tok = list.front(); tok; tok = tok ? tok->next() : nullptr) {
if (goback) {
tok = tok->previous();
goback = false;
}
if (Token::Match(tok, "(|[|{")) {
tok = tok->link();
continue;
}
if (!Token::Match(tok, "namespace %name%| {"))
continue;
const bool isAnonymousNS = tok->strAt(1) == "{";
if (tok->strAt(3 - isAnonymousNS) == "}") {
tok->deleteNext(3 - isAnonymousNS); // remove '%name%| { }'
if (!tok->previous()) {
// remove 'namespace' or replace it with ';' if isolated
tok->deleteThis();
goback = true;
} else { // '%any% namespace %any%'
tok = tok->previous(); // goto previous token
tok->deleteNext(); // remove next token: 'namespace'
if (tok->str() == "{") {
// Go back in case we were within a namespace that's empty now
tok = tok->tokAt(-2) ? tok->tokAt(-2) : tok->previous();
goback = true;
}
}
} else {
tok = tok->tokAt(2 - isAnonymousNS);
}
}
}
void Tokenizer::removeRedundantSemicolons()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->link() && tok->str() == "(") {
tok = tok->link();
continue;
}
for (;;) {
if (Token::simpleMatch(tok, "; ;")) {
tok->deleteNext();
} else if (Token::simpleMatch(tok, "; { ; }")) {
tok->deleteNext(3);
} else {
break;
}
}
}
}
bool Tokenizer::simplifyAddBraces()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
Token const * tokRet=simplifyAddBracesToCommand(tok);
if (!tokRet)
return false;
}
return true;
}
Token *Tokenizer::simplifyAddBracesToCommand(Token *tok)
{
Token * tokEnd=tok;
if (Token::Match(tok,"for|switch|BOOST_FOREACH")) {
tokEnd=simplifyAddBracesPair(tok,true);
} else if (tok->str()=="while") {
Token *tokPossibleDo=tok->previous();
if (Token::simpleMatch(tok->previous(), "{"))
tokPossibleDo = nullptr;
else if (Token::simpleMatch(tokPossibleDo,"}"))
tokPossibleDo = tokPossibleDo->link();
if (!tokPossibleDo || tokPossibleDo->strAt(-1) != "do")
tokEnd=simplifyAddBracesPair(tok,true);
} else if (tok->str()=="do") {
tokEnd=simplifyAddBracesPair(tok,false);
if (tokEnd!=tok) {
// walk on to next token, i.e. "while"
// such that simplifyAddBracesPair does not close other braces
// before the "while"
if (tokEnd) {
tokEnd=tokEnd->next();
if (!tokEnd || tokEnd->str()!="while") // no while
syntaxError(tok);
}
}
} else if (tok->str()=="if" && !Token::simpleMatch(tok->tokAt(-2), "operator \"\"")) {
tokEnd=simplifyAddBracesPair(tok,true);
if (!tokEnd)
return nullptr;
if (tokEnd->strAt(1) == "else") {
Token * tokEndNextNext= tokEnd->tokAt(2);
if (!tokEndNextNext || tokEndNextNext->str() == "}")
syntaxError(tokEndNextNext);
if (tokEndNextNext->str() == "if")
// do not change "else if ..." to "else { if ... }"
tokEnd=simplifyAddBracesToCommand(tokEndNextNext);
else
tokEnd=simplifyAddBracesPair(tokEnd->next(),false);
}
}
return tokEnd;
}
Token *Tokenizer::simplifyAddBracesPair(Token *tok, bool commandWithCondition)
{
Token * tokCondition=tok->next();
if (!tokCondition) // Missing condition
return tok;
Token *tokAfterCondition=tokCondition;
if (commandWithCondition) {
if (tokCondition->str()=="(")
tokAfterCondition=tokCondition->link();
else
syntaxError(tok); // Bad condition
if (!tokAfterCondition || tokAfterCondition->strAt(1) == "]")
syntaxError(tok); // Bad condition
tokAfterCondition=tokAfterCondition->next();
if (!tokAfterCondition || Token::Match(tokAfterCondition, ")|}|,")) {
// No tokens left where to add braces around
return tok;
}
}
// Skip labels
Token * tokStatement = tokAfterCondition;
while (true) {
if (Token::Match(tokStatement, "%name% :"))
tokStatement = tokStatement->tokAt(2);
else if (tokStatement->str() == "case") {
tokStatement = skipCaseLabel(tokStatement);
if (!tokStatement)
return tok;
if (tokStatement->str() != ":")
syntaxError(tokStatement);
tokStatement = tokStatement->next();
} else
break;
if (!tokStatement)
return tok;
}
Token * tokBracesEnd=nullptr;
if (tokStatement->str() == "{") {
// already surrounded by braces
if (tokStatement != tokAfterCondition) {
// Move the opening brace before labels
Token::move(tokStatement, tokStatement, tokAfterCondition->previous());
}
tokBracesEnd = tokStatement->link();
} else if (Token::simpleMatch(tokStatement, "try {") &&
Token::simpleMatch(tokStatement->linkAt(1), "} catch (")) {
tokAfterCondition->previous()->insertToken("{");
Token * tokOpenBrace = tokAfterCondition->previous();
Token * tokEnd = tokStatement->linkAt(1)->linkAt(2)->linkAt(1);
if (!tokEnd) {
syntaxError(tokStatement);
}
tokEnd->insertToken("}");
Token * tokCloseBrace = tokEnd->next();
Token::createMutualLinks(tokOpenBrace, tokCloseBrace);
tokBracesEnd = tokCloseBrace;
} else {
Token * tokEnd = simplifyAddBracesToCommand(tokStatement);
if (!tokEnd) // Ticket #4887
return tok;
if (tokEnd->str()!="}") {
// Token does not end with brace
// Look for ; to add own closing brace after it
while (tokEnd && !Token::Match(tokEnd, ";|)|}")) {
if (tokEnd->tokType()==Token::eBracket || tokEnd->str() == "(") {
tokEnd = tokEnd->link();
if (!tokEnd) {
// Inner bracket does not close
return tok;
}
}
tokEnd=tokEnd->next();
}
if (!tokEnd || tokEnd->str() != ";") {
// No trailing ;
if (tokStatement->isUpperCaseName())
unknownMacroError(tokStatement);
else
syntaxError(tokStatement);
}
}
tokAfterCondition->previous()->insertToken("{");
Token * tokOpenBrace=tokAfterCondition->previous();
tokEnd->insertToken("}");
Token * tokCloseBrace=tokEnd->next();
Token::createMutualLinks(tokOpenBrace,tokCloseBrace);
tokBracesEnd=tokCloseBrace;
}
return tokBracesEnd;
}
void Tokenizer::simplifyFunctionParameters()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->link() && Token::Match(tok, "{|[|(")) {
tok = tok->link();
}
// Find the function e.g. foo( x ) or foo( x, y )
else if (Token::Match(tok, "%name% ( %name% [,)]") &&
!(tok->strAt(-1) == ":" || tok->strAt(-1) == "," || tok->strAt(-1) == "::")) {
// We have found old style function, now we need to change it
// First step: Get list of argument names in parentheses
std::map<std::string, Token *> argumentNames;
bool bailOut = false;
const Token * tokparam = nullptr;
//take count of the function name..
const std::string& funcName(tok->str());
//floating token used to check for parameters
Token *tok1 = tok;
while (nullptr != (tok1 = tok1->tokAt(2))) {
if (!Token::Match(tok1, "%name% [,)]")) {
bailOut = true;
break;
}
//same parameters: take note of the parameter
if (argumentNames.find(tok1->str()) != argumentNames.end())
tokparam = tok1;
else if (tok1->str() != funcName)
argumentNames[tok1->str()] = tok1;
else {
if (tok1->strAt(1) == ")") {
if (tok1->strAt(-1) == ",") {
tok1 = tok1->tokAt(-2);
tok1->deleteNext(2);
} else {
tok1 = tok1->previous();
tok1->deleteNext();
bailOut = true;
break;
}
} else {
tok1 = tok1->tokAt(-2);
tok1->next()->deleteNext(2);
}
}
if (tok1->strAt(1) == ")") {
tok1 = tok1->tokAt(2);
//expect at least a type name after round brace..
if (!tok1 || !tok1->isName())
bailOut = true;
break;
}
}
//goto '('
tok = tok->next();
if (bailOut) {
tok = tok->link();
continue;
}
tok1 = tok->link()->next();
// there should be the sequence '; {' after the round parentheses
for (const Token* tok2 = tok1; tok2; tok2 = tok2->next()) {
if (Token::simpleMatch(tok2, "; {"))
break;
if (tok2->str() == "{") {
bailOut = true;
break;
}
}
if (bailOut) {
tok = tok->link();
continue;
}
// Last step: check out if the declarations between ')' and '{' match the parameters list
std::map<std::string, Token *> argumentNames2;
while (tok1 && tok1->str() != "{") {
if (Token::Match(tok1, "(|)")) {
bailOut = true;
break;
}
if (tok1->str() == ";") {
if (tokparam) {
syntaxError(tokparam);
}
Token *tok2 = tok1->previous();
while (tok2->str() == "]")
tok2 = tok2->link()->previous();
//it should be a name..
if (!tok2->isName()) {
bailOut = true;
break;
}
if (argumentNames2.find(tok2->str()) != argumentNames2.end()) {
//same parameter names...
syntaxError(tok1);
} else
argumentNames2[tok2->str()] = tok2;
if (argumentNames.find(tok2->str()) == argumentNames.end()) {
//non-matching parameter... bailout
bailOut = true;
break;
}
}
tok1 = tok1->next();
}
if (bailOut || !tok1) {
tok = tok->link();
continue;
}
//the two containers may not hold the same size...
//in that case, the missing parameters are defined as 'int'
if (argumentNames.size() != argumentNames2.size()) {
//move back 'tok1' to the last ';'
tok1 = tok1->previous();
for (const std::pair<const std::string, Token *>& argumentName : argumentNames) {
if (argumentNames2.find(argumentName.first) == argumentNames2.end()) {
//add the missing parameter argument declaration
tok1->insertToken(";");
tok1->insertToken(argumentName.first);
//register the change inside argumentNames2
argumentNames2[argumentName.first] = tok1->next();
tok1->insertToken("int");
}
}
}
while (tok->str() != ")") {
//initialize start and end tokens to be moved
Token *declStart = argumentNames2[tok->strAt(1)];
Token *declEnd = declStart;
while (declStart->strAt(-1) != ";" && declStart->strAt(-1) != ")")
declStart = declStart->previous();
while (declEnd->strAt(1) != ";" && declEnd->strAt(1) != "{")
declEnd = declEnd->next();
//remove ';' after declaration
declEnd->deleteNext();
//replace the parameter name in the parentheses with all the declaration
Token::replace(tok->next(), declStart, declEnd);
//since there are changes to tokens, put tok where tok1 is
tok = declEnd->next();
//fix up line number
if (tok->str() == ",")
tok->linenr(tok->previous()->linenr());
}
//goto forward and continue
tok = tok->linkAt(1);
}
}
}
void Tokenizer::simplifyPointerToStandardType()
{
if (!isC())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "& %name% [ 0 ] !!["))
continue;
if (!Token::Match(tok->previous(), "[,(=]"))
continue;
// Remove '[ 0 ]' suffix
Token::eraseTokens(tok->next(), tok->tokAt(5));
// Remove '&' prefix
tok = tok->previous();
if (!tok)
break;
tok->deleteNext();
}
}
void Tokenizer::simplifyFunctionPointers()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
// #2873 - do not simplify function pointer usage here:
// (void)(xy(*p)(0));
if (Token::simpleMatch(tok, ") (")) {
tok = tok->linkAt(1);
continue;
}
// check for function pointer cast
if (Token::Match(tok, "( %type% %type%| *| *| ( * ) (") ||
Token::Match(tok, "static_cast < %type% %type%| *| *| ( * ) (")) {
Token *tok1 = tok;
if (tok1->isCpp() && tok1->str() == "static_cast")
tok1 = tok1->next();
tok1 = tok1->next();
if (Token::Match(tok1->next(), "%type%"))
tok1 = tok1->next();
while (tok1->strAt(1) == "*")
tok1 = tok1->next();
// check that the cast ends
if (!Token::Match(tok1->linkAt(4), ") )|>"))
continue;
// ok simplify this function pointer cast to an ordinary pointer cast
tok1->deleteNext();
tok1->next()->deleteNext();
Token::eraseTokens(tok1->next(), tok1->linkAt(2)->next());
continue;
}
// check for start of statement
if (tok->previous() && !Token::Match(tok->previous(), "{|}|;|,|(|public:|protected:|private:"))
continue;
if (Token::Match(tok, "delete|else|return|throw|typedef"))
continue;
while (Token::Match(tok, "%type%|:: %type%|::"))
tok = tok->next();
Token *tok2 = (tok && tok->isName()) ? tok->next() : nullptr;
while (Token::Match(tok2, "*|&"))
tok2 = tok2->next();
if (!tok2 || tok2->str() != "(")
continue;
while (Token::Match(tok2, "(|:: %type%"))
tok2 = tok2->tokAt(2);
if (!Token::Match(tok2, "(|:: * *| %name%"))
continue;
tok2 = tok2->tokAt(2);
if (tok2->str() == "*")
tok2 = tok2->next();
while (Token::Match(tok2, "%type%|:: %type%|::"))
tok2 = tok2->next();
if (!Token::Match(tok2, "%name% ) (") &&
!Token::Match(tok2, "%name% [ ] ) (") &&
!(Token::Match(tok2, "%name% (") && Token::simpleMatch(tok2->linkAt(1), ") ) (")))
continue;
while (tok && tok->str() != "(")
tok = tok->next();
// check that the declaration ends
if (!tok || !tok->link() || !tok->link()->next()) {
syntaxError(nullptr);
}
Token *endTok = tok->link()->linkAt(1);
if (Token::simpleMatch(endTok, ") throw ("))
endTok = endTok->linkAt(2);
if (!Token::Match(endTok, ") const|volatile| const|volatile| ;|,|)|=|[|{"))
continue;
while (Token::Match(endTok->next(), "const|volatile"))
endTok->deleteNext();
// ok simplify this function pointer to an ordinary pointer
if (Token::simpleMatch(tok->link()->previous(), ") )")) {
// Function returning function pointer
// void (*dostuff(void))(void) {}
Token::eraseTokens(tok->link(), endTok->next());
tok->link()->deleteThis();
tok->deleteThis();
} else {
Token::eraseTokens(tok->link()->linkAt(1), endTok->next());
// remove variable names
int indent = 0;
for (Token* tok3 = tok->link()->tokAt(2); Token::Match(tok3, "%name%|*|&|[|(|)|::|,|<"); tok3 = tok3->next()) {
if (tok3->str() == ")" && --indent < 0)
break;
if (tok3->str() == "<" && tok3->link())
tok3 = tok3->link();
else if (Token::Match(tok3, "["))
tok3 = tok3->link();
else if (tok3->str() == "(") {
tok3 = tok3->link();
if (Token::simpleMatch(tok3, ") (")) {
tok3 = tok3->next();
++indent;
} else
break;
}
if (Token::Match(tok3, "%type%|*|&|> %name% [,)[]"))
tok3->deleteNext();
}
// TODO Keep this info
while (Token::Match(tok, "( %type% ::"))
tok->deleteNext(2);
}
}
}
void Tokenizer::simplifyVarDecl(const bool only_k_r_fpar)
{
simplifyVarDecl(list.front(), nullptr, only_k_r_fpar);
}
void Tokenizer::simplifyVarDecl(Token * tokBegin, const Token * const tokEnd, const bool only_k_r_fpar)
{
const bool cpp = isCPP();
const bool isCPP11 = cpp && (mSettings.standards.cpp >= Standards::CPP11);
// Split up variable declarations..
// "int a=4;" => "int a; a=4;"
bool finishedwithkr = true;
bool scopeDecl = false;
for (Token *tok = tokBegin; tok != tokEnd; tok = tok->next()) {
if (Token::Match(tok, "{|;"))
scopeDecl = false;
if (cpp) {
if (Token::Match(tok, "class|struct|namespace|union"))
scopeDecl = true;
if (Token::Match(tok, "decltype|noexcept (")) {
tok = tok->linkAt(1);
// skip decltype(...){...}
if (tok && Token::simpleMatch(tok->previous(), ") {"))
tok = tok->link();
} else if (Token::simpleMatch(tok, "= {") ||
(!scopeDecl && Token::Match(tok, "%name%|> {") &&
!Token::Match(tok, "else|try|do|const|constexpr|override|volatile|noexcept"))) {
if (!tok->linkAt(1))
syntaxError(tokBegin);
// Check for lambdas before skipping
if (Token::Match(tok->tokAt(-2), ") . %name%")) { // trailing return type
// TODO: support lambda without parameter clause?
Token* lambdaStart = tok->linkAt(-2)->previous();
if (Token::simpleMatch(lambdaStart, "]"))
lambdaStart = lambdaStart->link();
Token* lambdaEnd = findLambdaEndScope(lambdaStart);
if (lambdaEnd)
simplifyVarDecl(lambdaEnd->link()->next(), lambdaEnd, only_k_r_fpar);
} else {
for (Token* tok2 = tok->next(); tok2 != tok->linkAt(1); tok2 = tok2->next()) {
Token* lambdaEnd = findLambdaEndScope(tok2);
if (!lambdaEnd)
continue;
simplifyVarDecl(lambdaEnd->link()->next(), lambdaEnd, only_k_r_fpar);
}
}
tok = tok->linkAt(1);
}
} else if (Token::simpleMatch(tok, "= {")) {
tok = tok->linkAt(1);
}
if (!tok) {
syntaxError(tokBegin);
}
if (only_k_r_fpar && finishedwithkr) {
if (Token::Match(tok, "(|[|{")) {
tok = tok->link();
if (tok->next() && Token::Match(tok, ") !!{"))
tok = tok->next();
else
continue;
} else
continue;
} else if (tok->str() == "(") {
if (cpp) {
for (Token * tok2 = tok; tok2 && tok2 != tok->link(); tok2 = tok2->next()) {
if (Token::Match(tok2, "[(,] [")) {
// lambda function at tok2->next()
// find start of lambda body
Token * lambdaBody = tok2;
while (lambdaBody && lambdaBody != tok2->link() && lambdaBody->str() != "{")
lambdaBody = lambdaBody->next();
if (lambdaBody && lambdaBody != tok2->link() && lambdaBody->link())
simplifyVarDecl(lambdaBody, lambdaBody->link()->next(), only_k_r_fpar);
}
}
}
tok = tok->link();
}
if (!tok)
syntaxError(nullptr); // #7043 invalid code
if (tok->previous() && !Token::Match(tok->previous(), "{|}|;|)|public:|protected:|private:"))
continue;
if (Token::simpleMatch(tok, "template <"))
continue;
Token *type0 = tok;
if (!Token::Match(type0, "::|extern| %type%"))
continue;
if (Token::Match(type0, "else|return|public:|protected:|private:"))
continue;
if (isCPP11 && type0->str() == "using")
continue;
if (cpp && Token::Match(type0, "namespace|delete"))
continue;
bool isconst = false;
bool isstatic = false;
Token *tok2 = type0;
int typelen = 1;
if (Token::Match(tok2, "::|extern")) {
tok2 = tok2->next();
typelen++;
}
//check if variable is declared 'const' or 'static' or both
while (tok2) {
if (!Token::Match(tok2, "const|static|constexpr") && Token::Match(tok2, "%type% const|static")) {
tok2 = tok2->next();
++typelen;
}
if (Token::Match(tok2, "const|constexpr"))
isconst = true;
else if (Token::Match(tok2, "static|constexpr"))
isstatic = true;
else if (Token::Match(tok2, "%type% :: %type%")) {
tok2 = tok2->next();
++typelen;
}
else
break;
if (tok2->strAt(1) == "*")
break;
if (Token::Match(tok2->next(), "& %name% ,"))
break;
tok2 = tok2->next();
++typelen;
}
// strange looking variable declaration => don't split up.
if (Token::Match(tok2, "%type% *|&| %name% , %type% *|&| %name%"))
continue;
if (Token::Match(tok2, "struct|union|class %type%")) {
tok2 = tok2->next();
++typelen;
}
// check for qualification..
if (Token::Match(tok2, ":: %type%")) {
++typelen;
tok2 = tok2->next();
}
//skip combinations of templates and namespaces
while (!isC() && (Token::Match(tok2, "%type% <") || Token::Match(tok2, "%type% ::"))) {
if (tok2->strAt(1) == "<" && !TemplateSimplifier::templateParameters(tok2->next())) {
tok2 = nullptr;
break;
}
typelen += 2;
tok2 = tok2->tokAt(2);
if (tok2 && tok2->strAt(-1) == "::")
continue;
int indentlevel = 0;
int parens = 0;
for (Token *tok3 = tok2; tok3; tok3 = tok3->next()) {
++typelen;
if (!parens && tok3->str() == "<") {
++indentlevel;
} else if (!parens && tok3->str() == ">") {
if (indentlevel == 0) {
tok2 = tok3->next();
break;
}
--indentlevel;
} else if (!parens && tok3->str() == ">>") {
if (indentlevel <= 1) {
tok2 = tok3->next();
break;
}
indentlevel -= 2;
} else if (tok3->str() == "(") {
++parens;
} else if (tok3->str() == ")") {
if (!parens) {
tok2 = nullptr;
break;
}
--parens;
} else if (tok3->str() == ";") {
break;
}
}
if (Token::Match(tok2, ":: %type%")) {
++typelen;
tok2 = tok2->next();
}
// east const
if (Token::simpleMatch(tok2, "const"))
isconst = true;
}
//pattern: "%type% *| ... *| const| %name% ,|="
if (Token::Match(tok2, "%type%") ||
(tok2 && tok2->previous() && tok2->strAt(-1) == ">")) {
Token *varName = tok2;
if (!tok2->previous() || tok2->strAt(-1) != ">")
varName = varName->next();
else
--typelen;
if (cpp && Token::Match(varName, "public:|private:|protected:|using"))
continue;
//skip all the pointer part
bool isPointerOrRef = false;
while (Token::simpleMatch(varName, "*") || Token::Match(varName, "& %name% ,")) {
isPointerOrRef = true;
varName = varName->next();
}
while (Token::Match(varName, "%type% %type%")) {
if (varName->str() != "const" && varName->str() != "volatile") {
++typelen;
}
varName = varName->next();
}
// Function pointer
if (Token::simpleMatch(varName, "( *") &&
Token::Match(varName->link()->previous(), "%name% ) (") &&
Token::simpleMatch(varName->link()->linkAt(1), ") =")) {
Token *endDecl = varName->link()->linkAt(1);
varName = varName->link()->previous();
endDecl->insertToken(";");
endDecl = endDecl->next();
endDecl->next()->isSplittedVarDeclEq(true);
endDecl->insertToken(varName->str());
endDecl->next()->setMacroName(varName->getMacroName());
continue;
}
//non-VLA case
if (Token::Match(varName, "%name% ,|=")) {
if (varName->str() != "operator") {
tok2 = varName->next(); // The ',' or '=' token
if (tok2->str() == "=" && (isstatic || (isconst && !isPointerOrRef))) {
//do not split const non-pointer variables..
while (tok2 && tok2->str() != "," && tok2->str() != ";") {
if (Token::Match(tok2, "{|(|["))
tok2 = tok2->link();
const Token *tok3 = tok2;
if (!isC() && tok2->str() == "<" && TemplateSimplifier::templateParameters(tok2) > 0) {
tok2 = tok2->findClosingBracket();
}
if (!tok2)
syntaxError(tok3); // #6881 invalid code
tok2 = tok2->next();
}
if (tok2 && tok2->str() == ";")
tok2 = nullptr;
}
} else
tok2 = nullptr;
}
//VLA case
else if (Token::Match(varName, "%name% [")) {
tok2 = varName->next();
while (Token::Match(tok2->link(), "] ,|=|["))
tok2 = tok2->link()->next();
if (!Token::Match(tok2, "=|,"))
tok2 = nullptr;
if (tok2 && tok2->str() == "=") {
while (tok2 && tok2->str() != "," && tok2->str() != ";") {
if (Token::Match(tok2, "{|(|["))
tok2 = tok2->link();
tok2 = tok2->next();
}
if (tok2 && tok2->str() == ";")
tok2 = nullptr;
}
}
// brace initialization
else if (Token::Match(varName, "%name% {")) {
tok2 = varName->next();
tok2 = tok2->link();
if (tok2)
tok2 = tok2->next();
if (tok2 && tok2->str() != ",")
tok2 = nullptr;
}
// function declaration
else if (Token::Match(varName, "%name% (")) {
Token* commaTok = varName->linkAt(1)->next();
while (Token::Match(commaTok, "const|noexcept|override|final")) {
commaTok = commaTok->next();
if (Token::Match(commaTok, "( true|false )"))
commaTok = commaTok->link()->next();
}
tok2 = Token::simpleMatch(commaTok, ",") ? commaTok : nullptr;
}
else
tok2 = nullptr;
} else {
tok2 = nullptr;
}
if (!tok2) {
if (only_k_r_fpar)
finishedwithkr = false;
continue;
}
if (tok2->str() == ",") {
tok2->str(";");
tok2->isSplittedVarDeclComma(true);
//TODO: should we have to add also template '<>' links?
TokenList::insertTokens(tok2, type0, typelen);
}
else {
Token *eq = tok2;
while (tok2) {
if (Token::Match(tok2, "{|(|["))
tok2 = tok2->link();
else if (!isC() && tok2->str() == "<" && ((tok2->previous()->isName() && !tok2->previous()->varId()) || tok2->strAt(-1) == "]"))
tok2 = tok2->findClosingBracket();
else if (std::strchr(";,", tok2->str()[0])) {
// "type var =" => "type var; var ="
const Token *varTok = type0->tokAt(typelen);
while (Token::Match(varTok, "%name%|*|& %name%|*|&"))
varTok = varTok->next();
if (!varTok)
syntaxError(tok2); // invalid code
TokenList::insertTokens(eq, varTok, 2);
eq->str(";");
eq->isSplittedVarDeclEq(true);
// "= x, " => "= x; type "
if (tok2->str() == ",") {
tok2->str(";");
tok2->isSplittedVarDeclComma(true);
TokenList::insertTokens(tok2, type0, typelen);
}
break;
}
if (tok2)
tok2 = tok2->next();
}
}
finishedwithkr = (only_k_r_fpar && tok2 && tok2->strAt(1) == "{");
}
}
void Tokenizer::simplifyStaticConst()
{
// This function will simplify the token list so that the qualifiers "extern", "static"
// and "const" appear in the same order as in the array below.
const std::string qualifiers[] = {"extern", "static", "const"};
// Move 'const' before all other qualifiers and types and then
// move 'static' before all other qualifiers and types, ...
for (Token *tok = list.front(); tok; tok = tok->next()) {
bool continue2 = false;
for (std::size_t i = 0; i < sizeof(qualifiers)/sizeof(qualifiers[0]); i++) {
// Keep searching for a qualifier
if (!tok->next() || tok->strAt(1) != qualifiers[i])
continue;
// Look backwards to find the beginning of the declaration
Token* leftTok = tok;
bool behindOther = false;
for (; leftTok; leftTok = leftTok->previous()) {
for (std::size_t j = 0; j <= i; j++) {
if (leftTok->str() == qualifiers[j]) {
behindOther = true;
break;
}
}
if (behindOther)
break;
if (isCPP() && Token::simpleMatch(leftTok, ">")) {
Token* opening = leftTok->findOpeningBracket();
if (opening) {
leftTok = opening;
continue;
}
}
if (!Token::Match(leftTok, "%type%|struct|::") ||
(isCPP() && Token::Match(leftTok, "private:|protected:|public:|operator|template"))) {
break;
}
}
// The token preceding the declaration should indicate the start of a declaration
if (leftTok == tok)
continue;
if (leftTok && !behindOther && !Token::Match(leftTok, ";|{|}|(|,|private:|protected:|public:")) {
continue2 = true;
break;
}
// Move the qualifier to the left-most position in the declaration
tok->deleteNext();
if (!leftTok) {
list.front()->insertToken(qualifiers[i]);
list.front()->swapWithNext();
tok = list.front();
} else if (leftTok->next()) {
leftTok->next()->insertTokenBefore(qualifiers[i]);
tok = leftTok->next();
} else {
leftTok->insertToken(qualifiers[i]);
tok = leftTok;
}
}
if (continue2)
continue;
}
}
void Tokenizer::simplifyVariableMultipleAssign()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% = %name% = %num%|%name% ;")) {
// skip intermediate assignments
Token *tok2 = tok->previous();
while (tok2 &&
tok2->str() == "=" &&
Token::Match(tok2->previous(), "%name%")) {
tok2 = tok2->tokAt(-2);
}
if (!tok2 || tok2->str() != ";") {
continue;
}
Token *stopAt = tok->tokAt(2);
const Token *valueTok = stopAt->tokAt(2);
const std::string& value(valueTok->str());
tok2 = tok2->next();
while (tok2 != stopAt) {
tok2->next()->insertToken(";");
tok2->next()->insertToken(value);
tok2 = tok2->tokAt(4);
}
}
}
}
// Binary operators simplification map
static const std::unordered_map<std::string, std::string> cAlternativeTokens = {
std::make_pair("and", "&&")
, std::make_pair("and_eq", "&=")
, std::make_pair("bitand", "&")
, std::make_pair("bitor", "|")
, std::make_pair("not_eq", "!=")
, std::make_pair("or", "||")
, std::make_pair("or_eq", "|=")
, std::make_pair("xor", "^")
, std::make_pair("xor_eq", "^=")
};
// Simplify the C alternative tokens:
// and => &&
// and_eq => &=
// bitand => &
// bitor => |
// compl => ~
// not => !
// not_eq => !=
// or => ||
// or_eq => |=
// xor => ^
// xor_eq => ^=
bool Tokenizer::simplifyCAlternativeTokens()
{
/* executable scope level */
int executableScopeLevel = 0;
std::vector<Token *> alt;
bool replaceAll = false; // replace all or none
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == ")") {
if (const Token *end = isFunctionHead(tok, "{")) {
++executableScopeLevel;
tok = const_cast<Token *>(end);
continue;
}
}
if (tok->str() == "{") {
if (executableScopeLevel > 0)
++executableScopeLevel;
continue;
}
if (tok->str() == "}") {
if (executableScopeLevel > 0)
--executableScopeLevel;
continue;
}
if (!tok->isName())
continue;
const std::unordered_map<std::string, std::string>::const_iterator cOpIt = cAlternativeTokens.find(tok->str());
if (cOpIt != cAlternativeTokens.end()) {
alt.push_back(tok);
// Is this a variable declaration..
if (isC() && Token::Match(tok->previous(), "%type%|* %name% [;,=]"))
return false;
if (!Token::Match(tok->previous(), "%name%|%num%|%char%|)|]|> %name% %name%|%num%|%char%|%op%|("))
continue;
if (Token::Match(tok->next(), "%assign%|%or%|%oror%|&&|*|/|%|^") && !Token::Match(tok->previous(), "%num%|%char%|) %name% *"))
continue;
if (executableScopeLevel == 0 && Token::Match(tok, "%name% (")) {
const Token *start = tok;
while (Token::Match(start, "%name%|*"))
start = start->previous();
if (!start || Token::Match(start, "[;}]"))
continue;
}
replaceAll = true;
} else if (Token::Match(tok, "not|compl")) {
alt.push_back(tok);
if ((Token::Match(tok->previous(), "%assign%") || Token::Match(tok->next(), "%num%")) && !Token::Match(tok->next(), ".|->")) {
replaceAll = true;
continue;
}
// Don't simplify 'not p;' (in case 'not' is a type)
if (!Token::Match(tok->next(), "%name%|(") ||
Token::Match(tok->previous(), "[;{}]") ||
(executableScopeLevel == 0U && tok->strAt(-1) == "("))
continue;
replaceAll = true;
}
}
if (!replaceAll)
return false;
for (Token *tok: alt) {
const std::unordered_map<std::string, std::string>::const_iterator cOpIt = cAlternativeTokens.find(tok->str());
if (cOpIt != cAlternativeTokens.end())
tok->str(cOpIt->second);
else if (tok->str() == "not")
tok->str("!");
else
tok->str("~");
}
return !alt.empty();
}
// int i(0); => int i; i = 0;
// int i(0), j; => int i; i = 0; int j;
void Tokenizer::simplifyInitVar()
{
if (isC())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName() || (tok->previous() && !Token::Match(tok->previous(), "[;{}]")))
continue;
if (tok->str() == "return")
continue;
if (Token::Match(tok, "class|struct|union| %type% *| %name% ( &| %any% ) ;")) {
tok = initVar(tok);
} else if (Token::Match(tok, "%type% *| %name% ( %type% (")) {
const Token* tok2 = tok->tokAt(2);
if (!tok2->link())
tok2 = tok2->next();
if (!tok2->link() || (tok2->link()->strAt(1) == ";" && !Token::simpleMatch(tok2->linkAt(2), ") (")))
tok = initVar(tok);
} else if (Token::Match(tok, "class|struct|union| %type% *| %name% ( &| %any% ) ,") && tok->str() != "new") {
Token *tok1 = tok->tokAt(5);
while (tok1->str() != ",")
tok1 = tok1->next();
tok1->str(";");
const int numTokens = (Token::Match(tok, "class|struct|union")) ? 2 : 1;
TokenList::insertTokens(tok1, tok, numTokens);
tok = initVar(tok);
}
}
}
Token * Tokenizer::initVar(Token * tok)
{
// call constructor of class => no simplification
if (Token::Match(tok, "class|struct|union")) {
if (tok->strAt(2) != "*")
return tok;
tok = tok->next();
} else if (!tok->isStandardType() && tok->str() != "auto" && tok->strAt(1) != "*")
return tok;
// goto variable name..
tok = tok->next();
if (tok->str() == "*")
tok = tok->next();
// sizeof is not a variable name..
if (tok->str() == "sizeof")
return tok;
// check initializer..
if (tok->tokAt(2)->isStandardType() || tok->strAt(2) == "void")
return tok;
if (!tok->tokAt(2)->isNumber() && !Token::Match(tok->tokAt(2), "%type% (") && tok->strAt(2) != "&" && tok->tokAt(2)->varId() == 0)
return tok;
// insert '; var ='
tok->insertToken(";");
tok->next()->insertToken(tok->str());
tok->tokAt(2)->varId(tok->varId());
tok = tok->tokAt(2);
tok->insertToken("=");
// goto '('..
tok = tok->tokAt(2);
// delete ')'
tok->link()->deleteThis();
// delete this
tok->deleteThis();
return tok;
}
void Tokenizer::elseif()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() != "else")
continue;
if (!Token::Match(tok->previous(), ";|}"))
syntaxError(tok->previous());
if (!Token::Match(tok->next(), "%name%"))
continue;
if (tok->strAt(1) != "if")
unknownMacroError(tok->next());
for (Token *tok2 = tok; tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, "(|{|["))
tok2 = tok2->link();
if (Token::Match(tok2, "}|;")) {
if (tok2->next() && tok2->strAt(1) != "else") {
tok->insertToken("{");
tok2->insertToken("}");
Token::createMutualLinks(tok->next(), tok2->next());
break;
}
}
}
}
}
void Tokenizer::simplifyIfSwitchForInit()
{
if (!isCPP() || mSettings.standards.cpp < Standards::CPP17)
return;
const bool forInit = (mSettings.standards.cpp >= Standards::CPP20);
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "if|switch|for ("))
continue;
Token *semicolon = tok->tokAt(2);
while (!Token::Match(semicolon, "[;)]")) {
if (Token::Match(semicolon, "(|{|[") && semicolon->link())
semicolon = semicolon->link();
semicolon = semicolon->next();
}
if (semicolon->str() != ";")
continue;
if (tok->str() == "for") {
if (!forInit)
continue;
// Is it a for range..
const Token *tok2 = semicolon->next();
bool rangeFor = false;
while (!Token::Match(tok2, "[;)]")) {
if (tok2->str() == "(")
tok2 = tok2->link();
else if (!rangeFor && tok2->str() == "?")
break;
else if (tok2->str() == ":")
rangeFor = true;
tok2 = tok2->next();
}
if (!rangeFor || tok2->str() != ")")
continue;
}
Token *endpar = tok->linkAt(1);
if (!Token::simpleMatch(endpar, ") {"))
continue;
Token *endscope = endpar->linkAt(1);
if (Token::simpleMatch(endscope, "} else {"))
endscope = endscope->linkAt(2);
// Simplify, the initialization expression is broken out..
semicolon->insertToken(tok->str());
semicolon->next()->insertToken("(");
Token::createMutualLinks(semicolon->tokAt(2), endpar);
tok->deleteNext();
tok->str("{");
endscope->insertToken("}");
Token::createMutualLinks(tok, endscope->next());
tok->isSimplifiedScope(true);
}
}
bool Tokenizer::simplifyRedundantParentheses()
{
bool ret = false;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() != "(")
continue;
if (tok->isCpp() && Token::simpleMatch(tok->previous(), "} (")) {
const Token* plp = tok->linkAt(-1)->previous();
if (Token::Match(plp, "%name%|>|] {") || (Token::simpleMatch(plp, ")") && Token::simpleMatch(plp->link()->previous(), "]")))
continue;
}
if (Token::simpleMatch(tok, "( {"))
continue;
if (Token::Match(tok->link(), ") %num%")) {
tok = tok->link();
continue;
}
// Do not simplify if there is comma inside parentheses..
if (Token::Match(tok->previous(), "%op% (") || Token::Match(tok->link(), ") %op%")) {
bool innerComma = false;
for (const Token *inner = tok->link()->previous(); inner != tok; inner = inner->previous()) {
if (inner->str() == ")")
inner = inner->link();
if (inner->str() == ",") {
innerComma = true;
break;
}
}
if (innerComma)
continue;
}
// !!operator = ( x ) ;
if (tok->strAt(-2) != "operator" &&
tok->previous() && tok->strAt(-1) == "=" &&
tok->next() && tok->strAt(1) != "{" &&
Token::simpleMatch(tok->link(), ") ;")) {
tok->link()->deleteThis();
tok->deleteThis();
continue;
}
if (isCPP() && Token::Match(tok->tokAt(-2), "[;{}=(] new (") && Token::Match(tok->link(), ") [;,{}[]")) {
// Remove the parentheses in "new (type)" constructs
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (Token::Match(tok->previous(), "! ( %name% )")) {
// Remove the parentheses
tok->deleteThis();
tok->deleteNext();
ret = true;
}
if (Token::Match(tok->previous(), "[(,;{}] ( %name% ) .")) {
// Remove the parentheses
tok->deleteThis();
tok->deleteNext();
ret = true;
}
if (Token::Match(tok->previous(), "[(,;{}] ( %name% (") && !tok->next()->isKeyword() &&
tok->link()->previous() == tok->linkAt(2)) {
// We have "( func ( *something* ))", remove the outer
// parentheses
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (Token::Match(tok->previous(), "[,;{}] ( delete [| ]| %name% ) ;")) {
// We have "( delete [| ]| var )", remove the outer
// parentheses
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (!Token::simpleMatch(tok->tokAt(-2), "operator delete") &&
Token::Match(tok->previous(), "delete|; (") &&
(tok->strAt(-1) != "delete" || tok->next()->varId() > 0) &&
Token::Match(tok->link(), ") ;|,")) {
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (Token::Match(tok->previous(), "[(!*;{}] ( %name% )") &&
(tok->next()->varId() != 0 || Token::Match(tok->tokAt(3), "[+-/=]")) && !tok->next()->isStandardType()) {
// We have "( var )", remove the parentheses
tok->deleteThis();
tok->deleteNext();
ret = true;
}
while (Token::Match(tok->previous(), "[;{}[(,!*] ( %name% .")) {
Token *tok2 = tok->tokAt(2);
while (Token::Match(tok2, ". %name%")) {
tok2 = tok2->tokAt(2);
}
if (tok2 != tok->link())
break;
// We have "( var . var . ... . var )", remove the parentheses
tok = tok->previous();
tok->deleteNext();
tok2->deleteThis();
ret = true;
}
while (Token::Match(tok->previous(), "[{([,] ( !!{") &&
Token::Match(tok->link(), ") [;,])] !!{") &&
!Token::simpleMatch(tok->tokAt(-2), "operator ,") && // Ticket #5709
!Token::findsimplematch(tok, ",", tok->link())) {
// We have "( ... )", remove the parentheses
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (Token::simpleMatch(tok->previous(), ", (") &&
Token::simpleMatch(tok->link(), ") =")) {
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
// Simplify "!!operator !!%name%|)|]|>|>> ( %num%|%bool% ) %op%|;|,|)"
if (Token::Match(tok, "( %bool%|%num% ) %cop%|;|,|)") &&
tok->strAt(-2) != "operator" &&
tok->previous() &&
!Token::Match(tok->previous(), "%name%|)|]") &&
(!(isCPP() && Token::Match(tok->previous(),">|>>")))) {
tok->link()->deleteThis();
tok->deleteThis();
ret = true;
}
if (Token::Match(tok->previous(), "*|& ( %name% )")) {
// We may have a variable declaration looking like "type_name *(var_name)"
Token *tok2 = tok->tokAt(-2);
while (Token::Match(tok2, "%type%|static|const|extern") && tok2->str() != "operator") {
tok2 = tok2->previous();
}
if (tok2 && !Token::Match(tok2, "[;,{]")) {
// Not a variable declaration
} else {
tok->deleteThis();
tok->deleteNext();
}
}
}
return ret;
}
void Tokenizer::simplifyTypeIntrinsics()
{
static const std::unordered_map<std::string, std::string> intrinsics = {
{ "__has_nothrow_assign", "has_nothrow_assign" },
{ "__has_nothrow_constructor", "has_nothrow_constructor" },
{ "__has_nothrow_copy", "has_nothrow_copy" },
{ "__has_trivial_assign", "has_trivial_assign" },
{ "__has_trivial_constructor", "has_trivial_constructor" },
{ "__has_trivial_copy", "has_trivial_copy" },
{ "__has_trivial_destructor", "has_trivial_destructor" },
{ "__has_virtual_destructor", "has_virtual_destructor" },
{ "__is_abstract", "is_abstract" },
{ "__is_aggregate", "is_aggregate" },
{ "__is_assignable", "is_assignable" },
{ "__is_base_of", "is_base_of" },
{ "__is_class", "is_class" },
{ "__is_constructible", "is_constructible" },
{ "__is_convertible_to", "is_convertible_to" },
{ "__is_destructible", "is_destructible" },
{ "__is_empty", "is_empty" },
{ "__is_enum", "is_enum" },
{ "__is_final", "is_final" },
{ "__is_nothrow_assignable", "is_nothrow_assignable" },
{ "__is_nothrow_constructible", "is_nothrow_constructible" },
{ "__is_nothrow_destructible", "is_nothrow_destructible" },
{ "__is_pod", "is_pod" },
{ "__is_polymorphic", "is_polymorphic" },
{ "__is_trivially_assignable", "is_trivially_assignable" },
{ "__is_trivially_constructible", "is_trivially_constructible" },
{ "__is_union", "is_union" },
};
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
auto p = intrinsics.find(tok->str());
if (p == intrinsics.end())
continue;
Token * end = tok->linkAt(1);
Token * prev = tok->previous();
tok->str(p->second);
prev->insertToken("::");
prev->insertToken("std");
tok->next()->str("<");
end->str(">");
end->insertToken("}");
end->insertToken("{");
Token::createMutualLinks(end->tokAt(1), end->tokAt(2));
}
}
//---------------------------------------------------------------------------
// Helper functions for handling the tokens list
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
bool Tokenizer::isScopeNoReturn(const Token *endScopeToken, bool *unknown) const
{
std::string unknownFunc;
const bool ret = mSettings.library.isScopeNoReturn(endScopeToken,&unknownFunc);
if (!unknownFunc.empty() && mSettings.summaryReturn.find(unknownFunc) != mSettings.summaryReturn.end()) {
return false;
}
if (unknown)
*unknown = !unknownFunc.empty();
if (!unknownFunc.empty() && mSettings.checkLibrary) {
bool warn = true;
if (Token::simpleMatch(endScopeToken->tokAt(-2), ") ; }")) {
const Token * const ftok = endScopeToken->linkAt(-2)->previous();
if (ftok && (ftok->type() || ftok->function() || ftok->variable())) // constructor call
warn = false;
}
if (warn) {
reportError(endScopeToken->previous(),
Severity::information,
"checkLibraryNoReturn",
"--check-library: Function " + unknownFunc + "() should have <noreturn> configuration");
}
}
return ret;
}
//---------------------------------------------------------------------------
void Tokenizer::syntaxError(const Token *tok, const std::string &code) const
{
printDebugOutput(0, std::cout);
throw InternalError(tok, code.empty() ? "syntax error" : "syntax error: " + code, InternalError::SYNTAX);
}
void Tokenizer::unmatchedToken(const Token *tok) const
{
printDebugOutput(0, std::cout);
throw InternalError(tok,
"Unmatched '" + tok->str() + "'. Configuration: '" + mConfiguration + "'.",
InternalError::SYNTAX);
}
void Tokenizer::syntaxErrorC(const Token *tok, const std::string &what) const
{
printDebugOutput(0, std::cout);
throw InternalError(tok, "Code '"+what+"' is invalid C code.", "Use --std, -x or --language to enforce C++. Or --cpp-header-probe to identify C++ headers via the Emacs marker.", InternalError::SYNTAX);
}
void Tokenizer::unknownMacroError(const Token *tok1) const
{
printDebugOutput(0, std::cout);
throw InternalError(tok1, "There is an unknown macro here somewhere. Configuration is required. If " + tok1->str() + " is a macro then please configure it.", InternalError::UNKNOWN_MACRO);
}
void Tokenizer::unhandled_macro_class_x_y(const Token *tok) const
{
reportError(tok,
Severity::information,
"class_X_Y",
"The code '" +
tok->str() + " " +
tok->strAt(1) + " " +
tok->strAt(2) + " " +
tok->strAt(3) + "' is not handled. You can use -I or --include to add handling of this code.");
}
void Tokenizer::macroWithSemicolonError(const Token *tok, const std::string ¯oName) const
{
reportError(tok,
Severity::information,
"macroWithSemicolon",
"Ensure that '" + macroName + "' is defined either using -I, --include or -D.");
}
void Tokenizer::cppcheckError(const Token *tok) const
{
printDebugOutput(0, std::cout);
throw InternalError(tok, "Analysis failed. If the code is valid then please report this failure.", InternalError::INTERNAL);
}
void Tokenizer::unhandledCharLiteral(const Token *tok, const std::string& msg) const
{
std::string s = tok ? (" " + tok->str()) : "";
for (std::size_t i = 0; i < s.size(); ++i) {
if ((unsigned char)s[i] >= 0x80)
s.clear();
}
reportError(tok,
Severity::portability,
"nonStandardCharLiteral",
"Non-standard character literal" + s + ". " + msg);
}
/**
* Helper function to check whether number is equal to integer constant X
* or floating point pattern X.0
* @param s the string to check
* @param intConstant the integer constant to check against
* @param floatConstant the string with stringified float constant to check against
* @return true in case s is equal to X or X.0 and false otherwise.
*/
static bool isNumberOneOf(const std::string &s, MathLib::bigint intConstant, const char* floatConstant)
{
if (MathLib::isInt(s)) {
if (MathLib::toBigNumber(s) == intConstant)
return true;
} else if (MathLib::isFloat(s)) {
if (MathLib::toString(MathLib::toDoubleNumber(s)) == floatConstant)
return true;
}
return false;
}
// ------------------------------------------------------------------------
// Helper function to check whether number is one (1 or 0.1E+1 or 1E+0) or not?
// @param s the string to check
// @return true in case s is one and false otherwise.
// ------------------------------------------------------------------------
bool Tokenizer::isOneNumber(const std::string &s)
{
if (!MathLib::isPositive(s))
return false;
return isNumberOneOf(s, 1L, "1.0");
}
// ------------------------------------------------------------------------
void Tokenizer::checkConfiguration() const
{
if (!mSettings.checkConfiguration)
return;
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
if (tok->isControlFlowKeyword())
continue;
for (const Token *tok2 = tok->tokAt(2); tok2 && tok2->str() != ")"; tok2 = tok2->next()) {
if (tok2->str() == ";") {
macroWithSemicolonError(tok, tok->str());
break;
}
if (Token::Match(tok2, "(|{"))
tok2 = tok2->link();
}
}
}
void Tokenizer::validateC() const
{
if (isCPP())
return;
for (const Token *tok = tokens(); tok; tok = tok->next()) {
// That might trigger false positives, but it's much faster to have this truncated pattern
if (Token::Match(tok, "const_cast|dynamic_cast|reinterpret_cast|static_cast <"))
syntaxErrorC(tok, "C++ cast <...");
// Template function..
if (Token::Match(tok, "%name% < %name% > (")) {
const Token *tok2 = tok->tokAt(5);
while (tok2 && !Token::Match(tok2, "[()]"))
tok2 = tok2->next();
if (Token::simpleMatch(tok2, ") {"))
syntaxErrorC(tok, tok->str() + '<' + tok->strAt(2) + ">() {}");
}
if (tok->previous() && !Token::Match(tok->previous(), "[;{}]"))
continue;
if (Token::Match(tok, "using namespace %name% ;"))
syntaxErrorC(tok, "using namespace " + tok->strAt(2));
if (Token::Match(tok, "template < class|typename %name% [,>]"))
syntaxErrorC(tok, "template<...");
if (Token::Match(tok, "%name% :: %name%"))
syntaxErrorC(tok, tok->str() + tok->strAt(1) + tok->strAt(2));
if (Token::Match(tok, "class|namespace %name% :|::|{"))
syntaxErrorC(tok, tok->str() + tok->strAt(1) + tok->strAt(2));
}
}
void Tokenizer::validate() const
{
std::stack<const Token *> linkTokens;
const Token *lastTok = nullptr;
for (const Token *tok = tokens(); tok; tok = tok->next()) {
lastTok = tok;
if (Token::Match(tok, "[{([]") || (tok->str() == "<" && tok->link())) {
if (tok->link() == nullptr)
cppcheckError(tok);
linkTokens.push(tok);
}
else if (Token::Match(tok, "[})]]") || (Token::Match(tok, ">|>>") && tok->link())) {
if (tok->link() == nullptr)
cppcheckError(tok);
if (linkTokens.empty())
cppcheckError(tok);
if (tok->link() != linkTokens.top())
cppcheckError(tok);
if (tok != tok->link()->link())
cppcheckError(tok);
linkTokens.pop();
}
else if (tok->link() != nullptr)
cppcheckError(tok);
}
if (!linkTokens.empty())
cppcheckError(linkTokens.top());
// Validate that the Tokenizer::list.back() is updated correctly during simplifications
if (lastTok != list.back())
cppcheckError(lastTok);
}
static const Token *findUnmatchedTernaryOp(const Token * const begin, const Token * const end, int depth = 0)
{
std::stack<const Token *> ternaryOp;
for (const Token *tok = begin; tok != end && tok->str() != ";"; tok = tok->next()) {
if (tok->str() == "?")
ternaryOp.push(tok);
else if (!ternaryOp.empty() && tok->str() == ":")
ternaryOp.pop();
else if (depth < 100 && Token::Match(tok,"(|[")) {
const Token *inner = findUnmatchedTernaryOp(tok->next(), tok->link(), depth+1);
if (inner)
return inner;
tok = tok->link();
}
}
return ternaryOp.empty() ? nullptr : ternaryOp.top();
}
static bool isCPPAttribute(const Token * tok)
{
return Token::simpleMatch(tok, "[ [") && tok->link() && tok->link()->previous() == tok->linkAt(1);
}
static bool isAlignAttribute(const Token * tok)
{
return Token::simpleMatch(tok, "alignas (") && tok->linkAt(1);
}
template<typename T>
static T* skipCPPOrAlignAttribute(T * tok)
{
if (isCPPAttribute(tok))
return tok->link();
if (isAlignAttribute(tok)) {
return tok->linkAt(1);
}
return tok;
}
static bool isNonMacro(const Token* tok)
{
if (tok->isKeyword() || tok->isStandardType())
return true;
if (cAlternativeTokens.count(tok->str()) > 0)
return true;
if (startsWith(tok->str(), "__")) // attribute/annotation
return true;
if (Token::simpleMatch(tok, "alignas ("))
return true;
return false;
}
void Tokenizer::reportUnknownMacros() const
{
// Report unknown macros used in expressions "%name% %num%"
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name% %num%")) {
// A keyword is not an unknown macro
if (tok->isKeyword())
continue;
if (Token::Match(tok->previous(), "%op%|("))
unknownMacroError(tok);
}
}
// Report unknown macros before } "{ .. if (x) MACRO }"
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, ")|; %name% } !!)")) {
if (tok->link() && !Token::simpleMatch(tok->link()->tokAt(-1), "if"))
continue;
const Token* prev = tok->linkAt(2);
while (Token::simpleMatch(prev, "{"))
prev = prev->previous();
if (Token::Match(prev, ";|)"))
unknownMacroError(tok->next());
}
}
// Report unknown macros that contain several statements "MACRO(a;b;c)"
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
if (!tok->isUpperCaseName())
continue;
const Token *endTok = tok->linkAt(1);
for (const Token *inner = tok->tokAt(2); inner != endTok; inner = inner->next()) {
if (Token::Match(inner, "[[({]"))
inner = inner->link();
else if (inner->str() == ";")
unknownMacroError(tok);
}
}
// Report unknown macros that contain struct initialization "MACRO(a, .b=3)"
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
const Token *endTok = tok->linkAt(1);
for (const Token *inner = tok->tokAt(2); inner != endTok; inner = inner->next()) {
if (Token::Match(inner, "[[({]"))
inner = inner->link();
else if (Token::Match(inner->previous(), "[,(] . %name% =|{"))
unknownMacroError(tok);
}
}
const bool cpp = isCPP();
// Report unknown macros in non-executable scopes..
std::set<std::string> possible;
for (const Token *tok = tokens(); tok; tok = tok->next()) {
// Skip executable scopes..
if (tok->str() == "{") {
const Token *prev = tok->previous();
while (prev && prev->isName())
prev = prev->previous();
if (prev && prev->str() == ")")
tok = tok->link();
else
possible.clear();
} else if (tok->str() == "}")
possible.clear();
if (Token::Match(tok, "%name% (") && tok->isUpperCaseName() && Token::simpleMatch(tok->linkAt(1), ") (") && Token::simpleMatch(tok->linkAt(1)->linkAt(1), ") {")) {
// A keyword is not an unknown macro
if (tok->isKeyword())
continue;
const Token *bodyStart = tok->linkAt(1)->linkAt(1)->tokAt(2);
const Token *bodyEnd = tok->link();
for (const Token *tok2 = bodyStart; tok2 && tok2 != bodyEnd; tok2 = tok2->next()) {
if (Token::Match(tok2, "if|switch|for|while|return"))
unknownMacroError(tok);
}
} else if (Token::Match(tok, "%name% (") && tok->isUpperCaseName() && Token::Match(tok->linkAt(1), ") %name% (") && Token::Match(tok->linkAt(1)->linkAt(2), ") [;{]")) {
if (!(tok->linkAt(1)->next() && tok->linkAt(1)->next()->isKeyword())) { // e.g. noexcept(true)
if (possible.count(tok->str()) == 0)
possible.insert(tok->str());
else
unknownMacroError(tok);
}
} else if (cpp && Token::Match(tok, "public|private|protected %name% :")) {
unknownMacroError(tok->next());
}
}
// String concatenation with unknown macros
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if ((Token::Match(tok, "%str% %name% (") && Token::Match(tok->linkAt(2), ") %str%")) ||
(Token::Match(tok, "%str% %name% %str%") && !(startsWith(tok->strAt(1), "PRI") || startsWith(tok->strAt(1), "SCN")))) { // TODO: implement macros in std.cfg
if (tok->next()->isKeyword())
continue;
unknownMacroError(tok->next());
}
if (Token::Match(tok, "[(,] %name% (") && Token::Match(tok->linkAt(2), ") %name% %name%|,|)")) {
if (tok->next()->isKeyword() || tok->linkAt(2)->next()->isKeyword())
continue;
if (cAlternativeTokens.count(tok->linkAt(2)->strAt(1)) > 0)
continue;
if (startsWith(tok->strAt(1), "__")) // attribute/annotation
continue;
if (tok->next()->isStandardType() && !tok->linkAt(2)->next()->isStandardType())
unknownMacroError(tok->linkAt(2)->next());
else
unknownMacroError(tok->next());
}
}
// Report unknown macros without commas or operators inbetween statements: MACRO1() MACRO2()
for (const Token* tok = tokens(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
if (isNonMacro(tok) && !tok->isStandardType())
continue;
const Token* endTok = tok->linkAt(1);
if (!Token::Match(endTok, ") %name% (|."))
continue;
const Token* tok2 = endTok->next();
if (isNonMacro(tok2))
continue;
if (tok2->strAt(1) == "(") {
if (Token::Match(tok->previous(), "%name%|::|>"))
continue;
}
unknownMacroError(tok->isStandardType() ? tok2 : tok);
}
}
void Tokenizer::findGarbageCode() const
{
const bool cpp = isCPP();
const bool isCPP11 = cpp && mSettings.standards.cpp >= Standards::CPP11;
static const std::unordered_set<std::string> nonConsecutiveKeywords{ "break",
"continue",
"for",
"goto",
"if",
"return",
"switch",
"throw",
"typedef",
"while" };
for (const Token *tok = tokens(); tok; tok = tok->next()) {
// initialization: = {
if (Token::simpleMatch(tok, "= {") && Token::simpleMatch(tok->linkAt(1), "} ("))
syntaxError(tok->linkAt(1));
// Inside [] there can't be ; or various keywords
else if (tok->str() == "[") {
for (const Token* inner = tok->next(); inner != tok->link(); inner = inner->next()) {
if (Token::Match(inner, "(|[|{"))
inner = inner->link();
else if (Token::Match(inner, ";|goto|return|typedef"))
syntaxError(inner);
}
}
// array assignment
else if (Token::Match(tok, "%assign% [") && Token::simpleMatch(tok->linkAt(1), "] ;"))
syntaxError(tok, tok->str() + "[...];");
else if (Token::Match(tok, "[({<] %assign%"))
syntaxError(tok);
else if (Token::Match(tok, "%assign% >"))
syntaxError(tok);
else if (Token::Match(tok, "[`\\@]"))
syntaxError(tok);
// UNKNOWN_MACRO(return)
if (tok->isKeyword() && Token::Match(tok, "throw|return )") && Token::Match(tok->linkAt(1)->previous(), "%name% ("))
unknownMacroError(tok->linkAt(1)->previous());
// UNKNOWN_MACRO(return)
else if (Token::Match(tok, "%name% throw|return") && std::isupper(tok->str()[0]))
unknownMacroError(tok);
// Assign/increment/decrement literal
else if (Token::Match(tok, "!!) %num%|%str%|%char% %assign%|++|--")) {
if (!cpp || mSettings.standards.cpp < Standards::CPP20 || !Token::Match(tok->previous(), "%name% : %num% ="))
syntaxError(tok, tok->strAt(1) + " " + tok->strAt(2));
}
else if (Token::simpleMatch(tok, ") return") && !Token::Match(tok->link()->previous(), "if|while|for (")) {
if (tok->link()->previous() && tok->link()->previous()->isUpperCaseName())
unknownMacroError(tok->link()->previous());
else
syntaxError(tok);
}
if (tok->isControlFlowKeyword() && Token::Match(tok, "if|while|for|switch")) { // if|while|for|switch (EXPR) { ... }
if (tok->previous() && !Token::Match(tok->previous(), "%name%|:|;|{|}|)")) {
if (Token::Match(tok->previous(), "[,(]")) {
const Token *prev = tok->previous();
while (prev && prev->str() != "(") {
if (prev->str() == ")")
prev = prev->link();
prev = prev->previous();
}
if (prev && Token::Match(prev->previous(), "%name% ("))
unknownMacroError(prev->previous());
}
if (!Token::simpleMatch(tok->tokAt(-2), "operator \"\" if"))
syntaxError(tok);
}
if (!Token::Match(tok->next(), "( !!)"))
syntaxError(tok);
if (tok->str() != "for") {
if (isGarbageExpr(tok->next(), tok->linkAt(1), cpp && (mSettings.standards.cpp>=Standards::cppstd_t::CPP17)))
syntaxError(tok);
}
}
// keyword keyword
if (tok->isKeyword() && nonConsecutiveKeywords.count(tok->str()) != 0) {
if (Token::Match(tok, "%name% %name%") && nonConsecutiveKeywords.count(tok->strAt(1)) == 1)
syntaxError(tok);
const Token* prev = tok;
while (prev && prev->isName())
prev = prev->previous();
if (Token::Match(prev, "%op%|%num%|%str%|%char%")) {
if (!Token::simpleMatch(tok->tokAt(-2), "operator \"\" if") &&
!Token::simpleMatch(tok->tokAt(-2), "extern \"C\"") &&
!Token::simpleMatch(prev, "> typedef"))
syntaxError(tok, prev == tok->previous() ? (prev->str() + " " + tok->str()) : (prev->str() + " .. " + tok->str()));
}
}
}
// invalid struct declaration
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "struct|class|enum %name%| {") && (!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) {
const Token *tok2 = tok->linkAt(tok->next()->isName() ? 2 : 1);
if (Token::Match(tok2, "} %op%")) {
tok2 = tok2->next();
if (!Token::Match(tok2, "*|&|&&"))
syntaxError(tok2, "Unexpected token '" + tok2->str() + "'");
while (Token::Match(tok2, "*|&|&&"))
tok2 = tok2->next();
if (!Token::Match(tok2, "%name%"))
syntaxError(tok2, "Unexpected token '" + (tok2 ? tok2->str() : "") + "'");
}
}
if (tok->str() == "enum") {
if (Token::Match(tok->next(), ": %num%| {"))
syntaxError(tok->tokAt(2), "Unexpected token '" + tok->strAt(2) + "'");
if (const Token* start = SymbolDatabase::isEnumDefinition(tok)) {
for (const Token* tok2 = start->next(); tok2 && tok2 != start->link(); tok2 = tok2->next()) {
if (Token::simpleMatch(tok2, "sizeof (")) {
tok2 = tok2->linkAt(1);
continue;
}
if (tok2->str() == ";")
syntaxError(tok2);
}
}
}
}
// Keywords in global scope
static const std::unordered_set<std::string> nonGlobalKeywords{"break",
"continue",
"for",
"goto",
"if",
"return",
"switch",
"while",
"try",
"catch"};
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (tok->str() == "{")
tok = tok->link();
else if (tok->isKeyword() && nonGlobalKeywords.count(tok->str()) && !Token::Match(tok->tokAt(-2), "operator %str%"))
syntaxError(tok, "keyword '" + tok->str() + "' is not allowed in global scope");
}
// case keyword must be inside switch
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "switch (")) {
if (Token::simpleMatch(tok->linkAt(1), ") {")) {
tok = tok->linkAt(1)->linkAt(1);
continue;
}
const Token *switchToken = tok;
tok = tok->linkAt(1);
if (!tok)
syntaxError(switchToken);
// Look for the end of the switch statement, i.e. the first semi-colon or '}'
for (; tok; tok = tok->next()) {
if (tok->str() == "{") {
tok = tok->link();
}
if (Token::Match(tok, ";|}")) {
// We're at the end of the switch block
if (tok->str() == "}" && tok->strAt(-1) == ":") // Invalid case
syntaxError(switchToken);
break;
}
}
if (!tok)
break;
} else if (tok->str() == "(") {
tok = tok->link();
} else if (tok->str() == "case") {
syntaxError(tok);
}
}
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!Token::simpleMatch(tok, "for (")) // find for loops
continue;
// count number of semicolons
int semicolons = 0, colons = 0;
const Token* const startTok = tok;
tok = tok->linkAt(1)->previous(); // find ")" of the for-loop
// walk backwards until we find the beginning (startTok) of the for() again
for (; tok != startTok; tok = tok->previous()) {
if (tok->str() == ";") { // do the counting
semicolons++;
} else if (tok->str() == ":") {
colons++;
} else if (tok->str() == ")") { // skip pairs of ( )
tok = tok->link();
}
}
// if we have an invalid number of semicolons inside for( ), assume syntax error
if (semicolons > 2)
syntaxError(tok);
if (semicolons == 1 && !(cpp && mSettings.standards.cpp >= Standards::CPP20))
syntaxError(tok);
if (semicolons == 0 && colons == 0)
syntaxError(tok);
}
// Operators without operands..
const Token *templateEndToken = nullptr;
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (!templateEndToken) {
if (tok->str() == "<" && cpp)
templateEndToken = tok->findClosingBracket();
} else {
if (templateEndToken == tok)
templateEndToken = nullptr;
if (Token::Match(tok, "> %cop%"))
continue;
}
// skip C++ attributes [[...]]
if (isCPP11 && (isCPPAttribute(tok) || isAlignAttribute(tok))) {
tok = skipCPPOrAlignAttribute(tok);
continue;
}
{
bool match1 = Token::Match(tok, "%or%|%oror%|==|!=|+|-|/|!|>=|<=|~|^|++|--|::|sizeof");
bool match2 = Token::Match(tok->next(), "{|if|else|while|do|for|return|switch|break");
if (cpp) {
match1 = match1 || Token::Match(tok, "throw|decltype|typeof");
match2 = match2 || Token::Match(tok->next(), "try|catch|namespace");
}
if (match1 && !tok->isIncDecOp()) {
match2 = match2 || Token::Match(tok->next(), "%assign%");
}
if (match1 && match2)
syntaxError(tok);
}
if (Token::Match(tok, "%or%|%oror%|~|^|!|%comp%|+|-|/|%")) {
std::string code;
if (Token::Match(tok->next(), ")|]|}"))
code = tok->str() + tok->strAt(1);
if (Token::simpleMatch(tok->next(), "( )"))
code = tok->str() + "()";
if (!code.empty()) {
if (isC() || (tok->str() != ">" && !Token::simpleMatch(tok->previous(), "operator")))
syntaxError(tok, code);
}
}
if (Token::Match(tok, "%num%|%bool%|%char%|%str% %num%|%bool%|%char%|%str%") && !Token::Match(tok, "%str% %str%"))
syntaxError(tok);
if (Token::Match(tok, "%num%|%bool%|%char%|%str% {|(")) {
if (tok->strAt(1) == "(")
syntaxError(tok);
else if (!(tok->tokType() == Token::Type::eString && Token::simpleMatch(tok->tokAt(-1), "extern")) &&
!(tok->tokType() == Token::Type::eBoolean && cpp && Token::simpleMatch(tok->tokAt(-1), "requires")))
syntaxError(tok);
}
if (Token::Match(tok, "( ) %num%|%bool%|%char%|%str%"))
syntaxError(tok);
if (Token::Match(tok, "%assign% typename|class %assign%"))
syntaxError(tok);
if (Token::Match(tok, "%assign% [;)}]") && (!cpp || !Token::simpleMatch(tok->previous(), "operator")))
syntaxError(tok);
if (Token::Match(tok, "; %assign%"))
syntaxError(tok);
if (Token::Match(tok, "%cop%|=|,|[ %or%|%oror%|/|%"))
syntaxError(tok);
if (Token::Match(tok, "[;([{] %comp%|%oror%|%or%|%|/"))
syntaxError(tok);
if (Token::Match(tok, "%cop%|= ]") && !(cpp && Token::Match(tok->previous(), "%type%|[|,|%num% &|=|> ]")))
syntaxError(tok);
if (Token::Match(tok, "[+-] [;,)]}]") && !(cpp && Token::simpleMatch(tok->previous(), "operator")))
syntaxError(tok);
if (Token::simpleMatch(tok, ",") &&
!Token::Match(tok->tokAt(-2), "[ = , &|%name%")) {
if (Token::Match(tok->previous(), "(|[|{|<|%assign%|%or%|%oror%|==|!=|+|-|/|!|>=|<=|~|^|::|sizeof"))
syntaxError(tok);
if (cpp && Token::Match(tok->previous(), "throw|decltype|typeof"))
syntaxError(tok);
if (Token::Match(tok->next(), ")|]|>|%assign%|%or%|%oror%|==|!=|/|>=|<=|&&"))
syntaxError(tok);
}
if (Token::simpleMatch(tok, ".") &&
!Token::simpleMatch(tok->previous(), ".") &&
!Token::simpleMatch(tok->next(), ".") &&
!Token::Match(tok->previous(), "{|, . %name% =|.|[|{") &&
!Token::Match(tok->previous(), ", . %name%")) {
if (!Token::Match(tok->previous(), "%name%|)|]|>|}"))
syntaxError(tok, tok->strAt(-1) + " " + tok->str() + " " + tok->strAt(1));
if (!Token::Match(tok->next(), "%name%|*|~"))
syntaxError(tok, tok->strAt(-1) + " " + tok->str() + " " + tok->strAt(1));
}
if (Token::Match(tok, "[{,] . %name%") && !Token::Match(tok->tokAt(3), "[.=[{]"))
syntaxError(tok->next());
if (Token::Match(tok, "[!|+-/%^~] )|]"))
syntaxError(tok);
if (Token::Match(tok, "==|!=|<=|>= %comp%") && tok->strAt(-1) != "operator")
syntaxError(tok, tok->str() + " " + tok->strAt(1));
if (Token::simpleMatch(tok, "::") && (!Token::Match(tok->next(), "%name%|*|~") ||
(tok->next()->isKeyword() && !Token::Match(tok->next(), "new|delete|operator"))))
syntaxError(tok);
if (Token::Match(tok, "& %comp%|&&|%oror%|&|%or%") && tok->strAt(1) != ">")
syntaxError(tok);
if (Token::Match(tok, "^ %op%") && !Token::Match(tok->next(), "[>*+-!~]"))
syntaxError(tok);
if (Token::Match(tok, ": [)]=]"))
syntaxError(tok);
if (Token::Match(tok, "typedef [,;:]"))
syntaxError(tok);
if (Token::Match(tok, "!|~ %comp%") &&
!(cpp && tok->strAt(1) == ">" && Token::simpleMatch(tok->tokAt(-1), "operator")))
syntaxError(tok);
if (Token::Match(tok, "] %name%") && (!cpp || !(tok->tokAt(-1) && Token::simpleMatch(tok->tokAt(-2), "delete [")))) {
if (tok->next()->isUpperCaseName())
unknownMacroError(tok->next());
else
syntaxError(tok);
}
if (tok->link() && Token::Match(tok, "[([]") && (!tok->tokAt(-1) || !tok->tokAt(-1)->isControlFlowKeyword())) {
const Token* const end = tok->link();
for (const Token* inner = tok->next(); inner != end; inner = inner->next()) {
if (inner->str() == "{")
inner = inner->link();
else if (inner->str() == ";" || (Token::simpleMatch(inner, ", ,") && (!cpp || !Token::simpleMatch(inner->previous(), "operator")))) {
if (tok->tokAt(-1) && tok->tokAt(-1)->isUpperCaseName())
unknownMacroError(tok->tokAt(-1));
else
syntaxError(inner);
}
}
}
if ((!cpp || !Token::simpleMatch(tok->previous(), "operator")) && Token::Match(tok, "[,;] ,"))
syntaxError(tok);
if (tok->str() == "typedef") {
for (const Token* tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) {
if (tok2->str() == "{") {
tok2 = tok2->link();
continue;
}
if (isUnevaluated(tok2)) {
tok2 = tok2->linkAt(1);
continue;
}
if (!tok2->next() || tok2->isControlFlowKeyword() || Token::Match(tok2, "typedef|static|."))
syntaxError(tok);
if (Token::Match(tok2, "%name% %name%") && tok2->str() == tok2->strAt(1)) {
if (Token::simpleMatch(tok2->tokAt(2), ";"))
continue;
if (tok2->isStandardType() && tok2->str() == "long")
continue;
if (Token::Match(tok2->tokAt(-1), "enum|struct|union") || (isCPP() && Token::Match(tok2->tokAt(-1), "class|::")))
continue;
syntaxError(tok2);
}
}
}
if (cpp && tok->str() == "namespace" && tok->tokAt(-1)) {
if (!Token::Match(tok->tokAt(-1), ";|{|}|using|inline")) {
if (tok->tokAt(-1)->isUpperCaseName())
unknownMacroError(tok->tokAt(-1));
else if (tok->linkAt(-1) && tok->linkAt(-1)->tokAt(-1) && tok->linkAt(-1)->tokAt(-1)->isUpperCaseName())
unknownMacroError(tok->linkAt(-1)->tokAt(-1));
else
syntaxError(tok);
}
}
}
// ternary operator without :
if (const Token *ternaryOp = findUnmatchedTernaryOp(tokens(), nullptr))
syntaxError(ternaryOp);
// Code must not start with an arithmetical operand
if (Token::Match(list.front(), "%cop%"))
syntaxError(list.front());
// Code must end with } ; ) NAME
if (!Token::Match(list.back(), "%name%|;|}|)"))
syntaxError(list.back());
if (list.back()->str() == ")" && !Token::Match(list.back()->link()->previous(), "%name%|> ("))
syntaxError(list.back());
for (const Token *end = list.back(); end && end->isName(); end = end->previous()) {
if (Token::Match(end, "void|char|short|int|long|float|double|const|volatile|static|inline|struct|class|enum|union|template|sizeof|case|break|continue|typedef"))
syntaxError(list.back());
}
if ((list.back()->str()==")" || list.back()->str()=="}") && list.back()->previous() && list.back()->previous()->isControlFlowKeyword())
syntaxError(list.back()->previous());
// Garbage templates..
if (cpp) {
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "< >") && !(Token::Match(tok->tokAt(-1), "%name%") || (tok->tokAt(-1) && Token::Match(tok->tokAt(-2), "operator %op%"))))
syntaxError(tok);
if (Token::simpleMatch(tok, ": template") && !Token::Match(tok->tokAt(-1), "public|private|protected"))
syntaxError(tok);
if (!Token::simpleMatch(tok, "template <"))
continue;
if (!tok->tokAt(2) || tok->tokAt(2)->isLiteral())
syntaxError(tok);
if (tok->previous() && !Token::Match(tok->previous(), ":|,|;|{|}|)|<|>|\"C++\"")) {
if (tok->previous()->isUpperCaseName())
unknownMacroError(tok->previous());
else
syntaxError(tok);
}
const Token * const tok1 = tok->next()->findClosingBracket();
if (!tok1)
syntaxError(tok);
if (!Token::Match(tok1, ">|>> ::|...| %name%") &&
!Token::Match(tok1, ">|>> [ [ %name%") &&
!Token::Match(tok1, "> >|*"))
syntaxError(tok1->next() ? tok1->next() : tok);
}
}
// Objective C/C++
for (const Token *tok = tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "[;{}] [ %name% %name% ] ;"))
syntaxError(tok->next());
}
}
bool Tokenizer::isGarbageExpr(const Token *start, const Token *end, bool allowSemicolon)
{
for (const Token *tok = start; tok != end; tok = tok->next()) {
if (tok->isControlFlowKeyword())
return true;
if (!allowSemicolon && tok->str() == ";")
return true;
if (tok->str() == "{")
tok = tok->link();
}
return false;
}
std::string Tokenizer::simplifyString(const std::string &source)
{
std::string str = source;
for (std::string::size_type i = 0; i + 1U < str.size(); ++i) {
if (str[i] != '\\')
continue;
int c = 'a'; // char
int sz = 0; // size of stringdata
if (str[i+1] == 'x') {
sz = 2;
while (sz < 4 && std::isxdigit((unsigned char)str[i+sz]))
sz++;
if (sz > 2) {
std::istringstream istr(str.substr(i+2, sz-2));
istr >> std::hex >> c;
}
} else if (MathLib::isOctalDigit(str[i+1])) {
sz = 2;
while (sz < 4 && MathLib::isOctalDigit(str[i+sz]))
sz++;
std::istringstream istr(str.substr(i+1, sz-1));
istr >> std::oct >> c;
str = str.replace(i, sz, std::string(1U, (char)c));
continue;
}
if (sz <= 2)
i++;
else if (i+sz < str.size())
str.replace(i, sz, std::string(1U, (char)c));
else
str.replace(i, str.size() - i - 1U, "a");
}
return str;
}
void Tokenizer::simplifyFunctionTryCatch()
{
if (!isCPP())
return;
for (Token * tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "try {|:"))
continue;
if (!isFunctionHead(tok->previous(), "try"))
continue;
Token* tryStartToken = skipInitializerList(tok->next());
if (!Token::simpleMatch(tryStartToken, "{"))
syntaxError(tryStartToken, "Invalid function-try-catch block code. Did not find '{' for try body.");
// find the end of the last catch block
Token * const tryEndToken = tryStartToken->link();
Token * endToken = tryEndToken;
while (Token::simpleMatch(endToken, "} catch (")) {
endToken = endToken->linkAt(2)->next();
if (!endToken)
break;
if (endToken->str() != "{") {
endToken = nullptr;
break;
}
endToken = endToken->link();
}
if (!endToken || endToken == tryEndToken)
continue;
tok->previous()->insertToken("{");
endToken->insertToken("}");
Token::createMutualLinks(tok->previous(), endToken->next());
}
}
static bool isAnonymousEnum(const Token* tok)
{
if (!Token::Match(tok, "enum {|:"))
return false;
if (tok->index() > 2 && Token::Match(tok->tokAt(-3), "using %name% ="))
return false;
const Token* end = tok->next();
if (end->str() == ":") {
end = end->next();
while (Token::Match(end, "%name%|::"))
end = end->next();
}
return end && Token::Match(end->link(), "} (| %type%| )| [,;[({=]");
}
void Tokenizer::simplifyStructDecl()
{
const bool cpp = isCPP();
// A counter that is used when giving unique names for anonymous structs.
int count = 0;
// Add names for anonymous structs
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName())
continue;
// check for anonymous struct/union
if (Token::Match(tok, "struct|union {")) {
if (Token::Match(tok->linkAt(1), "} const| *|&| const| %type% ,|;|[|(|{|=")) {
tok->insertToken("Anonymous" + std::to_string(count++));
}
}
// check for derived anonymous class/struct
else if (cpp && Token::Match(tok, "class|struct :")) {
const Token *tok1 = Token::findsimplematch(tok, "{");
if (tok1 && Token::Match(tok1->link(), "} const| *|&| const| %type% ,|;|[|(|{")) {
tok->insertToken("Anonymous" + std::to_string(count++));
}
}
// check for anonymous enum
else if (isAnonymousEnum(tok)) {
Token *start = tok->strAt(1) == ":" ? tok->linkAt(3) : tok->linkAt(1);
if (start && Token::Match(start->next(), "( %type% )")) {
start->linkAt(1)->deleteThis();
start->next()->deleteThis();
}
tok->insertToken("Anonymous" + std::to_string(count++));
}
}
// "{" token for current scope
std::stack<const Token*> scopeStart;
const Token* functionEnd = nullptr;
for (Token *tok = list.front(); tok; tok = tok->next()) {
// check for start of scope and determine if it is in a function
if (tok->str() == "{") {
scopeStart.push(tok);
if (!functionEnd && Token::Match(tok->previous(), "const|)"))
functionEnd = tok->link();
}
// end of scope
else if (tok->str() == "}") {
if (!scopeStart.empty())
scopeStart.pop();
if (tok == functionEnd)
functionEnd = nullptr;
}
// check for named struct/union
else if (Token::Match(tok, "class|struct|union|enum %type% :|{")) {
Token *start = tok;
while (Token::Match(start->previous(), "%type%"))
start = start->previous();
const Token * const type = tok->next();
Token *next = tok->tokAt(2);
while (next && !Token::Match(next, "[{;]"))
next = next->next();
if (!next || next->str() == ";")
continue;
Token* after = next->link();
if (!after)
break; // see #4869 segmentation fault in Tokenizer::simplifyStructDecl (invalid code)
// check for named type
if (Token::Match(after->next(), "const|static|volatile| *|&| const| (| %type% )| ,|;|[|=|(|{")) {
after->insertToken(";");
after = after->next();
while (!Token::Match(start, "struct|class|union|enum")) {
after->insertToken(start->str());
after = after->next();
start->deleteThis();
}
tok = start;
if (!after)
break; // see #4869 segmentation fault in Tokenizer::simplifyStructDecl (invalid code)
after->insertToken(type->str());
if (start->str() != "class") {
after->insertToken(start->str());
after = after->next();
}
after = after->tokAt(2);
if (Token::Match(after, "( %type% )")) {
after->link()->deleteThis();
after->deleteThis();
}
// check for initialization
if (Token::Match(after, "%any% (|{")) {
after->insertToken("=");
after = after->next();
const bool isEnum = start->str() == "enum";
if (!isEnum && cpp) {
after->insertToken(type->str());
after = after->next();
}
if (isEnum) {
if (Token::Match(after->next(), "{ !!}")) {
after->next()->str("(");
after->linkAt(1)->str(")");
}
}
}
}
}
// check for anonymous struct/union
else {
// unnamed anonymous struct/union so possibly remove it
bool done = false;
while (!done && Token::Match(tok, "struct|union {") && Token::simpleMatch(tok->linkAt(1), "} ;")) {
done = true;
// is this a class/struct/union scope?
bool isClassStructUnionScope = false;
if (!scopeStart.empty()) {
for (const Token* tok2 = scopeStart.top()->previous(); tok2 && !Token::Match(tok2, "[;{}]"); tok2 = tok2->previous()) {
if (Token::Match(tok2, "class|struct|union")) {
isClassStructUnionScope = true;
break;
}
}
}
// remove unnamed anonymous struct/union
// * not in class/struct/union scopes
if (Token::simpleMatch(tok->linkAt(1), "} ;") && !isClassStructUnionScope && tok->str() != "union") {
tok->linkAt(1)->previous()->deleteNext(2);
tok->deleteNext();
tok->deleteThis();
done = false;
}
}
}
}
}
void Tokenizer::simplifyCallingConvention()
{
const bool windows = mSettings.platform.isWindows();
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (Token::Match(tok, "__cdecl|__stdcall|__fastcall|__thiscall|__clrcall|__syscall|__pascal|__fortran|__far|__near") || (windows && Token::Match(tok, "WINAPI|APIENTRY|CALLBACK"))) {
tok->deleteThis();
}
}
}
static bool isAttribute(const Token* tok, bool gcc) {
return gcc ? Token::Match(tok, "__attribute__|__attribute (") : Token::Match(tok, "__declspec|_declspec (");
}
static Token* getTokenAfterAttributes(Token* tok, bool gccattr) {
Token* after = tok;
while (isAttribute(after, gccattr))
after = after->linkAt(1)->next();
return after;
}
static Token* getVariableTokenAfterAttributes(Token* tok) {
Token *vartok = nullptr;
Token *after = getTokenAfterAttributes(tok, true);
// check if after variable name
if (Token::Match(after, ";|=")) {
Token *prev = tok->previous();
while (Token::simpleMatch(prev, "]"))
prev = prev->link()->previous();
if (Token::Match(prev, "%type%"))
vartok = prev;
}
// check if before variable name
else if (Token::Match(after, "%type%"))
vartok = after;
return vartok;
}
Token* Tokenizer::getAttributeFuncTok(Token* tok, bool gccattr) const {
if (!Token::Match(tok, "%name% ("))
return nullptr;
Token* const after = getTokenAfterAttributes(tok, gccattr);
if (!after)
syntaxError(tok);
if (Token::Match(after, "%name%|*|&|(")) {
Token *ftok = after;
while (Token::Match(ftok, "%name%|::|<|*|& !!(")) {
if (ftok->str() == "<") {
ftok = ftok->findClosingBracket();
if (!ftok)
break;
}
ftok = ftok->next();
}
if (Token::simpleMatch(ftok, "( *"))
ftok = ftok->tokAt(2);
if (Token::Match(ftok, "%name% (|)"))
return ftok;
} else if (Token::Match(after, "[;{=:]")) {
Token *prev = tok->previous();
while (Token::Match(prev, "%name%"))
prev = prev->previous();
if (Token::simpleMatch(prev, ")")) {
if (Token::Match(prev->link()->previous(), "%name% ("))
return prev->link()->previous();
if (Token::Match(prev->link()->tokAt(-2), "%name% ) ("))
return prev->link()->tokAt(-2);
}
if (Token::simpleMatch(prev, ")") && Token::Match(prev->link()->tokAt(-2), "operator %op% (") && isCPP())
return prev->link()->tokAt(-2);
if ((!prev || Token::Match(prev, "[;{}*]")) && Token::Match(tok->previous(), "%name%"))
return tok->previous();
}
return nullptr;
}
void Tokenizer::simplifyDeclspec()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
while (isAttribute(tok, false)) {
if (Token::Match(tok->tokAt(2), "noreturn|nothrow|dllexport")) {
Token *functok = getAttributeFuncTok(tok, false);
if (functok) {
if (tok->strAt(2) == "noreturn")
functok->isAttributeNoreturn(true);
else if (tok->strAt(2) == "nothrow")
functok->isAttributeNothrow(true);
else
functok->isAttributeExport(true);
}
} else if (tok->strAt(2) == "property")
tok->linkAt(1)->insertToken("__property");
Token::eraseTokens(tok, tok->linkAt(1)->next());
tok->deleteThis();
}
}
}
void Tokenizer::simplifyAttribute()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isKeyword() && Token::Match(tok, "%type% (") && !mSettings.library.isNotLibraryFunction(tok)) {
if (mSettings.library.isFunctionConst(tok->str(), true))
tok->isAttributePure(true);
if (mSettings.library.isFunctionConst(tok->str(), false))
tok->isAttributeConst(true);
}
while (isAttribute(tok, true)) {
Token *functok = getAttributeFuncTok(tok, true);
for (Token *attr = tok->tokAt(2); attr->str() != ")"; attr = attr->next()) {
if (Token::Match(attr, "%name% ("))
attr = attr->linkAt(1);
if (Token::Match(attr, "[(,] constructor|__constructor__ [,()]")) {
if (!functok)
syntaxError(tok);
functok->isAttributeConstructor(true);
}
else if (Token::Match(attr, "[(,] destructor|__destructor__ [,()]")) {
if (!functok)
syntaxError(tok);
functok->isAttributeDestructor(true);
}
else if (Token::Match(attr, "[(,] unused|__unused__|used|__used__ [,)]")) {
Token *vartok = getVariableTokenAfterAttributes(tok);
if (vartok) {
const std::string &attribute(attr->strAt(1));
if (attribute.find("unused") != std::string::npos)
vartok->isAttributeUnused(true);
else
vartok->isAttributeUsed(true);
}
}
else if (Token::Match(attr, "[(,] pure|__pure__|const|__const__|noreturn|__noreturn__|nothrow|__nothrow__|warn_unused_result [,)]")) {
if (!functok)
syntaxError(tok);
const std::string &attribute(attr->strAt(1));
if (attribute.find("pure") != std::string::npos)
functok->isAttributePure(true);
else if (attribute.find("const") != std::string::npos)
functok->isAttributeConst(true);
else if (attribute.find("noreturn") != std::string::npos)
functok->isAttributeNoreturn(true);
else if (attribute.find("nothrow") != std::string::npos)
functok->isAttributeNothrow(true);
else if (attribute.find("warn_unused_result") != std::string::npos)
functok->isAttributeNodiscard(true);
}
else if (Token::Match(attr, "[(,] packed [,)]") && Token::simpleMatch(tok->previous(), "}"))
tok->previous()->isAttributePacked(true);
else if (functok && Token::simpleMatch(attr, "( __visibility__ ( \"default\" ) )"))
functok->isAttributeExport(true);
else if (Token::Match(attr, "[(,] cleanup ( %name% )")) {
Token *vartok = getVariableTokenAfterAttributes(tok);
if (vartok) {
const std::string& funcname = attr->strAt(3);
vartok->addAttributeCleanup(funcname);
}
}
}
Token::eraseTokens(tok, tok->linkAt(1)->next());
tok->deleteThis();
}
}
}
void Tokenizer::simplifyCppcheckAttribute()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() != "(")
continue;
if (!tok->previous())
continue;
const std::string &attr = tok->strAt(-1);
if (!startsWith(attr, "__cppcheck_"))
continue;
if (attr.compare(attr.size()-2, 2, "__") != 0) // TODO: ends_with("__")
continue;
Token *vartok = tok->link();
while (Token::Match(vartok->next(), "%name%|*|&|::")) {
vartok = vartok->next();
if (Token::Match(vartok, "%name% (") && startsWith(vartok->str(),"__cppcheck_"))
vartok = vartok->linkAt(1);
}
if (vartok->isName()) {
if (Token::Match(tok->previous(), "__cppcheck_low__ ( %num% )"))
vartok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::LOW,
MathLib::toBigNumber(tok->strAt(1)));
else if (Token::Match(tok->previous(), "__cppcheck_high__ ( %num% )"))
vartok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::HIGH,
MathLib::toBigNumber(tok->strAt(1)));
}
// Delete cppcheck attribute..
if (tok->tokAt(-2)) {
tok = tok->tokAt(-2);
Token::eraseTokens(tok, tok->linkAt(2)->next());
} else {
tok = tok->previous();
Token::eraseTokens(tok, tok->linkAt(1)->next());
tok->str(";");
}
}
}
void Tokenizer::simplifyCPPAttribute()
{
// According to cppreference alignas is a c21 feature however the macro is often available when compiling c11
const bool hasAlignas = ((isCPP() && mSettings.standards.cpp >= Standards::CPP11) || (isC() && mSettings.standards.c >= Standards::C11));
const bool hasCppAttribute = ((isCPP() && mSettings.standards.cpp >= Standards::CPP11) || (isC() && mSettings.standards.c >= Standards::C23));
if (!hasAlignas && !hasCppAttribute)
return;
for (Token *tok = list.front(); tok;) {
if (!isCPPAttribute(tok) && !isAlignAttribute(tok)) {
tok = tok->next();
continue;
}
if (isCPPAttribute(tok)) {
if (!hasCppAttribute) {
tok = skipCPPOrAlignAttribute(tok)->next();
continue;
}
if (Token::findsimplematch(tok->tokAt(2), "noreturn", tok->link())) {
Token * head = skipCPPOrAlignAttribute(tok)->next();
while (isCPPAttribute(head) || isAlignAttribute(head))
head = skipCPPOrAlignAttribute(head)->next();
while (Token::Match(head, "%name%|::|*|&|<|>|,")) // skip return type
head = head->next();
if (head && head->str() == "(" && isFunctionHead(head, "{|;")) {
head->previous()->isAttributeNoreturn(true);
}
} else if (Token::findsimplematch(tok->tokAt(2), "nodiscard", tok->link())) {
Token * head = skipCPPOrAlignAttribute(tok)->next();
while (isCPPAttribute(head) || isAlignAttribute(head))
head = skipCPPOrAlignAttribute(head)->next();
while (Token::Match(head, "%name%|::|*|&|<|>|,"))
head = head->next();
if (head && head->str() == "(" && isFunctionHead(head, "{|;")) {
head->previous()->isAttributeNodiscard(true);
}
} else if (Token::findsimplematch(tok->tokAt(2), "maybe_unused", tok->link())) {
Token* head = skipCPPOrAlignAttribute(tok)->next();
while (isCPPAttribute(head) || isAlignAttribute(head))
head = skipCPPOrAlignAttribute(head)->next();
head->isAttributeMaybeUnused(true);
} else if (Token::Match(tok->previous(), ") [ [ expects|ensures|assert default|audit|axiom| : %name% <|<=|>|>= %num% ] ]")) {
const Token *vartok = tok->tokAt(4);
if (vartok->str() == ":")
vartok = vartok->next();
Token *argtok = tok->tokAt(-2);
while (argtok && argtok->str() != "(") {
if (argtok->str() == vartok->str())
break;
if (argtok->str() == ")")
argtok = argtok->link();
argtok = argtok->previous();
}
if (argtok && argtok->str() == vartok->str()) {
if (vartok->strAt(1) == ">=")
argtok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::LOW,
MathLib::toBigNumber(vartok->strAt(2)));
else if (vartok->strAt(1) == ">")
argtok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::LOW,
MathLib::toBigNumber(vartok->strAt(2)) + 1);
else if (vartok->strAt(1) == "<=")
argtok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::HIGH,
MathLib::toBigNumber(vartok->strAt(2)));
else if (vartok->strAt(1) == "<")
argtok->setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type::HIGH,
MathLib::toBigNumber(vartok->strAt(2)) - 1);
}
}
} else {
// alignas(expr)
if (!hasAlignas) {
tok = skipCPPOrAlignAttribute(tok)->next();
continue;
}
// alignment requirements could be checked here
Token* atok = nullptr;
if (Token::Match(tok->previous(), "%name%"))
atok = tok->previous();
else {
atok = tok;
while (isCPPAttribute(atok) || isAlignAttribute(atok))
atok = skipCPPOrAlignAttribute(atok)->next();
}
if (atok) {
std::string a;
for (const Token* t = tok->tokAt(2); t && t->str() != ")"; t = t->next())
a += " " + t->str();
if (a.size() > 1)
atok->addAttributeAlignas(a.substr(1));
}
}
Token::eraseTokens(tok, skipCPPOrAlignAttribute(tok)->next());
tok->deleteThis();
}
}
void Tokenizer::simplifySpaceshipOperator()
{
if (isCPP() && mSettings.standards.cpp >= Standards::CPP20) {
for (Token *tok = list.front(); tok && tok->next(); tok = tok->next()) {
if (Token::simpleMatch(tok, "<= >")) {
tok->str("<=>");
tok->deleteNext();
}
}
}
}
static const std::unordered_set<std::string> keywords = {
"inline"
, "_inline"
, "__inline"
, "__forceinline"
, "register"
, "__restrict"
, "__restrict__"
, "__thread"
};
// Remove "inline", "register", "restrict", "override", "static" and "constexpr"
// "restrict" keyword
// - New to 1999 ANSI/ISO C standard
// - Not in C++ standard yet
void Tokenizer::simplifyKeyword()
{
// FIXME: There is a risk that "keywords" are removed by mistake. This
// code should be fixed so it doesn't remove variables etc. Nonstandard
// keywords should be defined with a library instead. For instance the
// linux kernel code at least uses "_inline" as struct member name at some
// places.
const bool c99 = isC() && mSettings.standards.c >= Standards::C99;
const bool cpp11 = isCPP() && mSettings.standards.cpp >= Standards::CPP11;
const bool cpp20 = isCPP() && mSettings.standards.cpp >= Standards::CPP20;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (keywords.find(tok->str()) != keywords.end()) {
// Don't remove struct members
if (!Token::simpleMatch(tok->previous(), ".")) {
const bool isinline = (tok->str().find("inline") != std::string::npos);
const bool isrestrict = (tok->str().find("restrict") != std::string::npos);
if (isinline || isrestrict) {
for (Token *temp = tok->next(); Token::Match(temp, "%name%"); temp = temp->next()) {
if (isinline)
temp->isInline(true);
if (isrestrict)
temp->isRestrict(true);
}
}
tok->deleteThis(); // Simplify..
}
}
if (isC() || mSettings.standards.cpp == Standards::CPP03) {
if (tok->str() == "auto")
tok->deleteThis();
}
// simplify static keyword:
// void foo( int [ static 5 ] ); ==> void foo( int [ 5 ] );
if (Token::Match(tok, "[ static %num%"))
tok->deleteNext();
if (c99) {
auto getTypeTokens = [tok]() {
std::vector<Token*> ret;
for (Token *temp = tok; Token::Match(temp, "%name%"); temp = temp->previous()) {
if (!temp->isKeyword())
ret.emplace_back(temp);
}
for (Token *temp = tok->next(); Token::Match(temp, "%name%"); temp = temp->next()) {
if (!temp->isKeyword())
ret.emplace_back(temp);
}
return ret;
};
if (tok->str() == "restrict") {
for (Token* temp: getTypeTokens())
temp->isRestrict(true);
tok->deleteThis();
}
if (mSettings.standards.c >= Standards::C11) {
while (tok->str() == "_Atomic") {
for (Token* temp: getTypeTokens())
temp->isAtomic(true);
tok->deleteThis();
}
}
}
else if (cpp11) {
if (cpp20 && tok->str() == "consteval") {
tok->originalName(tok->str());
tok->str("constexpr");
} else if (cpp20 && tok->str() == "constinit") {
tok->deleteThis();
}
// final:
// 1) struct name final { }; <- struct is final
if (Token::Match(tok->previous(), "struct|class|union %type%")) {
Token* finalTok = tok->next();
if (tok->isUpperCaseName() && Token::Match(finalTok, "%type%") && finalTok->str() != "final") {
tok = finalTok;
finalTok = finalTok->next();
}
if (Token::simpleMatch(finalTok, "<")) { // specialization
finalTok = finalTok->findClosingBracket();
if (finalTok)
finalTok = finalTok->next();
}
if (Token::Match(finalTok, "final [:{]")) {
finalTok->deleteThis();
tok->previous()->isFinalType(true);
}
}
// noexcept -> noexcept(true)
// 2) void f() noexcept; -> void f() noexcept(true);
else if (Token::Match(tok, ") const|override|final| noexcept :|{|;|,|const|override|final")) {
// Insertion is done in inverse order
// The brackets are linked together accordingly afterwards
Token* tokNoExcept = tok->next();
while (tokNoExcept->str() != "noexcept")
tokNoExcept = tokNoExcept->next();
tokNoExcept->insertToken(")");
Token * braceEnd = tokNoExcept->next();
tokNoExcept->insertToken("true");
tokNoExcept->insertToken("(");
Token * braceStart = tokNoExcept->next();
tok = tok->tokAt(3);
Token::createMutualLinks(braceStart, braceEnd);
}
// 3) thread_local -> static
// on single thread thread_local has the effect of static
else if (tok->str() == "thread_local") {
tok->originalName(tok->str());
tok->str("static");
}
}
}
}
static Token* setTokenDebug(Token* start, TokenDebug td)
{
if (!start->link())
return nullptr;
Token* end = start->link();
start->deleteThis();
for (Token* tok = start; tok != end; tok = tok->next()) {
tok->setTokenDebug(td);
}
end->deleteThis();
return end;
}
void Tokenizer::simplifyDebug()
{
if (!mSettings.debugnormal && !mSettings.debugwarnings)
return;
static const std::unordered_map<std::string, TokenDebug> m = {{"debug_valueflow", TokenDebug::ValueFlow},
{"debug_valuetype", TokenDebug::ValueType}};
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (!Token::Match(tok, "%name% ("))
continue;
auto it = m.find(tok->str());
if (it != m.end()) {
tok->deleteThis();
tok = setTokenDebug(tok, it->second);
}
}
}
void Tokenizer::simplifyAssignmentBlock()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "[;{}] %name% = ( {")) {
const std::string &varname = tok->strAt(1);
// goto the "} )"
int indentlevel = 0;
Token *tok2 = tok;
while (nullptr != (tok2 = tok2->next())) {
if (Token::Match(tok2, "(|{"))
++indentlevel;
else if (Token::Match(tok2, ")|}")) {
if (indentlevel <= 2)
break;
--indentlevel;
} else if (indentlevel == 2 && tok2->str() == varname && Token::Match(tok2->previous(), "%type%|*"))
// declaring variable in inner scope with same name as lhs variable
break;
}
if (indentlevel == 2 && Token::simpleMatch(tok2, "} )")) {
tok2 = tok2->tokAt(-3);
if (Token::Match(tok2, "[;{}] %num%|%name% ;")) {
tok2->insertToken("=");
tok2->insertToken(tok->strAt(1));
tok2->next()->varId(tok->next()->varId());
tok->deleteNext(3);
tok2->tokAt(5)->deleteNext();
}
}
}
}
}
// Remove __asm..
void Tokenizer::simplifyAsm()
{
std::string instruction;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "__asm|_asm|asm {") &&
tok->linkAt(1)->next()) {
instruction = tok->tokAt(2)->stringifyList(tok->linkAt(1));
Token::eraseTokens(tok, tok->linkAt(1)->next());
}
else if (Token::Match(tok, "asm|__asm|__asm__ volatile|__volatile|__volatile__| (")) {
// Goto "("
Token *partok = tok->next();
if (partok->str() != "(")
partok = partok->next();
instruction = partok->next()->stringifyList(partok->link());
Token::eraseTokens(tok, partok->link()->next());
}
else if (Token::Match(tok, "_asm|__asm")) {
Token *endasm = tok->next();
const Token *firstSemiColon = nullptr;
int comment = 0;
while (Token::Match(endasm, "%num%|%name%|,|:|;") || (endasm && endasm->linenr() == comment)) {
if (Token::Match(endasm, "_asm|__asm|__endasm"))
break;
if (endasm->str() == ";") {
comment = endasm->linenr();
if (!firstSemiColon)
firstSemiColon = endasm;
}
endasm = endasm->next();
}
if (Token::simpleMatch(endasm, "__endasm")) {
instruction = tok->next()->stringifyList(endasm);
Token::eraseTokens(tok, endasm->next());
if (!Token::simpleMatch(tok->next(), ";"))
tok->insertToken(";");
} else if (firstSemiColon) {
instruction = tok->next()->stringifyList(firstSemiColon);
Token::eraseTokens(tok, firstSemiColon);
} else if (!endasm) {
instruction = tok->next()->stringifyList(endasm);
Token::eraseTokens(tok, endasm);
tok->insertToken(";");
} else
continue;
}
else
continue;
if (Token::Match(tok->previous(), ") %name% %name% (")) {
tok->deleteThis();
continue;
}
// insert "asm ( "instruction" )"
tok->str("asm");
if (tok->strAt(1) != ";" && tok->strAt(1) != "{")
tok->insertToken(";");
tok->insertToken(")");
tok->insertToken("\"" + instruction + "\"");
tok->insertToken("(");
tok = tok->next();
Token::createMutualLinks(tok, tok->tokAt(2));
//move the new tokens in the same line as ";" if available
tok = tok->tokAt(2);
if (tok->next() && tok->strAt(1) == ";" &&
tok->next()->linenr() != tok->linenr()) {
const int endposition = tok->next()->linenr();
tok = tok->tokAt(-3);
for (int i = 0; i < 4; ++i) {
tok = tok->next();
tok->linenr(endposition);
}
}
}
}
void Tokenizer::simplifyAsm2()
{
// Block declarations: ^{}
// A C extension used to create lambda like closures.
// Put ^{} statements in asm()
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() != "^")
continue;
if (Token::simpleMatch(tok, "^ {") || (Token::simpleMatch(tok->linkAt(1), ") {") && tok->strAt(-1) != "operator")) {
Token * start = tok;
while (start && !Token::Match(start, "[,(;{}=]")) {
if (start->link() && Token::Match(start, ")|]|>"))
start = start->link();
start = start->previous();
}
const Token *last = tok->linkAt(1);
if (Token::simpleMatch(last, ") {"))
last = last->linkAt(1);
last = last->next();
while (last && !Token::Match(last, "%cop%|,|;|{|}|)")) {
if (Token::Match(last, "(|["))
last = last->link();
last = last->next();
}
if (start && last) {
std::string asmcode;
while (start->next() != last) {
asmcode += start->strAt(1);
start->deleteNext();
}
if (last->str() == "}")
start->insertToken(";");
start->insertToken(")");
start->insertToken("\"" + asmcode + "\"");
start->insertToken("(");
start->insertToken("asm");
start->tokAt(2)->link(start->tokAt(4));
start->tokAt(4)->link(start->tokAt(2));
tok = start->tokAt(4);
}
}
}
}
void Tokenizer::simplifyAt()
{
std::set<std::string> var;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%name%|]|) @ %num%|%name%|%str%|(")) {
const Token *end = tok->tokAt(2);
if (end->isLiteral())
end = end->next();
else if (end->str() == "(") {
int par = 0;
while ((end = end->next()) != nullptr) {
if (end->str() == "(")
par++;
else if (end->str() == ")") {
if (--par < 0)
break;
}
}
end = end ? end->next() : nullptr;
} else if (var.find(end->str()) != var.end())
end = end->next();
else
continue;
if (Token::Match(end, ": %num% ;"))
end = end->tokAt(2);
if (Token::Match(end, "[;=]")) {
if (tok->isName())
var.insert(tok->str());
tok->isAtAddress(true);
Token::eraseTokens(tok, end);
}
}
// keywords in compiler from cosmic software for STM8
// TODO: Should use platform configuration.
if (Token::Match(tok, "@ builtin|eeprom|far|inline|interrupt|near|noprd|nostack|nosvf|packed|stack|svlreg|tiny|vector")) {
tok->str(tok->strAt(1) + "@");
tok->deleteNext();
}
}
}
// Simplify bitfields
void Tokenizer::simplifyBitfields()
{
bool goback = false;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (goback) {
goback = false;
tok = tok->previous();
}
Token *last = nullptr;
if (Token::simpleMatch(tok, "for ("))
tok = tok->linkAt(1);
if (!Token::Match(tok, ";|{|}|public:|protected:|private:"))
continue;
bool isEnum = false;
if (tok->str() == "}") {
const Token *type = tok->link()->previous();
while (type && type->isName()) {
if (type->str() == "enum") {
isEnum = true;
break;
}
type = type->previous();
}
}
if (Token::Match(tok->next(), "const| %type% %name% :") &&
!Token::Match(tok->next(), "case|public|protected|private|class|struct") &&
!Token::simpleMatch(tok->tokAt(2), "default :")) {
Token *tok1 = (tok->strAt(1) == "const") ? tok->tokAt(3) : tok->tokAt(2);
if (Token::Match(tok1, "%name% : %num% [;=]"))
tok1->setBits(MathLib::toBigNumber(tok1->strAt(2)));
if (tok1 && tok1->tokAt(2) &&
(Token::Match(tok1->tokAt(2), "%bool%|%num%") ||
!Token::Match(tok1->tokAt(2), "public|protected|private| %type% ::|<|,|{|;"))) {
while (tok1->next() && !Token::Match(tok1->next(), "[;,)]{}=]")) {
if (Token::Match(tok1->next(), "[([]"))
Token::eraseTokens(tok1, tok1->linkAt(1));
tok1->deleteNext();
}
last = tok1->next();
}
} else if (isEnum && Token::Match(tok, "} %name%| : %num% ;")) {
if (tok->strAt(1) == ":") {
tok->deleteNext(2);
tok->insertToken("Anonymous");
} else {
tok->next()->deleteNext(2);
}
} else if (Token::Match(tok->next(), "const| %type% : %num%|%bool% ;") &&
tok->strAt(1) != "default") {
const int offset = (tok->strAt(1) == "const") ? 1 : 0;
if (!Token::Match(tok->tokAt(3 + offset), "[{};()]")) {
tok->deleteNext(4 + offset);
goback = true;
}
}
if (last && last->str() == ",") {
Token * tok1 = last;
tok1->str(";");
const Token *const tok2 = tok->next();
tok1->insertToken(tok2->str());
tok1 = tok1->next();
tok1->isSigned(tok2->isSigned());
tok1->isUnsigned(tok2->isUnsigned());
tok1->isLong(tok2->isLong());
}
}
}
static bool isStdContainerOrIterator(const Token* tok, const Settings& settings)
{
const Library::Container* ctr = settings.library.detectContainerOrIterator(tok, nullptr, /*withoutStd*/ true);
return ctr && startsWith(ctr->startPattern, "std ::");
}
static bool isStdSmartPointer(const Token* tok, const Settings& settings)
{
const Library::SmartPointer* ptr = settings.library.detectSmartPointer(tok, /*withoutStd*/ true);
return ptr && startsWith(ptr->name, "std::");
}
// Add std:: in front of std classes, when using namespace std; was given
void Tokenizer::simplifyNamespaceStd()
{
if (!isCPP())
return;
std::set<std::string> userFunctions;
for (Token* tok = Token::findsimplematch(list.front(), "using namespace std ;"); tok; tok = tok->next()) {
bool insert = false;
if (Token::Match(tok, "enum class|struct| %name%| :|{")) { // Don't replace within enum definitions
skipEnumBody(tok);
}
if (!tok->isName() || tok->isKeyword() || tok->isStandardType() || tok->varId())
continue;
if (Token::Match(tok->previous(), ".|::|namespace"))
continue;
if (Token::simpleMatch(tok->next(), "(")) {
if (isFunctionHead(tok->next(), "{"))
userFunctions.insert(tok->str());
else if (isFunctionHead(tok->next(), ";")) {
const Token *start = tok;
while (Token::Match(start->previous(), "%type%|*|&"))
start = start->previous();
if (start != tok && start->isName() && !start->isKeyword() && (!start->previous() || Token::Match(start->previous(), "[;{}]")))
userFunctions.insert(tok->str());
}
if (userFunctions.find(tok->str()) == userFunctions.end() && mSettings.library.matchArguments(tok, "std::" + tok->str()))
insert = true;
} else if (Token::simpleMatch(tok->next(), "<") &&
(isStdContainerOrIterator(tok, mSettings) || isStdSmartPointer(tok, mSettings)))
insert = true;
else if (mSettings.library.hasAnyTypeCheck("std::" + tok->str()) ||
mSettings.library.podtype("std::" + tok->str()) ||
isStdContainerOrIterator(tok, mSettings))
insert = true;
if (insert) {
tok->previous()->insertToken("std");
tok->previous()->linenr(tok->linenr()); // For stylistic reasons we put the std:: in the same line as the following token
tok->previous()->fileIndex(tok->fileIndex());
tok->previous()->insertToken("::");
}
}
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (Token::simpleMatch(tok, "using namespace std ;")) {
Token::eraseTokens(tok, tok->tokAt(4));
tok->deleteThis();
}
}
}
void Tokenizer::simplifyMicrosoftMemoryFunctions()
{
// skip if not Windows
if (!mSettings.platform.isWindows())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->strAt(1) != "(")
continue;
if (Token::Match(tok, "CopyMemory|RtlCopyMemory|RtlCopyBytes")) {
tok->str("memcpy");
} else if (Token::Match(tok, "MoveMemory|RtlMoveMemory")) {
tok->str("memmove");
} else if (Token::Match(tok, "FillMemory|RtlFillMemory|RtlFillBytes")) {
// FillMemory(dst, len, val) -> memset(dst, val, len)
tok->str("memset");
Token *tok1 = tok->tokAt(2);
if (tok1)
tok1 = tok1->nextArgument(); // Second argument
if (tok1) {
Token *tok2 = tok1->nextArgument(); // Third argument
if (tok2)
Token::move(tok1->previous(), tok2->tokAt(-2), tok->linkAt(1)->previous()); // Swap third with second argument
}
} else if (Token::Match(tok, "ZeroMemory|RtlZeroMemory|RtlZeroBytes|RtlSecureZeroMemory")) {
// ZeroMemory(dst, len) -> memset(dst, 0, len)
tok->str("memset");
Token *tok1 = tok->tokAt(2);
if (tok1)
tok1 = tok1->nextArgument(); // Second argument
if (tok1) {
tok1 = tok1->previous();
tok1->insertToken("0");
tok1 = tok1->next();
tok1->insertToken(",");
}
} else if (Token::simpleMatch(tok, "RtlCompareMemory")) {
// RtlCompareMemory(src1, src2, len) -> memcmp(src1, src2, len)
tok->str("memcmp");
// For the record, when memcmp returns 0, both strings are equal.
// When RtlCompareMemory returns len, both strings are equal.
// It might be needed to improve this replacement by something
// like ((len - memcmp(src1, src2, len)) % (len + 1)) to
// respect execution path (if required)
}
}
}
namespace {
struct triplet {
triplet(const char* m, const char* u) : mbcs(m), unicode(u) {}
std::string mbcs, unicode;
};
const std::map<std::string, triplet> apis = {
std::make_pair("_topen", triplet("open", "_wopen")),
std::make_pair("_tsopen_s", triplet("_sopen_s", "_wsopen_s")),
std::make_pair("_tfopen", triplet("fopen", "_wfopen")),
std::make_pair("_tfopen_s", triplet("fopen_s", "_wfopen_s")),
std::make_pair("_tfreopen", triplet("freopen", "_wfreopen")),
std::make_pair("_tfreopen_s", triplet("freopen_s", "_wfreopen_s")),
std::make_pair("_tcscat", triplet("strcat", "wcscat")),
std::make_pair("_tcschr", triplet("strchr", "wcschr")),
std::make_pair("_tcscmp", triplet("strcmp", "wcscmp")),
std::make_pair("_tcsdup", triplet("strdup", "wcsdup")),
std::make_pair("_tcscpy", triplet("strcpy", "wcscpy")),
std::make_pair("_tcslen", triplet("strlen", "wcslen")),
std::make_pair("_tcsncat", triplet("strncat", "wcsncat")),
std::make_pair("_tcsncpy", triplet("strncpy", "wcsncpy")),
std::make_pair("_tcsnlen", triplet("strnlen", "wcsnlen")),
std::make_pair("_tcsrchr", triplet("strrchr", "wcsrchr")),
std::make_pair("_tcsstr", triplet("strstr", "wcsstr")),
std::make_pair("_tcstok", triplet("strtok", "wcstok")),
std::make_pair("_ftprintf", triplet("fprintf", "fwprintf")),
std::make_pair("_tprintf", triplet("printf", "wprintf")),
std::make_pair("_stprintf", triplet("sprintf", "swprintf")),
std::make_pair("_sntprintf", triplet("_snprintf", "_snwprintf")),
std::make_pair("_ftscanf", triplet("fscanf", "fwscanf")),
std::make_pair("_tscanf", triplet("scanf", "wscanf")),
std::make_pair("_stscanf", triplet("sscanf", "swscanf")),
std::make_pair("_ftprintf_s", triplet("fprintf_s", "fwprintf_s")),
std::make_pair("_tprintf_s", triplet("printf_s", "wprintf_s")),
std::make_pair("_stprintf_s", triplet("sprintf_s", "swprintf_s")),
std::make_pair("_sntprintf_s", triplet("_snprintf_s", "_snwprintf_s")),
std::make_pair("_ftscanf_s", triplet("fscanf_s", "fwscanf_s")),
std::make_pair("_tscanf_s", triplet("scanf_s", "wscanf_s")),
std::make_pair("_stscanf_s", triplet("sscanf_s", "swscanf_s"))
};
}
void Tokenizer::simplifyMicrosoftStringFunctions()
{
// skip if not Windows
if (!mSettings.platform.isWindows())
return;
const bool ansi = mSettings.platform.type == Platform::Type::Win32A;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->strAt(1) != "(")
continue;
const std::map<std::string, triplet>::const_iterator match = apis.find(tok->str());
if (match!=apis.end()) {
tok->str(ansi ? match->second.mbcs : match->second.unicode);
tok->originalName(match->first);
} else if (Token::Match(tok, "_T|_TEXT|TEXT ( %char%|%str% )")) {
tok->deleteNext();
tok->deleteThis();
tok->deleteNext();
if (!ansi) {
tok->isLong(true);
if (tok->str()[0] != 'L')
tok->str("L" + tok->str());
}
while (Token::Match(tok->next(), "_T|_TEXT|TEXT ( %char%|%str% )")) {
tok->next()->deleteNext();
tok->next()->deleteThis();
tok->next()->deleteNext();
tok->concatStr(tok->strAt(1));
tok->deleteNext();
}
}
}
}
// Remove Borland code
void Tokenizer::simplifyBorland()
{
// skip if not Windows
if (!mSettings.platform.isWindows())
return;
if (isC())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "( __closure * %name% )")) {
tok->deleteNext();
}
}
// I think that these classes are always declared at the outer scope
// I save some time by ignoring inner classes.
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "{" && !Token::Match(tok->tokAt(-2), "namespace %type%")) {
tok = tok->link();
if (!tok)
break;
} else if (Token::Match(tok, "class %name% :|{")) {
while (tok && tok->str() != "{" && tok->str() != ";")
tok = tok->next();
if (!tok)
break;
if (tok->str() == ";")
continue;
const Token* end = tok->link()->next();
for (Token *tok2 = tok->next(); tok2 != end; tok2 = tok2->next()) {
if (tok2->str() == "__property" &&
Token::Match(tok2->previous(), ";|{|}|protected:|public:|__published:")) {
while (tok2->next() && !Token::Match(tok2->next(), "{|;"))
tok2->deleteNext();
tok2->deleteThis();
if (tok2->str() == "{") {
Token::eraseTokens(tok2, tok2->link());
tok2->deleteNext();
tok2->deleteThis();
// insert "; __property ;"
tok2->previous()->insertToken(";");
tok2->previous()->insertToken("__property");
tok2->previous()->insertToken(";");
}
}
}
}
}
}
void Tokenizer::createSymbolDatabase()
{
if (!mSymbolDatabase)
mSymbolDatabase = new SymbolDatabase(*this, mSettings, mErrorLogger);
mSymbolDatabase->validate();
}
bool Tokenizer::operatorEnd(const Token * tok)
{
if (tok && tok->str() == ")") {
if (isFunctionHead(tok, "{|;|?|:|["))
return true;
tok = tok->next();
while (tok && !Token::Match(tok, "[=;{),]")) {
if (Token::Match(tok, "const|volatile|override")) {
tok = tok->next();
} else if (tok->str() == "noexcept") {
tok = tok->next();
if (tok && tok->str() == "(") {
tok = tok->link()->next();
}
} else if (tok->str() == "throw" && tok->next() && tok->strAt(1) == "(") {
tok = tok->linkAt(1)->next();
}
// unknown macros ") MACRO {" and ") MACRO(...) {"
else if (tok->isUpperCaseName()) {
tok = tok->next();
if (tok && tok->str() == "(") {
tok = tok->link()->next();
}
} else if (Token::Match(tok, "%op% !!(") ||
(Token::Match(tok, "%op% (") && !isFunctionHead(tok->next(), "{")))
break;
else
return false;
}
return true;
}
return false;
}
void Tokenizer::simplifyOperatorName()
{
if (isC())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "using|:: operator %op%|%name% ;")) {
tok->next()->str("operator" + tok->strAt(2));
tok->next()->deleteNext();
continue;
}
if (tok->str() != "operator")
continue;
// operator op
if (Token::Match(tok, "operator %op% (") && !operatorEnd(tok->linkAt(2))) {
tok->str(tok->str() + tok->strAt(1));
tok->deleteNext();
continue;
}
std::string op;
Token *par = tok->next();
bool done = false;
while (!done && par) {
done = true;
if (par->isName()) {
op += par->str();
par = par->next();
// merge namespaces eg. 'operator std :: string () const {'
if (Token::Match(par, ":: %name%|%op%|.")) {
op += par->str();
par = par->next();
}
done = false;
} else if (Token::Match(par, ".|%op%|,")) {
// check for operator in template
if (par->str() == "," && !op.empty())
break;
if (!(Token::Match(par, "<|>") && !op.empty())) {
op += par->str() == "." ? par->originalName() : par->str();
par = par->next();
done = false;
}
} else if (Token::simpleMatch(par, "[ ]")) {
op += "[]";
par = par->tokAt(2);
done = false;
} else if (Token::Match(par, "( *| )")) {
// break out and simplify..
if (operatorEnd(par->next()))
break;
while (par->str() != ")") {
op += par->str();
par = par->next();
}
op += ")";
par = par->next();
if (Token::simpleMatch(par, "...")) {
op.clear();
par = nullptr;
break;
}
done = false;
} else if (Token::Match(par, "\"\" %name% )| (|;|<")) {
op += "\"\"";
op += par->strAt(1);
par = par->tokAt(2);
if (par->str() == ")") {
par->link()->deleteThis();
par = par->next();
par->deletePrevious();
tok = par->tokAt(-3);
}
done = true;
} else if (par->str() == "::") {
op += par->str();
par = par->next();
done = false;
} else if (par->str() == ";" || par->str() == ")") {
done = true;
} else if (par->str() != "(") {
syntaxError(par, "operator");
}
}
const bool returnsRef = Token::simpleMatch(par, "( & (") && tok->next()->isName();
if (par && !op.empty()) {
if (returnsRef) {
par->next()->insertToken("operator" + op)->isOperatorKeyword(true);
tok->deleteThis();
}
else {
tok->str("operator" + op);
Token::eraseTokens(tok, par);
}
}
if (!op.empty() && !returnsRef)
tok->isOperatorKeyword(true);
}
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%op% %str% %name%")) {
const std::string name = tok->strAt(2);
Token * const str = tok->next();
str->deleteNext();
tok->insertToken("operator\"\"" + name);
tok = tok->next();
tok->isOperatorKeyword(true);
tok->insertToken("(");
str->insertToken(")");
Token::createMutualLinks(tok->next(), str->next());
str->insertToken(std::to_string(Token::getStrLength(str)));
str->insertToken(",");
}
}
if (mSettings.debugwarnings) {
const Token *tok = list.front();
while ((tok = Token::findsimplematch(tok, "operator")) != nullptr) {
reportError(tok, Severity::debug, "debug",
"simplifyOperatorName: found unsimplified operator name");
tok = tok->next();
}
}
}
void Tokenizer::simplifyOverloadedOperators()
{
if (isC())
return;
std::set<std::string> classNames;
std::set<nonneg int> classVars;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName())
continue;
if (Token::simpleMatch(tok, "this ) (") && Token::simpleMatch(tok->tokAt(-2), "( *")) {
tok = tok->next();
tok->insertToken("operator()");
tok->insertToken(".");
continue;
}
// Get classes that have operator() member
if (Token::Match(tok, "class|struct %name% [:{]")) {
int indent = 0;
for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) {
if (tok2->str() == "}")
break;
if (indent == 0 && tok2->str() == ";")
break;
if (tok2->str() == "{") {
if (indent == 0)
++indent;
else
tok2 = tok2->link();
} else if (indent == 1 && Token::simpleMatch(tok2, "operator() (") && isFunctionHead(tok2->next(), ";{")) {
classNames.insert(tok->strAt(1));
break;
}
}
}
// Get variables that have operator() member
if (Token::Match(tok, "%type% &| %var%") && classNames.find(tok->str()) != classNames.end()) {
tok = tok->next();
while (!tok->isName())
tok = tok->next();
classVars.insert(tok->varId());
}
// Simplify operator() calls
if (Token::Match(tok, "%var% (") && classVars.find(tok->varId()) != classVars.end()) {
// constructor init list..
if (Token::Match(tok->previous(), "[:,]")) {
const Token *start = tok->previous();
while (Token::simpleMatch(start, ",")) {
if (Token::simpleMatch(start->previous(), ")"))
start = start->linkAt(-1);
else
break;
if (Token::Match(start->previous(), "%name%"))
start = start->tokAt(-2);
else
break;
}
const Token *after = tok->linkAt(1);
while (Token::Match(after, ")|} , %name% (|{"))
after = after->linkAt(3);
// Do not simplify initlist
if (Token::simpleMatch(start, ":") && Token::simpleMatch(after, ") {"))
continue;
}
tok->insertToken("operator()");
tok->insertToken(".");
}
}
}
// remove unnecessary member qualification..
void Tokenizer::removeUnnecessaryQualification()
{
if (isC())
return;
std::vector<Space> classInfo;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "class|struct|namespace %type% :|{") &&
(!tok->previous() || tok->strAt(-1) != "enum")) {
Space info;
info.isNamespace = tok->str() == "namespace";
tok = tok->next();
info.className = tok->str();
tok = tok->next();
while (tok && tok->str() != "{")
tok = tok->next();
if (!tok)
return;
info.bodyEnd = tok->link();
classInfo.push_back(std::move(info));
} else if (!classInfo.empty()) {
if (tok == classInfo.back().bodyEnd)
classInfo.pop_back();
else if (tok->str() == classInfo.back().className &&
!classInfo.back().isNamespace && tok->strAt(-1) != ":" &&
(Token::Match(tok, "%type% :: ~| %type% (") ||
Token::Match(tok, "%type% :: operator"))) {
const Token *tok1 = tok->tokAt(3);
if (tok->strAt(2) == "operator") {
// check for operator ()
if (tok1->str() == "(")
tok1 = tok1->next();
while (tok1 && tok1->str() != "(") {
if (tok1->str() == ";")
break;
tok1 = tok1->next();
}
if (!tok1 || tok1->str() != "(")
continue;
} else if (tok->strAt(2) == "~")
tok1 = tok1->next();
if (!tok1 || !Token::Match(tok1->link(), ") const| {|;|:")) {
continue;
}
const bool isConstructorOrDestructor =
Token::Match(tok, "%type% :: ~| %type%") && (tok->strAt(2) == tok->str() || (tok->strAt(2) == "~" && tok->strAt(3) == tok->str()));
if (!isConstructorOrDestructor) {
bool isPrependedByType = Token::Match(tok->previous(), "%type%");
if (!isPrependedByType) {
const Token* tok2 = tok->tokAt(-2);
isPrependedByType = Token::Match(tok2, "%type% *|&");
}
if (!isPrependedByType) {
const Token* tok3 = tok->tokAt(-3);
isPrependedByType = Token::Match(tok3, "%type% * *|&");
}
if (!isPrependedByType) {
// It's not a constructor declaration and it's not a function declaration so
// this is a function call which can have all the qualifiers just fine - skip.
continue;
}
}
}
}
}
}
void Tokenizer::printUnknownTypes() const
{
if (!mSymbolDatabase)
return;
std::vector<std::pair<std::string, const Token *>> unknowns;
for (int i = 1; i <= mVarId; ++i) {
const Variable *var = mSymbolDatabase->getVariableFromVarId(i);
if (!var)
continue;
// is unknown type?
if (var->type() || var->typeStartToken()->isStandardType())
continue;
std::string name;
const Token * nameTok;
// single token type?
if (var->typeStartToken() == var->typeEndToken()) {
nameTok = var->typeStartToken();
name = nameTok->str();
}
// complicated type
else {
const Token *tok = var->typeStartToken();
int level = 0;
nameTok = tok;
while (tok) {
// skip pointer and reference part of type
if (level == 0 && Token::Match(tok, "*|&"))
break;
name += tok->str();
if (Token::Match(tok, "struct|union|enum"))
name += " ";
// pointers and references are OK in template
else if (tok->str() == "<")
++level;
else if (tok->str() == ">")
--level;
if (tok == var->typeEndToken())
break;
tok = tok->next();
}
}
unknowns.emplace_back(std::move(name), nameTok);
}
if (!unknowns.empty()) {
std::string last;
int count = 0;
for (auto it = unknowns.cbegin(); it != unknowns.cend(); ++it) {
// skip types is std namespace because they are not interesting
if (it->first.find("std::") != 0) {
if (it->first != last) {
last = it->first;
count = 1;
reportError(it->second, Severity::debug, "debug", "Unknown type \'" + it->first + "\'.");
} else {
if (count < 3) // limit same type to 3
reportError(it->second, Severity::debug, "debug", "Unknown type \'" + it->first + "\'.");
count++;
}
}
}
}
}
void Tokenizer::prepareTernaryOpForAST()
{
// http://en.cppreference.com/w/cpp/language/operator_precedence says about ternary operator:
// "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored."
// The AST parser relies on this function to add such parentheses where necessary.
for (Token* tok = list.front(); tok; tok = tok->next()) {
if (tok->str() == "?") {
bool parenthesesNeeded = false;
int depth = 0;
Token* tok2 = tok->next();
for (; tok2; tok2 = tok2->next()) {
if (tok2->link() && Token::Match(tok2, "[|(|<"))
tok2 = tok2->link();
else if (tok2->str() == ":") {
if (depth == 0)
break;
depth--;
} else if (tok2->str() == ";" || (tok2->link() && tok2->str() != "{" && tok2->str() != "}"))
break;
else if (tok2->str() == ",")
parenthesesNeeded = true;
else if (tok2->str() == "<")
parenthesesNeeded = true;
else if (tok2->str() == "?") {
depth++;
parenthesesNeeded = true;
}
}
if (parenthesesNeeded && tok2 && tok2->str() == ":") {
tok->insertToken("(");
tok2->insertTokenBefore(")");
Token::createMutualLinks(tok->next(), tok2->previous());
}
}
}
}
void Tokenizer::reportError(const Token* tok, const Severity severity, const std::string& id, const std::string& msg, bool inconclusive) const
{
const std::list<const Token*> callstack(1, tok);
reportError(callstack, severity, id, msg, inconclusive);
}
void Tokenizer::reportError(const std::list<const Token*>& callstack, Severity severity, const std::string& id, const std::string& msg, bool inconclusive) const
{
const ErrorMessage errmsg(callstack, &list, severity, id, msg, inconclusive ? Certainty::inconclusive : Certainty::normal);
mErrorLogger.reportErr(errmsg);
}
void Tokenizer::setPodTypes()
{
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName() || tok->varId())
continue;
// pod type
const Library::PodType *podType = mSettings.library.podtype(tok->str());
if (podType) {
const Token *prev = tok->previous();
while (prev && prev->isName())
prev = prev->previous();
if (prev && !Token::Match(prev, ";|{|}|,|("))
continue;
tok->isStandardType(true);
}
}
}
const Token *Tokenizer::findSQLBlockEnd(const Token *tokSQLStart)
{
const Token *tokLastEnd = nullptr;
for (const Token *tok = tokSQLStart->tokAt(2); tok != nullptr; tok = tok->next()) {
if (tokLastEnd == nullptr && tok->str() == ";")
tokLastEnd = tok;
else if (tok->str() == "__CPPCHECK_EMBEDDED_SQL_EXEC__") {
if (Token::simpleMatch(tok->tokAt(-2), "END - __CPPCHECK_EMBEDDED_SQL_EXEC__ ;"))
return tok->next();
return tokLastEnd;
} else if (Token::Match(tok, "{|}|==|&&|!|^|<<|>>|++|+=|-=|/=|*=|>>=|<<=|~"))
break; // We are obviously outside the SQL block
}
return tokLastEnd;
}
void Tokenizer::simplifyNestedNamespace()
{
if (!isCPP())
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "namespace %name% ::") && tok->strAt(-1) != "using") {
Token * tok2 = tok->tokAt(2);
// validate syntax
while (Token::Match(tok2, ":: %name%"))
tok2 = tok2->tokAt(2);
if (!tok2 || tok2->str() != "{")
return; // syntax error
std::stack<Token *> links;
tok2 = tok->tokAt(2);
while (tok2->str() == "::") {
links.push(tok2);
tok2->str("{");
tok2->insertToken("namespace");
tok2 = tok2->tokAt(3);
}
tok = tok2;
if (!links.empty() && tok2->str() == "{") {
tok2 = tok2->link();
while (!links.empty()) {
tok2->insertToken("}");
tok2 = tok2->next();
Token::createMutualLinks(links.top(), tok2);
links.pop();
}
}
}
}
}
void Tokenizer::simplifyCoroutines()
{
if (!isCPP() || mSettings.standards.cpp < Standards::CPP20)
return;
for (Token *tok = list.front(); tok; tok = tok->next()) {
if (!tok->isName() || !Token::Match(tok, "co_return|co_yield|co_await"))
continue;
Token *end = tok->next();
while (end && end->str() != ";") {
if (Token::Match(end, "[({[]"))
end = end->link();
else if (Token::Match(end, "[)]}]"))
break;
end = end->next();
}
if (Token::simpleMatch(end, ";")) {
tok->insertToken("(");
end->previous()->insertToken(")");
Token::createMutualLinks(tok->next(), end->previous());
}
}
}
static bool sameTokens(const Token *first, const Token *last, const Token *other)
{
while (other && first->str() == other->str()) {
if (first == last)
return true;
first = first->next();
other = other->next();
}
return false;
}
static bool alreadyHasNamespace(const Token *first, const Token *last, const Token *end)
{
while (end && last->str() == end->str()) {
if (first == last)
return true;
last = last->previous();
end = end->previous();
}
return false;
}
static Token * deleteAlias(Token * tok)
{
Token::eraseTokens(tok, Token::findsimplematch(tok, ";"));
// delete first token
tok->deleteThis();
// delete ';' if not last token
tok->deleteThis();
return tok;
}
void Tokenizer::simplifyNamespaceAliases()
{
if (!isCPP())
return;
int scope = 0;
for (Token *tok = list.front(); tok; tok = tok->next()) {
bool isPrev{};
if (tok->str() == "{")
scope++;
else if (tok->str() == "}")
scope--;
else if (Token::Match(tok, "namespace %name% =") || (isPrev = Token::Match(tok->previous(), "namespace %name% ="))) {
if (isPrev)
tok = tok->previous();
if (tok->tokAt(-1) && !Token::Match(tok->tokAt(-1), "[;{}]"))
syntaxError(tok->tokAt(-1));
const std::string name(tok->strAt(1));
Token * tokNameStart = tok->tokAt(3);
Token * tokNameEnd = tokNameStart;
while (tokNameEnd && tokNameEnd->next() && tokNameEnd->strAt(1) != ";") {
if (tokNameEnd->str() == "(") {
if (tokNameEnd->previous()->isName())
unknownMacroError(tokNameEnd->previous());
else
syntaxError(tokNameEnd);
}
tokNameEnd = tokNameEnd->next();
}
if (!tokNameEnd)
return; // syntax error
int endScope = scope;
Token * tokLast = tokNameEnd->next();
if (!tokLast)
return;
Token * tokNext = tokLast->next();
Token * tok2 = tokNext;
while (tok2 && endScope >= scope) {
if (Token::simpleMatch(tok2, "{"))
endScope++;
else if (Token::simpleMatch(tok2, "}"))
endScope--;
else if (tok2->str() == name) {
if (Token::Match(tok2->previous(), "namespace %name% =")) {
// check for possible duplicate aliases
if (sameTokens(tokNameStart, tokNameEnd, tok2->tokAt(2))) {
// delete duplicate
tok2 = deleteAlias(tok2->previous());
continue;
}
// conflicting declaration (syntax error)
// cppcheck-suppress duplicateBranch - remove when TODO below is addressed
if (endScope == scope) {
// delete conflicting declaration
tok2 = deleteAlias(tok2->previous());
}
// new declaration
else {
// TODO: use the new alias in this scope
tok2 = deleteAlias(tok2->previous());
}
continue;
}
if (tok2->strAt(1) == "::" && !alreadyHasNamespace(tokNameStart, tokNameEnd, tok2)) {
if (Token::simpleMatch(tok2->tokAt(-1), "::") && tokNameStart->str() == "::")
tok2->deletePrevious();
tok2->str(tokNameStart->str());
Token * tok3 = tokNameStart;
while (tok3 != tokNameEnd) {
tok2->insertToken(tok3->strAt(1));
tok2 = tok2->next();
tok3 = tok3->next();
}
}
}
tok2 = tok2->next();
}
if (tok->previous() && tokNext) {
Token::eraseTokens(tok->previous(), tokNext);
tok = tokNext->previous();
} else if (tok->previous()) {
Token::eraseTokens(tok->previous(), tokLast);
tok = tokLast;
} else if (tokNext) {
Token::eraseTokens(tok, tokNext);
tok->deleteThis();
} else {
Token::eraseTokens(tok, tokLast);
tok->deleteThis();
}
}
}
}
void Tokenizer::setDirectives(std::list<Directive> directives)
{
mDirectives = std::move(directives);
}
bool Tokenizer::hasIfdef(const Token *start, const Token *end) const
{
const auto& directives = mDirectives;
return std::any_of(directives.cbegin(), directives.cend(), [&](const Directive& d) {
return startsWith(d.str, "#if") &&
d.linenr >= start->linenr() &&
d.linenr <= end->linenr() &&
start->fileIndex() < list.getFiles().size() &&
d.file == list.getFiles()[start->fileIndex()];
});
}
bool Tokenizer::isPacked(const Token * bodyStart) const
{
const auto& directives = mDirectives;
// TODO: should this return true if the #pragma exists in any line before the start token?
return std::any_of(directives.cbegin(), directives.cend(), [&](const Directive& d) {
return d.linenr < bodyStart->linenr() && d.str == "#pragma pack(1)" && d.file == list.getFiles().front();
});
}
| null |
873 | cpp | cppcheck | errortypes.h | lib/errortypes.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef errortypesH
#define errortypesH
//---------------------------------------------------------------------------
#include "config.h"
#include <cstdint>
#include <stdexcept>
#include <list>
#include <string>
#include <utility>
/// @addtogroup Core
/// @{
class Token;
/** @brief Simple container to be thrown when internal error is detected. */
struct CPPCHECKLIB InternalError {
enum Type : std::uint8_t {AST, SYNTAX, UNKNOWN_MACRO, INTERNAL, LIMIT, INSTANTIATION};
InternalError(const Token *tok, std::string errorMsg, Type type = INTERNAL);
InternalError(const Token *tok, std::string errorMsg, std::string details, Type type = INTERNAL);
const Token *token;
std::string errorMessage;
std::string details;
Type type;
std::string id;
};
class TerminateException : public std::runtime_error {
public:
TerminateException() : std::runtime_error("terminate") {}
};
enum class Certainty : std::uint8_t {
normal, inconclusive
};
enum class Checks : std::uint8_t {
unusedFunction, missingInclude, internalCheck
};
/** @brief enum class for severity. Used when reporting errors. */
enum class Severity : std::uint8_t {
/**
* No severity (default value).
*/
none,
/**
* Programming error.
* This indicates severe error like memory leak etc.
* The error is certain.
*/
error,
/**
* Warning.
* Used for dangerous coding style that can cause severe runtime errors.
* For example: forgetting to initialize a member variable in a constructor.
*/
warning,
/**
* Style warning.
* Used for general code cleanup recommendations. Fixing these
* will not fix any bugs but will make the code easier to maintain.
* For example: redundant code, unreachable code, etc.
*/
style,
/**
* Performance warning.
* Not an error as is but suboptimal code and fixing it probably leads
* to faster performance of the compiled code.
*/
performance,
/**
* Portability warning.
* This warning indicates the code is not properly portable for
* different platforms and bitnesses (32/64 bit). If the code is meant
* to compile in different platforms and bitnesses these warnings
* should be fixed.
*/
portability,
/**
* Checking information.
* Information message about the checking (process) itself. These
* messages inform about header files not found etc issues that are
* not errors in the code but something user needs to know.
*/
information,
/**
* Debug message.
* Debug-mode message useful for the developers.
*/
debug,
/**
* Internal message.
* Message will not be shown to the user.
* Tracking what checkers is executed, tracking suppressed critical errors, etc.
*/
internal
};
CPPCHECKLIB std::string severityToString(Severity severity);
CPPCHECKLIB Severity severityFromString(const std::string &severity);
struct CWE {
explicit CWE(unsigned short cweId) : id(cweId) {}
unsigned short id;
};
using ErrorPathItem = std::pair<const Token *, std::string>;
using ErrorPath = std::list<ErrorPathItem>;
/// @}
//---------------------------------------------------------------------------
#endif // errortypesH
| null |
874 | cpp | cppcheck | checkleakautovar.cpp | lib/checkleakautovar.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// Leaks when using auto variables
//---------------------------------------------------------------------------
#include "checkleakautovar.h"
#include "astutils.h"
#include "checkmemoryleak.h" // <- CheckMemoryLeak::memoryLeak
#include "checknullpointer.h" // <- CheckNullPointer::isPointerDeRef
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "errortypes.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <array>
#include <cstddef>
#include <list>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckLeakAutoVar instance;
}
static const CWE CWE672(672U);
static const CWE CWE415(415U);
// Hardcoded allocation types (not from library)
static constexpr int NEW_ARRAY = -2;
static constexpr int NEW = -1;
static const std::array<std::pair<std::string, std::string>, 4> alloc_failed_conds {{{"==", "0"}, {"<", "0"}, {"==", "-1"}, {"<=", "-1"}}};
static const std::array<std::pair<std::string, std::string>, 5> alloc_success_conds {{{"!=", "0"}, {">", "0"}, {"!=", "-1"}, {">=", "0"}, {">", "-1"}}};
static bool isAutoDeallocType(const Type* type) {
if (!type || !type->classScope)
return true;
if (type->classScope->numConstructors > 0)
return true;
const std::list<Variable>& varlist = type->classScope->varlist;
if (std::any_of(varlist.begin(), varlist.end(), [](const Variable& v) {
return !v.valueType() || (!v.valueType()->isPrimitive() && !v.valueType()->container);
}))
return true;
if (std::none_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [](const Type::BaseInfo& bi) {
return isAutoDeallocType(bi.type);
}))
return false;
return true;
}
/**
* @brief Is variable type some class with automatic deallocation?
* @param var variable token
* @return true unless it can be seen there is no automatic deallocation
*/
static bool isAutoDealloc(const Variable *var)
{
if (var->valueType() && var->valueType()->type != ValueType::Type::RECORD && var->valueType()->type != ValueType::Type::UNKNOWN_TYPE)
return false;
// return false if the type is a simple record type without side effects
// a type that has no side effects (no constructors and no members with constructors)
/** @todo false negative: check constructors for side effects */
return isAutoDeallocType(var->type());
}
template<std::size_t N>
static bool isVarTokComparison(const Token * tok, const Token ** vartok,
const std::array<std::pair<std::string, std::string>, N>& ops)
{
return std::any_of(ops.cbegin(), ops.cend(), [&](const std::pair<std::string, std::string>& op) {
return astIsVariableComparison(tok, op.first, op.second, vartok);
});
}
//---------------------------------------------------------------------------
void VarInfo::possibleUsageAll(const std::pair<const Token*, Usage>& functionUsage)
{
possibleUsage.clear();
for (std::map<int, AllocInfo>::const_iterator it = alloctype.cbegin(); it != alloctype.cend(); ++it)
possibleUsage[it->first] = functionUsage;
}
void CheckLeakAutoVar::leakError(const Token *tok, const std::string &varname, int type) const
{
const CheckMemoryLeak checkmemleak(mTokenizer, mErrorLogger, mSettings);
if (Library::isresource(type))
checkmemleak.resourceLeakError(tok, varname);
else
checkmemleak.memleakError(tok, varname);
}
void CheckLeakAutoVar::mismatchError(const Token *deallocTok, const Token *allocTok, const std::string &varname) const
{
const CheckMemoryLeak c(mTokenizer, mErrorLogger, mSettings);
const std::list<const Token *> callstack = { allocTok, deallocTok };
c.mismatchAllocDealloc(callstack, varname);
}
void CheckLeakAutoVar::deallocUseError(const Token *tok, const std::string &varname) const
{
const CheckMemoryLeak c(mTokenizer, mErrorLogger, mSettings);
c.deallocuseError(tok, varname);
}
void CheckLeakAutoVar::deallocReturnError(const Token *tok, const Token *deallocTok, const std::string &varname)
{
const std::list<const Token *> locations = { deallocTok, tok };
reportError(locations, Severity::error, "deallocret", "$symbol:" + varname + "\nReturning/dereferencing '$symbol' after it is deallocated / released", CWE672, Certainty::normal);
}
void CheckLeakAutoVar::configurationInfo(const Token* tok, const std::pair<const Token*, VarInfo::Usage>& functionUsage)
{
if (mSettings->checkLibrary && functionUsage.second == VarInfo::USED &&
(!functionUsage.first || !functionUsage.first->function() || !functionUsage.first->function()->hasBody())) {
std::string funcStr = functionUsage.first ? mSettings->library.getFunctionName(functionUsage.first) : "f";
if (funcStr.empty())
funcStr = "unknown::" + functionUsage.first->str();
reportError(tok,
Severity::information,
"checkLibraryUseIgnore",
"--check-library: Function " + funcStr + "() should have <use>/<leak-ignore> configuration");
}
}
void CheckLeakAutoVar::doubleFreeError(const Token *tok, const Token *prevFreeTok, const std::string &varname, int type)
{
const std::list<const Token *> locations = { prevFreeTok, tok };
if (Library::isresource(type))
reportError(locations, Severity::error, "doubleFree", "$symbol:" + varname + "\nResource handle '$symbol' freed twice.", CWE415, Certainty::normal);
else
reportError(locations, Severity::error, "doubleFree", "$symbol:" + varname + "\nMemory pointed to by '$symbol' is freed twice.", CWE415, Certainty::normal);
}
void CheckLeakAutoVar::check()
{
if (mSettings->clang)
return;
logChecker("CheckLeakAutoVar::check"); // notclang
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Local variables that are known to be non-zero.
const std::set<int> notzero;
// Check function scopes
for (const Scope * scope : symbolDatabase->functionScopes) {
if (scope->hasInlineOrLambdaFunction())
continue;
// Empty variable info
VarInfo varInfo;
checkScope(scope->bodyStart, varInfo, notzero, 0);
}
}
static bool isVarUsedInTree(const Token *tok, nonneg int varid)
{
if (!tok)
return false;
if (tok->varId() == varid)
return true;
if (tok->str() == "(" && Token::simpleMatch(tok->astOperand1(), "sizeof"))
return false;
return isVarUsedInTree(tok->astOperand1(), varid) || isVarUsedInTree(tok->astOperand2(), varid);
}
static bool isPointerReleased(const Token *startToken, const Token *endToken, nonneg int varid)
{
for (const Token *tok = startToken; tok && tok != endToken; tok = tok->next()) {
if (tok->varId() != varid)
continue;
if (Token::Match(tok, "%var% . release ( )"))
return true;
if (Token::Match(tok, "%var% ="))
return false;
}
return false;
}
static bool isLocalVarNoAutoDealloc(const Token *varTok)
{
// not a local variable nor argument?
const Variable *var = varTok->variable();
if (!var)
return true;
if (!var->isArgument() && (!var->isLocal() || var->isStatic()))
return false;
// Don't check reference variables
if (var->isReference() && !var->isArgument())
return false;
// non-pod variable
if (varTok->isCpp()) {
// Possibly automatically deallocated memory
if (isAutoDealloc(var) && Token::Match(varTok, "%var% [=({] new"))
return false;
if (!var->isPointer() && !var->typeStartToken()->isStandardType())
return false;
}
return true;
}
/** checks if nameToken is a name of a function in a function call:
* func(arg)
* or
* func<temp1_arg>(arg)
* @param nameToken Function name token
* @return opening parenthesis token or NULL if not a function call
*/
static const Token * isFunctionCall(const Token * nameToken)
{
if (!nameToken->isStandardType() && nameToken->isName()) {
nameToken = nameToken->next();
// check if function is a template
if (nameToken && nameToken->link() && nameToken->str() == "<") {
// skip template arguments
nameToken = nameToken->link()->next();
}
// check for '('
if (nameToken && nameToken->link() && !nameToken->isCast() && nameToken->str() == "(") {
// returning opening parenthesis pointer
return nameToken;
}
}
return nullptr;
}
static const Token* getOutparamAllocation(const Token* tok, const Settings& settings)
{
if (!tok)
return nullptr;
int argn{};
const Token* ftok = getTokenArgumentFunction(tok, argn);
if (!ftok)
return nullptr;
if (const Library::AllocFunc* allocFunc = settings.library.getAllocFuncInfo(ftok)) {
if (allocFunc->arg == argn + 1)
return ftok;
}
return nullptr;
}
static const Token* getReturnValueFromOutparamAlloc(const Token* alloc, const Settings& settings)
{
if (const Token* ftok = getOutparamAllocation(alloc, settings)) {
if (Token::simpleMatch(ftok->astParent()->astParent(), "="))
return ftok->next()->astParent()->astOperand1();
}
return nullptr;
}
bool CheckLeakAutoVar::checkScope(const Token * const startToken,
VarInfo &varInfo,
std::set<int> notzero,
nonneg int recursiveCount)
{
#if ASAN
static const nonneg int recursiveLimit = 300;
#elif defined(__MINGW32__)
// testrunner crashes with stack overflow in CI
static constexpr nonneg int recursiveLimit = 600;
#else
static constexpr nonneg int recursiveLimit = 1000;
#endif
if (++recursiveCount > recursiveLimit) // maximum number of "else if ()"
throw InternalError(startToken, "Internal limit: CheckLeakAutoVar::checkScope() Maximum recursive count of 1000 reached.", InternalError::LIMIT);
std::map<int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype;
auto& possibleUsage = varInfo.possibleUsage;
const std::set<int> conditionalAlloc(varInfo.conditionalAlloc);
// Parse all tokens
const Token * const endToken = startToken->link();
for (const Token *tok = startToken; tok && tok != endToken; tok = tok->next()) {
if (!tok->scope()->isExecutable()) {
tok = tok->scope()->bodyEnd;
if (!tok) // Ticket #6666 (crash upon invalid code)
break;
}
// check each token
{
const bool isInit = Token::Match(tok, "%var% {|(") && tok->variable() && tok == tok->variable()->nameToken() && tok->variable()->isPointer();
const Token * nextTok = isInit ? nullptr : checkTokenInsideExpression(tok, varInfo);
if (nextTok) {
tok = nextTok;
continue;
}
}
// look for end of statement
const bool isInit = Token::Match(tok->tokAt(-1), "%var% {|(") && tok->tokAt(-1)->variable() && tok->tokAt(-1) == tok->tokAt(-1)->variable()->nameToken();
if ((!Token::Match(tok, "[;{},]") || Token::Match(tok->next(), "[;{},]")) && !(isInit && tok->str() == "("))
continue;
if (Token::Match(tok, "[;{},] %var% ["))
continue;
if (!isInit)
tok = tok->next();
if (!tok || tok == endToken)
break;
if (Token::Match(tok, "%name% (") && isUnevaluated(tok)) {
tok = tok->linkAt(1);
continue;
}
if (Token::Match(tok, "const %type%"))
tok = tok->tokAt(2);
while (!isInit && tok->str() == "(")
tok = tok->next();
while (tok->isUnaryOp("*") && tok->astOperand1()->isUnaryOp("&"))
tok = tok->astOperand1()->astOperand1();
// parse statement, skip to last member
const Token* varTok = isInit ? tok->tokAt(-1) : tok;
while (Token::Match(varTok, "%name% ::|. %name% !!("))
varTok = varTok->tokAt(2);
const Token *ftok = tok;
if (ftok->str() == "::")
ftok = ftok->next();
while (Token::Match(ftok, "%name% :: %name%"))
ftok = ftok->tokAt(2);
// bailout for variable passed to library function with out parameter
if (const Library::Function *libFunc = mSettings->library.getFunction(ftok)) {
using ArgumentChecks = Library::ArgumentChecks;
using Direction = ArgumentChecks::Direction;
const std::vector<const Token *> args = getArguments(ftok);
const std::map<int, ArgumentChecks> &argChecks = libFunc->argumentChecks;
bool hasOutParam = std::any_of(argChecks.cbegin(), argChecks.cend(), [](const std::pair<int, ArgumentChecks> &pair) {
return std::any_of(pair.second.direction.cbegin(), pair.second.direction.cend(), [](const Direction dir) {
return dir == Direction::DIR_OUT;
});
});
if (hasOutParam) {
for (int i = 0; i < args.size(); i++) {
if (!argChecks.count(i + 1))
continue;
const ArgumentChecks argCheck = argChecks.at(i + 1);
const bool isInParam = std::any_of(argCheck.direction.cbegin(), argCheck.direction.cend(), [&](const Direction dir) {
return dir == Direction::DIR_IN;
});
if (!isInParam)
continue;
const Token *inTok = args[i];
int indirect = 0;
while (inTok->isUnaryOp("&")) {
inTok = inTok->astOperand1();
indirect++;
}
if (inTok->isVariable() && indirect) {
varInfo.erase(inTok->varId());
}
}
}
}
auto isAssignment = [](const Token* varTok) -> const Token* {
if (varTok->varId()) {
const Token* top = varTok;
while (top->astParent()) {
top = top->astParent();
if (!Token::Match(top, "(|*|&|."))
break;
}
if (top->str() == "=" && succeeds(top, varTok))
return top;
}
return nullptr;
};
// assignment..
if (const Token* const tokAssignOp = isInit ? varTok : isAssignment(varTok)) {
if (Token::simpleMatch(tokAssignOp->astOperand1(), "."))
continue;
// taking address of another variable..
if (Token::Match(tokAssignOp, "= %var% +|;|?|%comp%")) {
if (varTok->tokAt(2)->varId() != varTok->varId()) {
// If variable points at allocated memory => error
leakIfAllocated(varTok, varInfo);
// no multivariable checking currently => bail out for rhs variables
for (const Token *tok2 = varTok; tok2; tok2 = tok2->next()) {
if (tok2->str() == ";") {
break;
}
if (tok2->varId()) {
varInfo.erase(tok2->varId());
}
}
}
}
// right ast part (after `=` operator)
const Token* tokRightAstOperand = tokAssignOp->astOperand2();
while (tokRightAstOperand && tokRightAstOperand->isCast())
tokRightAstOperand = tokRightAstOperand->astOperand2() ? tokRightAstOperand->astOperand2() : tokRightAstOperand->astOperand1();
// is variable used in rhs?
if (isVarUsedInTree(tokRightAstOperand, varTok->varId()))
continue;
// Variable has already been allocated => error
if (conditionalAlloc.find(varTok->varId()) == conditionalAlloc.end())
leakIfAllocated(varTok, varInfo);
varInfo.erase(varTok->varId());
if (!isLocalVarNoAutoDealloc(varTok))
continue;
// allocation?
const Token *const fTok = tokRightAstOperand ? tokRightAstOperand->previous() : nullptr;
if (Token::Match(fTok, "%type% (")) {
const Library::AllocFunc* f = mSettings->library.getAllocFuncInfo(fTok);
if (f && f->arg == -1) {
VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()];
varAlloc.type = f->groupId;
varAlloc.status = VarInfo::ALLOC;
varAlloc.allocTok = fTok;
}
changeAllocStatusIfRealloc(alloctype, fTok, varTok);
} else if (varTok->isCpp() && Token::Match(varTok->tokAt(2), "new !!(")) {
const Token* tok2 = varTok->tokAt(2)->astOperand1();
const bool arrayNew = (tok2 && (tok2->str() == "[" || (Token::Match(tok2, "(|{") && tok2->astOperand1() && tok2->astOperand1()->str() == "[")));
VarInfo::AllocInfo& varAlloc = alloctype[varTok->varId()];
varAlloc.type = arrayNew ? NEW_ARRAY : NEW;
varAlloc.status = VarInfo::ALLOC;
varAlloc.allocTok = varTok->tokAt(2);
}
// Assigning non-zero value variable. It might be used to
// track the execution for a later if condition.
if (Token::Match(varTok->tokAt(2), "%num% ;") && MathLib::toBigNumber(varTok->strAt(2)) != 0)
notzero.insert(varTok->varId());
else if (Token::Match(varTok->tokAt(2), "- %type% ;") && varTok->tokAt(3)->isUpperCaseName())
notzero.insert(varTok->varId());
else
notzero.erase(varTok->varId());
}
// if/else
else if (Token::simpleMatch(tok, "if (")) {
bool skipIfBlock = false;
bool skipElseBlock = false;
const Token *condTok = tok->astSibling();
if (condTok && condTok->hasKnownIntValue()) {
skipIfBlock = !condTok->getKnownIntValue();
skipElseBlock = !skipIfBlock;
}
// Parse function calls inside the condition
const Token * closingParenthesis = tok->linkAt(1);
for (const Token *innerTok = tok->tokAt(2); innerTok && innerTok != closingParenthesis; innerTok = innerTok->next()) {
if (isUnevaluated(innerTok)) {
innerTok = innerTok->linkAt(1);
continue;
}
// TODO: replace with checkTokenInsideExpression()
const Token* const openingPar = isFunctionCall(innerTok);
if (!openingPar)
checkTokenInsideExpression(innerTok, varInfo);
if (!isLocalVarNoAutoDealloc(innerTok))
continue;
// Check assignments in the if-statement. Skip multiple assignments since we don't track those
if (Token::Match(innerTok, "%var% =") && innerTok->astParent() == innerTok->next() &&
!(innerTok->next()->astParent() && innerTok->next()->astParent()->isAssignmentOp())) {
// allocation?
// right ast part (after `=` operator)
const Token* tokRightAstOperand = innerTok->next()->astOperand2();
while (tokRightAstOperand && tokRightAstOperand->isCast())
tokRightAstOperand = tokRightAstOperand->astOperand2() ? tokRightAstOperand->astOperand2() : tokRightAstOperand->astOperand1();
if (tokRightAstOperand && Token::Match(tokRightAstOperand->previous(), "%type% (")) {
const Token * fTok = tokRightAstOperand->previous();
const Library::AllocFunc* f = mSettings->library.getAllocFuncInfo(fTok);
if (f && f->arg == -1) {
VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()];
varAlloc.type = f->groupId;
varAlloc.status = VarInfo::ALLOC;
varAlloc.allocTok = fTok;
} else {
// Fixme: warn about leak
alloctype.erase(innerTok->varId());
}
changeAllocStatusIfRealloc(alloctype, fTok, varTok);
} else if (innerTok->isCpp() && Token::Match(innerTok->tokAt(2), "new !!(")) {
const Token* tok2 = innerTok->tokAt(2)->astOperand1();
const bool arrayNew = (tok2 && (tok2->str() == "[" || (tok2->str() == "(" && tok2->astOperand1() && tok2->astOperand1()->str() == "[")));
VarInfo::AllocInfo& varAlloc = alloctype[innerTok->varId()];
varAlloc.type = arrayNew ? NEW_ARRAY : NEW;
varAlloc.status = VarInfo::ALLOC;
varAlloc.allocTok = innerTok->tokAt(2);
}
}
// check for function call
if (openingPar) {
const Library::AllocFunc* allocFunc = mSettings->library.getDeallocFuncInfo(innerTok);
// innerTok is a function name
const VarInfo::AllocInfo allocation(0, VarInfo::NOALLOC);
functionCall(innerTok, openingPar, varInfo, allocation, allocFunc);
innerTok = openingPar->link();
}
}
if (Token::simpleMatch(closingParenthesis, ") {")) {
VarInfo varInfo1(varInfo); // VarInfo for if code
VarInfo varInfo2(varInfo); // VarInfo for else code
// Skip expressions before commas
const Token * astOperand2AfterCommas = tok->next()->astOperand2();
while (Token::simpleMatch(astOperand2AfterCommas, ","))
astOperand2AfterCommas = astOperand2AfterCommas->astOperand2();
// Recursively scan variable comparisons in condition
visitAstNodes(astOperand2AfterCommas, [&](const Token *tok3) {
if (!tok3)
return ChildrenToVisit::none;
if (tok3->str() == "&&" || tok3->str() == "||") {
// FIXME: handle && ! || better
return ChildrenToVisit::op1_and_op2;
}
if (tok3->str() == "(" && Token::Match(tok3->astOperand1(), "UNLIKELY|LIKELY")) {
return ChildrenToVisit::op2;
}
if (tok3->str() == "(" && tok3->previous()->isName()) {
const std::vector<const Token *> params = getArguments(tok3->previous());
for (const Token *par : params) {
if (!par->isComparisonOp())
continue;
const Token *vartok = nullptr;
if (isVarTokComparison(par, &vartok, alloc_success_conds) ||
(isVarTokComparison(par, &vartok, alloc_failed_conds))) {
varInfo1.erase(vartok->varId());
varInfo2.erase(vartok->varId());
}
}
return ChildrenToVisit::none;
}
const Token *vartok = nullptr;
if (isVarTokComparison(tok3, &vartok, alloc_success_conds)) {
varInfo2.reallocToAlloc(vartok->varId());
varInfo2.erase(vartok->varId());
if (astIsVariableComparison(tok3, "!=", "0", &vartok) &&
(notzero.find(vartok->varId()) != notzero.end()))
varInfo2.clear();
if (std::any_of(varInfo1.alloctype.begin(), varInfo1.alloctype.end(), [&](const std::pair<int, VarInfo::AllocInfo>& info) {
if (info.second.status != VarInfo::ALLOC)
return false;
const Token* ret = getReturnValueFromOutparamAlloc(info.second.allocTok, *mSettings);
return ret && vartok && ret->varId() && ret->varId() == vartok->varId();
})) {
varInfo1.clear();
}
} else if (isVarTokComparison(tok3, &vartok, alloc_failed_conds)) {
varInfo1.reallocToAlloc(vartok->varId());
varInfo1.erase(vartok->varId());
}
return ChildrenToVisit::none;
});
if (!skipIfBlock && !checkScope(closingParenthesis->next(), varInfo1, notzero, recursiveCount)) {
varInfo.clear();
continue;
}
closingParenthesis = closingParenthesis->linkAt(1);
if (Token::simpleMatch(closingParenthesis, "} else {")) {
if (!skipElseBlock && !checkScope(closingParenthesis->tokAt(2), varInfo2, notzero, recursiveCount)) {
varInfo.clear();
return false;
}
tok = closingParenthesis->linkAt(2)->previous();
} else {
tok = closingParenthesis->previous();
}
VarInfo old;
old.swap(varInfo);
std::map<int, VarInfo::AllocInfo>::const_iterator it;
for (it = old.alloctype.cbegin(); it != old.alloctype.cend(); ++it) {
const int varId = it->first;
if (old.conditionalAlloc.find(varId) == old.conditionalAlloc.end())
continue;
if (varInfo1.alloctype.find(varId) == varInfo1.alloctype.end() ||
varInfo2.alloctype.find(varId) == varInfo2.alloctype.end()) {
varInfo1.erase(varId);
varInfo2.erase(varId);
}
}
// Conditional allocation in varInfo1
for (it = varInfo1.alloctype.cbegin(); it != varInfo1.alloctype.cend(); ++it) {
if (varInfo2.alloctype.find(it->first) == varInfo2.alloctype.end() &&
old.alloctype.find(it->first) == old.alloctype.end()) {
varInfo.conditionalAlloc.insert(it->first);
}
}
// Conditional allocation in varInfo2
for (it = varInfo2.alloctype.cbegin(); it != varInfo2.alloctype.cend(); ++it) {
if (varInfo1.alloctype.find(it->first) == varInfo1.alloctype.end() &&
old.alloctype.find(it->first) == old.alloctype.end()) {
varInfo.conditionalAlloc.insert(it->first);
}
}
// Conditional allocation/deallocation
for (it = varInfo1.alloctype.cbegin(); it != varInfo1.alloctype.cend(); ++it) {
if (it->second.managed() && conditionalAlloc.find(it->first) != conditionalAlloc.end()) {
varInfo.conditionalAlloc.erase(it->first);
varInfo2.erase(it->first);
}
}
for (it = varInfo2.alloctype.cbegin(); it != varInfo2.alloctype.cend(); ++it) {
if (it->second.managed() && conditionalAlloc.find(it->first) != conditionalAlloc.end()) {
varInfo.conditionalAlloc.erase(it->first);
varInfo1.erase(it->first);
}
}
alloctype.insert(varInfo1.alloctype.cbegin(), varInfo1.alloctype.cend());
alloctype.insert(varInfo2.alloctype.cbegin(), varInfo2.alloctype.cend());
possibleUsage.insert(varInfo1.possibleUsage.cbegin(), varInfo1.possibleUsage.cend());
possibleUsage.insert(varInfo2.possibleUsage.cbegin(), varInfo2.possibleUsage.cend());
}
}
// unknown control.. (TODO: handle loops)
else if ((Token::Match(tok, "%type% (") && Token::simpleMatch(tok->linkAt(1), ") {")) || Token::simpleMatch(tok, "do {")) {
varInfo.clear();
return false;
}
// return
else if (tok->str() == "return") {
ret(tok, varInfo);
varInfo.clear();
}
// throw
else if (tok->isCpp() && tok->str() == "throw") {
bool tryFound = false;
const Scope* scope = tok->scope();
while (scope && scope->isExecutable()) {
if (scope->type == Scope::eTry)
tryFound = true;
scope = scope->nestedIn;
}
// If the execution leaves the function then treat it as return
if (!tryFound)
ret(tok, varInfo);
varInfo.clear();
}
// delete
else if (tok->isCpp() && tok->str() == "delete") {
const Token * delTok = tok;
if (Token::simpleMatch(delTok->astOperand1(), "."))
continue;
const bool arrayDelete = Token::simpleMatch(tok->next(), "[ ]");
if (arrayDelete)
tok = tok->tokAt(3);
else
tok = tok->next();
bool startparen;
if ((startparen = (tok->str() == "(")))
tok = tok->next();
while (Token::Match(tok, "%name% ::|.") || (startparen && Token::Match(tok, "%name% ,")))
tok = tok->tokAt(2);
const bool isnull = tok->hasKnownIntValue() && tok->values().front().intvalue == 0;
if (!isnull && tok->varId() && tok->strAt(1) != "[") {
const VarInfo::AllocInfo allocation(arrayDelete ? NEW_ARRAY : NEW, VarInfo::DEALLOC, delTok);
changeAllocStatus(varInfo, allocation, tok, tok);
}
}
// Function call..
else if (const Token* openingPar = isFunctionCall(ftok)) {
const Library::AllocFunc* af = mSettings->library.getDeallocFuncInfo(ftok);
VarInfo::AllocInfo allocation(af ? af->groupId : 0, VarInfo::DEALLOC, ftok);
if (allocation.type == 0)
allocation.status = VarInfo::NOALLOC;
if (Token::simpleMatch(ftok->astParent(), "(") && Token::simpleMatch(ftok->astParent()->astOperand2(), "."))
continue;
functionCall(ftok, openingPar, varInfo, allocation, af);
tok = ftok->linkAt(1);
// Handle scopes that might be noreturn
if (allocation.status == VarInfo::NOALLOC && Token::simpleMatch(tok, ") ; }")) {
if (ftok->isKeyword())
continue;
bool unknown = false;
if (mTokenizer->isScopeNoReturn(tok->tokAt(2), &unknown)) {
if (!unknown)
varInfo.clear();
else {
if (ftok->function() && !ftok->function()->isAttributeNoreturn() &&
!(ftok->function()->functionScope && mTokenizer->isScopeNoReturn(ftok->function()->functionScope->bodyEnd))) // check function scope
continue;
const std::string functionName(mSettings->library.getFunctionName(ftok));
if (!mSettings->library.isLeakIgnore(functionName) && !mSettings->library.isUse(functionName)) {
const VarInfo::Usage usage = Token::simpleMatch(openingPar, "( )") ? VarInfo::NORET : VarInfo::USED; // TODO: check parameters passed to function
varInfo.possibleUsageAll({ ftok, usage });
}
}
}
}
continue;
}
// goto => weird execution path
else if (tok->str() == "goto") {
varInfo.clear();
return false;
}
// continue/break
else if (Token::Match(tok, "continue|break ;")) {
varInfo.clear();
}
// Check smart pointer
else if (Token::Match(ftok, "%name% <") && mSettings->library.isSmartPointer(tok)) {
const Token * typeEndTok = ftok->linkAt(1);
if (!Token::Match(typeEndTok, "> %var% {|( %var% ,|)|}"))
continue;
tok = typeEndTok->linkAt(2);
const int varid = typeEndTok->next()->varId();
if (isPointerReleased(typeEndTok->tokAt(2), endToken, varid))
continue;
bool arrayDelete = false;
if (Token::findsimplematch(ftok->next(), "[ ]", typeEndTok))
arrayDelete = true;
// Check deleter
const Token * deleterToken = nullptr;
const Token * endDeleterToken = nullptr;
const Library::AllocFunc* af = nullptr;
if (Token::Match(ftok, "unique_ptr < %type% ,")) {
deleterToken = ftok->tokAt(4);
endDeleterToken = typeEndTok;
} else if (Token::Match(typeEndTok, "> %var% {|( %var% ,")) {
deleterToken = typeEndTok->tokAt(5);
endDeleterToken = typeEndTok->linkAt(2);
}
if (deleterToken) {
// Skip the decaying plus in expressions like +[](T*){}
if (deleterToken->str() == "+") {
deleterToken = deleterToken->next();
}
// Check if its a pointer to a function
const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken);
if (dtok) {
dtok = dtok->next();
af = mSettings->library.getDeallocFuncInfo(dtok);
}
if (!dtok || !af) {
const Token * tscopeStart = nullptr;
const Token * tscopeEnd = nullptr;
// If the deleter is a lambda, check if it calls the dealloc function
if (deleterToken->str() == "[" &&
Token::simpleMatch(deleterToken->link(), "] (") &&
// TODO: Check for mutable keyword
Token::simpleMatch(deleterToken->link()->linkAt(1), ") {")) {
tscopeStart = deleterToken->link()->linkAt(1)->tokAt(1);
tscopeEnd = tscopeStart->link();
// check user-defined deleter function
} else if (dtok && dtok->function()) {
const Scope* tscope = dtok->function()->functionScope;
if (tscope) {
tscopeStart = tscope->bodyStart;
tscopeEnd = tscope->bodyEnd;
}
// If the deleter is a class, check if class calls the dealloc function
} else if ((dtok = Token::findmatch(deleterToken, "%type%", endDeleterToken)) && dtok->type()) {
const Scope * tscope = dtok->type()->classScope;
if (tscope) {
tscopeStart = tscope->bodyStart;
tscopeEnd = tscope->bodyEnd;
}
}
if (tscopeStart && tscopeEnd) {
for (const Token *tok2 = tscopeStart; tok2 != tscopeEnd; tok2 = tok2->next()) {
af = mSettings->library.getDeallocFuncInfo(tok2);
if (af)
break;
}
} else { // there is a deleter, but we can't check it -> assume that it deallocates correctly
varInfo.clear();
continue;
}
}
}
const Token * vtok = typeEndTok->tokAt(3);
const VarInfo::AllocInfo allocation(af ? af->groupId : (arrayDelete ? NEW_ARRAY : NEW), VarInfo::OWNED, ftok);
changeAllocStatus(varInfo, allocation, vtok, vtok);
} else if (Token::Match(tok, "%var% ."))
checkTokenInsideExpression(tok, varInfo);
}
ret(endToken, varInfo, true);
return true;
}
const Token * CheckLeakAutoVar::checkTokenInsideExpression(const Token * const tok, VarInfo &varInfo, bool inFuncCall)
{
// Deallocation and then dereferencing pointer..
if (tok->varId() > 0) {
// TODO : Write a separate checker for this that uses valueFlowForward.
const std::map<int, VarInfo::AllocInfo>::const_iterator var = varInfo.alloctype.find(tok->varId());
if (var != varInfo.alloctype.end()) {
bool unknown = false;
if (var->second.status == VarInfo::DEALLOC && tok->valueType() && tok->valueType()->pointer &&
CheckNullPointer::isPointerDeRef(tok, unknown, *mSettings, /*checkNullArg*/ false) && !unknown) {
deallocUseError(tok, tok->str());
} else if (Token::simpleMatch(tok->tokAt(-2), "= &")) {
varInfo.erase(tok->varId());
} else {
// check if tok is assigned into another variable
const Token *rhs = tok;
bool isAssignment = false;
while (rhs->astParent()) {
if (rhs->astParent()->str() == "=") {
isAssignment = true;
break;
}
rhs = rhs->astParent();
}
while (rhs->isCast()) {
rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1();
}
if (rhs->varId() == tok->varId() && isAssignment) {
// simple assignment
varInfo.erase(tok->varId());
} else if (rhs->astParent() && rhs->str() == "(" && !mSettings->library.returnValue(rhs->astOperand1()).empty()) {
// #9298, assignment through return value of a function
const std::string &returnValue = mSettings->library.returnValue(rhs->astOperand1());
if (startsWith(returnValue, "arg")) {
int argn;
const Token *func = getTokenArgumentFunction(tok, argn);
if (func) {
const std::string arg = "arg" + std::to_string(argn + 1);
if (returnValue == arg) {
varInfo.erase(tok->varId());
}
}
}
}
}
} else if (Token::Match(tok->previous(), "& %name% = %var% ;")) {
varInfo.referenced.insert(tok->tokAt(2)->varId());
}
}
// check for function call
const Token * const openingPar = inFuncCall ? nullptr : isFunctionCall(tok);
if (openingPar) {
const Library::AllocFunc* allocFunc = mSettings->library.getDeallocFuncInfo(tok);
VarInfo::AllocInfo alloc(allocFunc ? allocFunc->groupId : 0, VarInfo::DEALLOC, tok);
if (alloc.type == 0)
alloc.status = VarInfo::NOALLOC;
functionCall(tok, openingPar, varInfo, alloc, nullptr);
const std::string &returnValue = mSettings->library.returnValue(tok);
if (startsWith(returnValue, "arg"))
// the function returns one of its argument, we need to process a potential assignment
return openingPar;
return isCPPCast(tok->astParent()) ? openingPar : openingPar->link();
}
return nullptr;
}
void CheckLeakAutoVar::changeAllocStatusIfRealloc(std::map<int, VarInfo::AllocInfo> &alloctype, const Token *fTok, const Token *retTok) const
{
const Library::AllocFunc* f = mSettings->library.getReallocFuncInfo(fTok);
if (f && f->arg == -1 && f->reallocArg > 0 && f->reallocArg <= numberOfArguments(fTok)) {
const Token* argTok = getArguments(fTok).at(f->reallocArg - 1);
if (alloctype.find(argTok->varId()) != alloctype.end()) {
VarInfo::AllocInfo& argAlloc = alloctype[argTok->varId()];
if (argAlloc.type != 0 && argAlloc.type != f->groupId)
mismatchError(fTok, argAlloc.allocTok, argTok->str());
argAlloc.status = VarInfo::REALLOC;
argAlloc.allocTok = fTok;
}
VarInfo::AllocInfo& retAlloc = alloctype[retTok->varId()];
retAlloc.type = f->groupId;
retAlloc.status = VarInfo::ALLOC;
retAlloc.allocTok = fTok;
retAlloc.reallocedFromType = argTok->varId();
}
}
void CheckLeakAutoVar::changeAllocStatus(VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Token* tok, const Token* arg)
{
std::map<int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype;
const std::map<int, VarInfo::AllocInfo>::iterator var = alloctype.find(arg->varId());
if (var != alloctype.end()) {
// bailout if function is also allocating, since the argument might be moved
// to the return value, such as in fdopen
if (allocation.allocTok && mSettings->library.getAllocFuncInfo(allocation.allocTok)) {
varInfo.erase(arg->varId());
return;
}
if (allocation.status == VarInfo::NOALLOC) {
// possible usage
varInfo.possibleUsage[arg->varId()] = { tok, VarInfo::USED };
if (var->second.status == VarInfo::DEALLOC && arg->strAt(-1) == "&")
varInfo.erase(arg->varId());
} else if (var->second.managed()) {
doubleFreeError(tok, var->second.allocTok, arg->str(), allocation.type);
var->second.status = allocation.status;
} else if (var->second.type != allocation.type && var->second.type != 0) {
// mismatching allocation and deallocation
mismatchError(tok, var->second.allocTok, arg->str());
varInfo.erase(arg->varId());
} else {
// deallocation
var->second.status = allocation.status;
var->second.type = allocation.type;
var->second.allocTok = allocation.allocTok;
}
} else if (allocation.status != VarInfo::NOALLOC && allocation.status != VarInfo::OWNED && !Token::simpleMatch(tok->astTop(), "return")) {
auto& allocInfo = alloctype[arg->varId()];
allocInfo.status = VarInfo::DEALLOC;
allocInfo.allocTok = tok;
allocInfo.type = allocation.type;
}
}
void CheckLeakAutoVar::functionCall(const Token *tokName, const Token *tokOpeningPar, VarInfo &varInfo, const VarInfo::AllocInfo& allocation, const Library::AllocFunc* af)
{
// Ignore function call?
const bool isLeakIgnore = mSettings->library.isLeakIgnore(mSettings->library.getFunctionName(tokName));
if (mSettings->library.getReallocFuncInfo(tokName))
return;
if (tokName->next()->valueType() && tokName->next()->valueType()->container && tokName->next()->valueType()->container->stdStringLike)
return;
const Token * const tokFirstArg = tokOpeningPar->next();
if (!tokFirstArg || tokFirstArg->str() == ")") {
// no arguments
return;
}
int argNr = 1;
for (const Token *funcArg = tokFirstArg; funcArg; funcArg = funcArg->nextArgument()) {
const Token* arg = funcArg;
if (arg->isCpp()) {
int tokAdvance = 0;
if (arg->str() == "new")
tokAdvance = 1;
else if (Token::simpleMatch(arg, "* new"))
tokAdvance = 2;
if (tokAdvance > 0) {
arg = arg->tokAt(tokAdvance);
if (Token::simpleMatch(arg, "( std :: nothrow )"))
arg = arg->tokAt(5);
}
}
// Skip casts
if (arg->isKeyword() && arg->astParent() && arg->astParent()->isCast())
arg = arg->astParent();
while (arg && arg->isCast())
arg = arg->astOperand2() ? arg->astOperand2() : arg->astOperand1();
const Token * const argTypeStartTok = arg;
while (Token::Match(arg, "%name% .|:: %name%"))
arg = arg->tokAt(2);
if ((Token::Match(arg, "%var% [-,)] !!.") && !(arg->variable() && arg->variable()->isArray())) ||
(Token::Match(arg, "& %var% !!.") && !(arg->next()->variable() && arg->next()->variable()->isArray()))) {
// goto variable
const bool isAddressOf = arg->str() == "&";
if (isAddressOf)
arg = arg->next();
const bool isnull = !isAddressOf && (arg->hasKnownIntValue() && arg->values().front().intvalue == 0);
// Is variable allocated?
if (!isnull && (!af || af->arg == argNr)) {
const Library::AllocFunc* deallocFunc = mSettings->library.getDeallocFuncInfo(tokName);
VarInfo::AllocInfo dealloc(deallocFunc ? deallocFunc->groupId : 0, VarInfo::DEALLOC, tokName);
if (const Library::AllocFunc* allocFunc = mSettings->library.getAllocFuncInfo(tokName)) {
if (mSettings->library.getDeallocFuncInfo(tokName)) {
changeAllocStatus(varInfo, dealloc.type == 0 ? allocation : dealloc, tokName, arg);
}
if (allocFunc->arg == argNr &&
!(arg->variable() && arg->variable()->isArgument() && arg->valueType() && arg->valueType()->pointer > 1) &&
(isAddressOf || (arg->valueType() && arg->valueType()->pointer == 2))) {
leakIfAllocated(arg, varInfo);
VarInfo::AllocInfo& varAlloc = varInfo.alloctype[arg->varId()];
varAlloc.type = allocFunc->groupId;
varAlloc.status = VarInfo::ALLOC;
varAlloc.allocTok = arg;
}
}
else if (isLeakIgnore)
checkTokenInsideExpression(arg, varInfo);
else
changeAllocStatus(varInfo, dealloc.type == 0 ? allocation : dealloc, tokName, arg);
}
}
// Check smart pointer
else if (Token::Match(arg, "%name% < %type%") && mSettings->library.isSmartPointer(argTypeStartTok)) {
const Token * typeEndTok = arg->linkAt(1);
const Token * allocTok = nullptr;
if (!Token::Match(typeEndTok, "> {|( %var% ,|)|}"))
continue;
bool arrayDelete = false;
if (Token::findsimplematch(arg->next(), "[ ]", typeEndTok))
arrayDelete = true;
// Check deleter
const Token * deleterToken = nullptr;
const Token * endDeleterToken = nullptr;
const Library::AllocFunc* sp_af = nullptr;
if (Token::Match(arg, "unique_ptr < %type% ,")) {
deleterToken = arg->tokAt(4);
endDeleterToken = typeEndTok;
} else if (Token::Match(typeEndTok, "> {|( %var% ,")) {
deleterToken = typeEndTok->tokAt(4);
endDeleterToken = typeEndTok->linkAt(1);
}
if (deleterToken) {
// Check if its a pointer to a function
const Token * dtok = Token::findmatch(deleterToken, "& %name%", endDeleterToken);
if (dtok) {
sp_af = mSettings->library.getDeallocFuncInfo(dtok->tokAt(1));
} else {
// If the deleter is a class, check if class calls the dealloc function
dtok = Token::findmatch(deleterToken, "%type%", endDeleterToken);
if (dtok && dtok->type()) {
const Scope * tscope = dtok->type()->classScope;
for (const Token *tok2 = tscope->bodyStart; tok2 != tscope->bodyEnd; tok2 = tok2->next()) {
sp_af = mSettings->library.getDeallocFuncInfo(tok2);
if (sp_af) {
allocTok = tok2;
break;
}
}
}
}
}
const Token * vtok = typeEndTok->tokAt(2);
const VarInfo::AllocInfo sp_allocation(sp_af ? sp_af->groupId : (arrayDelete ? NEW_ARRAY : NEW), VarInfo::OWNED, allocTok);
changeAllocStatus(varInfo, sp_allocation, vtok, vtok);
} else {
const Token* const nextArg = funcArg->nextArgument();
while (arg && ((nextArg && arg != nextArg) || (!nextArg && arg != tokOpeningPar->link()))) {
checkTokenInsideExpression(arg, varInfo, /*inFuncCall*/ isLeakIgnore);
if (isLambdaCaptureList(arg))
break;
arg = arg->next();
}
}
// TODO: check each token in argument expression (could contain multiple variables)
argNr++;
}
}
void CheckLeakAutoVar::leakIfAllocated(const Token *vartok,
const VarInfo &varInfo)
{
const std::map<int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype;
const auto& possibleUsage = varInfo.possibleUsage;
const std::map<int, VarInfo::AllocInfo>::const_iterator var = alloctype.find(vartok->varId());
if (var != alloctype.cend() && var->second.status == VarInfo::ALLOC) {
const auto use = possibleUsage.find(vartok->varId());
if (use == possibleUsage.end()) {
leakError(vartok, vartok->str(), var->second.type);
} else {
configurationInfo(vartok, use->second);
}
}
}
void CheckLeakAutoVar::ret(const Token *tok, VarInfo &varInfo, const bool isEndOfScope)
{
const std::map<int, VarInfo::AllocInfo> &alloctype = varInfo.alloctype;
const auto& possibleUsage = varInfo.possibleUsage;
std::vector<int> toRemove;
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (std::map<int, VarInfo::AllocInfo>::const_iterator it = alloctype.cbegin(); it != alloctype.cend(); ++it) {
// don't warn if variable is conditionally allocated, unless it leaves the scope
if (!isEndOfScope && !it->second.managed() && varInfo.conditionalAlloc.find(it->first) != varInfo.conditionalAlloc.end())
continue;
// don't warn if there is a reference of the variable
if (varInfo.referenced.find(it->first) != varInfo.referenced.end())
continue;
const int varid = it->first;
const Variable *var = symbolDatabase->getVariableFromVarId(varid);
if (var) {
// don't warn if we leave an inner scope
if (isEndOfScope && var->scope() && tok != var->scope()->bodyEnd)
continue;
enum class PtrUsage : std::uint8_t { NONE, DEREF, PTR } used = PtrUsage::NONE;
for (const Token *tok2 = tok; tok2; tok2 = tok2->next()) {
if (tok2->str() == ";")
break;
if (!Token::Match(tok2, "return|(|{|,|*"))
continue;
const Token* tok3 = tok2->next();
while (tok3 && tok3->isCast() && tok3->valueType() &&
(tok3->valueType()->pointer ||
(tok3->valueType()->typeSize(mSettings->platform) == 0) ||
(tok3->valueType()->typeSize(mSettings->platform) >= mSettings->platform.sizeof_pointer)))
tok3 = tok3->astOperand2() ? tok3->astOperand2() : tok3->astOperand1();
if (tok3 && tok3->varId() == varid)
tok2 = tok3->next();
else if (Token::Match(tok3, "& %varid% . %name%", varid))
tok2 = tok3->tokAt(4);
else if (Token::simpleMatch(tok3, "*") && tok3->next()->varId() == varid)
tok2 = tok3;
else
continue;
if (Token::Match(tok2, "[});,+]") && (!astIsBool(tok) || tok2->str() != ";")) {
used = PtrUsage::PTR;
break;
}
if (Token::Match(tok2, "[|.|*")) {
used = PtrUsage::DEREF;
break;
}
}
// don't warn when returning after checking return value of outparam allocation
const Token* outparamFunc{};
if ((tok->scope()->type == Scope::ScopeType::eIf || tok->scope()->type== Scope::ScopeType::eElse) &&
(outparamFunc = getOutparamAllocation(it->second.allocTok, *mSettings))) {
const Scope* scope = tok->scope();
if (scope->type == Scope::ScopeType::eElse) {
scope = scope->bodyStart->tokAt(-2)->scope();
}
const Token* const ifEnd = scope->bodyStart->previous();
const Token* const ifStart = ifEnd->link();
const Token* const alloc = it->second.allocTok;
if (precedes(ifStart, alloc) && succeeds(ifEnd, alloc)) { // allocation and check in if
if (outparamFunc->next()->astParent() == ifStart || Token::Match(outparamFunc->next()->astParent(), "%comp%"))
continue;
} else { // allocation result assigned to variable
const Token* const retAssign = outparamFunc->next()->astParent();
if (Token::simpleMatch(retAssign, "=") && retAssign->astOperand1()->varId()) {
bool isRetComp = false;
for (const Token* tok2 = ifStart; tok2 != ifEnd; tok2 = tok2->next()) {
if (tok2->varId() == retAssign->astOperand1()->varId()) {
isRetComp = true;
break;
}
}
if (isRetComp)
continue;
}
}
}
// return deallocated pointer
if (used != PtrUsage::NONE && it->second.status == VarInfo::DEALLOC)
deallocReturnError(tok, it->second.allocTok, var->name());
else if (used != PtrUsage::PTR && !it->second.managed() && !var->isReference()) {
const auto use = possibleUsage.find(varid);
if (use == possibleUsage.end()) {
leakError(tok, var->name(), it->second.type);
} else if (!use->second.first->variable()) { // TODO: handle constructors
configurationInfo(tok, use->second);
}
}
toRemove.push_back(varid);
}
}
for (const int varId : toRemove)
varInfo.erase(varId);
}
| null |
875 | cpp | cppcheck | fwdanalysis.cpp | lib/fwdanalysis.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "fwdanalysis.h"
#include "astutils.h"
#include "config.h"
#include "library.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "vfvalue.h"
#include <list>
#include <string>
#include <utility>
static bool isUnchanged(const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local)
{
for (const Token *tok = startToken; tok != endToken; tok = tok->next()) {
if (!local && Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {"))
// TODO: this is a quick bailout
return false;
if (tok->varId() == 0 || exprVarIds.find(tok->varId()) == exprVarIds.end())
continue;
const Token *parent = tok;
while (parent->astParent() && !parent->astParent()->isAssignmentOp() && parent->astParent()->tokType() != Token::Type::eIncDecOp) {
if (parent->str() == "," || parent->isUnaryOp("&"))
// TODO: This is a quick bailout
return false;
parent = parent->astParent();
}
if (parent->astParent()) {
if (parent->astParent()->tokType() == Token::Type::eIncDecOp)
return false;
if (parent->astParent()->isAssignmentOp() && parent == parent->astParent()->astOperand1())
return false;
}
}
return true;
}
static bool hasFunctionCall(const Token *tok)
{
if (!tok)
return false;
if (Token::Match(tok, "%name% ("))
// todo, const/pure function?
return true;
return hasFunctionCall(tok->astOperand1()) || hasFunctionCall(tok->astOperand2());
}
static bool hasGccCompoundStatement(const Token *tok)
{
if (!tok)
return false;
if (tok->str() == "{" && Token::simpleMatch(tok->previous(), "( {"))
return true;
return hasGccCompoundStatement(tok->astOperand1()) || hasGccCompoundStatement(tok->astOperand2());
}
static bool nonLocal(const Variable* var, bool deref)
{
return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) || var->isStatic() || var->isReference() || var->isExtern();
}
static bool hasVolatileCastOrVar(const Token *expr)
{
bool ret = false;
visitAstNodes(expr,
[&ret](const Token *tok) {
if (tok->variable() && tok->variable()->isVolatile())
ret = true;
else if (Token::simpleMatch(tok, "( volatile"))
ret = true;
return ret ? ChildrenToVisit::none : ChildrenToVisit::op1_and_op2;
});
return ret;
}
FwdAnalysis::Result FwdAnalysis::checkRecursive(const Token *expr, const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local, bool inInnerClass, int depth)
{
// Parse the given tokens
if (++depth > 1000)
return Result(Result::Type::BAILOUT);
for (const Token* tok = startToken; precedes(tok, endToken); tok = tok->next()) {
if (Token::simpleMatch(tok, "try {")) {
// TODO: handle try
return Result(Result::Type::BAILOUT);
}
if (Token::simpleMatch(tok, "break ;")) {
return Result(Result::Type::BREAK, tok);
}
if (Token::simpleMatch(tok, "goto"))
return Result(Result::Type::BAILOUT);
if (!inInnerClass && tok->str() == "{" && tok->scope()->isClassOrStruct()) {
// skip returns from local class definition
FwdAnalysis::Result result = checkRecursive(expr, tok, tok->link(), exprVarIds, local, true, depth);
if (result.type != Result::Type::NONE)
return result;
tok=tok->link();
}
if (tok->str() == "continue")
// TODO
return Result(Result::Type::BAILOUT);
if (const Token *lambdaEndToken = findLambdaEndToken(tok)) {
tok = lambdaEndToken;
const Result lambdaResult = checkRecursive(expr, lambdaEndToken->link()->next(), lambdaEndToken, exprVarIds, local, inInnerClass, depth);
if (lambdaResult.type == Result::Type::READ || lambdaResult.type == Result::Type::BAILOUT)
return lambdaResult;
}
if (Token::Match(tok, "return|throw")) {
// TODO: Handle these better
// Is expr variable used in expression?
const Token* opTok = tok->astOperand1();
if (!opTok)
opTok = tok->next();
std::pair<const Token*, const Token*> startEndTokens = opTok->findExpressionStartEndTokens();
FwdAnalysis::Result result =
checkRecursive(expr, startEndTokens.first, startEndTokens.second->next(), exprVarIds, local, true, depth);
if (result.type != Result::Type::NONE)
return result;
// #9167: if the return is inside an inner class, it does not tell us anything
if (!inInnerClass) {
if (!local && mWhat == What::Reassign)
return Result(Result::Type::BAILOUT);
return Result(Result::Type::RETURN);
}
}
if (tok->str() == "}") {
// Known value => possible value
if (tok->scope() == expr->scope())
mValueFlowKnown = false;
if (tok->scope()->isLoopScope()) {
// check condition
const Token *conditionStart = nullptr;
const Token *conditionEnd = nullptr;
if (Token::simpleMatch(tok->link()->previous(), ") {")) {
conditionEnd = tok->link()->previous();
conditionStart = conditionEnd->link();
} else if (Token::simpleMatch(tok->link()->previous(), "do {") && Token::simpleMatch(tok, "} while (")) {
conditionStart = tok->tokAt(2);
conditionEnd = conditionStart->link();
}
if (conditionStart && conditionEnd) {
bool used = false;
for (const Token *condTok = conditionStart; condTok != conditionEnd; condTok = condTok->next()) {
if (exprVarIds.find(condTok->varId()) != exprVarIds.end()) {
used = true;
break;
}
}
if (used)
return Result(Result::Type::BAILOUT);
}
// check loop body again..
const FwdAnalysis::Result &result = checkRecursive(expr, tok->link(), tok, exprVarIds, local, inInnerClass, depth);
if (result.type == Result::Type::BAILOUT || result.type == Result::Type::READ)
return result;
}
}
if (Token::simpleMatch(tok, "else {"))
tok = tok->linkAt(1);
if (Token::simpleMatch(tok, "asm ("))
return Result(Result::Type::BAILOUT);
if (mWhat == What::ValueFlow && (Token::Match(tok, "while|for (") || Token::simpleMatch(tok, "do {"))) {
const Token *bodyStart = nullptr;
const Token *conditionStart = nullptr;
if (Token::simpleMatch(tok, "do {")) {
bodyStart = tok->next();
if (Token::simpleMatch(bodyStart->link(), "} while ("))
conditionStart = bodyStart->link()->tokAt(2);
} else {
conditionStart = tok->next();
if (Token::simpleMatch(conditionStart->link(), ") {"))
bodyStart = conditionStart->link()->next();
}
if (!bodyStart || !conditionStart)
return Result(Result::Type::BAILOUT);
// Is expr changed in condition?
if (!isUnchanged(conditionStart, conditionStart->link(), exprVarIds, local))
return Result(Result::Type::BAILOUT);
// Is expr changed in loop body?
if (!isUnchanged(bodyStart, bodyStart->link(), exprVarIds, local))
return Result(Result::Type::BAILOUT);
}
if (mWhat == What::ValueFlow && Token::simpleMatch(tok, "if (") && Token::simpleMatch(tok->linkAt(1), ") {")) {
const Token *bodyStart = tok->linkAt(1)->next();
const Token *conditionStart = tok->next();
const Token *condTok = conditionStart->astOperand2();
if (condTok->hasKnownIntValue()) {
const bool cond = condTok->values().front().intvalue;
if (cond) {
FwdAnalysis::Result result = checkRecursive(expr, bodyStart, bodyStart->link(), exprVarIds, local, true, depth);
if (result.type != Result::Type::NONE)
return result;
} else if (Token::simpleMatch(bodyStart->link(), "} else {")) {
bodyStart = bodyStart->link()->tokAt(2);
FwdAnalysis::Result result = checkRecursive(expr, bodyStart, bodyStart->link(), exprVarIds, local, true, depth);
if (result.type != Result::Type::NONE)
return result;
}
}
tok = bodyStart->link();
if (isReturnScope(tok, mSettings.library))
return Result(Result::Type::BAILOUT);
if (Token::simpleMatch(tok, "} else {"))
tok = tok->linkAt(2);
if (!tok)
return Result(Result::Type::BAILOUT);
// Is expr changed in condition?
if (!isUnchanged(conditionStart, conditionStart->link(), exprVarIds, local))
return Result(Result::Type::BAILOUT);
// Is expr changed in condition body?
if (!isUnchanged(bodyStart, bodyStart->link(), exprVarIds, local))
return Result(Result::Type::BAILOUT);
}
if (!local && Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) {
// TODO: this is a quick bailout
return Result(Result::Type::BAILOUT);
}
if (mWhat == What::Reassign &&
Token::simpleMatch(tok, ";") &&
Token::simpleMatch(tok->astParent(), ";") &&
Token::simpleMatch(tok->astParent()->astParent(), "(") &&
Token::simpleMatch(tok->astParent()->astParent()->previous(), "for (") &&
!isUnchanged(tok, tok->astParent()->astParent()->link(), exprVarIds, local))
// TODO: This is a quick bailout to avoid FP #9420, there are false negatives (TODO_ASSERT_EQUALS)
return Result(Result::Type::BAILOUT);
if (expr->isName() && Token::Match(tok, "%name% (") && tok->str().find('<') != std::string::npos && tok->str().find(expr->str()) != std::string::npos)
return Result(Result::Type::BAILOUT);
if (exprVarIds.find(tok->varId()) != exprVarIds.end()) {
const Token *parent = tok;
bool other = false;
bool same = tok->astParent() && isSameExpression(false, expr, tok, mSettings, true, false, nullptr);
while (!same && Token::Match(parent->astParent(), "*|.|::|[|(|%cop%")) {
parent = parent->astParent();
if (parent->str() == "(" && !parent->isCast())
break;
if (isSameExpression(false, expr, parent, mSettings, true, false, nullptr)) {
same = true;
if (mWhat == What::ValueFlow) {
KnownAndToken v;
v.known = mValueFlowKnown;
v.token = parent;
mValueFlow.push_back(v);
}
}
if (Token::Match(parent, ". %var%") && parent->next()->varId() && exprVarIds.find(parent->next()->varId()) == exprVarIds.end() &&
isSameExpression(false, expr->astOperand1(), parent->astOperand1(), mSettings, true, false, nullptr)) {
other = true;
break;
}
}
if (mWhat != What::ValueFlow && same && Token::simpleMatch(parent->astParent(), "[") && parent == parent->astParent()->astOperand2()) {
return Result(Result::Type::READ);
}
if (other)
continue;
if (Token::simpleMatch(parent->astParent(), "=") && parent == parent->astParent()->astOperand1()) {
if (!local && hasFunctionCall(parent->astParent()->astOperand2())) {
// TODO: this is a quick bailout
return Result(Result::Type::BAILOUT);
}
if (hasOperand(parent->astParent()->astOperand2(), expr)) {
if (mWhat == What::Reassign)
return Result(Result::Type::READ);
continue;
}
const auto startEnd = parent->astParent()->astOperand2()->findExpressionStartEndTokens();
for (const Token* tok2 = startEnd.first; tok2 != startEnd.second; tok2 = tok2->next()) {
if (tok2->tokType() == Token::eLambda)
return Result(Result::Type::BAILOUT);
// TODO: analyze usage in lambda
}
// ({ .. })
if (hasGccCompoundStatement(parent->astParent()->astOperand2()))
return Result(Result::Type::BAILOUT);
// cppcheck-suppress shadowFunction - TODO: fix this
const bool reassign = isSameExpression(false, expr, parent, mSettings, false, false, nullptr);
if (reassign)
return Result(Result::Type::WRITE, parent->astParent());
return Result(Result::Type::READ);
}
if (mWhat == What::Reassign) {
if (parent->variable() && parent->variable()->type() && parent->variable()->type()->isUnionType() && parent->varId() == expr->varId()) {
while (parent && Token::simpleMatch(parent->astParent(), "."))
parent = parent->astParent();
if (parent && parent->valueType() && Token::simpleMatch(parent->astParent(), "=") && !Token::Match(parent->astParent()->astParent(), "%assign%") && parent->astParent()->astOperand1() == parent) {
const Token * assignment = parent->astParent()->astOperand2();
while (Token::simpleMatch(assignment, ".") && assignment->varId() != expr->varId())
assignment = assignment->astOperand1();
if (assignment && assignment->varId() != expr->varId()) {
if (assignment->valueType() && assignment->valueType()->pointer) // Bailout
return Result(Result::Type::BAILOUT);
return Result(Result::Type::WRITE, parent->astParent());
}
}
return Result(Result::Type::READ);
}
if (parent->valueType() && parent->valueType()->pointer && Token::Match(parent->astParent(), "%assign%"))
return Result(Result::Type::READ);
}
if (Token::Match(parent->astParent(), "%assign%") && !parent->astParent()->astParent() && parent == parent->astParent()->astOperand1()) {
if (mWhat == What::Reassign)
return Result(Result::Type::BAILOUT, parent->astParent());
if (mWhat == What::UnusedValue && (!parent->valueType() || parent->valueType()->reference != Reference::None))
return Result(Result::Type::BAILOUT, parent->astParent());
continue;
}
if (mWhat == What::UnusedValue && parent->isUnaryOp("&") && Token::Match(parent->astParent(), "[,(]")) {
// Pass variable to function the writes it
const Token *ftok = parent->astParent();
while (Token::simpleMatch(ftok, ","))
ftok = ftok->astParent();
if (ftok && Token::Match(ftok->previous(), "%name% (")) {
const std::vector<const Token *> args = getArguments(ftok);
int argnr = 0;
while (argnr < args.size() && args[argnr] != parent)
argnr++;
if (argnr < args.size()) {
if (mSettings.library.getArgDirection(ftok->astOperand1(), argnr + 1) == Library::ArgumentChecks::Direction::DIR_OUT)
continue;
}
}
return Result(Result::Type::BAILOUT, parent->astParent());
}
// TODO: this is a quick bailout
return Result(Result::Type::BAILOUT, parent->astParent());
}
if (Token::Match(tok, ")|do {")) {
if (tok->str() == ")" && Token::simpleMatch(tok->link()->previous(), "switch ("))
// TODO: parse switch
return Result(Result::Type::BAILOUT);
const Result &result1 = checkRecursive(expr, tok->tokAt(2), tok->linkAt(1), exprVarIds, local, inInnerClass, depth);
if (result1.type == Result::Type::READ || result1.type == Result::Type::BAILOUT)
return result1;
if (mWhat == What::UnusedValue && result1.type == Result::Type::WRITE && expr->variable() && expr->variable()->isReference())
return result1;
if (mWhat == What::ValueFlow && result1.type == Result::Type::WRITE)
mValueFlowKnown = false;
if (mWhat == What::Reassign && result1.type == Result::Type::BREAK) {
const Token *scopeEndToken = findNextTokenFromBreak(result1.token);
if (scopeEndToken) {
const Result &result2 = checkRecursive(expr, scopeEndToken->next(), endToken, exprVarIds, local, inInnerClass, depth);
if (result2.type == Result::Type::BAILOUT)
return result2;
}
}
if (Token::simpleMatch(tok->linkAt(1), "} else {")) {
const Token *elseStart = tok->linkAt(1)->tokAt(2);
const Result &result2 = checkRecursive(expr, elseStart, elseStart->link(), exprVarIds, local, inInnerClass, depth);
if (mWhat == What::ValueFlow && result2.type == Result::Type::WRITE)
mValueFlowKnown = false;
if (result2.type == Result::Type::READ || result2.type == Result::Type::BAILOUT)
return result2;
if (result1.type == Result::Type::WRITE && result2.type == Result::Type::WRITE)
return result1;
tok = elseStart->link();
} else {
tok = tok->linkAt(1);
}
}
}
return Result(Result::Type::NONE);
}
std::set<nonneg int> FwdAnalysis::getExprVarIds(const Token* expr, bool* localOut, bool* unknownVarIdOut) const
{
// all variable ids in expr.
std::set<nonneg int> exprVarIds;
bool local = true;
bool unknownVarId = false;
visitAstNodes(expr,
[&](const Token *tok) {
if (tok->str() == "[" && mWhat == What::UnusedValue)
return ChildrenToVisit::op1;
if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") {
// unknown variable
unknownVarId = true;
return ChildrenToVisit::none;
}
if (tok->varId() > 0) {
exprVarIds.insert(tok->varId());
if (!Token::simpleMatch(tok->previous(), ".")) {
const Variable *var = tok->variable();
if (var && var->isReference() && var->isLocal() && Token::Match(var->nameToken(), "%var% [=(]") && !isGlobalData(var->nameToken()->next()->astOperand2()))
return ChildrenToVisit::none;
const bool deref = tok->astParent() && (tok->astParent()->isUnaryOp("*") || (tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1()));
local &= !nonLocal(tok->variable(), deref);
}
}
return ChildrenToVisit::op1_and_op2;
});
if (localOut)
*localOut = local;
if (unknownVarIdOut)
*unknownVarIdOut = unknownVarId;
return exprVarIds;
}
FwdAnalysis::Result FwdAnalysis::check(const Token* expr, const Token* startToken, const Token* endToken)
{
// all variable ids in expr.
bool local = true;
bool unknownVarId = false;
std::set<nonneg int> exprVarIds = getExprVarIds(expr, &local, &unknownVarId);
if (unknownVarId)
return Result(FwdAnalysis::Result::Type::BAILOUT);
if (mWhat == What::Reassign && isGlobalData(expr))
local = false;
// In unused values checking we do not want to check assignments to
// global data.
if (mWhat == What::UnusedValue && isGlobalData(expr))
return Result(FwdAnalysis::Result::Type::BAILOUT);
Result result = checkRecursive(expr, startToken, endToken, exprVarIds, local, false);
// Break => continue checking in outer scope
while (mWhat!=What::ValueFlow && result.type == FwdAnalysis::Result::Type::BREAK) {
const Token *scopeEndToken = findNextTokenFromBreak(result.token);
if (!scopeEndToken)
break;
result = checkRecursive(expr, scopeEndToken->next(), endToken, exprVarIds, local, false);
}
return result;
}
bool FwdAnalysis::hasOperand(const Token *tok, const Token *lhs) const
{
if (!tok)
return false;
if (isSameExpression(false, tok, lhs, mSettings, false, false, nullptr))
return true;
return hasOperand(tok->astOperand1(), lhs) || hasOperand(tok->astOperand2(), lhs);
}
const Token *FwdAnalysis::reassign(const Token *expr, const Token *startToken, const Token *endToken)
{
if (hasVolatileCastOrVar(expr))
return nullptr;
mWhat = What::Reassign;
Result result = check(expr, startToken, endToken);
return result.type == FwdAnalysis::Result::Type::WRITE ? result.token : nullptr;
}
bool FwdAnalysis::unusedValue(const Token *expr, const Token *startToken, const Token *endToken)
{
if (isEscapedAlias(expr))
return false;
if (hasVolatileCastOrVar(expr))
return false;
if (Token::simpleMatch(expr, "[") && astIsContainerView(expr->astOperand1()))
return false;
mWhat = What::UnusedValue;
Result result = check(expr, startToken, endToken);
return (result.type == FwdAnalysis::Result::Type::NONE || result.type == FwdAnalysis::Result::Type::RETURN) && !possiblyAliased(expr, startToken);
}
bool FwdAnalysis::possiblyAliased(const Token *expr, const Token *startToken) const
{
if (expr->isUnaryOp("*") && !expr->astOperand1()->isUnaryOp("&"))
return true;
if (Token::simpleMatch(expr, ". *"))
return true;
if (expr->str() == "(" && Token::simpleMatch(expr->astOperand1(), "."))
return true;
const bool macro = false;
const bool pure = false;
const bool followVar = false;
for (const Token *tok = startToken; tok; tok = tok->previous()) {
if (Token::Match(tok, "%name% (") && !Token::Match(tok, "if|while|for")) {
// Is argument passed by reference?
const std::vector<const Token*> args = getArguments(tok);
for (int argnr = 0; argnr < args.size(); ++argnr) {
if (!Token::Match(args[argnr], "%name%|.|::"))
continue;
if (tok->function() && tok->function()->getArgumentVar(argnr) && !tok->function()->getArgumentVar(argnr)->isReference() && !tok->function()->isConst())
continue;
for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) {
if (isSameExpression(macro, subexpr, args[argnr], mSettings, pure, followVar)) {
const Scope* scope = expr->scope(); // if there is no other variable, assume no aliasing
if (scope->varlist.size() > 1)
return true;
}
}
}
continue;
}
const Token *addrOf = nullptr;
if (Token::Match(tok, "& %name% ="))
addrOf = tok->tokAt(2)->astOperand2();
else if (tok->isUnaryOp("&"))
addrOf = tok->astOperand1();
else if (Token::simpleMatch(tok, "std :: ref ("))
addrOf = tok->tokAt(3)->astOperand2();
else if (tok->valueType() && tok->valueType()->pointer &&
(Token::Match(tok, "%var% = %var% ;") || Token::Match(tok, "%var% {|( %var% }|)")) &&
Token::Match(expr->previous(), "%varid% [", tok->tokAt(2)->varId()))
addrOf = tok->tokAt(2);
else
continue;
for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) {
if (subexpr != addrOf && isSameExpression(macro, subexpr, addrOf, mSettings, pure, followVar))
return true;
}
}
return false;
}
bool FwdAnalysis::isEscapedAlias(const Token* expr)
{
for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) {
for (const ValueFlow::Value &val : subexpr->values()) {
if (!val.isLocalLifetimeValue())
continue;
const Variable* var = val.tokvalue->variable();
if (!var)
continue;
if (!var->isLocal())
return true;
if (var->isArgument())
return true;
}
}
return false;
}
| null |
876 | cpp | cppcheck | settings.h | lib/settings.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef settingsH
#define settingsH
//---------------------------------------------------------------------------
#include "addoninfo.h"
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "platform.h"
#include "standards.h"
#include "suppressions.h"
#include <algorithm>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <list>
#include <map>
#include <set>
#include <string>
#include <tuple>
#include <vector>
#include <unordered_set>
#include <utility>
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
#include <cstdio>
#endif
enum class SHOWTIME_MODES : std::uint8_t;
namespace ValueFlow {
class Value;
}
/// @addtogroup Core
/// @{
template<typename T>
class SimpleEnableGroup {
uint32_t mFlags = 0;
public:
uint32_t intValue() const {
return mFlags;
}
void clear() {
mFlags = 0;
}
void fill() {
mFlags = 0xFFFFFFFF;
}
bool isEnabled(T flag) const {
return (mFlags & (1U << (uint32_t)flag)) != 0;
}
void enable(T flag) {
mFlags |= (1U << (uint32_t)flag);
}
void enable(SimpleEnableGroup<T> group) {
mFlags |= group.intValue();
}
void disable(T flag) {
mFlags &= ~(1U << (uint32_t)flag);
}
void disable(SimpleEnableGroup<T> group) {
mFlags &= ~(group.intValue());
}
void setEnabled(T flag, bool enabled) {
if (enabled)
enable(flag);
else
disable(flag);
}
};
/**
* @brief This is just a container for general settings so that we don't need
* to pass individual values to functions or constructors now or in the
* future when we might have even more detailed settings.
*/
class CPPCHECKLIB WARN_UNUSED Settings {
private:
/** @brief terminate checking */
static std::atomic<bool> mTerminated;
public:
Settings();
static std::string loadCppcheckCfg(Settings& settings, Suppressions& suppressions, bool debug = false);
static std::pair<std::string, std::string> getNameAndVersion(const std::string& productName);
/** @brief addons, either filename of python/json file or json data */
std::unordered_set<std::string> addons;
/** @brief the loaded addons infos */
std::vector<AddonInfo> addonInfos;
/** @brief Path to the python interpreter to be used to run addons. */
std::string addonPython;
/** @brief Paths used as base for conversion to relative paths. */
std::vector<std::string> basePaths;
/** @brief --cppcheck-build-dir. Always uses / as path separator. No trailing path separator. */
std::string buildDir;
/** @brief check all configurations (false if -D or --max-configs is used */
bool checkAllConfigurations = true;
/** Is the 'configuration checking' wanted? */
bool checkConfiguration{};
/**
* Check code in the headers, this is on by default but can
* be turned off to save CPU */
bool checkHeaders = true;
/** Check for incomplete info in library files? */
bool checkLibrary{};
/** @brief The maximum time in seconds for the checks of a single file */
int checksMaxTime{};
/** @brief --checkers-report=<filename> : Generate report of executed checkers */
std::string checkersReportFilename;
/** @brief check unknown function return values */
std::set<std::string> checkUnknownFunctionReturn;
/** Check unused/uninstantiated templates */
bool checkUnusedTemplates = true;
/** Use Clang */
bool clang{};
/** Custom Clang executable */
std::string clangExecutable = "clang";
/** Use clang-tidy */
bool clangTidy{};
/** Internal: Clear the simplecpp non-existing include cache */
bool clearIncludeCache{};
/** @brief include paths excluded from checking the configuration */
std::set<std::string> configExcludePaths;
/** cppcheck.cfg: Custom product name */
std::string cppcheckCfgProductName;
/** cppcheck.cfg: About text */
std::string cppcheckCfgAbout;
/** @brief check Emacs marker to detect extension-less and *.h files as C++ */
bool cppHeaderProbe{};
/** @brief Are we running from DACA script? */
bool daca{};
/** @brief Internal: Is --debug-lookup or --debug-lookup=all given? */
bool debuglookup{};
/** @brief Internal: Is --debug-lookup=addon given? */
bool debuglookupAddon{};
/** @brief Internal: Is --debug-lookup=config given? */
bool debuglookupConfig{};
/** @brief Internal: Is --debug-lookup=library given? */
bool debuglookupLibrary{};
/** @brief Internal: Is --debug-lookup=platform given? */
bool debuglookupPlatform{};
/** @brief Is --debug-normal given? */
bool debugnormal{};
/** @brief Is --debug-simplified given? */
bool debugSimplified{};
/** @brief Is --debug-template given? */
bool debugtemplate{};
/** @brief Is --debug-warnings given? */
bool debugwarnings{};
/** @brief Is --dump given? */
bool dump{};
/** @brief Name of the language that is enforced. Empty per default. */
Standards::Language enforcedLang{};
#if defined(USE_WINDOWS_SEH) || defined(USE_UNIX_SIGNAL_HANDLING)
/** @brief Is --exception-handling given */
bool exceptionHandling{};
FILE* exceptionOutput = stdout;
#endif
enum class ExecutorType : std::uint8_t
{
#ifdef HAS_THREADING_MODEL_THREAD
Thread,
#endif
#ifdef HAS_THREADING_MODEL_FORK
Process
#endif
};
ExecutorType executor;
// argv[0]
std::string exename;
/** @brief If errors are found, this value is returned from main().
Default value is 0. */
int exitCode{};
/** @brief List of --file-filter for analyzing special files */
std::vector<std::string> fileFilters;
/** @brief Force checking the files with "too many" configurations (--force). */
bool force{};
/** @brief List of include paths, e.g. "my/includes/" which should be used
for finding include files inside source files. (-I) */
std::list<std::string> includePaths;
/** @brief Is --inline-suppr given? */
bool inlineSuppressions{};
/** @brief How many processes/threads should do checking at the same
time. Default is 1. (-j N) */
unsigned int jobs = 1;
/** @brief --library= */
std::list<std::string> libraries;
/** Library */
Library library;
/** @brief Load average value */
int loadAverage{};
/** @brief Maximum number of configurations to check before bailing.
Default is 12. (--max-configs=N) */
int maxConfigs = 12;
/** @brief --max-ctu-depth */
int maxCtuDepth = 2;
/** @brief max template recursion */
int maxTemplateRecursion = 100;
/** @brief write results (--output-file=<file>) */
std::string outputFile;
enum class OutputFormat : std::uint8_t {text, plist, sarif, xml};
OutputFormat outputFormat = OutputFormat::text;
Platform platform;
/** @brief pid of cppcheck. Intention is that this is set in the main process. */
int pid;
/** @brief plist output (--plist-output=<dir>) */
std::string plistOutput;
/** @brief Extra arguments for Cppcheck Premium addon */
std::string premiumArgs;
/** Is checker id enabled by premiumArgs */
bool isPremiumEnabled(const char id[]) const;
/** @brief Using -E for debugging purposes */
bool preprocessOnly{};
/** @brief Is --quiet given? */
bool quiet{};
/** @brief Use relative paths in output. */
bool relativePaths{};
/** @brief --report-progress */
int reportProgress{-1};
#ifdef HAVE_RULES
/** Rule */
struct CPPCHECKLIB Rule {
std::string tokenlist = "normal"; // use normal tokenlist
std::string pattern;
std::string id = "rule"; // default id
std::string summary;
Severity severity = Severity::style; // default severity
};
/**
* @brief Extra rules
*/
std::list<Rule> rules;
#endif
/**
* @brief Safety certified behavior
* Show checkers report when Cppcheck finishes
* Make cppcheck checking more strict about critical errors
* - returns nonzero if there is critical errors
* - a critical error id is not suppressed (by mistake?) with glob pattern
*/
bool safety = false;
/** Do not only check how interface is used. Also check that interface is safe. */
struct CPPCHECKLIB SafeChecks {
static const char XmlRootName[];
static const char XmlClasses[];
static const char XmlExternalFunctions[];
static const char XmlInternalFunctions[];
static const char XmlExternalVariables[];
void clear() {
classes = externalFunctions = internalFunctions = externalVariables = false;
}
/**
* Public interface of classes
* - public function parameters can have any value
* - public functions can be called in any order
* - public variables can have any value
*/
bool classes{};
/**
* External functions
* - external functions can be called in any order
* - function parameters can have any values
*/
bool externalFunctions{};
/**
* Experimental: assume that internal functions can be used in any way
* This is only available in the GUI.
*/
bool internalFunctions{};
/**
* Global variables that can be modified outside the TU.
* - Such variable can have "any" value
*/
bool externalVariables{};
};
SafeChecks safeChecks;
SimpleEnableGroup<Severity> severity;
SimpleEnableGroup<Certainty> certainty;
SimpleEnableGroup<Checks> checks;
/** @brief show timing information (--showtime=file|summary|top5) */
SHOWTIME_MODES showtime{};
/** Struct contains standards settings */
Standards standards;
/** @brief suppressions */
Suppressions supprs;
/** @brief The output format in which the errors are printed in text mode,
e.g. "{severity} {file}:{line} {message} {id}" */
std::string templateFormat;
/** @brief The output format in which the error locations are printed in
* text mode, e.g. "{file}:{line} {info}" */
std::string templateLocation;
/** @brief The maximum time in seconds for the template instantiation */
std::size_t templateMaxTime{};
/** @brief The maximum time in seconds for the typedef simplification */
std::size_t typedefMaxTime{};
/** @brief defines given by the user */
std::string userDefines;
/** @brief undefines given by the user */
std::set<std::string> userUndefs;
/** @brief forced includes given by the user */
std::list<std::string> userIncludes;
// TODO: adjust all options so 0 means "disabled" and -1 "means "unlimited"
struct ValueFlowOptions
{
/** @brief the maximum iterations to execute */
std::size_t maxIterations = 4;
/** @brief maximum numer if-branches */
int maxIfCount = -1;
/** @brief maximum number of sets of arguments to pass to subfuncions */
int maxSubFunctionArgs = 256;
/** @brief Experimental: maximum execution time */
int maxTime = -1;
/** @brief Control if condition expression analysis is performed */
bool doConditionExpressionAnalysis = true;
/** @brief Maximum performed for-loop count */
int maxForLoopCount = 10000;
/** @brief Maximum performed forward branches */
int maxForwardBranches = -1;
/** @brief Maximum performed alignof recursion */
int maxAlignOfRecursion = 100;
/** @brief Maximum performed sizeof recursion */
int maxSizeOfRecursion = 100;
/** @brief Maximum expression varid depth */
int maxExprVarIdDepth = 4;
};
/** @brief The ValueFlow options */
ValueFlowOptions vfOptions;
/** @brief Is --verbose given? */
bool verbose{};
/** @brief write XML results (--xml) */
bool xml{};
/** @brief XML version (--xml-version=..) */
int xml_version = 2;
/**
* @brief return true if a included file is to be excluded in Preprocessor::getConfigs
* @return true for the file to be excluded.
*/
bool configurationExcluded(const std::string &file) const {
return std::any_of(configExcludePaths.begin(), configExcludePaths.end(), [&file](const std::string& path) {
return file.length() >= path.length() && file.compare(0, path.length(), path) == 0;
});
}
/**
* @brief Enable extra checks by id. See isEnabled()
* @param str single id or list of id values to be enabled
* or empty string to enable all. e.g. "style,possibleError"
* @return error message. empty upon success
*/
std::string addEnabled(const std::string &str);
/**
* @brief Disable extra checks by id
* @param str single id or list of id values to be enabled
* or empty string to enable all. e.g. "style,possibleError"
* @return error message. empty upon success
*/
std::string removeEnabled(const std::string &str);
/**
* @brief Returns true if given value can be shown
* @return true if the value can be shown
*/
bool isEnabled(const ValueFlow::Value *value, bool inconclusiveCheck=false) const;
/** Is library specified? */
bool hasLib(const std::string &lib) const {
return std::find(libraries.cbegin(), libraries.cend(), lib) != libraries.cend();
}
/** @brief Request termination of checking */
static void terminate(bool t = true) {
Settings::mTerminated = t;
}
/** @brief termination requested? */
static bool terminated() {
return Settings::mTerminated;
}
std::set<std::string> summaryReturn;
void loadSummaries();
bool useSingleJob() const {
return jobs == 1;
}
enum class CheckLevel : std::uint8_t {
reduced,
normal,
exhaustive
};
CheckLevel checkLevel = CheckLevel::exhaustive;
void setCheckLevel(CheckLevel level);
using ExecuteCmdFn = std::function<int (std::string,std::vector<std::string>,std::string,std::string&)>;
void setMisraRuleTexts(const ExecuteCmdFn& executeCommand);
void setMisraRuleTexts(const std::string& data);
std::string getMisraRuleText(const std::string& id, const std::string& text) const;
static ExecutorType defaultExecutor();
private:
static std::string parseEnabled(const std::string &str, std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> &groups);
std::string applyEnabled(const std::string &str, bool enable);
std::map<std::string, std::string> mMisraRuleTexts;
};
/// @}
//---------------------------------------------------------------------------
#endif // settingsH
| null |
877 | cpp | cppcheck | checksizeof.h | lib/checksizeof.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checksizeofH
#define checksizeofH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/** @brief checks on usage of sizeof() operator */
class CPPCHECKLIB CheckSizeof : public Check {
public:
/** @brief This constructor is used when registering the CheckClass */
CheckSizeof() : Check(myName()) {}
private:
/** @brief This constructor is used when running checks. */
CheckSizeof(const Tokenizer* tokenizer, const Settings* settings, ErrorLogger* errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer& tokenizer, ErrorLogger* errorLogger) override {
CheckSizeof checkSizeof(&tokenizer, &tokenizer.getSettings(), errorLogger);
// Checks
checkSizeof.sizeofsizeof();
checkSizeof.sizeofCalculation();
checkSizeof.sizeofFunction();
checkSizeof.suspiciousSizeofCalculation();
checkSizeof.checkSizeofForArrayParameter();
checkSizeof.checkSizeofForPointerSize();
checkSizeof.checkSizeofForNumericParameter();
checkSizeof.sizeofVoid();
}
/** @brief %Check for 'sizeof sizeof ..' */
void sizeofsizeof();
/** @brief %Check for calculations inside sizeof */
void sizeofCalculation();
/** @brief %Check for function call inside sizeof */
void sizeofFunction();
/** @brief %Check for suspicious calculations with sizeof results */
void suspiciousSizeofCalculation();
/** @brief %Check for using sizeof with array given as function argument */
void checkSizeofForArrayParameter();
/** @brief %Check for using sizeof of a variable when allocating it */
void checkSizeofForPointerSize();
/** @brief %Check for using sizeof with numeric given as function argument */
void checkSizeofForNumericParameter();
/** @brief %Check for using sizeof(void) */
void sizeofVoid();
// Error messages..
void sizeofsizeofError(const Token* tok);
void sizeofCalculationError(const Token* tok, bool inconclusive);
void sizeofFunctionError(const Token* tok);
void multiplySizeofError(const Token* tok);
void divideSizeofError(const Token* tok);
void sizeofForArrayParameterError(const Token* tok);
void sizeofForPointerError(const Token* tok, const std::string &varname);
void divideBySizeofError(const Token* tok, const std::string &memfunc);
void sizeofForNumericParameterError(const Token* tok);
void sizeofVoidError(const Token *tok);
void sizeofDereferencedVoidPointerError(const Token *tok, const std::string &varname);
void arithOperationsOnVoidPointerError(const Token* tok, const std::string &varname, const std::string &vartype);
void getErrorMessages(ErrorLogger* errorLogger, const Settings* settings) const override {
CheckSizeof c(nullptr, settings, errorLogger);
c.sizeofForArrayParameterError(nullptr);
c.sizeofForPointerError(nullptr, "varname");
c.divideBySizeofError(nullptr, "memset");
c.sizeofForNumericParameterError(nullptr);
c.sizeofsizeofError(nullptr);
c.sizeofCalculationError(nullptr, false);
c.sizeofFunctionError(nullptr);
c.multiplySizeofError(nullptr);
c.divideSizeofError(nullptr);
c.sizeofVoidError(nullptr);
c.sizeofDereferencedVoidPointerError(nullptr, "varname");
c.arithOperationsOnVoidPointerError(nullptr, "varname", "vartype");
}
static std::string myName() {
return "Sizeof";
}
std::string classInfo() const override {
return "sizeof() usage checks\n"
"- sizeof for array given as function argument\n"
"- sizeof for numeric given as function argument\n"
"- using sizeof(pointer) instead of the size of pointed data\n"
"- look for 'sizeof sizeof ..'\n"
"- look for calculations inside sizeof()\n"
"- look for function calls inside sizeof()\n"
"- look for suspicious calculations with sizeof()\n"
"- using 'sizeof(void)' which is undefined\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checksizeofH
| null |
878 | cpp | cppcheck | symboldatabase.h | lib/symboldatabase.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef symboldatabaseH
#define symboldatabaseH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "mathlib.h"
#include "sourcelocation.h"
#include "token.h"
#include "utils.h"
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <iosfwd>
#include <list>
#include <map>
#include <set>
#include <string>
#include <utility>
#include <vector>
class Platform;
class ErrorLogger;
class Function;
class Scope;
class Settings;
class SymbolDatabase;
class Tokenizer;
class ValueType;
enum class Reference : std::uint8_t {
None,
LValue,
RValue
};
/**
* @brief Access control enumerations.
*/
enum class AccessControl : std::uint8_t { Public, Protected, Private, Global, Namespace, Argument, Local, Throw };
/**
* @brief Array dimension information.
*/
struct Dimension {
const Token* tok{}; ///< size token
MathLib::bigint num{}; ///< (assumed) dimension length when size is a number, 0 if not known
bool known = true; ///< Known size
};
/** @brief Information about a class type. */
class CPPCHECKLIB Type {
public:
const Token* classDef; ///< Points to "class" token
const Scope* classScope;
const Scope* enclosingScope;
enum class NeedInitialization : std::uint8_t {
Unknown, True, False
} needInitialization = NeedInitialization::Unknown;
struct BaseInfo {
std::string name;
const Type* type{};
const Token* nameTok{};
AccessControl access{}; // public/protected/private
bool isVirtual{};
// allow ordering within containers
bool operator<(const BaseInfo& rhs) const {
return this->type < rhs.type;
}
};
struct FriendInfo {
const Token* nameStart{};
const Token* nameEnd{};
const Type* type{};
};
std::vector<BaseInfo> derivedFrom;
std::vector<FriendInfo> friendList;
const Token* typeStart{};
const Token* typeEnd{};
MathLib::bigint sizeOf{};
explicit Type(const Token* classDef_ = nullptr, const Scope* classScope_ = nullptr, const Scope* enclosingScope_ = nullptr) :
classDef(classDef_),
classScope(classScope_),
enclosingScope(enclosingScope_) {
if (classDef_ && classDef_->str() == "enum")
needInitialization = NeedInitialization::True;
else if (classDef_ && classDef_->str() == "using") {
typeStart = classDef->tokAt(3);
typeEnd = typeStart;
while (typeEnd->next() && typeEnd->strAt(1) != ";") {
if (Token::simpleMatch(typeEnd, "decltype ("))
typeEnd = typeEnd->linkAt(1);
else
typeEnd = typeEnd->next();
}
}
}
std::string name() const;
const std::string& type() const {
return classDef ? classDef->str() : emptyString;
}
bool isClassType() const;
bool isEnumType() const;
bool isStructType() const;
bool isUnionType() const;
bool isTypeAlias() const {
return classDef && classDef->str() == "using";
}
const Token *initBaseInfo(const Token *tok, const Token *tok1);
const Function* getFunction(const std::string& funcName) const;
/**
* Check for circulare dependencies, i.e. loops within the class hierarchy
* @param ancestors list of ancestors. For internal usage only, clients should not supply this argument.
* @return true if there is a circular dependency
*/
bool hasCircularDependencies(std::set<BaseInfo>* ancestors = nullptr) const;
/**
* Check for dependency
* @param ancestor potential ancestor
* @return true if there is a dependency
*/
bool findDependency(const Type* ancestor) const;
bool isDerivedFrom(const std::string & ancestor) const;
};
struct CPPCHECKLIB Enumerator {
explicit Enumerator(const Scope * scope_) : scope(scope_) {}
const Scope * scope;
const Token* name{};
MathLib::bigint value{};
const Token* start{};
const Token* end{};
bool value_known{};
};
/** @brief Information about a member variable. */
class CPPCHECKLIB Variable {
/** @brief flags mask used to access specific bit. */
enum {
fIsMutable = (1 << 0), /** @brief mutable variable */
fIsStatic = (1 << 1), /** @brief static variable */
fIsConst = (1 << 2), /** @brief const variable */
fIsExtern = (1 << 3), /** @brief extern variable */
fIsClass = (1 << 4), /** @brief user defined type */
fIsArray = (1 << 5), /** @brief array variable */
fIsPointer = (1 << 6), /** @brief pointer variable */
fIsReference = (1 << 7), /** @brief reference variable */
fIsRValueRef = (1 << 8), /** @brief rvalue reference variable */
fHasDefault = (1 << 9), /** @brief function argument with default value */
fIsStlType = (1 << 10), /** @brief STL type ('std::') */
fIsStlString = (1 << 11), /** @brief std::string|wstring|basic_string<T>|u16string|u32string */
fIsFloatType = (1 << 12), /** @brief Floating point type */
fIsVolatile = (1 << 13), /** @brief volatile */
fIsSmartPointer = (1 << 14),/** @brief std::shared_ptr|unique_ptr */
fIsMaybeUnused = (1 << 15), /** @brief marked [[maybe_unused]] */
fIsInit = (1 << 16), /** @brief Is variable initialized in declaration */
};
/**
* Get specified flag state.
* @param flag_ flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag_) const {
return ((mFlags & flag_) != 0);
}
/**
* Set specified flag state.
* @param flag_ flag to set state
* @param state_ new state of flag
*/
void setFlag(unsigned int flag_, bool state_) {
mFlags = state_ ? mFlags | flag_ : mFlags & ~flag_;
}
/**
* @brief parse and save array dimension information
* @param settings Platform settings and library
* @param isContainer Is the array container-like?
* @return true if array, false if not
*/
bool arrayDimensions(const Settings& settings, bool& isContainer);
public:
Variable(const Token *name_, const Token *start_, const Token *end_,
nonneg int index_, AccessControl access_, const Type *type_,
const Scope *scope_, const Settings& settings)
: mNameToken(name_),
mTypeStartToken(start_),
mTypeEndToken(end_),
mIndex(index_),
mAccess(access_),
mFlags(0),
mType(type_),
mScope(scope_) {
evaluate(settings);
}
Variable(const Token *name_, const std::string &clangType, const Token *typeStart,
const Token *typeEnd, nonneg int index_, AccessControl access_,
const Type *type_, const Scope *scope_);
Variable(const Variable &var, const Scope *scope);
Variable(const Variable &var);
~Variable();
Variable &operator=(const Variable &var) &;
/**
* Get name token.
* @return name token
*/
const Token *nameToken() const {
return mNameToken;
}
/**
* Get type start token.
* The type start token doesn't account 'static' and 'const' qualifiers
* E.g.:
* static const int * const p = ...;
* type start token ^
* @return type start token
*/
const Token *typeStartToken() const {
return mTypeStartToken;
}
/**
* Get type end token.
* The type end token doesn't account the forward 'const' qualifier
* E.g.:
* static const int * const p = ...;
* type end token ^
* @return type end token
*/
const Token *typeEndToken() const {
return mTypeEndToken;
}
/**
* Get end token of variable declaration
* E.g.
* int i[2][3] = ...
* end token ^
* @return variable declaration end token
*/
const Token *declEndToken() const;
/**
* Get name string.
* @return name string
*/
const std::string &name() const {
// name may not exist for function arguments
if (mNameToken)
return mNameToken->str();
return emptyString;
}
/**
* Get declaration ID (varId used for variable in its declaration).
* @return declaration ID
*/
nonneg int declarationId() const {
// name may not exist for function arguments
if (mNameToken)
return mNameToken->varId();
return 0;
}
/**
* Get index of variable in declared order.
* @return variable index
*/
nonneg int index() const {
return mIndex;
}
/**
* Is variable public.
* @return true if public, false if not
*/
bool isPublic() const {
return mAccess == AccessControl::Public;
}
/**
* Is variable protected.
* @return true if protected, false if not
*/
bool isProtected() const {
return mAccess == AccessControl::Protected;
}
/**
* Is variable private.
* @return true if private, false if not
*/
bool isPrivate() const {
return mAccess == AccessControl::Private;
}
/**
* Is variable global.
* @return true if global, false if not
*/
bool isGlobal() const {
return mAccess == AccessControl::Global;
}
/**
* Is variable in a namespace.
* @return true if in a namespace, false if not
*/
// cppcheck-suppress unusedFunction
bool isNamespace() const {
return mAccess == AccessControl::Namespace;
}
/**
* Is variable a function argument.
* @return true if a function argument, false if not
*/
bool isArgument() const {
return mAccess == AccessControl::Argument;
}
/**
* Is variable local.
* @return true if local, false if not
*/
bool isLocal() const {
return (mAccess == AccessControl::Local) && !isExtern();
}
/**
* Is variable a member of a user-defined type.
* @return true if member, false if not or unknown
*/
bool isMember() const;
/**
* Is variable mutable.
* @return true if mutable, false if not
*/
bool isMutable() const {
return getFlag(fIsMutable);
}
/**
* Is variable volatile.
* @return true if volatile, false if not
*/
bool isVolatile() const {
return getFlag(fIsVolatile);
}
/**
* Is variable static.
* @return true if static, false if not
*/
bool isStatic() const {
return getFlag(fIsStatic);
}
/**
* Is variable extern.
* @return true if extern, false if not
*/
bool isExtern() const {
return getFlag(fIsExtern);
}
/**
* Is variable const.
* @return true if const, false if not
*/
bool isConst() const {
return getFlag(fIsConst);
}
/**
* Is variable a throw type.
* @return true if throw type, false if not
*/
bool isThrow() const {
return mAccess == AccessControl::Throw;
}
/**
* Is variable a user defined (or unknown) type.
* @return true if user defined type, false if not
*/
bool isClass() const {
return getFlag(fIsClass);
}
/**
* Is variable an array.
* @return true if array, false if not
*/
bool isArray() const {
return getFlag(fIsArray) && !getFlag(fIsPointer);
}
/**
* Is pointer variable.
* @return true if pointer, false otherwise
*/
bool isPointer() const {
return getFlag(fIsPointer);
}
/**
* Is variable a pointer to an array
* @return true if pointer to array, false otherwise
*/
bool isPointerToArray() const {
return isPointer() && getFlag(fIsArray);
}
/**
* Is variable an array of pointers
* @return true if array or pointers, false otherwise
*/
bool isPointerArray() const;
/**
* Is array or pointer variable.
* @return true if pointer or array, false otherwise
*/
bool isArrayOrPointer() const {
return getFlag(fIsArray) || getFlag(fIsPointer);
}
/**
* Is reference variable.
* @return true if reference, false otherwise
*/
bool isReference() const {
return getFlag(fIsReference);
}
/**
* Is reference variable.
* @return true if reference, false otherwise
*/
bool isRValueReference() const {
return getFlag(fIsRValueRef);
}
/**
* Is variable unsigned.
* @return true only if variable _is_ unsigned. if the sign is unknown, false is returned.
*/
bool isUnsigned() const;
/**
* Does variable have a default value.
* @return true if has a default falue, false if not
*/
bool hasDefault() const {
return getFlag(fHasDefault);
}
/**
* Is variable initialized in its declaration
* @return true if variable declaration contains initialization
*/
bool isInit() const {
return getFlag(fIsInit);
}
/**
* Get Type pointer of known type.
* @return pointer to type if known, NULL if not known
*/
const Type *type() const {
return mType;
}
/**
* Get Scope pointer of known type.
* @return pointer to type scope if known, NULL if not known
*/
const Scope *typeScope() const {
return mType ? mType->classScope : nullptr;
}
/**
* Get Scope pointer of enclosing scope.
* @return pointer to enclosing scope
*/
const Scope *scope() const {
return mScope;
}
/**
* Get array dimensions.
* @return array dimensions vector
*/
const std::vector<Dimension> &dimensions() const {
return mDimensions;
}
/**
* Get array dimension length.
* @return length of dimension
*/
MathLib::bigint dimension(nonneg int index_) const {
return mDimensions.at(index_).num;
}
/**
* Get array dimension known.
* @return length of dimension known
*/
bool dimensionKnown(nonneg int index_) const {
return mDimensions.at(index_).known;
}
void setDimensions(const std::vector<Dimension> &dimensions_) {
mDimensions = dimensions_;
}
/**
* Checks if the variable is an STL type ('std::')
* E.g.:
* std::string s;
* ...
* sVar->isStlType() == true
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlType() const {
return getFlag(fIsStlType);
}
/**
* Checks if the variable is an STL type ('std::')
* E.g.:
* std::string s;
* ...
* sVar->isStlType() == true
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlStringType() const {
return getFlag(fIsStlString);
}
bool isStlStringViewType() const;
bool isSmartPointer() const {
return getFlag(fIsSmartPointer);
}
const Type* smartPointerType() const;
const Type* iteratorType() const;
/**
* Checks if the variable is of any of the STL types passed as arguments ('std::')
* E.g.:
* std::string s;
* ...
* const char *str[] = {"string", "wstring"};
* sVar->isStlType(str) == true
* @param stlType stl type
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlType(const std::string& stlType) const {
return isStlType() && stlType==mTypeStartToken->strAt(2);
}
/**
* Checks if the variable is of any of the STL types passed as arguments ('std::')
* E.g.:
* std::string s;
* ...
* const std::set<std::string> str = make_container< std::set<std::string> >() << "string" << "wstring";
* sVar->isStlType(str) == true
* @param stlTypes set of stl types
* @return true if it is an stl type and its type matches any of the types in 'stlTypes'
*/
bool isStlType(const std::set<std::string>& stlTypes) const {
return isStlType() && stlTypes.find(mTypeStartToken->strAt(2))!=stlTypes.end();
}
/**
* Determine whether it's a floating number type
* @return true if the type is known and it's a floating type (float, double and long double) or a pointer/array to it
*/
bool isFloatingType() const {
return getFlag(fIsFloatType);
}
/**
* Determine whether it's an enumeration type
* @return true if the type is known and it's an enumeration type
*/
bool isEnumType() const {
return type() && type()->isEnumType();
}
bool isMaybeUnused() const {
return getFlag(fIsMaybeUnused);
}
const ValueType *valueType() const {
return mValueType;
}
void setValueType(const ValueType &valueType);
AccessControl accessControl() const {
return mAccess;
}
std::string getTypeName() const;
private:
// only symbol database can change the type
friend class SymbolDatabase;
/**
* Set Type pointer to known type.
* @param t type
*/
void type(const Type * t) {
mType = t;
}
/** @brief variable name token */
const Token *mNameToken;
/** @brief variable type start token */
const Token *mTypeStartToken;
/** @brief variable type end token */
const Token *mTypeEndToken;
/** @brief order declared */
nonneg int mIndex;
/** @brief what section is this variable declared in? */
AccessControl mAccess; // public/protected/private
/** @brief flags */
unsigned int mFlags;
/** @brief pointer to user defined type info (for known types) */
const Type *mType;
/** @brief pointer to scope this variable is in */
const Scope *mScope;
const ValueType* mValueType{};
/** @brief array dimensions */
std::vector<Dimension> mDimensions;
/** @brief fill in information, depending on Tokens given at instantiation */
void evaluate(const Settings& settings);
};
class CPPCHECKLIB Function {
// only symbol database can change this
friend class SymbolDatabase;
/** @brief flags mask used to access specific bit. */
enum {
fHasBody = (1 << 0), ///< @brief has implementation
fIsInline = (1 << 1), ///< @brief implementation in class definition
fIsConst = (1 << 2), ///< @brief is const
fHasVirtualSpecifier = (1 << 3), ///< @brief does declaration contain 'virtual' specifier
fIsPure = (1 << 4), ///< @brief is pure virtual
fIsStatic = (1 << 5), ///< @brief is static
fIsStaticLocal = (1 << 6), ///< @brief is static local
fIsExtern = (1 << 7), ///< @brief is extern
fIsFriend = (1 << 8), ///< @brief is friend
fIsExplicit = (1 << 9), ///< @brief is explicit
fIsDefault = (1 << 10), ///< @brief is default
fIsDelete = (1 << 11), ///< @brief is delete
fHasOverrideSpecifier = (1 << 12), ///< @brief does declaration contain 'override' specifier?
fHasFinalSpecifier = (1 << 13), ///< @brief does declaration contain 'final' specifier?
fIsNoExcept = (1 << 14), ///< @brief is noexcept
fIsThrow = (1 << 15), ///< @brief is throw
fIsOperator = (1 << 16), ///< @brief is operator
fHasLvalRefQual = (1 << 17), ///< @brief has & lvalue ref-qualifier
fHasRvalRefQual = (1 << 18), ///< @brief has && rvalue ref-qualifier
fIsVariadic = (1 << 19), ///< @brief is variadic
fIsVolatile = (1 << 20), ///< @brief is volatile
fHasTrailingReturnType = (1 << 21), ///< @brief has trailing return type
fIsEscapeFunction = (1 << 22), ///< @brief Function throws or exits
fIsInlineKeyword = (1 << 23), ///< @brief Function has "inline" keyword
fIsConstexpr = (1 << 24), ///< @brief is constexpr
};
/**
* Get specified flag state.
* @param flag flag to get state of
* @return true if flag set or false in flag not set
*/
bool getFlag(unsigned int flag) const {
return ((mFlags & flag) != 0);
}
/**
* Set specified flag state.
* @param flag flag to set state
* @param state new state of flag
*/
void setFlag(unsigned int flag, bool state) {
mFlags = state ? mFlags | flag : mFlags & ~flag;
}
public:
enum Type : std::uint8_t { eConstructor, eCopyConstructor, eMoveConstructor, eOperatorEqual, eDestructor, eFunction, eLambda };
Function(const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef);
Function(const Token *tokenDef, const std::string &clangType);
const std::string &name() const {
return tokenDef->str();
}
std::string fullName() const;
nonneg int argCount() const {
return argumentList.size();
}
nonneg int minArgCount() const {
return argumentList.size() - initArgCount;
}
const Variable* getArgumentVar(nonneg int num) const;
nonneg int initializedArgCount() const {
return initArgCount;
}
void addArguments(const SymbolDatabase *symbolDatabase, const Scope *scope);
/** @brief check if this function is virtual in the base classes */
bool isImplicitlyVirtual(bool defaultVal = false, bool* pFoundAllBaseClasses = nullptr) const;
std::vector<const Function*> getOverloadedFunctions() const;
/** @brief get function in base class that is overridden */
const Function *getOverriddenFunction(bool *foundAllBaseClasses = nullptr) const;
bool isLambda() const {
return type==eLambda;
}
bool isConstructor() const {
return type==eConstructor ||
type==eCopyConstructor ||
type==eMoveConstructor;
}
bool isDestructor() const {
return type==eDestructor;
}
bool isAttributeConstructor() const {
return tokenDef->isAttributeConstructor();
}
bool isAttributeDestructor() const {
return tokenDef->isAttributeDestructor();
}
bool isAttributePure() const {
return tokenDef->isAttributePure();
}
bool isAttributeConst() const {
return tokenDef->isAttributeConst();
}
bool isAttributeNoreturn() const {
return tokenDef->isAttributeNoreturn();
}
bool isAttributeNothrow() const {
return tokenDef->isAttributeNothrow();
}
bool isAttributeNodiscard() const {
return tokenDef->isAttributeNodiscard();
}
bool hasBody() const {
return getFlag(fHasBody);
}
bool isInline() const {
return getFlag(fIsInline);
}
bool isConst() const {
return getFlag(fIsConst);
}
bool hasVirtualSpecifier() const {
return getFlag(fHasVirtualSpecifier);
}
bool isPure() const {
return getFlag(fIsPure);
}
bool isStatic() const {
return getFlag(fIsStatic);
}
bool isStaticLocal() const {
return getFlag(fIsStaticLocal);
}
bool isExtern() const {
return getFlag(fIsExtern);
}
bool isFriend() const {
return getFlag(fIsFriend);
}
bool isExplicit() const {
return getFlag(fIsExplicit);
}
bool isDefault() const {
return getFlag(fIsDefault);
}
bool isDelete() const {
return getFlag(fIsDelete);
}
bool isNoExcept() const {
return getFlag(fIsNoExcept);
}
bool isThrow() const {
return getFlag(fIsThrow);
}
bool hasOverrideSpecifier() const {
return getFlag(fHasOverrideSpecifier);
}
bool hasFinalSpecifier() const {
return getFlag(fHasFinalSpecifier);
}
bool isOperator() const {
return getFlag(fIsOperator);
}
bool hasLvalRefQualifier() const {
return getFlag(fHasLvalRefQual);
}
bool hasRvalRefQualifier() const {
return getFlag(fHasRvalRefQual);
}
bool isVariadic() const {
return getFlag(fIsVariadic);
}
bool isVolatile() const {
return getFlag(fIsVolatile);
}
bool hasTrailingReturnType() const {
return getFlag(fHasTrailingReturnType);
}
void hasBody(bool state) {
setFlag(fHasBody, state);
}
bool isInlineKeyword() const {
return getFlag(fIsInlineKeyword);
}
bool isEscapeFunction() const {
return getFlag(fIsEscapeFunction);
}
void isEscapeFunction(bool state) {
setFlag(fIsEscapeFunction, state);
}
bool isConstexpr() const {
return getFlag(fIsConstexpr);
}
void isConstexpr(bool state) {
setFlag(fIsConstexpr, state);
}
bool isSafe(const Settings &settings) const;
const Token* tokenDef{}; ///< function name token in class definition
const Token* argDef{}; ///< function argument start '(' in class definition
const Token* token{}; ///< function name token in implementation
const Token* arg{}; ///< function argument start '('
const Token* retDef{}; ///< function return type token
const ::Type* retType{}; ///< function return type
const Scope* functionScope{}; ///< scope of function body
const Scope* nestedIn{}; ///< Scope the function is declared in
std::list<Variable> argumentList; ///< argument list, must remain list due to clangimport usage!
nonneg int initArgCount{}; ///< number of args with default values
Type type = eFunction; ///< constructor, destructor, ...
const Token* noexceptArg{}; ///< noexcept token
const Token* throwArg{}; ///< throw token
const Token* templateDef{}; ///< points to 'template <' before function
const Token* functionPointerUsage{}; ///< function pointer usage
AccessControl access{}; ///< public/protected/private
bool argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, nonneg int path_length) const;
static bool returnsConst(const Function* function, bool unknown = false);
static bool returnsPointer(const Function* function, bool unknown = false);
static bool returnsReference(const Function* function, bool unknown = false, bool includeRValueRef = false);
static bool returnsStandardType(const Function* function, bool unknown = false);
static bool returnsVoid(const Function* function, bool unknown = false);
static std::vector<const Token*> findReturns(const Function* f);
const Token* returnDefEnd() const {
if (this->hasTrailingReturnType())
return Token::findmatch(retDef, "{|;");
return tokenDef;
}
/**
* @return token to ":" if the function is a constructor
* and it contains member initialization otherwise a nullptr is returned
*/
const Token * constructorMemberInitialization() const;
private:
/** Recursively determine if this function overrides a virtual function in a base class */
const Function * getOverriddenFunctionRecursive(const ::Type* baseType, bool *foundAllBaseClasses) const;
unsigned int mFlags{};
void isInline(bool state) {
setFlag(fIsInline, state);
}
void isConst(bool state) {
setFlag(fIsConst, state);
}
void hasVirtualSpecifier(bool state) {
setFlag(fHasVirtualSpecifier, state);
}
void isPure(bool state) {
setFlag(fIsPure, state);
}
void isStatic(bool state) {
setFlag(fIsStatic, state);
}
void isStaticLocal(bool state) {
setFlag(fIsStaticLocal, state);
}
void isExtern(bool state) {
setFlag(fIsExtern, state);
}
void isFriend(bool state) {
setFlag(fIsFriend, state);
}
void isExplicit(bool state) {
setFlag(fIsExplicit, state);
}
void isDefault(bool state) {
setFlag(fIsDefault, state);
}
void isDelete(bool state) {
setFlag(fIsDelete, state);
}
void isNoExcept(bool state) {
setFlag(fIsNoExcept, state);
}
void isThrow(bool state) {
setFlag(fIsThrow, state);
}
void isOperator(bool state) {
setFlag(fIsOperator, state);
}
void hasLvalRefQualifier(bool state) {
setFlag(fHasLvalRefQual, state);
}
void hasRvalRefQualifier(bool state) {
setFlag(fHasRvalRefQual, state);
}
void isVariadic(bool state) {
setFlag(fIsVariadic, state);
}
void isVolatile(bool state) {
setFlag(fIsVolatile, state);
}
void hasTrailingReturnType(bool state) {
setFlag(fHasTrailingReturnType, state);
}
void isInlineKeyword(bool state) {
setFlag(fIsInlineKeyword, state);
}
RET_NONNULL const Token *setFlags(const Token *tok1, const Scope *scope);
};
class CPPCHECKLIB Scope {
// let tests access private function for testing
friend class TestSymbolDatabase;
public:
struct UsingInfo {
const Token *start;
const Scope *scope;
};
enum ScopeType : std::uint8_t { eGlobal, eClass, eStruct, eUnion, eNamespace, eFunction, eIf, eElse, eFor, eWhile, eDo, eSwitch, eUnconditional, eTry, eCatch, eLambda, eEnum };
Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_);
Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_, ScopeType type_, const Token *start_);
const SymbolDatabase* check{};
std::string className;
const Token* classDef{}; ///< class/struct/union/namespace token
const Token* bodyStart{}; ///< '{' token
const Token* bodyEnd{}; ///< '}' token
std::list<Function> functionList;
std::multimap<std::string, const Function *> functionMap;
std::list<Variable> varlist;
const Scope* nestedIn{};
std::vector<Scope *> nestedList;
nonneg int numConstructors{};
nonneg int numCopyOrMoveConstructors{};
std::vector<UsingInfo> usingList;
ScopeType type{};
Type* definedType{};
std::map<std::string, Type*> definedTypesMap;
std::vector<const Token *> bodyStartList;
// function specific fields
const Scope* functionOf{}; ///< scope this function belongs to
Function* function{}; ///< function info for this function
// enum specific fields
const Token* enumType{};
bool enumClass{};
std::vector<Enumerator> enumeratorList;
void setBodyStartEnd(const Token *start) {
bodyStart = start;
bodyEnd = start ? start->link() : nullptr;
if (start)
bodyStartList.push_back(start);
}
bool isAnonymous() const {
// TODO: Check if class/struct is anonymous
return className.size() > 9 && startsWith(className,"Anonymous") && std::isdigit(className[9]);
}
const Enumerator * findEnumerator(const std::string & name) const {
auto it = std::find_if(enumeratorList.cbegin(), enumeratorList.cend(), [&](const Enumerator& i) {
return i.name->str() == name;
});
return it == enumeratorList.end() ? nullptr : &*it;
}
bool isNestedIn(const Scope * outer) const {
if (!outer)
return false;
if (outer == this)
return true;
const Scope * parent = nestedIn;
while (outer != parent && parent)
parent = parent->nestedIn;
return parent && parent == outer;
}
static Function* nestedInFunction(const Scope* scope) {
while (scope) {
if (scope->type == Scope::eFunction)
break;
scope = scope->nestedIn;
}
if (!scope)
return nullptr;
return scope->function;
}
bool isClassOrStruct() const {
return (type == eClass || type == eStruct);
}
bool isClassOrStructOrUnion() const {
return (type == eClass || type == eStruct || type == eUnion);
}
bool isExecutable() const {
return type != eClass && type != eStruct && type != eUnion && type != eGlobal && type != eNamespace && type != eEnum;
}
bool isLoopScope() const {
return type == Scope::ScopeType::eFor || type == Scope::ScopeType::eWhile || type == Scope::ScopeType::eDo;
}
bool isLocal() const {
return (type == eIf || type == eElse ||
type == eFor || type == eWhile || type == eDo ||
type == eSwitch || type == eUnconditional ||
type == eTry || type == eCatch);
}
// Is there lambda/inline function(s) in this scope?
bool hasInlineOrLambdaFunction(const Token** tokStart = nullptr) const;
/**
* @brief find a function
* @param tok token of function call
* @param requireConst if const refers to a const variable only const methods should be matched
* @return pointer to function if found or NULL if not found
*/
const Function *findFunction(const Token *tok, bool requireConst=false, Reference ref=Reference::None) const;
const Scope *findRecordInNestedList(const std::string & name, bool isC = false) const;
Scope *findRecordInNestedList(const std::string & name, bool isC = false);
const Type* findType(const std::string& name) const;
Type* findType(const std::string& name);
/**
* @brief find if name is in nested list
* @param name name of nested scope
*/
Scope *findInNestedListRecursive(const std::string & name);
void addVariable(const Token *token_, const Token *start_,
const Token *end_, AccessControl access_, const Type *type_,
const Scope *scope_, const Settings& settings);
/** @brief initialize varlist */
void getVariableList(const Settings& settings);
const Function *getDestructor() const;
void addFunction(Function func) {
functionList.push_back(std::move(func));
const Function * back = &functionList.back();
functionMap.emplace(back->tokenDef->str(), back);
}
AccessControl defaultAccess() const;
/**
* @brief check if statement is variable declaration and add it if it is
* @param tok pointer to start of statement
* @param varaccess access control of statement
* @param settings Settings
* @return pointer to last token
*/
const Token *checkVariable(const Token *tok, AccessControl varaccess, const Settings& settings);
/**
* @brief get variable from name
* @param varname name of variable
* @return pointer to variable
*/
const Variable *getVariable(const std::string &varname) const;
const Token * addEnum(const Token * tok);
const Scope *findRecordInBase(const std::string &name) const;
std::vector<const Scope*> findAssociatedScopes() const;
private:
/**
* @brief helper function for getVariableList()
* @param tok pointer to token to check
* @param vartok populated with pointer to the variable token, if found
* @param typetok populated with pointer to the type token, if found
* @return true if tok points to a variable declaration, false otherwise
*/
bool isVariableDeclaration(const Token* tok, const Token*& vartok, const Token*& typetok) const;
void findFunctionInBase(const std::string & name, nonneg int args, std::vector<const Function *> & matches) const;
/** @brief initialize varlist */
void getVariableList(const Settings& settings, const Token *start, const Token *end);
};
/** Value type */
class CPPCHECKLIB ValueType {
public:
enum Sign : std::uint8_t { UNKNOWN_SIGN, SIGNED, UNSIGNED } sign = UNKNOWN_SIGN;
enum Type : std::uint8_t {
UNKNOWN_TYPE,
POD,
NONSTD,
RECORD,
SMART_POINTER,
CONTAINER,
ITERATOR,
VOID,
BOOL,
CHAR,
SHORT,
WCHAR_T,
INT,
LONG,
LONGLONG,
UNKNOWN_INT,
FLOAT,
DOUBLE,
LONGDOUBLE
} type = UNKNOWN_TYPE;
nonneg int bits{}; ///< bitfield bitcount
nonneg int pointer{}; ///< 0=>not pointer, 1=>*, 2=>**, 3=>***, etc
nonneg int constness{}; ///< bit 0=data, bit 1=*, bit 2=**
nonneg int volatileness{}; ///< bit 0=data, bit 1=*, bit 2=**
Reference reference = Reference::None; ///< Is the outermost indirection of this type a reference or rvalue
///< reference or not? pointer=2, Reference=LValue would be a T**&
const Scope* typeScope{}; ///< if the type definition is seen this point out the type scope
const ::Type* smartPointerType{}; ///< Smart pointer type
const Token* smartPointerTypeToken{}; ///< Smart pointer type token
const Library::SmartPointer* smartPointer{}; ///< Smart pointer
const Library::Container* container{}; ///< If the type is a container defined in a cfg file, this is the used
///< container
const Token* containerTypeToken{}; ///< The container type token. the template argument token that defines the
///< container element type.
std::string originalTypeName; ///< original type name as written in the source code. eg. this might be "uint8_t"
///< when type is CHAR.
ErrorPath debugPath; ///< debug path to the type
ValueType() = default;
ValueType(Sign s, Type t, nonneg int p)
: sign(s),
type(t),
pointer(p)
{}
ValueType(Sign s, Type t, nonneg int p, nonneg int c)
: sign(s),
type(t),
pointer(p),
constness(c)
{}
ValueType(Sign s, Type t, nonneg int p, nonneg int c, nonneg int v)
: sign(s),
type(t),
pointer(p),
constness(c),
volatileness(v)
{}
ValueType(Sign s, Type t, nonneg int p, nonneg int c, std::string otn)
: sign(s),
type(t),
pointer(p),
constness(c),
originalTypeName(std::move(otn))
{}
static ValueType parseDecl(const Token *type, const Settings &settings);
static Type typeFromString(const std::string &typestr, bool longType);
enum class MatchResult : std::uint8_t { UNKNOWN, SAME, FALLBACK1, FALLBACK2, NOMATCH };
static MatchResult matchParameter(const ValueType *call, const ValueType *func);
static MatchResult matchParameter(const ValueType *call, const Variable *callVar, const Variable *funcVar);
bool isPrimitive() const {
return (type >= ValueType::Type::BOOL);
}
bool isIntegral() const {
return (type >= ValueType::Type::BOOL && type <= ValueType::Type::UNKNOWN_INT);
}
bool isFloat() const {
return (type >= ValueType::Type::FLOAT && type <= ValueType::Type::LONGDOUBLE);
}
bool fromLibraryType(const std::string &typestr, const Settings &settings);
bool isEnum() const {
return typeScope && typeScope->type == Scope::eEnum;
}
bool isConst(nonneg int indirect = 0) const;
bool isVolatile(nonneg int indirect = 0) const;
MathLib::bigint typeSize(const Platform &platform, bool p=false) const;
/// Check if type is the same ignoring const and references
bool isTypeEqual(const ValueType* that) const;
std::string str() const;
std::string dump() const;
void setDebugPath(const Token* tok, SourceLocation ctx, const SourceLocation &local = SourceLocation::current());
};
class CPPCHECKLIB SymbolDatabase {
friend class TestSymbolDatabase;
public:
SymbolDatabase(Tokenizer& tokenizer, const Settings& settings, ErrorLogger& errorLogger);
~SymbolDatabase();
/** @brief Information about all namespaces/classes/structures */
std::list<Scope> scopeList;
/** @brief Fast access to function scopes */
std::vector<const Scope*> functionScopes;
/** @brief Fast access to class and struct scopes */
std::vector<const Scope*> classAndStructScopes;
/** @brief Fast access to types */
std::list<Type> typeList;
/**
* @brief find a variable type if it's a user defined type
* @param start scope to start looking in
* @param typeTok token containing variable type
* @return pointer to type if found or NULL if not found
*/
const Type* findVariableType(const Scope* start, const Token* typeTok) const;
/**
* @brief find a function
* @param tok token of function call
* @return pointer to function if found or NULL if not found
*/
const Function* findFunction(const Token* tok) const;
/** For unit testing only */
const Scope* findScopeByName(const std::string& name) const;
const Type* findType(const Token* startTok, const Scope* startScope, bool lookOutside = false) const;
Type* findType(const Token* startTok, Scope* startScope, bool lookOutside = false)
{
return const_cast<Type*>(this->findType(startTok, static_cast<const Scope*>(startScope), lookOutside));
}
const Scope *findScope(const Token *tok, const Scope *startScope) const;
Scope *findScope(const Token *tok, Scope *startScope) {
return const_cast<Scope *>(this->findScope(tok, static_cast<const Scope *>(startScope)));
}
// cppcheck-suppress unusedFunction
bool isVarId(nonneg int varid) const {
return varid < mVariableList.size();
}
const Variable *getVariableFromVarId(nonneg int varId) const {
return mVariableList.at(varId);
}
const std::vector<const Variable *> & variableList() const {
return mVariableList;
}
/**
* @brief output a debug message
*/
void debugMessage(const Token *tok, const std::string &type, const std::string &msg) const;
void returnImplicitIntError(const Token *tok) const;
void printOut(const char * title = nullptr) const;
void printVariable(const Variable *var, const char *indent) const;
void printXml(std::ostream &out) const;
/*
* @brief Do a sanity check
*/
void validate() const;
/** Set valuetype in provided tokenlist */
void setValueTypeInTokenList(bool reportDebugWarnings, Token *tokens=nullptr);
/**
* Calculates sizeof value for given type.
* @param type Token which will contain e.g. "int", "*", or string.
* @return sizeof for given type, or 0 if it can't be calculated.
*/
nonneg int sizeOfType(const Token *type) const;
/** Set array dimensions when valueflow analysis is completed */
void setArrayDimensionsUsingValueFlow(); // cppcheck-suppress functionConst // has side effects
void clangSetVariables(const std::vector<const Variable *> &variableList);
void createSymbolDatabaseExprIds();
/* returns the opening { if tok points to enum */
static const Token* isEnumDefinition(const Token* tok);
private:
friend class Scope;
friend class Function;
// Create symboldatabase...
void createSymbolDatabaseFindAllScopes();
void createSymbolDatabaseClassInfo();
void createSymbolDatabaseVariableInfo();
void createSymbolDatabaseCopyAndMoveConstructors();
void createSymbolDatabaseFunctionScopes();
void createSymbolDatabaseClassAndStructScopes();
void createSymbolDatabaseFunctionReturnTypes();
void createSymbolDatabaseNeedInitialization();
void createSymbolDatabaseVariableSymbolTable();
void createSymbolDatabaseSetScopePointers();
void createSymbolDatabaseSetFunctionPointers(bool firstPass); // cppcheck-suppress functionConst // has side effects
void createSymbolDatabaseSetVariablePointers();
// cppcheck-suppress functionConst
void createSymbolDatabaseSetTypePointers();
void createSymbolDatabaseSetSmartPointerType();
void createSymbolDatabaseEnums(); // cppcheck-suppress functionConst // has side effects
void createSymbolDatabaseEscapeFunctions(); // cppcheck-suppress functionConst // has side effects
// cppcheck-suppress functionConst
void createSymbolDatabaseIncompleteVars();
void debugSymbolDatabase() const;
void addClassFunction(Scope *&scope, const Token *&tok, const Token *argStart);
RET_NONNULL static Function *addGlobalFunctionDecl(Scope*& scope, const Token* tok, const Token *argStart, const Token* funcStart);
Function *addGlobalFunction(Scope*& scope, const Token*& tok, const Token *argStart, const Token* funcStart);
void addNewFunction(Scope *&scope, const Token *&tok);
bool isFunction(const Token *tok, const Scope* outerScope, const Token *&funcStart, const Token *&argStart, const Token*& declEnd) const;
const Type *findTypeInNested(const Token *startTok, const Scope *startScope) const;
const Scope *findNamespace(const Token * tok, const Scope * scope) const;
static Function *findFunctionInScope(const Token *func, const Scope *ns, const std::string & path, nonneg int path_length);
static const Type *findVariableTypeInBase(const Scope *scope, const Token *typeTok);
using MemberIdMap = std::map<unsigned int, unsigned int>;
using VarIdMap = std::map<unsigned int, MemberIdMap>;
void fixVarId(VarIdMap & varIds, const Token * vartok, Token * membertok, const Variable * membervar);
/** Whether the token is a keyword as defined in http://en.cppreference.com/w/c/keyword and http://en.cppreference.com/w/cpp/keyword*/
static bool isReservedName(const Token* tok);
const Enumerator * findEnumerator(const Token * tok, std::set<std::string>& tokensThatAreNotEnumeratorValues) const;
void setValueType(Token* tok, const ValueType& valuetype, const SourceLocation &loc = SourceLocation::current());
void setValueType(Token* tok, const Variable& var, const SourceLocation &loc = SourceLocation::current());
void setValueType(Token* tok, const Enumerator& enumerator, const SourceLocation &loc = SourceLocation::current());
void validateExecutableScopes() const;
/**
* @brief Check variable list, e.g. variables w/o scope
*/
void validateVariables() const;
Tokenizer& mTokenizer;
const Settings &mSettings;
ErrorLogger &mErrorLogger;
/** variable symbol table */
std::vector<const Variable *> mVariableList;
/** list for missing types */
std::list<Type> mBlankTypes;
ValueType::Sign mDefaultSignedness;
};
//---------------------------------------------------------------------------
#endif // symboldatabaseH
| null |
879 | cpp | cppcheck | library.cpp | lib/library.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "library.h"
#include "astutils.h"
#include "errortypes.h"
#include "mathlib.h"
#include "path.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "vfvalue.h"
#include <algorithm>
#include <cctype>
#include <climits>
#include <cstring>
#include <iostream>
#include <list>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <string>
#include <unordered_set>
#include "xml.h"
struct Library::LibraryData
{
struct Platform {
const PlatformType *platform_type(const std::string &name) const {
const std::map<std::string, PlatformType>::const_iterator it = mPlatformTypes.find(name);
return (it != mPlatformTypes.end()) ? &(it->second) : nullptr;
}
std::map<std::string, PlatformType> mPlatformTypes;
};
class ExportedFunctions {
public:
void addPrefix(std::string prefix) {
mPrefixes.insert(std::move(prefix));
}
void addSuffix(std::string suffix) {
mSuffixes.insert(std::move(suffix));
}
bool isPrefix(const std::string& prefix) const {
return (mPrefixes.find(prefix) != mPrefixes.end());
}
bool isSuffix(const std::string& suffix) const {
return (mSuffixes.find(suffix) != mSuffixes.end());
}
private:
std::set<std::string> mPrefixes;
std::set<std::string> mSuffixes;
};
class CodeBlock {
public:
CodeBlock() = default;
void setStart(const char* s) {
mStart = s;
}
void setEnd(const char* e) {
mEnd = e;
}
void setOffset(const int o) {
mOffset = o;
}
void addBlock(const char* blockName) {
mBlocks.insert(blockName);
}
const std::string& start() const {
return mStart;
}
const std::string& end() const {
return mEnd;
}
int offset() const {
return mOffset;
}
bool isBlock(const std::string& blockName) const {
return mBlocks.find(blockName) != mBlocks.end();
}
private:
std::string mStart;
std::string mEnd;
int mOffset{};
std::set<std::string> mBlocks;
};
enum class FalseTrueMaybe : std::uint8_t { False, True, Maybe };
std::map<std::string, WarnInfo> mFunctionwarn;
std::set<std::string> mDefines;
std::unordered_map<std::string, Container> mContainers;
std::unordered_map<std::string, Function> mFunctions;
std::unordered_map<std::string, SmartPointer> mSmartPointers;
int mAllocId{};
std::set<std::string> mFiles;
std::map<std::string, AllocFunc> mAlloc; // allocation functions
std::map<std::string, AllocFunc> mDealloc; // deallocation functions
std::map<std::string, AllocFunc> mRealloc; // reallocation functions
std::unordered_map<std::string, FalseTrueMaybe> mNoReturn; // is function noreturn?
std::map<std::string, std::string> mReturnValue;
std::map<std::string, std::string> mReturnValueType;
std::map<std::string, int> mReturnValueContainer;
std::map<std::string, std::vector<MathLib::bigint>> mUnknownReturnValues;
std::map<std::string, bool> mReportErrors;
std::map<std::string, bool> mProcessAfterCode;
std::set<std::string> mMarkupExtensions; // file extensions of markup files
std::map<std::string, std::set<std::string>> mKeywords; // keywords for code in the library
std::unordered_map<std::string, CodeBlock> mExecutableBlocks; // keywords for blocks of executable code
std::map<std::string, ExportedFunctions> mExporters; // keywords that export variables/functions to libraries (meta-code/macros)
std::map<std::string, std::set<std::string>> mImporters; // keywords that import variables/functions
std::map<std::string, int> mReflection; // invocation of reflection
std::unordered_map<std::string, struct PodType> mPodTypes; // pod types
std::map<std::string, PlatformType> mPlatformTypes; // platform independent typedefs
std::map<std::string, Platform> mPlatforms; // platform dependent typedefs
std::map<std::pair<std::string,std::string>, TypeCheck> mTypeChecks;
std::unordered_map<std::string, NonOverlappingData> mNonOverlappingData;
std::unordered_set<std::string> mEntrypoints;
};
Library::Library()
: mData(new LibraryData())
{}
Library::~Library() = default;
Library::Library(const Library& other)
: mData(new LibraryData(*other.mData))
{}
Library& Library::operator=(const Library& other) &
{
mData.reset(new LibraryData(*other.mData));
return *this;
}
static std::vector<std::string> getnames(const char *names)
{
std::vector<std::string> ret;
while (const char *p = std::strchr(names,',')) {
ret.emplace_back(names, p-names);
names = p + 1;
}
ret.emplace_back(names);
return ret;
}
static void gettokenlistfromvalid(const std::string& valid, bool cpp, TokenList& tokenList)
{
std::istringstream istr(valid + ',');
tokenList.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C); // TODO: check result?
for (Token *tok = tokenList.front(); tok; tok = tok->next()) {
if (Token::Match(tok,"- %num%")) {
tok->str("-" + tok->strAt(1));
tok->deleteNext();
}
}
}
Library::Error Library::load(const char exename[], const char path[], bool debug)
{
if (std::strchr(path,',') != nullptr) {
throw std::runtime_error("handling of multiple libraries not supported");
}
const bool is_abs_path = Path::isAbsolute(path);
std::string absolute_path;
// open file..
tinyxml2::XMLDocument doc;
if (debug)
std::cout << "looking for library '" + std::string(path) + "'" << std::endl;
tinyxml2::XMLError error = xml_LoadFile(doc, path);
if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND) {
// failed to open file.. is there no extension?
std::string fullfilename(path);
if (Path::getFilenameExtension(fullfilename).empty()) {
fullfilename += ".cfg";
if (debug)
std::cout << "looking for library '" + fullfilename + "'" << std::endl;
error = xml_LoadFile(doc, fullfilename.c_str());
if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND)
absolute_path = Path::getAbsoluteFilePath(fullfilename);
}
// only perform further lookups when the given path was not absolute
if (!is_abs_path && error == tinyxml2::XML_ERROR_FILE_NOT_FOUND)
{
std::list<std::string> cfgfolders;
#ifdef FILESDIR
cfgfolders.emplace_back(FILESDIR "/cfg");
#endif
if (exename) {
const std::string exepath(Path::fromNativeSeparators(Path::getPathFromFilename(Path::getCurrentExecutablePath(exename))));
cfgfolders.push_back(exepath + "cfg");
cfgfolders.push_back(exepath);
}
while (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND && !cfgfolders.empty()) {
const std::string cfgfolder(cfgfolders.back());
cfgfolders.pop_back();
const char *sep = (!cfgfolder.empty() && endsWith(cfgfolder,'/') ? "" : "/");
const std::string filename(cfgfolder + sep + fullfilename);
if (debug)
std::cout << "looking for library '" + std::string(filename) + "'" << std::endl;
error = xml_LoadFile(doc, filename.c_str());
if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND)
absolute_path = Path::getAbsoluteFilePath(filename);
}
}
} else
absolute_path = Path::getAbsoluteFilePath(path);
if (error == tinyxml2::XML_SUCCESS) {
if (mData->mFiles.find(absolute_path) == mData->mFiles.end()) {
Error err = load(doc);
if (err.errorcode == ErrorCode::OK)
mData->mFiles.insert(absolute_path);
return err;
}
return Error(ErrorCode::OK); // ignore duplicates
}
if (debug)
std::cout << "library not found: '" + std::string(path) + "'" << std::endl;
if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND)
return Error(ErrorCode::FILE_NOT_FOUND);
doc.PrintError(); // TODO: do not print stray messages
return Error(ErrorCode::BAD_XML);
}
Library::Container::Yield Library::Container::yieldFrom(const std::string& yieldName)
{
if (yieldName == "at_index")
return Container::Yield::AT_INDEX;
if (yieldName == "item")
return Container::Yield::ITEM;
if (yieldName == "buffer")
return Container::Yield::BUFFER;
if (yieldName == "buffer-nt")
return Container::Yield::BUFFER_NT;
if (yieldName == "start-iterator")
return Container::Yield::START_ITERATOR;
if (yieldName == "end-iterator")
return Container::Yield::END_ITERATOR;
if (yieldName == "iterator")
return Container::Yield::ITERATOR;
if (yieldName == "size")
return Container::Yield::SIZE;
if (yieldName == "empty")
return Container::Yield::EMPTY;
return Container::Yield::NO_YIELD;
}
Library::Container::Action Library::Container::actionFrom(const std::string& actionName)
{
if (actionName == "resize")
return Container::Action::RESIZE;
if (actionName == "clear")
return Container::Action::CLEAR;
if (actionName == "push")
return Container::Action::PUSH;
if (actionName == "pop")
return Container::Action::POP;
if (actionName == "find")
return Container::Action::FIND;
if (actionName == "find-const")
return Container::Action::FIND_CONST;
if (actionName == "insert")
return Container::Action::INSERT;
if (actionName == "erase")
return Container::Action::ERASE;
if (actionName == "append")
return Container::Action::APPEND;
if (actionName == "change-content")
return Container::Action::CHANGE_CONTENT;
if (actionName == "change-internal")
return Container::Action::CHANGE_INTERNAL;
if (actionName == "change")
return Container::Action::CHANGE;
return Container::Action::NO_ACTION;
}
Library::Error Library::load(const tinyxml2::XMLDocument &doc)
{
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (rootnode == nullptr) {
doc.PrintError();
return Error(ErrorCode::BAD_XML);
}
if (strcmp(rootnode->Name(),"def") != 0)
return Error(ErrorCode::UNSUPPORTED_FORMAT, rootnode->Name());
const int format = rootnode->IntAttribute("format", 1); // Assume format version 1 if nothing else is specified (very old .cfg files had no 'format' attribute)
if (format > 2 || format <= 0)
return Error(ErrorCode::UNSUPPORTED_FORMAT);
std::set<std::string> unknown_elements;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const std::string nodename = node->Name();
if (nodename == "memory" || nodename == "resource") {
// get allocationId to use..
int allocationId = 0;
for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) {
if (strcmp(memorynode->Name(),"dealloc")==0) {
const auto names = getnames(memorynode->GetText());
for (const auto& n : names) {
const std::map<std::string, AllocFunc>::const_iterator it = mData->mDealloc.find(n);
if (it != mData->mDealloc.end()) {
allocationId = it->second.groupId;
break;
}
}
if (allocationId != 0)
break;
}
}
if (allocationId == 0) {
if (nodename == "memory") {
while (!ismemory(++mData->mAllocId)) {}
}
else {
while (!isresource(++mData->mAllocId)) {}
}
allocationId = mData->mAllocId;
}
// add alloc/dealloc/use functions..
for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) {
const std::string memorynodename = memorynode->Name();
const auto names = getnames(memorynode->GetText());
if (memorynodename == "alloc" || memorynodename == "realloc") {
AllocFunc temp;
temp.groupId = allocationId;
temp.initData = memorynode->BoolAttribute("init", true);
temp.arg = memorynode->IntAttribute("arg", -1);
const char *bufferSize = memorynode->Attribute("buffer-size");
if (!bufferSize)
temp.bufferSize = AllocFunc::BufferSize::none;
else {
if (std::strncmp(bufferSize, "malloc", 6) == 0)
temp.bufferSize = AllocFunc::BufferSize::malloc;
else if (std::strncmp(bufferSize, "calloc", 6) == 0)
temp.bufferSize = AllocFunc::BufferSize::calloc;
else if (std::strncmp(bufferSize, "strdup", 6) == 0)
temp.bufferSize = AllocFunc::BufferSize::strdup;
else
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize);
temp.bufferSizeArg1 = 1;
temp.bufferSizeArg2 = 2;
if (bufferSize[6] == 0) {
// use default values
} else if (bufferSize[6] == ':' && bufferSize[7] >= '1' && bufferSize[7] <= '5') {
temp.bufferSizeArg1 = bufferSize[7] - '0';
if (bufferSize[8] == ',' && bufferSize[9] >= '1' && bufferSize[9] <= '5')
temp.bufferSizeArg2 = bufferSize[9] - '0';
} else
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize);
}
if (memorynodename == "realloc")
temp.reallocArg = memorynode->IntAttribute("realloc-arg", 1);
auto& map = (memorynodename == "realloc") ? mData->mRealloc : mData->mAlloc;
for (const auto& n : names)
map[n] = temp;
} else if (memorynodename == "dealloc") {
AllocFunc temp;
temp.groupId = allocationId;
temp.arg = memorynode->IntAttribute("arg", 1);
for (const auto& n : names)
mData->mDealloc[n] = temp;
} else if (memorynodename == "use")
for (const auto& n : names)
mData->mFunctions[n].use = true;
else
unknown_elements.insert(memorynodename);
}
}
else if (nodename == "define") {
const char *name = node->Attribute("name");
if (name == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
const char *value = node->Attribute("value");
if (value == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
auto result = mData->mDefines.insert(std::string(name) + " " + value);
if (!result.second)
return Error(ErrorCode::DUPLICATE_DEFINE, name);
}
else if (nodename == "function") {
const char *name = node->Attribute("name");
if (name == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
for (const std::string &s : getnames(name)) {
const Error &err = loadFunction(node, s, unknown_elements);
if (err.errorcode != ErrorCode::OK)
return err;
}
}
else if (nodename == "reflection") {
for (const tinyxml2::XMLElement *reflectionnode = node->FirstChildElement(); reflectionnode; reflectionnode = reflectionnode->NextSiblingElement()) {
if (strcmp(reflectionnode->Name(), "call") != 0) {
unknown_elements.insert(reflectionnode->Name());
continue;
}
const char * const argString = reflectionnode->Attribute("arg");
if (!argString)
return Error(ErrorCode::MISSING_ATTRIBUTE, "arg");
mData->mReflection[reflectionnode->GetText()] = strToInt<int>(argString);
}
}
else if (nodename == "markup") {
const char * const extension = node->Attribute("ext");
if (!extension)
return Error(ErrorCode::MISSING_ATTRIBUTE, "ext");
mData->mMarkupExtensions.insert(extension);
mData->mReportErrors[extension] = (node->Attribute("reporterrors", "true") != nullptr);
mData->mProcessAfterCode[extension] = (node->Attribute("aftercode", "true") != nullptr);
for (const tinyxml2::XMLElement *markupnode = node->FirstChildElement(); markupnode; markupnode = markupnode->NextSiblingElement()) {
const std::string markupnodename = markupnode->Name();
if (markupnodename == "keywords") {
for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) {
if (strcmp(librarynode->Name(), "keyword") == 0) {
const char* nodeName = librarynode->Attribute("name");
if (nodeName == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
mData->mKeywords[extension].insert(nodeName);
} else
unknown_elements.insert(librarynode->Name());
}
}
else if (markupnodename == "exported") {
for (const tinyxml2::XMLElement *exporter = markupnode->FirstChildElement(); exporter; exporter = exporter->NextSiblingElement()) {
if (strcmp(exporter->Name(), "exporter") != 0) {
unknown_elements.insert(exporter->Name());
continue;
}
const char * const prefix = exporter->Attribute("prefix");
if (!prefix)
return Error(ErrorCode::MISSING_ATTRIBUTE, "prefix");
for (const tinyxml2::XMLElement *e = exporter->FirstChildElement(); e; e = e->NextSiblingElement()) {
const std::string ename = e->Name();
if (ename == "prefix")
mData->mExporters[prefix].addPrefix(e->GetText());
else if (ename == "suffix")
mData->mExporters[prefix].addSuffix(e->GetText());
else
unknown_elements.insert(ename);
}
}
}
else if (markupnodename == "imported") {
for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) {
if (strcmp(librarynode->Name(), "importer") == 0)
mData->mImporters[extension].insert(librarynode->GetText());
else
unknown_elements.insert(librarynode->Name());
}
}
else if (markupnodename == "codeblocks") {
for (const tinyxml2::XMLElement *blocknode = markupnode->FirstChildElement(); blocknode; blocknode = blocknode->NextSiblingElement()) {
const std::string blocknodename = blocknode->Name();
if (blocknodename == "block") {
const char * blockName = blocknode->Attribute("name");
if (blockName)
mData->mExecutableBlocks[extension].addBlock(blockName);
} else if (blocknodename == "structure") {
const char * start = blocknode->Attribute("start");
if (start)
mData->mExecutableBlocks[extension].setStart(start);
const char * end = blocknode->Attribute("end");
if (end)
mData->mExecutableBlocks[extension].setEnd(end);
const char * offset = blocknode->Attribute("offset");
if (offset) {
// cppcheck-suppress templateInstantiation - TODO: fix this - see #11631
mData->mExecutableBlocks[extension].setOffset(strToInt<int>(offset));
}
}
else
unknown_elements.insert(blocknodename);
}
}
else
unknown_elements.insert(markupnodename);
}
}
else if (nodename == "container") {
const char* const id = node->Attribute("id");
if (!id)
return Error(ErrorCode::MISSING_ATTRIBUTE, "id");
Container& container = mData->mContainers[id];
const char* const inherits = node->Attribute("inherits");
if (inherits) {
const std::unordered_map<std::string, Container>::const_iterator i = mData->mContainers.find(inherits);
if (i != mData->mContainers.end())
container = i->second; // Take values from parent and overwrite them if necessary
else
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, inherits);
}
const char* const startPattern = node->Attribute("startPattern");
if (startPattern) {
container.startPattern = startPattern;
container.startPattern2 = startPattern;
if (!endsWith(container.startPattern, '<'))
container.startPattern2 += " !!::";
}
const char* const endPattern = node->Attribute("endPattern");
if (endPattern)
container.endPattern = endPattern;
const char* const itEndPattern = node->Attribute("itEndPattern");
if (itEndPattern)
container.itEndPattern = itEndPattern;
const char* const opLessAllowed = node->Attribute("opLessAllowed");
if (opLessAllowed)
container.opLessAllowed = strcmp(opLessAllowed, "true") == 0;
const char* const hasInitializerListConstructor = node->Attribute("hasInitializerListConstructor");
if (hasInitializerListConstructor)
container.hasInitializerListConstructor = strcmp(hasInitializerListConstructor, "true") == 0;
const char* const view = node->Attribute("view");
if (view)
container.view = strcmp(view, "true") == 0;
for (const tinyxml2::XMLElement *containerNode = node->FirstChildElement(); containerNode; containerNode = containerNode->NextSiblingElement()) {
const std::string containerNodeName = containerNode->Name();
if (containerNodeName == "size" || containerNodeName == "access" || containerNodeName == "other") {
for (const tinyxml2::XMLElement *functionNode = containerNode->FirstChildElement(); functionNode; functionNode = functionNode->NextSiblingElement()) {
if (strcmp(functionNode->Name(), "function") != 0) {
unknown_elements.insert(functionNode->Name());
continue;
}
const char* const functionName = functionNode->Attribute("name");
if (!functionName)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
const char* const action_ptr = functionNode->Attribute("action");
Container::Action action = Container::Action::NO_ACTION;
if (action_ptr) {
std::string actionName = action_ptr;
action = Container::actionFrom(actionName);
if (action == Container::Action::NO_ACTION)
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName);
}
const char* const yield_ptr = functionNode->Attribute("yields");
Container::Yield yield = Container::Yield::NO_YIELD;
if (yield_ptr) {
std::string yieldName = yield_ptr;
yield = Container::yieldFrom(yieldName);
if (yield == Container::Yield::NO_YIELD)
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName);
}
const char* const returnType = functionNode->Attribute("returnType");
if (returnType)
container.functions[functionName].returnType = returnType;
container.functions[functionName].action = action;
container.functions[functionName].yield = yield;
}
if (containerNodeName == "size") {
const char* const templateArg = containerNode->Attribute("templateParameter");
if (templateArg)
container.size_templateArgNo = strToInt<int>(templateArg);
} else if (containerNodeName == "access") {
const char* const indexArg = containerNode->Attribute("indexOperator");
if (indexArg)
container.arrayLike_indexOp = strcmp(indexArg, "array-like") == 0;
}
} else if (containerNodeName == "type") {
const char* const templateArg = containerNode->Attribute("templateParameter");
if (templateArg)
container.type_templateArgNo = strToInt<int>(templateArg);
const char* const string = containerNode->Attribute("string");
if (string)
container.stdStringLike = strcmp(string, "std-like") == 0;
const char* const associative = containerNode->Attribute("associative");
if (associative)
container.stdAssociativeLike = strcmp(associative, "std-like") == 0;
const char* const unstable = containerNode->Attribute("unstable");
if (unstable) {
std::string unstableType = unstable;
if (unstableType.find("erase") != std::string::npos)
container.unstableErase = true;
if (unstableType.find("insert") != std::string::npos)
container.unstableInsert = true;
}
} else if (containerNodeName == "rangeItemRecordType") {
for (const tinyxml2::XMLElement* memberNode = node->FirstChildElement(); memberNode; memberNode = memberNode->NextSiblingElement()) {
const char *memberName = memberNode->Attribute("name");
const char *memberTemplateParameter = memberNode->Attribute("templateParameter");
Container::RangeItemRecordTypeItem member;
member.name = memberName ? memberName : "";
member.templateParameter = memberTemplateParameter ? strToInt<int>(memberTemplateParameter) : -1;
container.rangeItemRecordType.emplace_back(std::move(member));
}
} else
unknown_elements.insert(containerNodeName);
}
}
else if (nodename == "smart-pointer") {
const char *className = node->Attribute("class-name");
if (!className)
return Error(ErrorCode::MISSING_ATTRIBUTE, "class-name");
SmartPointer& smartPointer = mData->mSmartPointers[className];
smartPointer.name = className;
for (const tinyxml2::XMLElement* smartPointerNode = node->FirstChildElement(); smartPointerNode;
smartPointerNode = smartPointerNode->NextSiblingElement()) {
const std::string smartPointerNodeName = smartPointerNode->Name();
if (smartPointerNodeName == "unique")
smartPointer.unique = true;
}
}
else if (nodename == "type-checks") {
for (const tinyxml2::XMLElement *checkNode = node->FirstChildElement(); checkNode; checkNode = checkNode->NextSiblingElement()) {
const std::string &checkName = checkNode->Name();
for (const tinyxml2::XMLElement *checkTypeNode = checkNode->FirstChildElement(); checkTypeNode; checkTypeNode = checkTypeNode->NextSiblingElement()) {
const std::string checkTypeName = checkTypeNode->Name();
const char *typeName = checkTypeNode->GetText();
if (!typeName)
continue;
if (checkTypeName == "check")
mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::check;
else if (checkTypeName == "suppress")
mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::suppress;
else if (checkTypeName == "checkFiniteLifetime")
mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::checkFiniteLifetime;
}
}
}
else if (nodename == "podtype") {
const char * const name = node->Attribute("name");
if (!name)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
PodType podType;
podType.stdtype = PodType::Type::NO;
const char * const stdtype = node->Attribute("stdtype");
if (stdtype) {
if (std::strcmp(stdtype, "bool") == 0)
podType.stdtype = PodType::Type::BOOL;
else if (std::strcmp(stdtype, "char") == 0)
podType.stdtype = PodType::Type::CHAR;
else if (std::strcmp(stdtype, "short") == 0)
podType.stdtype = PodType::Type::SHORT;
else if (std::strcmp(stdtype, "int") == 0)
podType.stdtype = PodType::Type::INT;
else if (std::strcmp(stdtype, "long") == 0)
podType.stdtype = PodType::Type::LONG;
else if (std::strcmp(stdtype, "long long") == 0)
podType.stdtype = PodType::Type::LONGLONG;
}
const char * const size = node->Attribute("size");
if (size)
podType.size = strToInt<unsigned int>(size);
const char * const sign = node->Attribute("sign");
if (sign)
podType.sign = *sign;
for (const std::string &s : getnames(name))
mData->mPodTypes[s] = podType;
}
else if (nodename == "platformtype") {
const char * const type_name = node->Attribute("name");
if (type_name == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
const char *value = node->Attribute("value");
if (value == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
PlatformType type;
type.mType = value;
std::set<std::string> platform;
for (const tinyxml2::XMLElement *typenode = node->FirstChildElement(); typenode; typenode = typenode->NextSiblingElement()) {
const std::string typenodename = typenode->Name();
if (typenodename == "platform") {
const char * const type_attribute = typenode->Attribute("type");
if (type_attribute == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "type");
platform.insert(type_attribute);
} else if (typenodename == "signed")
type.mSigned = true;
else if (typenodename == "unsigned")
type.mUnsigned = true;
else if (typenodename == "long")
type.mLong = true;
else if (typenodename == "pointer")
type.mPointer= true;
else if (typenodename == "ptr_ptr")
type.mPtrPtr = true;
else if (typenodename == "const_ptr")
type.mConstPtr = true;
else
unknown_elements.insert(typenodename);
}
if (platform.empty()) {
const PlatformType * const type_ptr = platform_type(type_name, emptyString);
if (type_ptr) {
if (*type_ptr == type)
return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name);
return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name);
}
mData->mPlatformTypes[type_name] = std::move(type);
} else {
for (const std::string &p : platform) {
const PlatformType * const type_ptr = platform_type(type_name, p);
if (type_ptr) {
if (*type_ptr == type)
return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name);
return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name);
}
mData->mPlatforms[p].mPlatformTypes[type_name] = type;
}
}
}
else if (nodename == "entrypoint") {
const char * const type_name = node->Attribute("name");
if (type_name == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "name");
mData->mEntrypoints.emplace(type_name);
}
else
unknown_elements.insert(nodename);
}
if (!unknown_elements.empty()) {
std::string str;
for (std::set<std::string>::const_iterator i = unknown_elements.cbegin(); i != unknown_elements.cend();) {
str += *i;
if (++i != unknown_elements.end())
str += ", ";
}
return Error(ErrorCode::UNKNOWN_ELEMENT, str);
}
return Error(ErrorCode::OK);
}
Library::Error Library::loadFunction(const tinyxml2::XMLElement * const node, const std::string &name, std::set<std::string> &unknown_elements)
{
if (name.empty())
return Error(ErrorCode::OK);
// TODO: write debug warning if we modify an existing entry
Function& func = mData->mFunctions[name];
for (const tinyxml2::XMLElement *functionnode = node->FirstChildElement(); functionnode; functionnode = functionnode->NextSiblingElement()) {
const std::string functionnodename = functionnode->Name();
if (functionnodename == "noreturn") {
const char * const text = functionnode->GetText();
if (strcmp(text, "false") == 0)
mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::False;
else if (strcmp(text, "maybe") == 0)
mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::Maybe;
else
mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::True; // Safe
} else if (functionnodename == "pure")
func.ispure = true;
else if (functionnodename == "const") {
func.ispure = true;
func.isconst = true; // a constant function is pure
} else if (functionnodename == "leak-ignore")
func.leakignore = true;
else if (functionnodename == "not-overlapping-data") {
NonOverlappingData nonOverlappingData;
nonOverlappingData.ptr1Arg = functionnode->IntAttribute("ptr1-arg", -1);
nonOverlappingData.ptr2Arg = functionnode->IntAttribute("ptr2-arg", -1);
nonOverlappingData.sizeArg = functionnode->IntAttribute("size-arg", -1);
nonOverlappingData.strlenArg = functionnode->IntAttribute("strlen-arg", -1);
nonOverlappingData.countArg = functionnode->IntAttribute("count-arg", -1);
mData->mNonOverlappingData[name] = nonOverlappingData;
} else if (functionnodename == "use-retval") {
func.useretval = Library::UseRetValType::DEFAULT;
if (const char *type = functionnode->Attribute("type"))
if (std::strcmp(type, "error-code") == 0)
func.useretval = Library::UseRetValType::ERROR_CODE;
} else if (functionnodename == "returnValue") {
if (const char *expr = functionnode->GetText())
mData->mReturnValue[name] = expr;
if (const char *type = functionnode->Attribute("type"))
mData->mReturnValueType[name] = type;
if (const char *container = functionnode->Attribute("container"))
mData->mReturnValueContainer[name] = strToInt<int>(container);
// cppcheck-suppress shadowFunction - TODO: fix this
if (const char *unknownReturnValues = functionnode->Attribute("unknownValues")) {
if (std::strcmp(unknownReturnValues, "all") == 0) {
std::vector<MathLib::bigint> values{LLONG_MIN, LLONG_MAX};
mData->mUnknownReturnValues[name] = std::move(values);
}
}
} else if (functionnodename == "arg") {
const char* argNrString = functionnode->Attribute("nr");
if (!argNrString)
return Error(ErrorCode::MISSING_ATTRIBUTE, "nr");
const bool bAnyArg = strcmp(argNrString, "any") == 0;
const bool bVariadicArg = strcmp(argNrString, "variadic") == 0;
const int nr = (bAnyArg || bVariadicArg) ? -1 : strToInt<int>(argNrString);
ArgumentChecks &ac = func.argumentChecks[nr];
ac.optional = functionnode->Attribute("default") != nullptr;
ac.variadic = bVariadicArg;
const char * const argDirection = functionnode->Attribute("direction");
if (argDirection) {
const size_t argDirLen = strlen(argDirection);
ArgumentChecks::Direction dir = ArgumentChecks::Direction::DIR_UNKNOWN;
if (!strncmp(argDirection, "in", argDirLen)) {
dir = ArgumentChecks::Direction::DIR_IN;
} else if (!strncmp(argDirection, "out", argDirLen)) {
dir = ArgumentChecks::Direction::DIR_OUT;
} else if (!strncmp(argDirection, "inout", argDirLen)) {
dir = ArgumentChecks::Direction::DIR_INOUT;
}
if (const char* const argIndirect = functionnode->Attribute("indirect")) {
const int indirect = strToInt<int>(argIndirect);
ac.direction[indirect] = dir; // TODO: handle multiple directions/indirect levels
}
else
ac.direction.fill(dir);
}
for (const tinyxml2::XMLElement *argnode = functionnode->FirstChildElement(); argnode; argnode = argnode->NextSiblingElement()) {
const std::string argnodename = argnode->Name();
int indirect = 0;
const char * const indirectStr = argnode->Attribute("indirect");
if (indirectStr)
indirect = strToInt<int>(indirectStr);
if (argnodename == "not-bool")
ac.notbool = true;
else if (argnodename == "not-null")
ac.notnull = true;
else if (argnodename == "not-uninit")
ac.notuninit = indirect;
else if (argnodename == "formatstr")
ac.formatstr = true;
else if (argnodename == "strz")
ac.strz = true;
else if (argnodename == "valid") {
// Validate the validation expression
const char *p = argnode->GetText();
if (!isCompliantValidationExpression(p))
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, (!p ? "\"\"" : p));
// Set validation expression
ac.valid = p;
}
else if (argnodename == "minsize") {
const char *typeattr = argnode->Attribute("type");
if (!typeattr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "type");
ArgumentChecks::MinSize::Type type;
if (strcmp(typeattr,"strlen")==0)
type = ArgumentChecks::MinSize::Type::STRLEN;
else if (strcmp(typeattr,"argvalue")==0)
type = ArgumentChecks::MinSize::Type::ARGVALUE;
else if (strcmp(typeattr,"sizeof")==0)
type = ArgumentChecks::MinSize::Type::SIZEOF;
else if (strcmp(typeattr,"mul")==0)
type = ArgumentChecks::MinSize::Type::MUL;
else if (strcmp(typeattr,"value")==0)
type = ArgumentChecks::MinSize::Type::VALUE;
else
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, typeattr);
if (type == ArgumentChecks::MinSize::Type::VALUE) {
const char *valueattr = argnode->Attribute("value");
if (!valueattr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "value");
long long minsizevalue = 0;
try {
minsizevalue = strToInt<long long>(valueattr);
} catch (const std::runtime_error&) {
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr);
}
if (minsizevalue <= 0)
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr);
ac.minsizes.emplace_back(type, 0);
ac.minsizes.back().value = minsizevalue;
} else {
const char *argattr = argnode->Attribute("arg");
if (!argattr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "arg");
if (strlen(argattr) != 1 || argattr[0]<'0' || argattr[0]>'9')
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, argattr);
ac.minsizes.reserve(type == ArgumentChecks::MinSize::Type::MUL ? 2 : 1);
ac.minsizes.emplace_back(type, argattr[0] - '0');
if (type == ArgumentChecks::MinSize::Type::MUL) {
const char *arg2attr = argnode->Attribute("arg2");
if (!arg2attr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "arg2");
if (strlen(arg2attr) != 1 || arg2attr[0]<'0' || arg2attr[0]>'9')
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, arg2attr);
ac.minsizes.back().arg2 = arg2attr[0] - '0';
}
}
const char* baseTypeAttr = argnode->Attribute("baseType"); // used by VALUE, ARGVALUE
if (baseTypeAttr)
ac.minsizes.back().baseType = baseTypeAttr;
}
else if (argnodename == "iterator") {
ac.iteratorInfo.it = true;
const char* str = argnode->Attribute("type");
ac.iteratorInfo.first = (str && std::strcmp(str, "first") == 0);
ac.iteratorInfo.last = (str && std::strcmp(str, "last") == 0);
ac.iteratorInfo.container = argnode->IntAttribute("container", 0);
}
else
unknown_elements.insert(argnodename);
}
if (ac.notuninit == 0)
ac.notuninit = ac.notnull ? 1 : 0;
} else if (functionnodename == "ignorefunction") {
func.ignore = true;
} else if (functionnodename == "formatstr") {
func.formatstr = true;
const tinyxml2::XMLAttribute* scan = functionnode->FindAttribute("scan");
const tinyxml2::XMLAttribute* secure = functionnode->FindAttribute("secure");
func.formatstr_scan = scan && scan->BoolValue();
func.formatstr_secure = secure && secure->BoolValue();
} else if (functionnodename == "warn") {
WarnInfo wi;
const char* const severity = functionnode->Attribute("severity");
if (severity == nullptr)
return Error(ErrorCode::MISSING_ATTRIBUTE, "severity");
wi.severity = severityFromString(severity);
const char* const cstd = functionnode->Attribute("cstd");
if (cstd) {
if (!wi.standards.setC(cstd))
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, cstd);
} else
wi.standards.c = Standards::C89;
const char* const cppstd = functionnode->Attribute("cppstd");
if (cppstd) {
if (!wi.standards.setCPP(cppstd))
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, cppstd);
} else
wi.standards.cpp = Standards::CPP03;
const char* const reason = functionnode->Attribute("reason");
const char* const alternatives = functionnode->Attribute("alternatives");
if (reason && alternatives) {
// Construct message
wi.message = std::string(reason) + " function '" + name + "' called. It is recommended to use ";
std::vector<std::string> alt = getnames(alternatives);
for (std::size_t i = 0; i < alt.size(); ++i) {
wi.message += "'" + alt[i] + "'";
if (i == alt.size() - 1)
wi.message += " instead.";
else if (i == alt.size() - 2)
wi.message += " or ";
else
wi.message += ", ";
}
} else {
const char * const message = functionnode->GetText();
if (!message)
return Error(ErrorCode::MISSING_ATTRIBUTE, "\"reason\" and \"alternatives\" or some text.");
wi.message = message;
}
mData->mFunctionwarn[name] = std::move(wi);
} else if (functionnodename == "container") {
const char* const action_ptr = functionnode->Attribute("action");
Container::Action action = Container::Action::NO_ACTION;
if (action_ptr) {
std::string actionName = action_ptr;
action = Container::actionFrom(actionName);
if (action == Container::Action::NO_ACTION)
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName);
}
func.containerAction = action;
const char* const yield_ptr = functionnode->Attribute("yields");
Container::Yield yield = Container::Yield::NO_YIELD;
if (yield_ptr) {
std::string yieldName = yield_ptr;
yield = Container::yieldFrom(yieldName);
if (yield == Container::Yield::NO_YIELD)
return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName);
}
func.containerYield = yield;
const char* const returnType = functionnode->Attribute("returnType");
if (returnType)
func.returnType = returnType;
} else
unknown_elements.insert(functionnodename);
}
return Error(ErrorCode::OK);
}
bool Library::isIntArgValid(const Token *ftok, int argnr, const MathLib::bigint argvalue) const
{
const ArgumentChecks *ac = getarg(ftok, argnr);
if (!ac || ac->valid.empty())
return true;
if (ac->valid.find('.') != std::string::npos)
return isFloatArgValid(ftok, argnr, argvalue);
TokenList tokenList(nullptr);
gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList);
for (const Token *tok = tokenList.front(); tok; tok = tok->next()) {
if (tok->isNumber() && argvalue == MathLib::toBigNumber(tok->str()))
return true;
if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toBigNumber(tok->str()) && argvalue <= MathLib::toBigNumber(tok->strAt(2)))
return true;
if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toBigNumber(tok->str()))
return true;
if ((!tok->previous() || tok->strAt(-1) == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toBigNumber(tok->strAt(1)))
return true;
}
return false;
}
bool Library::isFloatArgValid(const Token *ftok, int argnr, double argvalue) const
{
const ArgumentChecks *ac = getarg(ftok, argnr);
if (!ac || ac->valid.empty())
return true;
TokenList tokenList(nullptr);
gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList);
for (const Token *tok = tokenList.front(); tok; tok = tok->next()) {
if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toDoubleNumber(tok->str()) && argvalue <= MathLib::toDoubleNumber(tok->strAt(2)))
return true;
if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toDoubleNumber(tok->str()))
return true;
if ((!tok->previous() || tok->strAt(-1) == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toDoubleNumber(tok->strAt(1)))
return true;
if (Token::Match(tok, "%num%") && MathLib::isFloat(tok->str()) && MathLib::isEqual(tok->str(), MathLib::toString(argvalue)))
return true;
if (Token::Match(tok, "! %num%") && MathLib::isFloat(tok->strAt(1)))
return MathLib::isNotEqual(tok->strAt(1), MathLib::toString(argvalue));
}
return false;
}
std::string Library::getFunctionName(const Token *ftok, bool &error) const
{
if (!ftok) {
error = true;
return "";
}
if (ftok->isName()) {
if (Token::simpleMatch(ftok->astParent(), "::"))
return ftok->str();
for (const Scope *scope = ftok->scope(); scope; scope = scope->nestedIn) {
if (!scope->isClassOrStruct())
continue;
const std::vector<Type::BaseInfo> &derivedFrom = scope->definedType->derivedFrom;
for (const Type::BaseInfo & baseInfo : derivedFrom) {
std::string name;
const Token* tok = baseInfo.nameTok; // baseInfo.name still contains template parameters, but is missing namespaces
if (tok->str() == "::")
tok = tok->next();
while (Token::Match(tok, "%name%|::")) {
name += tok->str();
tok = tok->next();
}
name += "::" + ftok->str();
if (mData->mFunctions.find(name) != mData->mFunctions.end() && matchArguments(ftok, name))
return name;
}
}
return ftok->str();
}
if (ftok->str() == "::") {
if (!ftok->astOperand2())
return getFunctionName(ftok->astOperand1(), error);
return getFunctionName(ftok->astOperand1(),error) + "::" + getFunctionName(ftok->astOperand2(),error);
}
if (ftok->str() == "." && ftok->astOperand1()) {
const std::string type = astCanonicalType(ftok->astOperand1(), ftok->originalName() == "->");
if (type.empty()) {
error = true;
return "";
}
return type + "::" + getFunctionName(ftok->astOperand2(),error);
}
error = true;
return "";
}
std::string Library::getFunctionName(const Token *ftok) const
{
if (!Token::Match(ftok, "%name% )| (") && (ftok->strAt(-1) != "&" || ftok->previous()->astOperand2()))
return "";
// Lookup function name using AST..
if (ftok->astParent()) {
bool error = false;
const Token * tok = ftok->astParent()->isUnaryOp("&") ? ftok->astParent()->astOperand1() : ftok->next()->astOperand1();
std::string ret = getFunctionName(tok, error);
if (error)
return {};
if (startsWith(ret, "::"))
ret.erase(0, 2);
return ret;
}
// Lookup function name without using AST..
if (Token::simpleMatch(ftok->previous(), "."))
return "";
if (!Token::Match(ftok->tokAt(-2), "%name% ::"))
return ftok->str();
std::string ret(ftok->str());
ftok = ftok->tokAt(-2);
while (Token::Match(ftok, "%name% ::")) {
ret = ftok->str() + "::" + ret;
ftok = ftok->tokAt(-2);
}
return ret;
}
bool Library::isnullargbad(const Token *ftok, int argnr) const
{
const ArgumentChecks *arg = getarg(ftok, argnr);
if (!arg) {
// scan format string argument should not be null
const std::string funcname = getFunctionName(ftok);
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(funcname);
if (it != mData->mFunctions.cend() && it->second.formatstr && it->second.formatstr_scan)
return true;
}
return arg && arg->notnull;
}
bool Library::isuninitargbad(const Token *ftok, int argnr, int indirect, bool *hasIndirect) const
{
const ArgumentChecks *arg = getarg(ftok, argnr);
if (!arg) {
// non-scan format string argument should not be uninitialized
const std::string funcname = getFunctionName(ftok);
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(funcname);
if (it != mData->mFunctions.cend() && it->second.formatstr && !it->second.formatstr_scan)
return true;
}
if (hasIndirect && arg && arg->notuninit >= 1)
*hasIndirect = true;
return arg && arg->notuninit >= indirect;
}
/** get allocation info for function */
const Library::AllocFunc* Library::getAllocFuncInfo(const Token *tok) const
{
while (Token::simpleMatch(tok, "::"))
tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!tok)
return nullptr;
const std::string funcname = getFunctionName(tok);
return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mAlloc, funcname);
}
/** get deallocation info for function */
const Library::AllocFunc* Library::getDeallocFuncInfo(const Token *tok) const
{
while (Token::simpleMatch(tok, "::"))
tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!tok)
return nullptr;
const std::string funcname = getFunctionName(tok);
return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mDealloc, funcname);
}
/** get reallocation info for function */
const Library::AllocFunc* Library::getReallocFuncInfo(const Token *tok) const
{
while (Token::simpleMatch(tok, "::"))
tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1();
if (!tok)
return nullptr;
const std::string funcname = getFunctionName(tok);
return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mRealloc, funcname);
}
/** get allocation id for function */
int Library::getAllocId(const Token *tok, int arg) const
{
const Library::AllocFunc* af = getAllocFuncInfo(tok);
return (af && af->arg == arg) ? af->groupId : 0;
}
/** get deallocation id for function */
int Library::getDeallocId(const Token *tok, int arg) const
{
const Library::AllocFunc* af = getDeallocFuncInfo(tok);
return (af && af->arg == arg) ? af->groupId : 0;
}
/** get reallocation id for function */
int Library::getReallocId(const Token *tok, int arg) const
{
const Library::AllocFunc* af = getReallocFuncInfo(tok);
return (af && af->arg == arg) ? af->groupId : 0;
}
const Library::ArgumentChecks * Library::getarg(const Token *ftok, int argnr) const
{
const Function* func = nullptr;
if (isNotLibraryFunction(ftok, &func))
return nullptr;
const std::map<int,ArgumentChecks>::const_iterator it2 = func->argumentChecks.find(argnr);
if (it2 != func->argumentChecks.cend())
return &it2->second;
const std::map<int,ArgumentChecks>::const_iterator it3 = func->argumentChecks.find(-1);
if (it3 != func->argumentChecks.cend())
return &it3->second;
return nullptr;
}
bool Library::isScopeNoReturn(const Token *end, std::string *unknownFunc) const
{
if (unknownFunc)
unknownFunc->clear();
if (Token::Match(end->tokAt(-2), "!!{ ; }")) {
const Token *lastTop = end->tokAt(-2)->astTop();
if (Token::simpleMatch(lastTop, "<<") &&
Token::simpleMatch(lastTop->astOperand1(), "(") &&
Token::Match(lastTop->astOperand1()->previous(), "%name% ("))
return isnoreturn(lastTop->astOperand1()->previous());
}
if (!Token::simpleMatch(end->tokAt(-2), ") ; }"))
return false;
const Token *funcname = end->linkAt(-2)->previous();
if (funcname->isCpp() && funcname->astTop()->str() == "throw")
return true;
const Token *start = funcname;
if (Token::Match(funcname->tokAt(-3),"( * %name% )")) {
funcname = funcname->previous();
start = funcname->tokAt(-3);
} else if (funcname->isName()) {
while (Token::Match(start, "%name%|.|::"))
start = start->previous();
} else {
return false;
}
if (Token::Match(start,"[;{}]") && Token::Match(funcname, "%name% )| (")) {
if (funcname->isKeyword())
return false;
if (funcname->str() == "exit")
return true;
if (!isnotnoreturn(funcname)) {
if (unknownFunc && !isnoreturn(funcname))
*unknownFunc = funcname->str();
return true;
}
}
return false;
}
// cppcheck-suppress unusedFunction - used in tests only
const std::unordered_map<std::string, Library::Container>& Library::containers() const
{
return mData->mContainers;
}
const Library::Container* Library::detectContainerInternal(const Token* const typeStart, DetectContainer detect, bool* isIterator, bool withoutStd) const
{
if (!typeStart)
return nullptr;
const Token* firstLinkedTok = nullptr;
for (const Token* tok = typeStart; tok && !tok->varId(); tok = tok->next()) {
if (!tok->link())
continue;
firstLinkedTok = tok;
break;
}
for (const std::pair<const std::string, Library::Container> & c : mData->mContainers) {
const Container& container = c.second;
if (container.startPattern.empty())
continue;
const int offset = (withoutStd && startsWith(container.startPattern2, "std :: ")) ? 7 : 0;
// If endPattern is undefined, it will always match, but itEndPattern has to be defined.
if (detect != IteratorOnly && container.endPattern.empty()) {
if (!Token::Match(typeStart, container.startPattern2.c_str() + offset))
continue;
if (isIterator)
*isIterator = false;
return &container;
}
if (!firstLinkedTok)
continue;
const bool matchedStartPattern = Token::Match(typeStart, container.startPattern2.c_str() + offset);
if (!matchedStartPattern)
continue;
if (detect != ContainerOnly && Token::Match(firstLinkedTok->link(), container.itEndPattern.c_str())) {
if (isIterator)
*isIterator = true;
return &container;
}
if (detect != IteratorOnly && Token::Match(firstLinkedTok->link(), container.endPattern.c_str())) {
if (isIterator)
*isIterator = false;
return &container;
}
}
return nullptr;
}
const Library::Container* Library::detectContainer(const Token* typeStart) const
{
return detectContainerInternal(typeStart, ContainerOnly);
}
const Library::Container* Library::detectIterator(const Token* typeStart) const
{
return detectContainerInternal(typeStart, IteratorOnly);
}
const Library::Container* Library::detectContainerOrIterator(const Token* typeStart, bool* isIterator, bool withoutStd) const
{
bool res;
const Library::Container* c = detectContainerInternal(typeStart, Both, &res, withoutStd);
if (c && isIterator)
*isIterator = res;
return c;
}
bool Library::isContainerYield(const Token * const cond, Library::Container::Yield y, const std::string& fallback)
{
if (!cond)
return false;
if (cond->str() == "(") {
const Token* tok = cond->astOperand1();
if (tok && tok->str() == ".") {
if (tok->astOperand1() && tok->astOperand1()->valueType()) {
if (const Library::Container *container = tok->astOperand1()->valueType()->container) {
return tok->astOperand2() && y == container->getYield(tok->astOperand2()->str());
}
} else if (!fallback.empty()) {
return Token::simpleMatch(cond, "( )") && cond->strAt(-1) == fallback;
}
}
}
return false;
}
Library::Container::Yield Library::getContainerYield(const Token* const cond)
{
if (Token::simpleMatch(cond, "(")) {
const Token* tok = cond->astOperand1();
if (tok && tok->str() == ".") {
if (tok->astOperand1() && tok->astOperand1()->valueType()) {
if (const Library::Container *container = tok->astOperand1()->valueType()->container) {
if (tok->astOperand2())
return container->getYield(tok->astOperand2()->str());
}
}
}
}
return Library::Container::Yield::NO_YIELD;
}
// returns true if ftok is not a library function
bool Library::isNotLibraryFunction(const Token *ftok, const Function **func) const
{
if (ftok->isKeyword() || ftok->isStandardType())
return true;
if (ftok->function() && ftok->function()->nestedIn && ftok->function()->nestedIn->type != Scope::eGlobal)
return true;
// variables are not library functions.
if (ftok->varId())
return true;
return !matchArguments(ftok, getFunctionName(ftok), func);
}
bool Library::matchArguments(const Token *ftok, const std::string &functionName, const Function **func) const
{
if (functionName.empty())
return false;
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName);
if (it == mData->mFunctions.cend())
return false;
const int callargs = numberOfArgumentsWithoutAst(ftok);
int args = 0;
int firstOptionalArg = -1;
for (const std::pair<const int, Library::ArgumentChecks> & argCheck : it->second.argumentChecks) {
args = std::max(argCheck.first, args);
if (argCheck.second.optional && (firstOptionalArg == -1 || firstOptionalArg > argCheck.first))
firstOptionalArg = argCheck.first;
if (argCheck.second.formatstr || argCheck.second.variadic) {
const bool b = args <= callargs;
if (b && func)
*func = &it->second;
return b;
}
}
const bool b = (firstOptionalArg < 0) ? args == callargs : (callargs >= firstOptionalArg-1 && callargs <= args);
if (b && func)
*func = &it->second;
return b;
}
const std::map<std::string, Library::WarnInfo>& Library::functionwarn() const
{
return mData->mFunctionwarn;
}
const Library::WarnInfo* Library::getWarnInfo(const Token* ftok) const
{
if (isNotLibraryFunction(ftok))
return nullptr;
const std::map<std::string, WarnInfo>::const_iterator i = mData->mFunctionwarn.find(getFunctionName(ftok));
if (i == mData->mFunctionwarn.cend())
return nullptr;
return &i->second;
}
bool Library::isCompliantValidationExpression(const char* p)
{
if (!p || !*p)
return false;
bool error = false;
bool range = false;
bool has_dot = false;
bool has_E = false;
error = *p == '.';
for (; *p; p++) {
if (std::isdigit(*p)) {
error |= (*(p + 1) == '-');
}
else if (*p == ':') {
// cppcheck-suppress bitwiseOnBoolean - TODO: fix this
error |= range | (*(p + 1) == '.');
range = true;
has_dot = false;
has_E = false;
}
else if ((*p == '-') || (*p == '+')) {
error |= (!std::isdigit(*(p + 1)));
}
else if (*p == ',') {
range = false;
error |= *(p + 1) == '.';
has_dot = false;
has_E = false;
} else if (*p == '.') {
// cppcheck-suppress bitwiseOnBoolean - TODO: fix this
error |= has_dot | (!std::isdigit(*(p + 1)));
has_dot = true;
} else if (*p == 'E' || *p == 'e') {
error |= has_E;
has_E = true;
} else if (*p == '!') {
error |= !((*(p+1) == '-') || (*(p+1) == '+') || (std::isdigit(*(p + 1))));
} else
return false;
}
return !error;
}
bool Library::formatstr_function(const Token* ftok) const
{
if (isNotLibraryFunction(ftok))
return false;
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok));
if (it != mData->mFunctions.cend())
return it->second.formatstr;
return false;
}
int Library::formatstr_argno(const Token* ftok) const
{
const std::map<int, Library::ArgumentChecks>& argumentChecksFunc = mData->mFunctions.at(getFunctionName(ftok)).argumentChecks;
auto it = std::find_if(argumentChecksFunc.cbegin(), argumentChecksFunc.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) {
return a.second.formatstr;
});
return it == argumentChecksFunc.cend() ? -1 : it->first - 1;
}
bool Library::formatstr_scan(const Token* ftok) const
{
return mData->mFunctions.at(getFunctionName(ftok)).formatstr_scan;
}
bool Library::formatstr_secure(const Token* ftok) const
{
return mData->mFunctions.at(getFunctionName(ftok)).formatstr_secure;
}
const Library::NonOverlappingData* Library::getNonOverlappingData(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return nullptr;
const std::unordered_map<std::string, NonOverlappingData>::const_iterator it = mData->mNonOverlappingData.find(getFunctionName(ftok));
return (it != mData->mNonOverlappingData.cend()) ? &it->second : nullptr;
}
Library::UseRetValType Library::getUseRetValType(const Token *ftok) const
{
if (isNotLibraryFunction(ftok)) {
if (Token::simpleMatch(ftok->astParent(), ".")) {
const Token* contTok = ftok->astParent()->astOperand1();
using Yield = Library::Container::Yield;
const Yield yield = astContainerYield(contTok);
if (yield == Yield::START_ITERATOR || yield == Yield::END_ITERATOR || yield == Yield::AT_INDEX ||
yield == Yield::SIZE || yield == Yield::EMPTY || yield == Yield::BUFFER || yield == Yield::BUFFER_NT ||
((yield == Yield::ITEM || yield == Yield::ITERATOR) && astContainerAction(contTok) == Library::Container::Action::NO_ACTION))
return Library::UseRetValType::DEFAULT;
}
return Library::UseRetValType::NONE;
}
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok));
if (it != mData->mFunctions.cend())
return it->second.useretval;
return Library::UseRetValType::NONE;
}
const std::string& Library::returnValue(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return emptyString;
const std::map<std::string, std::string>::const_iterator it = mData->mReturnValue.find(getFunctionName(ftok));
return it != mData->mReturnValue.cend() ? it->second : emptyString;
}
const std::string& Library::returnValueType(const Token *ftok) const
{
if (isNotLibraryFunction(ftok)) {
if (Token::simpleMatch(ftok->astParent(), ".") && ftok->astParent()->astOperand1()) {
const Token* contTok = ftok->astParent()->astOperand1();
if (contTok->valueType() && contTok->valueType()->container)
return contTok->valueType()->container->getReturnType(ftok->str());
}
return emptyString;
}
const std::map<std::string, std::string>::const_iterator it = mData->mReturnValueType.find(getFunctionName(ftok));
return it != mData->mReturnValueType.cend() ? it->second : emptyString;
}
int Library::returnValueContainer(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return -1;
const std::map<std::string, int>::const_iterator it = mData->mReturnValueContainer.find(getFunctionName(ftok));
return it != mData->mReturnValueContainer.cend() ? it->second : -1;
}
std::vector<MathLib::bigint> Library::unknownReturnValues(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return std::vector<MathLib::bigint>();
const std::map<std::string, std::vector<MathLib::bigint>>::const_iterator it = mData->mUnknownReturnValues.find(getFunctionName(ftok));
return (it == mData->mUnknownReturnValues.cend()) ? std::vector<MathLib::bigint>() : it->second;
}
const Library::Function *Library::getFunction(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return nullptr;
const std::unordered_map<std::string, Function>::const_iterator it1 = mData->mFunctions.find(getFunctionName(ftok));
if (it1 == mData->mFunctions.cend())
return nullptr;
return &it1->second;
}
bool Library::hasminsize(const Token *ftok) const
{
if (isNotLibraryFunction(ftok))
return false;
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok));
if (it == mData->mFunctions.cend())
return false;
return std::any_of(it->second.argumentChecks.cbegin(), it->second.argumentChecks.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) {
return !a.second.minsizes.empty();
});
}
Library::ArgumentChecks::Direction Library::getArgDirection(const Token* ftok, int argnr, int indirect) const
{
const ArgumentChecks* arg = getarg(ftok, argnr);
if (arg) {
if (indirect < 0 || indirect >= arg->direction.size())
return ArgumentChecks::Direction::DIR_UNKNOWN; // TODO: don't generate bad indirect values
return arg->direction[indirect];
}
if (formatstr_function(ftok)) {
const int fs_argno = formatstr_argno(ftok);
if (fs_argno >= 0 && argnr >= fs_argno) {
if (formatstr_scan(ftok))
return ArgumentChecks::Direction::DIR_OUT;
return ArgumentChecks::Direction::DIR_IN;
}
}
return ArgumentChecks::Direction::DIR_UNKNOWN;
}
bool Library::ignorefunction(const std::string& functionName) const
{
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName);
if (it != mData->mFunctions.cend())
return it->second.ignore;
return false;
}
const std::unordered_map<std::string, Library::Function>& Library::functions() const
{
return mData->mFunctions;
}
bool Library::isUse(const std::string& functionName) const
{
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName);
if (it != mData->mFunctions.cend())
return it->second.use;
return false;
}
bool Library::isLeakIgnore(const std::string& functionName) const
{
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName);
if (it != mData->mFunctions.cend())
return it->second.leakignore;
return false;
}
bool Library::isFunctionConst(const std::string& functionName, bool pure) const
{
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName);
if (it != mData->mFunctions.cend())
return pure ? it->second.ispure : it->second.isconst;
return false;
}
bool Library::isFunctionConst(const Token *ftok) const
{
if (ftok->function() && ftok->function()->isConst())
return true;
if (isNotLibraryFunction(ftok)) {
if (Token::simpleMatch(ftok->astParent(), ".")) {
using Yield = Library::Container::Yield;
const Yield yield = astContainerYield(ftok->astParent()->astOperand1());
if (yield == Yield::EMPTY || yield == Yield::SIZE || yield == Yield::BUFFER_NT)
return true;
}
return false;
}
const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok));
return (it != mData->mFunctions.cend() && it->second.isconst);
}
bool Library::isnoreturn(const Token *ftok) const
{
if (ftok->function() && ftok->function()->isAttributeNoreturn())
return true;
if (ftok->variable() && ftok->variable()->nameToken()->isAttributeNoreturn())
return true;
if (isNotLibraryFunction(ftok)) {
if (Token::simpleMatch(ftok->astParent(), ".")) {
const Token* contTok = ftok->astParent()->astOperand1();
if (astContainerAction(contTok) != Library::Container::Action::NO_ACTION ||
astContainerYield(contTok) != Library::Container::Yield::NO_YIELD)
return false;
}
return false;
}
const std::unordered_map<std::string, LibraryData::FalseTrueMaybe>::const_iterator it = mData->mNoReturn.find(getFunctionName(ftok));
if (it == mData->mNoReturn.end())
return false;
if (it->second == LibraryData::FalseTrueMaybe::Maybe)
return true;
return it->second == LibraryData::FalseTrueMaybe::True;
}
bool Library::isnotnoreturn(const Token *ftok) const
{
if (ftok->function() && ftok->function()->isAttributeNoreturn())
return false;
if (isNotLibraryFunction(ftok))
return hasAnyTypeCheck(getFunctionName(ftok));
const std::unordered_map<std::string, LibraryData::FalseTrueMaybe>::const_iterator it = mData->mNoReturn.find(getFunctionName(ftok));
if (it == mData->mNoReturn.end())
return false;
if (it->second == LibraryData::FalseTrueMaybe::Maybe)
return false;
return it->second == LibraryData::FalseTrueMaybe::False;
}
bool Library::markupFile(const std::string &path) const
{
return mData->mMarkupExtensions.find(Path::getFilenameExtensionInLowerCase(path)) != mData->mMarkupExtensions.end();
}
bool Library::processMarkupAfterCode(const std::string &path) const
{
const std::map<std::string, bool>::const_iterator it = mData->mProcessAfterCode.find(Path::getFilenameExtensionInLowerCase(path));
return (it == mData->mProcessAfterCode.cend() || it->second);
}
bool Library::reportErrors(const std::string &path) const
{
const std::map<std::string, bool>::const_iterator it = mData->mReportErrors.find(Path::getFilenameExtensionInLowerCase(path));
return (it == mData->mReportErrors.cend() || it->second);
}
bool Library::isexecutableblock(const std::string &file, const std::string &token) const
{
const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator it = mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file));
return (it != mData->mExecutableBlocks.cend() && it->second.isBlock(token));
}
int Library::blockstartoffset(const std::string &file) const
{
int offset = -1;
const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it
= mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file));
if (map_it != mData->mExecutableBlocks.end()) {
offset = map_it->second.offset();
}
return offset;
}
const std::string& Library::blockstart(const std::string &file) const
{
const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it
= mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file));
if (map_it != mData->mExecutableBlocks.end()) {
return map_it->second.start();
}
return emptyString;
}
const std::string& Library::blockend(const std::string &file) const
{
const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it
= mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file));
if (map_it != mData->mExecutableBlocks.end()) {
return map_it->second.end();
}
return emptyString;
}
bool Library::iskeyword(const std::string &file, const std::string &keyword) const
{
const std::map<std::string, std::set<std::string>>::const_iterator it =
mData->mKeywords.find(Path::getFilenameExtensionInLowerCase(file));
return (it != mData->mKeywords.end() && it->second.count(keyword));
}
bool Library::isimporter(const std::string& file, const std::string &importer) const
{
const std::map<std::string, std::set<std::string>>::const_iterator it =
mData->mImporters.find(Path::getFilenameExtensionInLowerCase(file));
return (it != mData->mImporters.end() && it->second.count(importer) > 0);
}
const Token* Library::getContainerFromYield(const Token* tok, Library::Container::Yield yield) const
{
if (!tok)
return nullptr;
if (Token::Match(tok->tokAt(-2), ". %name% (")) {
const Token* containerTok = tok->tokAt(-2)->astOperand1();
if (!astIsContainer(containerTok))
return nullptr;
if (containerTok->valueType()->container &&
containerTok->valueType()->container->getYield(tok->strAt(-1)) == yield)
return containerTok;
if (yield == Library::Container::Yield::EMPTY && Token::simpleMatch(tok->tokAt(-1), "empty ( )"))
return containerTok;
if (yield == Library::Container::Yield::SIZE && Token::Match(tok->tokAt(-1), "size|length ( )"))
return containerTok;
} else if (Token::Match(tok->previous(), "%name% (")) {
if (const Library::Function* f = this->getFunction(tok->previous())) {
if (f->containerYield == yield) {
return tok->astOperand2();
}
}
}
return nullptr;
}
// cppcheck-suppress unusedFunction
const Token* Library::getContainerFromAction(const Token* tok, Library::Container::Action action) const
{
if (!tok)
return nullptr;
if (Token::Match(tok->tokAt(-2), ". %name% (")) {
const Token* containerTok = tok->tokAt(-2)->astOperand1();
if (!astIsContainer(containerTok))
return nullptr;
if (containerTok->valueType()->container &&
containerTok->valueType()->container->getAction(tok->strAt(-1)) == action)
return containerTok;
if (Token::simpleMatch(tok->tokAt(-1), "empty ( )"))
return containerTok;
} else if (Token::Match(tok->previous(), "%name% (")) {
if (const Library::Function* f = this->getFunction(tok->previous())) {
if (f->containerAction == action) {
return tok->astOperand2();
}
}
}
return nullptr;
}
const std::unordered_map<std::string, Library::SmartPointer>& Library::smartPointers() const
{
return mData->mSmartPointers;
}
bool Library::isSmartPointer(const Token* tok) const
{
return detectSmartPointer(tok);
}
const Library::SmartPointer* Library::detectSmartPointer(const Token* tok, bool withoutStd) const
{
std::string typestr = withoutStd ? "std::" : "";
while (Token::Match(tok, "%name%|::")) {
typestr += tok->str();
tok = tok->next();
}
auto it = mData->mSmartPointers.find(typestr);
if (it == mData->mSmartPointers.end())
return nullptr;
return &it->second;
}
const Library::Container * getLibraryContainer(const Token * tok)
{
if (!tok)
return nullptr;
// TODO: Support dereferencing iterators
// TODO: Support dereferencing with ->
if (tok->isUnaryOp("*") && astIsPointer(tok->astOperand1())) {
for (const ValueFlow::Value& v:tok->astOperand1()->values()) {
if (!v.isLocalLifetimeValue())
continue;
if (v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address)
continue;
return getLibraryContainer(v.tokvalue);
}
}
if (!tok->valueType())
return nullptr;
return tok->valueType()->container;
}
Library::TypeCheck Library::getTypeCheck(std::string check, std::string typeName) const
{
auto it = mData->mTypeChecks.find(std::pair<std::string, std::string>(std::move(check), std::move(typeName)));
return it == mData->mTypeChecks.end() ? TypeCheck::def : it->second;
}
bool Library::hasAnyTypeCheck(const std::string& typeName) const
{
return std::any_of(mData->mTypeChecks.begin(), mData->mTypeChecks.end(), [&](const std::pair<std::pair<std::string, std::string>, Library::TypeCheck>& tc) {
return tc.first.second == typeName;
});
}
const Library::AllocFunc* Library::getAllocFuncInfo(const char name[]) const
{
return getAllocDealloc(mData->mAlloc, name);
}
const Library::AllocFunc* Library::getDeallocFuncInfo(const char name[]) const
{
return getAllocDealloc(mData->mDealloc, name);
}
// cppcheck-suppress unusedFunction
int Library::allocId(const char name[]) const
{
const AllocFunc* af = getAllocDealloc(mData->mAlloc, name);
return af ? af->groupId : 0;
}
int Library::deallocId(const char name[]) const
{
const AllocFunc* af = getAllocDealloc(mData->mDealloc, name);
return af ? af->groupId : 0;
}
const std::set<std::string> &Library::markupExtensions() const
{
return mData->mMarkupExtensions;
}
bool Library::isexporter(const std::string &prefix) const
{
return mData->mExporters.find(prefix) != mData->mExporters.end();
}
bool Library::isexportedprefix(const std::string &prefix, const std::string &token) const
{
const std::map<std::string, LibraryData::ExportedFunctions>::const_iterator it = mData->mExporters.find(prefix);
return (it != mData->mExporters.end() && it->second.isPrefix(token));
}
bool Library::isexportedsuffix(const std::string &prefix, const std::string &token) const
{
const std::map<std::string, LibraryData::ExportedFunctions>::const_iterator it = mData->mExporters.find(prefix);
return (it != mData->mExporters.end() && it->second.isSuffix(token));
}
bool Library::isreflection(const std::string &token) const
{
return mData->mReflection.find(token) != mData->mReflection.end();
}
int Library::reflectionArgument(const std::string &token) const
{
const std::map<std::string, int>::const_iterator it = mData->mReflection.find(token);
if (it != mData->mReflection.end())
return it->second;
return -1;
}
bool Library::isentrypoint(const std::string &func) const
{
return func == "main" || mData->mEntrypoints.find(func) != mData->mEntrypoints.end();
}
const std::set<std::string>& Library::defines() const
{
return mData->mDefines;
}
const Library::PodType *Library::podtype(const std::string &name) const
{
const std::unordered_map<std::string, struct PodType>::const_iterator it = mData->mPodTypes.find(name);
return (it != mData->mPodTypes.end()) ? &(it->second) : nullptr;
}
const Library::PlatformType *Library::platform_type(const std::string &name, const std::string & platform) const
{
const std::map<std::string, LibraryData::Platform>::const_iterator it = mData->mPlatforms.find(platform);
if (it != mData->mPlatforms.end()) {
const PlatformType * const type = it->second.platform_type(name);
if (type)
return type;
}
const std::map<std::string, PlatformType>::const_iterator it2 = mData->mPlatformTypes.find(name);
return (it2 != mData->mPlatformTypes.end()) ? &(it2->second) : nullptr;
}
| null |
880 | cpp | cppcheck | infer.cpp | lib/infer.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "infer.h"
#include "calculate.h"
#include "errortypes.h"
#include "token.h"
#include "valueptr.h"
#include <cassert>
#include <algorithm>
#include <functional>
#include <iterator>
#include <unordered_set>
#include <utility>
template<class Predicate, class Compare>
static const ValueFlow::Value* getCompareValue(const std::list<ValueFlow::Value>& values, Predicate pred, Compare compare)
{
const ValueFlow::Value* result = nullptr;
for (const ValueFlow::Value& value : values) {
if (!pred(value))
continue;
if (result)
result = &std::min(value, *result, [compare](const ValueFlow::Value& x, const ValueFlow::Value& y) {
return compare(x.intvalue, y.intvalue);
});
else
result = &value;
}
return result;
}
namespace {
struct Interval {
std::vector<MathLib::bigint> minvalue, maxvalue;
std::vector<const ValueFlow::Value*> minRef, maxRef;
void setMinValue(MathLib::bigint x, const ValueFlow::Value* ref = nullptr)
{
minvalue = {x};
if (ref)
minRef = {ref};
}
void setMaxValue(MathLib::bigint x, const ValueFlow::Value* ref = nullptr)
{
maxvalue = {x};
if (ref)
maxRef = {ref};
}
bool isLessThan(MathLib::bigint x, std::vector<const ValueFlow::Value*>* ref = nullptr) const
{
if (!this->maxvalue.empty() && this->maxvalue.front() < x) {
if (ref)
*ref = maxRef;
return true;
}
return false;
}
bool isGreaterThan(MathLib::bigint x, std::vector<const ValueFlow::Value*>* ref = nullptr) const
{
if (!this->minvalue.empty() && this->minvalue.front() > x) {
if (ref)
*ref = minRef;
return true;
}
return false;
}
bool isScalar() const {
return minvalue.size() == 1 && minvalue == maxvalue;
}
bool empty() const {
return minvalue.empty() && maxvalue.empty();
}
bool isScalarOrEmpty() const {
return empty() || isScalar();
}
MathLib::bigint getScalar() const
{
assert(isScalar());
return minvalue.front();
}
std::vector<const ValueFlow::Value*> getScalarRef() const
{
assert(isScalar());
if (minRef != maxRef)
return merge(minRef, maxRef);
return minRef;
}
static Interval fromInt(MathLib::bigint x, const ValueFlow::Value* ref = nullptr)
{
Interval result;
result.setMinValue(x, ref);
result.setMaxValue(x, ref);
return result;
}
template<class Predicate>
static Interval fromValues(const std::list<ValueFlow::Value>& values, Predicate predicate)
{
Interval result;
const ValueFlow::Value* minValue = getCompareValue(values, predicate, std::less<MathLib::bigint>{});
if (minValue) {
if (minValue->isImpossible() && minValue->bound == ValueFlow::Value::Bound::Upper)
result.setMinValue(minValue->intvalue + 1, minValue);
if (minValue->isPossible() && minValue->bound == ValueFlow::Value::Bound::Lower)
result.setMinValue(minValue->intvalue, minValue);
if (!minValue->isImpossible() && (minValue->bound == ValueFlow::Value::Bound::Point || minValue->isKnown()) &&
std::count_if(values.begin(), values.end(), predicate) == 1)
return Interval::fromInt(minValue->intvalue, minValue);
}
const ValueFlow::Value* maxValue = getCompareValue(values, predicate, std::greater<MathLib::bigint>{});
if (maxValue) {
if (maxValue->isImpossible() && maxValue->bound == ValueFlow::Value::Bound::Lower)
result.setMaxValue(maxValue->intvalue - 1, maxValue);
if (maxValue->isPossible() && maxValue->bound == ValueFlow::Value::Bound::Upper)
result.setMaxValue(maxValue->intvalue, maxValue);
assert(!maxValue->isKnown());
}
return result;
}
static Interval fromValues(const std::list<ValueFlow::Value>& values)
{
return Interval::fromValues(values, [](const ValueFlow::Value&) {
return true;
});
}
template<class F>
static std::vector<MathLib::bigint> apply(const std::vector<MathLib::bigint>& x,
const std::vector<MathLib::bigint>& y,
F f)
{
if (x.empty())
return {};
if (y.empty())
return {};
return {f(x.front(), y.front())};
}
static std::vector<const ValueFlow::Value*> merge(std::vector<const ValueFlow::Value*> x,
const std::vector<const ValueFlow::Value*>& y)
{
x.insert(x.end(), y.cbegin(), y.cend());
return x;
}
friend Interval operator-(const Interval& lhs, const Interval& rhs)
{
Interval result;
result.minvalue = Interval::apply(lhs.minvalue, rhs.maxvalue, std::minus<MathLib::bigint>{});
result.maxvalue = Interval::apply(lhs.maxvalue, rhs.minvalue, std::minus<MathLib::bigint>{});
if (!result.minvalue.empty())
result.minRef = merge(lhs.minRef, rhs.maxRef);
if (!result.maxvalue.empty())
result.maxRef = merge(lhs.maxRef, rhs.minRef);
return result;
}
static std::vector<int> equal(const Interval& lhs,
const Interval& rhs,
std::vector<const ValueFlow::Value*>* ref = nullptr)
{
if (!lhs.isScalar())
return {};
if (!rhs.isScalar())
return {};
if (ref)
*ref = merge(lhs.getScalarRef(), rhs.getScalarRef());
return {lhs.minvalue == rhs.minvalue};
}
static std::vector<int> compare(const Interval& lhs,
const Interval& rhs,
std::vector<const ValueFlow::Value*>* ref = nullptr)
{
Interval diff = lhs - rhs;
if (diff.isGreaterThan(0, ref))
return {1};
if (diff.isLessThan(0, ref))
return {-1};
std::vector<int> eq = Interval::equal(lhs, rhs, ref);
if (!eq.empty()) {
if (eq.front() == 0)
return {1, -1};
return {0};
}
if (diff.isGreaterThan(-1, ref))
return {0, 1};
if (diff.isLessThan(1, ref))
return {0, -1};
return {};
}
static std::vector<bool> compare(const std::string& op,
const Interval& lhs,
const Interval& rhs,
std::vector<const ValueFlow::Value*>* ref = nullptr)
{
std::vector<int> r = compare(lhs, rhs, ref);
if (r.empty())
return {};
bool b = calculate(op, r.front(), 0);
if (std::all_of(r.cbegin() + 1, r.cend(), [&](int i) {
return b == calculate(op, i, 0);
}))
return {b};
return {};
}
};
}
static void addToErrorPath(ValueFlow::Value& value, const std::vector<const ValueFlow::Value*>& refs)
{
std::unordered_set<const Token*> locations;
for (const ValueFlow::Value* ref : refs) {
if (ref->condition && !value.condition)
value.condition = ref->condition;
std::copy_if(ref->errorPath.cbegin(),
ref->errorPath.cend(),
std::back_inserter(value.errorPath),
[&](const ErrorPathItem& e) {
return locations.insert(e.first).second;
});
std::copy_if(ref->debugPath.cbegin(),
ref->debugPath.cend(),
std::back_inserter(value.debugPath),
[&](const ErrorPathItem& e) {
return locations.insert(e.first).second;
});
}
}
static void setValueKind(ValueFlow::Value& value, const std::vector<const ValueFlow::Value*>& refs)
{
bool isPossible = false;
bool isInconclusive = false;
for (const ValueFlow::Value* ref : refs) {
if (ref->isPossible())
isPossible = true;
if (ref->isInconclusive())
isInconclusive = true;
}
if (isInconclusive)
value.setInconclusive();
else if (isPossible)
value.setPossible();
else
value.setKnown();
}
static bool inferNotEqual(const std::list<ValueFlow::Value>& values, MathLib::bigint x)
{
return std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& value) {
return value.isImpossible() && value.intvalue == x;
});
}
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
std::list<ValueFlow::Value> lhsValues,
std::list<ValueFlow::Value> rhsValues)
{
std::vector<ValueFlow::Value> result;
auto notMatch = [&](const ValueFlow::Value& value) {
return !model->match(value);
};
lhsValues.remove_if(notMatch);
if (lhsValues.empty())
return result;
rhsValues.remove_if(notMatch);
if (rhsValues.empty())
return result;
Interval lhs = Interval::fromValues(lhsValues);
Interval rhs = Interval::fromValues(rhsValues);
if (op == "-") {
Interval diff = lhs - rhs;
if (diff.isScalar()) {
std::vector<const ValueFlow::Value*> refs = diff.getScalarRef();
ValueFlow::Value value(diff.getScalar());
addToErrorPath(value, refs);
setValueKind(value, refs);
result.push_back(std::move(value));
} else {
if (!diff.minvalue.empty()) {
ValueFlow::Value value(diff.minvalue.front() - 1);
value.setImpossible();
value.bound = ValueFlow::Value::Bound::Upper;
addToErrorPath(value, diff.minRef);
result.push_back(std::move(value));
}
if (!diff.maxvalue.empty()) {
ValueFlow::Value value(diff.maxvalue.front() + 1);
value.setImpossible();
value.bound = ValueFlow::Value::Bound::Lower;
addToErrorPath(value, diff.maxRef);
result.push_back(std::move(value));
}
}
} else if ((op == "!=" || op == "==") && lhs.isScalarOrEmpty() && rhs.isScalarOrEmpty()) {
if (lhs.isScalar() && rhs.isScalar()) {
std::vector<const ValueFlow::Value*> refs = Interval::merge(lhs.getScalarRef(), rhs.getScalarRef());
ValueFlow::Value value(calculate(op, lhs.getScalar(), rhs.getScalar()));
addToErrorPath(value, refs);
setValueKind(value, refs);
result.push_back(std::move(value));
} else {
std::vector<const ValueFlow::Value*> refs;
if (lhs.isScalar() && inferNotEqual(rhsValues, lhs.getScalar()))
refs = lhs.getScalarRef();
else if (rhs.isScalar() && inferNotEqual(lhsValues, rhs.getScalar()))
refs = rhs.getScalarRef();
if (!refs.empty()) {
ValueFlow::Value value(op == "!=");
addToErrorPath(value, refs);
setValueKind(value, refs);
result.push_back(std::move(value));
}
}
} else {
std::vector<const ValueFlow::Value*> refs;
std::vector<bool> r = Interval::compare(op, lhs, rhs, &refs);
if (!r.empty()) {
ValueFlow::Value value(r.front());
addToErrorPath(value, refs);
setValueKind(value, refs);
result.push_back(std::move(value));
}
}
return result;
}
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
MathLib::bigint lhs,
std::list<ValueFlow::Value> rhsValues)
{
return infer(model, op, {model->yield(lhs)}, std::move(rhsValues));
}
std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model,
const std::string& op,
std::list<ValueFlow::Value> lhsValues,
MathLib::bigint rhs)
{
return infer(model, op, std::move(lhsValues), {model->yield(rhs)});
}
std::vector<MathLib::bigint> getMinValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values)
{
return Interval::fromValues(values, [&](const ValueFlow::Value& v) {
return model->match(v);
}).minvalue;
}
std::vector<MathLib::bigint> getMaxValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values)
{
return Interval::fromValues(values, [&](const ValueFlow::Value& v) {
return model->match(v);
}).maxvalue;
}
namespace {
struct IntegralInferModel : InferModel {
bool match(const ValueFlow::Value& value) const override {
return value.isIntValue();
}
ValueFlow::Value yield(MathLib::bigint value) const override
{
ValueFlow::Value result(value);
result.valueType = ValueFlow::Value::ValueType::INT;
result.setKnown();
return result;
}
};
}
ValuePtr<InferModel> makeIntegralInferModel()
{
return IntegralInferModel{};
}
ValueFlow::Value inferCondition(const std::string& op, const Token* varTok, MathLib::bigint val)
{
if (!varTok)
return ValueFlow::Value{};
if (varTok->hasKnownIntValue())
return ValueFlow::Value{};
std::vector<ValueFlow::Value> r = infer(makeIntegralInferModel(), op, varTok->values(), val);
if (r.size() == 1 && r.front().isKnown())
return r.front();
return ValueFlow::Value{};
}
| null |
881 | cpp | cppcheck | programmemory.cpp | lib/programmemory.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "programmemory.h"
#include "astutils.h"
#include "calculate.h"
#include "infer.h"
#include "library.h"
#include "mathlib.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include "valueptr.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <stack>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
ExprIdToken::ExprIdToken(const Token* tok) : tok(tok), exprid(tok ? tok->exprId() : 0) {}
nonneg int ExprIdToken::getExpressionId() const {
return tok ? tok->exprId() : exprid;
}
std::size_t ExprIdToken::Hash::operator()(ExprIdToken etok) const
{
return std::hash<nonneg int>()(etok.getExpressionId());
}
void ProgramMemory::setValue(const Token* expr, const ValueFlow::Value& value) {
copyOnWrite();
(*mValues)[expr] = value;
ValueFlow::Value subvalue = value;
const Token* subexpr = solveExprValue(
expr,
[&](const Token* tok) -> std::vector<MathLib::bigint> {
if (tok->hasKnownIntValue())
return {tok->values().front().intvalue};
MathLib::bigint result = 0;
if (getIntValue(tok->exprId(), result))
return {result};
return {};
},
subvalue);
if (subexpr)
(*mValues)[subexpr] = std::move(subvalue);
}
const ValueFlow::Value* ProgramMemory::getValue(nonneg int exprid, bool impossible) const
{
const ProgramMemory::Map::const_iterator it = mValues->find(exprid);
const bool found = it != mValues->cend() && (impossible || !it->second.isImpossible());
if (found)
return &it->second;
return nullptr;
}
// cppcheck-suppress unusedFunction
bool ProgramMemory::getIntValue(nonneg int exprid, MathLib::bigint& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isIntValue()) {
result = value->intvalue;
return true;
}
return false;
}
void ProgramMemory::setIntValue(const Token* expr, MathLib::bigint value, bool impossible)
{
ValueFlow::Value v(value);
if (impossible)
v.setImpossible();
setValue(expr, v);
}
bool ProgramMemory::getTokValue(nonneg int exprid, const Token*& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isTokValue()) {
result = value->tokvalue;
return true;
}
return false;
}
// cppcheck-suppress unusedFunction
bool ProgramMemory::getContainerSizeValue(nonneg int exprid, MathLib::bigint& result) const
{
const ValueFlow::Value* value = getValue(exprid);
if (value && value->isContainerSizeValue()) {
result = value->intvalue;
return true;
}
return false;
}
bool ProgramMemory::getContainerEmptyValue(nonneg int exprid, MathLib::bigint& result) const
{
const ValueFlow::Value* value = getValue(exprid, true);
if (value && value->isContainerSizeValue()) {
if (value->isImpossible() && value->intvalue == 0) {
result = false;
return true;
}
if (!value->isImpossible()) {
result = (value->intvalue == 0);
return true;
}
}
return false;
}
void ProgramMemory::setContainerSizeValue(const Token* expr, MathLib::bigint value, bool isEqual)
{
ValueFlow::Value v(value);
v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE;
if (!isEqual)
v.valueKind = ValueFlow::Value::ValueKind::Impossible;
setValue(expr, v);
}
void ProgramMemory::setUnknown(const Token* expr) {
copyOnWrite();
(*mValues)[expr].valueType = ValueFlow::Value::ValueType::UNINIT;
}
bool ProgramMemory::hasValue(nonneg int exprid)
{
return mValues->find(exprid) != mValues->end();
}
const ValueFlow::Value& ProgramMemory::at(nonneg int exprid) const {
return mValues->at(exprid);
}
ValueFlow::Value& ProgramMemory::at(nonneg int exprid) {
copyOnWrite();
return mValues->at(exprid);
}
void ProgramMemory::erase_if(const std::function<bool(const ExprIdToken&)>& pred)
{
if (mValues->empty())
return;
// TODO: how to delay until we actuallly modify?
copyOnWrite();
for (auto it = mValues->begin(); it != mValues->end();) {
if (pred(it->first))
it = mValues->erase(it);
else
++it;
}
}
void ProgramMemory::swap(ProgramMemory &pm) NOEXCEPT
{
mValues.swap(pm.mValues);
}
void ProgramMemory::clear()
{
if (mValues->empty())
return;
copyOnWrite();
mValues->clear();
}
bool ProgramMemory::empty() const
{
return mValues->empty();
}
// NOLINTNEXTLINE(performance-unnecessary-value-param) - technically correct but we are moving the given values
void ProgramMemory::replace(ProgramMemory pm)
{
if (pm.empty())
return;
copyOnWrite();
for (auto&& p : (*pm.mValues)) {
(*mValues)[p.first] = std::move(p.second);
}
}
void ProgramMemory::copyOnWrite()
{
if (mValues.use_count() == 1)
return;
mValues = std::make_shared<Map>(*mValues);
}
static ValueFlow::Value execute(const Token* expr, ProgramMemory& pm, const Settings& settings);
static bool evaluateCondition(MathLib::bigint r, const Token* condition, ProgramMemory& pm, const Settings& settings)
{
if (!condition)
return false;
MathLib::bigint result = 0;
bool error = false;
execute(condition, pm, &result, &error, settings);
return !error && result == r;
}
bool conditionIsFalse(const Token* condition, ProgramMemory pm, const Settings& settings)
{
return evaluateCondition(0, condition, pm, settings);
}
bool conditionIsTrue(const Token* condition, ProgramMemory pm, const Settings& settings)
{
return evaluateCondition(1, condition, pm, settings);
}
static bool frontIs(const std::vector<MathLib::bigint>& v, bool i)
{
if (v.empty())
return false;
if (v.front())
return i;
return !i;
}
static bool isTrue(const ValueFlow::Value& v)
{
if (v.isUninitValue())
return false;
if (v.isImpossible())
return v.intvalue == 0;
return v.intvalue != 0;
}
static bool isFalse(const ValueFlow::Value& v)
{
if (v.isUninitValue())
return false;
if (v.isImpossible())
return false;
return v.intvalue == 0;
}
static bool isTrueOrFalse(const ValueFlow::Value& v, bool b)
{
if (b)
return isTrue(v);
return isFalse(v);
}
// If the scope is a non-range for loop
static bool isBasicForLoop(const Token* tok)
{
if (!tok)
return false;
if (Token::simpleMatch(tok, "}"))
return isBasicForLoop(tok->link());
if (!Token::simpleMatch(tok->previous(), ") {"))
return false;
const Token* start = tok->linkAt(-1);
if (!start)
return false;
if (!Token::simpleMatch(start->previous(), "for ("))
return false;
if (!Token::simpleMatch(start->astOperand2(), ";"))
return false;
return true;
}
static void programMemoryParseCondition(ProgramMemory& pm, const Token* tok, const Token* endTok, const Settings& settings, bool then)
{
auto eval = [&](const Token* t) -> std::vector<MathLib::bigint> {
if (!t)
return std::vector<MathLib::bigint>{};
if (t->hasKnownIntValue())
return {t->values().front().intvalue};
MathLib::bigint result = 0;
bool error = false;
execute(t, pm, &result, &error, settings);
if (!error)
return {result};
return std::vector<MathLib::bigint>{};
};
if (Token::Match(tok, "==|>=|<=|<|>|!=")) {
ValueFlow::Value truevalue;
ValueFlow::Value falsevalue;
const Token* vartok = parseCompareInt(tok, truevalue, falsevalue, eval);
if (!vartok)
return;
if (vartok->exprId() == 0)
return;
if (!truevalue.isIntValue())
return;
if (endTok && findExpressionChanged(vartok, tok->next(), endTok, settings))
return;
const bool impossible = (tok->str() == "==" && !then) || (tok->str() == "!=" && then);
const ValueFlow::Value& v = then ? truevalue : falsevalue;
pm.setValue(vartok, impossible ? asImpossible(v) : v);
const Token* containerTok = settings.library.getContainerFromYield(vartok, Library::Container::Yield::SIZE);
if (containerTok)
pm.setContainerSizeValue(containerTok, v.intvalue, !impossible);
} else if (Token::simpleMatch(tok, "!")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, !then);
} else if (then && Token::simpleMatch(tok, "&&")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then);
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then);
} else if (!then && Token::simpleMatch(tok, "||")) {
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then);
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then);
} else if (Token::Match(tok, "&&|%oror%")) {
std::vector<MathLib::bigint> lhs = eval(tok->astOperand1());
std::vector<MathLib::bigint> rhs = eval(tok->astOperand2());
if (lhs.empty() || rhs.empty()) {
if (frontIs(lhs, !then))
programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then);
else if (frontIs(rhs, !then))
programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then);
else
pm.setIntValue(tok, 0, then);
}
} else if (tok && tok->exprId() > 0) {
if (endTok && findExpressionChanged(tok, tok->next(), endTok, settings))
return;
pm.setIntValue(tok, 0, then);
const Token* containerTok = settings.library.getContainerFromYield(tok, Library::Container::Yield::EMPTY);
if (containerTok)
pm.setContainerSizeValue(containerTok, 0, then);
}
}
static void fillProgramMemoryFromConditions(ProgramMemory& pm, const Scope* scope, const Token* endTok, const Settings& settings)
{
if (!scope)
return;
if (!scope->isLocal())
return;
assert(scope != scope->nestedIn);
fillProgramMemoryFromConditions(pm, scope->nestedIn, endTok, settings);
if (scope->type == Scope::eIf || scope->type == Scope::eWhile || scope->type == Scope::eElse || scope->type == Scope::eFor) {
const Token* condTok = getCondTokFromEnd(scope->bodyEnd);
if (!condTok)
return;
MathLib::bigint result = 0;
bool error = false;
execute(condTok, pm, &result, &error, settings);
if (error)
programMemoryParseCondition(pm, condTok, endTok, settings, scope->type != Scope::eElse);
}
}
static void fillProgramMemoryFromConditions(ProgramMemory& pm, const Token* tok, const Settings& settings)
{
fillProgramMemoryFromConditions(pm, tok->scope(), tok, settings);
}
static void fillProgramMemoryFromAssignments(ProgramMemory& pm, const Token* tok, const Settings& settings, const ProgramMemory& state, const ProgramMemory::Map& vars)
{
int indentlevel = 0;
for (const Token *tok2 = tok; tok2; tok2 = tok2->previous()) {
if ((Token::simpleMatch(tok2, "=") || Token::Match(tok2->previous(), "%var% (|{")) && tok2->astOperand1() &&
tok2->astOperand2()) {
bool setvar = false;
const Token* vartok = tok2->astOperand1();
for (const auto& p:vars) {
if (p.first != vartok->exprId())
continue;
if (vartok == tok)
continue;
pm.setValue(vartok, p.second);
setvar = true;
}
if (!setvar) {
if (!pm.hasValue(vartok->exprId())) {
const Token* valuetok = tok2->astOperand2();
pm.setValue(vartok, execute(valuetok, pm, settings));
}
}
} else if (tok2->exprId() > 0 && Token::Match(tok2, ".|(|[|*|%var%") && !pm.hasValue(tok2->exprId()) &&
isVariableChanged(tok2, 0, settings)) {
pm.setUnknown(tok2);
}
if (tok2->str() == "{") {
if (indentlevel <= 0) {
const Token* cond = getCondTokFromEnd(tok2->link());
// Keep progressing with anonymous/do scopes and always true branches
if (!Token::Match(tok2->previous(), "do|; {") && !conditionIsTrue(cond, state, settings) &&
(cond || !isBasicForLoop(tok2)))
break;
} else
--indentlevel;
if (Token::simpleMatch(tok2->previous(), "else {"))
tok2 = tok2->linkAt(-2)->previous();
}
if (tok2->str() == "}" && !Token::Match(tok2->link()->previous(), "%var% {")) {
const Token *cond = getCondTokFromEnd(tok2);
const bool inElse = Token::simpleMatch(tok2->link()->previous(), "else {");
if (cond) {
if (conditionIsFalse(cond, state, settings)) {
if (inElse) {
++indentlevel;
continue;
}
} else if (conditionIsTrue(cond, state, settings)) {
if (inElse)
tok2 = tok2->link()->tokAt(-2);
++indentlevel;
continue;
}
}
break;
}
}
}
static void removeModifiedVars(ProgramMemory& pm, const Token* tok, const Token* origin, const Settings& settings)
{
pm.erase_if([&](const ExprIdToken& e) {
return isVariableChanged(origin, tok, e.getExpressionId(), false, settings);
});
}
static ProgramMemory getInitialProgramState(const Token* tok,
const Token* origin,
const Settings& settings,
const ProgramMemory::Map& vars = ProgramMemory::Map {})
{
ProgramMemory pm;
if (origin) {
fillProgramMemoryFromConditions(pm, origin, settings);
const ProgramMemory state = pm;
fillProgramMemoryFromAssignments(pm, tok, settings, state, vars);
removeModifiedVars(pm, tok, origin, settings);
}
return pm;
}
ProgramMemoryState::ProgramMemoryState(const Settings& s) : settings(s)
{}
void ProgramMemoryState::replace(ProgramMemory pm, const Token* origin)
{
if (origin)
for (const auto& p : pm)
origins[p.first.getExpressionId()] = origin;
state.replace(std::move(pm));
}
static void addVars(ProgramMemory& pm, const ProgramMemory::Map& vars)
{
for (const auto& p:vars) {
const ValueFlow::Value &value = p.second;
pm.setValue(p.first.tok, value);
}
}
void ProgramMemoryState::addState(const Token* tok, const ProgramMemory::Map& vars)
{
ProgramMemory pm = state;
addVars(pm, vars);
fillProgramMemoryFromConditions(pm, tok, settings);
ProgramMemory local = pm;
fillProgramMemoryFromAssignments(pm, tok, settings, local, vars);
addVars(pm, vars);
replace(std::move(pm), tok);
}
void ProgramMemoryState::assume(const Token* tok, bool b, bool isEmpty)
{
ProgramMemory pm = state;
if (isEmpty)
pm.setContainerSizeValue(tok, 0, b);
else
programMemoryParseCondition(pm, tok, nullptr, settings, b);
const Token* origin = tok;
const Token* top = tok->astTop();
if (Token::Match(top->previous(), "for|while|if (") && !Token::simpleMatch(tok->astParent(), "?")) {
origin = top->link()->next();
if (!b && origin->link()) {
origin = origin->link();
}
}
replace(std::move(pm), origin);
}
void ProgramMemoryState::removeModifiedVars(const Token* tok)
{
const ProgramMemory& pm = state;
auto eval = [&](const Token* cond) -> std::vector<MathLib::bigint> {
ProgramMemory pm2 = pm;
auto result = execute(cond, pm2, settings);
if (isTrue(result))
return {1};
if (isFalse(result))
return {0};
return {};
};
state.erase_if([&](const ExprIdToken& e) {
const Token* start = origins[e.getExpressionId()];
const Token* expr = e.tok;
if (!expr || findExpressionChangedSkipDeadCode(expr, start, tok, settings, eval)) {
origins.erase(e.getExpressionId());
return true;
}
return false;
});
}
ProgramMemory ProgramMemoryState::get(const Token* tok, const Token* ctx, const ProgramMemory::Map& vars) const
{
ProgramMemoryState local = *this;
if (ctx)
local.addState(ctx, vars);
const Token* start = previousBeforeAstLeftmostLeaf(tok);
if (!start)
start = tok;
if (!ctx || precedes(start, ctx)) {
local.removeModifiedVars(start);
local.addState(start, vars);
} else {
local.removeModifiedVars(ctx);
}
return local.state;
}
ProgramMemory getProgramMemory(const Token* tok, const Token* expr, const ValueFlow::Value& value, const Settings& settings)
{
ProgramMemory programMemory;
programMemory.replace(getInitialProgramState(tok, value.tokvalue, settings));
programMemory.replace(getInitialProgramState(tok, value.condition, settings));
fillProgramMemoryFromConditions(programMemory, tok, settings);
programMemory.setValue(expr, value);
const ProgramMemory state = programMemory;
fillProgramMemoryFromAssignments(programMemory, tok, settings, state, {{expr, value}});
return programMemory;
}
static bool isNumericValue(const ValueFlow::Value& value) {
return value.isIntValue() || value.isFloatValue();
}
static double asFloat(const ValueFlow::Value& value)
{
return value.isFloatValue() ? value.floatValue : value.intvalue;
}
static std::string removeAssign(const std::string& assign) {
return std::string{assign.cbegin(), assign.cend() - 1};
}
namespace {
struct assign {
template<class T, class U>
void operator()(T& x, const U& y) const
{
x = y;
}
};
}
static bool isIntegralValue(const ValueFlow::Value& value)
{
return value.isIntValue() || value.isIteratorValue() || value.isSymbolicValue();
}
static ValueFlow::Value evaluate(const std::string& op, const ValueFlow::Value& lhs, const ValueFlow::Value& rhs)
{
ValueFlow::Value result;
if (lhs.isImpossible() && rhs.isImpossible())
return ValueFlow::Value::unknown();
if (lhs.isImpossible() || rhs.isImpossible()) {
// noninvertible
if (contains({"%", "/", "&", "|"}, op))
return ValueFlow::Value::unknown();
result.setImpossible();
}
if (isNumericValue(lhs) && isNumericValue(rhs)) {
if (lhs.isFloatValue() || rhs.isFloatValue()) {
result.valueType = ValueFlow::Value::ValueType::FLOAT;
bool error = false;
result.floatValue = calculate(op, asFloat(lhs), asFloat(rhs), &error);
if (error)
return ValueFlow::Value::unknown();
return result;
}
}
// Must be integral types
if (!isIntegralValue(lhs) && !isIntegralValue(rhs))
return ValueFlow::Value::unknown();
// If not the same type then one must be int
if (lhs.valueType != rhs.valueType && !lhs.isIntValue() && !rhs.isIntValue())
return ValueFlow::Value::unknown();
const bool compareOp = contains({"==", "!=", "<", ">", ">=", "<="}, op);
// Comparison must be the same type
if (compareOp && lhs.valueType != rhs.valueType)
return ValueFlow::Value::unknown();
// Only add, subtract, and compare for non-integers
if (!compareOp && !contains({"+", "-"}, op) && !lhs.isIntValue() && !rhs.isIntValue())
return ValueFlow::Value::unknown();
// Both can't be iterators for non-compare
if (!compareOp && lhs.isIteratorValue() && rhs.isIteratorValue())
return ValueFlow::Value::unknown();
// Symbolic values must be in the same ring
if (lhs.isSymbolicValue() && rhs.isSymbolicValue() && lhs.tokvalue != rhs.tokvalue)
return ValueFlow::Value::unknown();
if (!lhs.isIntValue() && !compareOp) {
result.valueType = lhs.valueType;
result.tokvalue = lhs.tokvalue;
} else if (!rhs.isIntValue() && !compareOp) {
result.valueType = rhs.valueType;
result.tokvalue = rhs.tokvalue;
} else {
result.valueType = ValueFlow::Value::ValueType::INT;
}
bool error = false;
result.intvalue = calculate(op, lhs.intvalue, rhs.intvalue, &error);
if (error)
return ValueFlow::Value::unknown();
if (result.isImpossible() && op == "!=") {
if (isTrue(result)) {
result.intvalue = 1;
} else if (isFalse(result)) {
result.intvalue = 0;
} else {
return ValueFlow::Value::unknown();
}
result.setPossible();
result.bound = ValueFlow::Value::Bound::Point;
}
return result;
}
using BuiltinLibraryFunction = std::function<ValueFlow::Value(const std::vector<ValueFlow::Value>&)>;
static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibraryFunctions()
{
std::unordered_map<std::string, BuiltinLibraryFunction> functions;
functions["strlen"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!(v.isTokValue() && v.tokvalue->tokType() == Token::eString))
return ValueFlow::Value::unknown();
v.valueType = ValueFlow::Value::ValueType::INT;
v.intvalue = Token::getStrLength(v.tokvalue);
v.tokvalue = nullptr;
return v;
};
functions["strcmp"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2)
return ValueFlow::Value::unknown();
const ValueFlow::Value& lhs = args[0];
if (!(lhs.isTokValue() && lhs.tokvalue->tokType() == Token::eString))
return ValueFlow::Value::unknown();
const ValueFlow::Value& rhs = args[1];
if (!(rhs.isTokValue() && rhs.tokvalue->tokType() == Token::eString))
return ValueFlow::Value::unknown();
ValueFlow::Value v(getStringLiteral(lhs.tokvalue->str()).compare(getStringLiteral(rhs.tokvalue->str())));
ValueFlow::combineValueProperties(lhs, rhs, v);
return v;
};
functions["strncmp"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 3)
return ValueFlow::Value::unknown();
const ValueFlow::Value& lhs = args[0];
if (!(lhs.isTokValue() && lhs.tokvalue->tokType() == Token::eString))
return ValueFlow::Value::unknown();
const ValueFlow::Value& rhs = args[1];
if (!(rhs.isTokValue() && rhs.tokvalue->tokType() == Token::eString))
return ValueFlow::Value::unknown();
const ValueFlow::Value& len = args[2];
if (!len.isIntValue())
return ValueFlow::Value::unknown();
ValueFlow::Value v(getStringLiteral(lhs.tokvalue->str())
.compare(0, len.intvalue, getStringLiteral(rhs.tokvalue->str()), 0, len.intvalue));
ValueFlow::combineValueProperties(lhs, rhs, v);
return v;
};
functions["sin"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sin(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["lgamma"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::lgamma(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["cos"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cos(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["tan"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tan(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["asin"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::asin(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["acos"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::acos(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["atan"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::atan(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["atan2"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::atan2(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["remainder"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::remainder(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["nextafter"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::nextafter(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["nexttoward"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::nexttoward(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["hypot"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::hypot(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["fdim"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::fdim(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["fmax"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::fmax(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["fmin"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::fmin(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["fmod"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::fmod(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["pow"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::pow(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["scalbln"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::scalbln(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["ldexp"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) {
return v.isFloatValue() || v.isIntValue();
}))
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
ValueFlow::Value v;
combineValueProperties(args[0], args[1], v);
v.floatValue = std::ldexp(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["ilogb"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.intvalue = std::ilogb(value);
v.valueType = ValueFlow::Value::ValueType::INT;
return v;
};
functions["erf"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::erf(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["erfc"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::erfc(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["floor"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::floor(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["sqrt"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sqrt(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["cbrt"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cbrt(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["ceil"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::ceil(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["exp"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::exp(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["exp2"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::exp2(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["expm1"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::expm1(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["fabs"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::fabs(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["log"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["log10"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log10(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["log1p"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log1p(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["log2"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::log2(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["logb"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::logb(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["nearbyint"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::nearbyint(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["sinh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::sinh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["cosh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::cosh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["tanh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tanh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["asinh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::asinh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["acosh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::acosh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["atanh"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::atanh(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["round"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::round(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["tgamma"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::tgamma(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
functions["trunc"] = [](const std::vector<ValueFlow::Value>& args) {
if (args.size() != 1)
return ValueFlow::Value::unknown();
ValueFlow::Value v = args[0];
if (!v.isFloatValue() && !v.isIntValue())
return ValueFlow::Value::unknown();
const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue;
v.floatValue = std::trunc(value);
v.valueType = ValueFlow::Value::ValueType::FLOAT;
return v;
};
return functions;
}
static BuiltinLibraryFunction getBuiltinLibraryFunction(const std::string& name)
{
static const std::unordered_map<std::string, BuiltinLibraryFunction> functions = createBuiltinLibraryFunctions();
auto it = functions.find(name);
if (it == functions.end())
return nullptr;
return it->second;
}
static bool TokenExprIdCompare(const Token* tok1, const Token* tok2) {
return tok1->exprId() < tok2->exprId();
}
static bool TokenExprIdEqual(const Token* tok1, const Token* tok2) {
return tok1->exprId() == tok2->exprId();
}
static std::vector<const Token*> setDifference(const std::vector<const Token*>& v1, const std::vector<const Token*>& v2)
{
std::vector<const Token*> result;
std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(result), &TokenExprIdCompare);
return result;
}
static bool evalSameCondition(const ProgramMemory& state,
const Token* storedValue,
const Token* cond,
const Settings& settings)
{
assert(!conditionIsTrue(cond, state, settings));
ProgramMemory pm = state;
programMemoryParseCondition(pm, storedValue, nullptr, settings, true);
if (pm == state)
return false;
return conditionIsTrue(cond, std::move(pm), settings);
}
static void pruneConditions(std::vector<const Token*>& conds,
bool b,
const std::unordered_map<nonneg int, ValueFlow::Value>& state)
{
conds.erase(std::remove_if(conds.begin(),
conds.end(),
[&](const Token* cond) {
if (cond->exprId() == 0)
return false;
auto it = state.find(cond->exprId());
if (it == state.end())
return false;
const ValueFlow::Value& v = it->second;
return isTrueOrFalse(v, !b);
}),
conds.end());
}
namespace {
struct Executor {
ProgramMemory* pm;
const Settings& settings;
int fdepth = 4;
int depth = 10;
Executor(ProgramMemory* pm, const Settings& settings) : pm(pm), settings(settings)
{
assert(pm != nullptr);
}
static ValueFlow::Value unknown() {
return ValueFlow::Value::unknown();
}
std::unordered_map<nonneg int, ValueFlow::Value> executeAll(const std::vector<const Token*>& toks,
const bool* b = nullptr) const
{
std::unordered_map<nonneg int, ValueFlow::Value> result;
auto state = *this;
for (const Token* tok : toks) {
ValueFlow::Value r = state.execute(tok);
if (r.isUninitValue())
continue;
const bool brk = b && isTrueOrFalse(r, *b);
result.emplace(tok->exprId(), std::move(r));
// Short-circuit evaluation
if (brk)
break;
}
return result;
}
static std::vector<const Token*> flattenConditions(const Token* tok)
{
return astFlatten(tok, tok->str().c_str());
}
static bool sortConditions(std::vector<const Token*>& conditions)
{
if (std::any_of(conditions.begin(), conditions.end(), [](const Token* child) {
return Token::Match(child, "&&|%oror%");
}))
return false;
std::sort(conditions.begin(), conditions.end(), &TokenExprIdCompare);
conditions.erase(std::unique(conditions.begin(), conditions.end(), &TokenExprIdCompare), conditions.end());
return !conditions.empty() && conditions.front()->exprId() != 0;
}
ValueFlow::Value executeMultiCondition(bool b, const Token* expr)
{
if (pm->hasValue(expr->exprId())) {
const ValueFlow::Value& v = utils::as_const(*pm).at(expr->exprId());
if (v.isIntValue())
return v;
}
// Evaluate recursively if there are no exprids
if ((expr->astOperand1() && expr->astOperand1()->exprId() == 0) ||
(expr->astOperand2() && expr->astOperand2()->exprId() == 0)) {
ValueFlow::Value lhs = execute(expr->astOperand1());
if (isTrueOrFalse(lhs, b))
return lhs;
ValueFlow::Value rhs = execute(expr->astOperand2());
if (isTrueOrFalse(rhs, b))
return rhs;
if (isTrueOrFalse(lhs, !b) && isTrueOrFalse(rhs, !b))
return lhs;
return unknown();
}
nonneg int n = astCount(expr, expr->str().c_str());
if (n > 50)
return unknown();
std::vector<const Token*> conditions1 = flattenConditions(expr);
if (conditions1.empty())
return unknown();
std::unordered_map<nonneg int, ValueFlow::Value> condValues = executeAll(conditions1, &b);
bool allNegated = true;
ValueFlow::Value negatedValue = unknown();
for (const auto& p : condValues) {
const ValueFlow::Value& v = p.second;
if (isTrueOrFalse(v, b))
return v;
allNegated &= isTrueOrFalse(v, !b);
if (allNegated && negatedValue.isUninitValue())
negatedValue = v;
}
if (condValues.size() == conditions1.size() && allNegated)
return negatedValue;
if (n > 4)
return unknown();
if (!sortConditions(conditions1))
return unknown();
for (const auto& p : *pm) {
const Token* tok = p.first.tok;
if (!tok)
continue;
const ValueFlow::Value& value = p.second;
if (tok->str() == expr->str() && !astHasExpr(tok, expr->exprId())) {
// TODO: Handle when it is greater
if (n != astCount(tok, expr->str().c_str()))
continue;
std::vector<const Token*> conditions2 = flattenConditions(tok);
if (!sortConditions(conditions2))
return unknown();
if (conditions1.size() == conditions2.size() &&
std::equal(conditions1.begin(), conditions1.end(), conditions2.begin(), &TokenExprIdEqual))
return value;
std::vector<const Token*> diffConditions1 = setDifference(conditions1, conditions2);
pruneConditions(diffConditions1, !b, condValues);
if (diffConditions1.size() == conditions1.size())
continue;
std::vector<const Token*> diffConditions2 = setDifference(conditions2, conditions1);
pruneConditions(diffConditions2, !b, executeAll(diffConditions2));
if (diffConditions1.size() != diffConditions2.size())
continue;
for (const Token* cond1 : diffConditions1) {
auto it = std::find_if(diffConditions2.begin(), diffConditions2.end(), [&](const Token* cond2) {
return evalSameCondition(*pm, cond2, cond1, settings);
});
if (it == diffConditions2.end())
break;
diffConditions2.erase(it);
}
if (diffConditions2.empty())
return value;
}
}
return unknown();
}
ValueFlow::Value executeImpl(const Token* expr)
{
const ValueFlow::Value* value = nullptr;
if (!expr)
return unknown();
if (expr->hasKnownIntValue() && !expr->isAssignmentOp() && expr->str() != ",")
return expr->values().front();
if ((value = expr->getKnownValue(ValueFlow::Value::ValueType::FLOAT)) ||
(value = expr->getKnownValue(ValueFlow::Value::ValueType::TOK)) ||
(value = expr->getKnownValue(ValueFlow::Value::ValueType::ITERATOR_START)) ||
(value = expr->getKnownValue(ValueFlow::Value::ValueType::ITERATOR_END)) ||
(value = expr->getKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE))) {
return *value;
}
if (expr->isNumber()) {
if (MathLib::isFloat(expr->str()))
return unknown();
MathLib::bigint i = MathLib::toBigNumber(expr->str());
if (i < 0 && astIsUnsigned(expr))
return unknown();
return ValueFlow::Value{i};
}
if (expr->isBoolean())
return ValueFlow::Value{expr->str() == "true"};
if (Token::Match(expr->tokAt(-2), ". %name% (") && astIsContainer(expr->tokAt(-2)->astOperand1())) {
const Token* containerTok = expr->tokAt(-2)->astOperand1();
const Library::Container::Yield yield = containerTok->valueType()->container->getYield(expr->strAt(-1));
if (yield == Library::Container::Yield::SIZE) {
ValueFlow::Value v = execute(containerTok);
if (!v.isContainerSizeValue())
return unknown();
v.valueType = ValueFlow::Value::ValueType::INT;
return v;
}
if (yield == Library::Container::Yield::EMPTY) {
ValueFlow::Value v = execute(containerTok);
if (!v.isContainerSizeValue())
return unknown();
if (v.isImpossible() && v.intvalue == 0)
return ValueFlow::Value{0};
if (!v.isImpossible())
return ValueFlow::Value{v.intvalue == 0};
}
} else if (expr->isAssignmentOp() && expr->astOperand1() && expr->astOperand2() &&
expr->astOperand1()->exprId() > 0) {
ValueFlow::Value rhs = execute(expr->astOperand2());
if (rhs.isUninitValue())
return unknown();
if (expr->str() != "=") {
if (!pm->hasValue(expr->astOperand1()->exprId()))
return unknown();
ValueFlow::Value& lhs = pm->at(expr->astOperand1()->exprId());
rhs = evaluate(removeAssign(expr->str()), lhs, rhs);
if (lhs.isIntValue())
ValueFlow::Value::visitValue(rhs, std::bind(assign{}, std::ref(lhs.intvalue), std::placeholders::_1));
else if (lhs.isFloatValue())
ValueFlow::Value::visitValue(rhs,
std::bind(assign{}, std::ref(lhs.floatValue), std::placeholders::_1));
else
return unknown();
return lhs;
}
pm->setValue(expr->astOperand1(), rhs);
return rhs;
} else if (expr->str() == "&&" && expr->astOperand1() && expr->astOperand2()) {
return executeMultiCondition(false, expr);
} else if (expr->str() == "||" && expr->astOperand1() && expr->astOperand2()) {
return executeMultiCondition(true, expr);
} else if (expr->str() == "," && expr->astOperand1() && expr->astOperand2()) {
execute(expr->astOperand1());
return execute(expr->astOperand2());
} else if (expr->tokType() == Token::eIncDecOp && expr->astOperand1() && expr->astOperand1()->exprId() != 0) {
if (!pm->hasValue(expr->astOperand1()->exprId()))
return ValueFlow::Value::unknown();
ValueFlow::Value& lhs = pm->at(expr->astOperand1()->exprId());
if (!lhs.isIntValue())
return unknown();
// overflow
if (!lhs.isImpossible() && lhs.intvalue == 0 && expr->str() == "--" && astIsUnsigned(expr->astOperand1()))
return unknown();
if (expr->str() == "++")
lhs.intvalue++;
else
lhs.intvalue--;
return lhs;
} else if (expr->str() == "[" && expr->astOperand1() && expr->astOperand2()) {
const Token* tokvalue = nullptr;
if (!pm->getTokValue(expr->astOperand1()->exprId(), tokvalue)) {
auto tokvalue_it = std::find_if(expr->astOperand1()->values().cbegin(),
expr->astOperand1()->values().cend(),
std::mem_fn(&ValueFlow::Value::isTokValue));
if (tokvalue_it == expr->astOperand1()->values().cend() || !tokvalue_it->isKnown()) {
return unknown();
}
tokvalue = tokvalue_it->tokvalue;
}
if (!tokvalue || !tokvalue->isLiteral()) {
return unknown();
}
const std::string strValue = tokvalue->strValue();
ValueFlow::Value rhs = execute(expr->astOperand2());
if (!rhs.isIntValue())
return unknown();
const MathLib::bigint index = rhs.intvalue;
if (index >= 0 && index < strValue.size())
return ValueFlow::Value{strValue[index]};
if (index == strValue.size())
return ValueFlow::Value{};
} else if (Token::Match(expr, "%cop%") && expr->astOperand1() && expr->astOperand2()) {
ValueFlow::Value lhs = execute(expr->astOperand1());
ValueFlow::Value rhs = execute(expr->astOperand2());
ValueFlow::Value r = unknown();
if (!lhs.isUninitValue() && !rhs.isUninitValue())
r = evaluate(expr->str(), lhs, rhs);
if (expr->isComparisonOp() && (r.isUninitValue() || r.isImpossible())) {
if (rhs.isIntValue() && !expr->astOperand1()->values().empty()) {
std::vector<ValueFlow::Value> result = infer(makeIntegralInferModel(),
expr->str(),
expr->astOperand1()->values(),
{std::move(rhs)});
if (!result.empty() && result.front().isKnown())
return std::move(result.front());
}
if (lhs.isIntValue() && !expr->astOperand2()->values().empty()) {
std::vector<ValueFlow::Value> result = infer(makeIntegralInferModel(),
expr->str(),
{std::move(lhs)},
expr->astOperand2()->values());
if (!result.empty() && result.front().isKnown())
return std::move(result.front());
}
return unknown();
}
return r;
}
// Unary ops
else if (Token::Match(expr, "!|+|-") && expr->astOperand1() && !expr->astOperand2()) {
ValueFlow::Value lhs = execute(expr->astOperand1());
if (!lhs.isIntValue())
return unknown();
if (expr->str() == "!") {
if (isTrue(lhs)) {
lhs.intvalue = 0;
} else if (isFalse(lhs)) {
lhs.intvalue = 1;
} else {
return unknown();
}
lhs.setPossible();
lhs.bound = ValueFlow::Value::Bound::Point;
}
if (expr->str() == "-")
lhs.intvalue = -lhs.intvalue;
return lhs;
} else if (expr->str() == "?" && expr->astOperand1() && expr->astOperand2()) {
ValueFlow::Value cond = execute(expr->astOperand1());
if (!cond.isIntValue())
return unknown();
const Token* child = expr->astOperand2();
if (isFalse(cond))
return execute(child->astOperand2());
if (isTrue(cond))
return execute(child->astOperand1());
return unknown();
} else if (expr->str() == "(" && expr->isCast()) {
if (expr->astOperand2()) {
if (expr->astOperand1()->str() != "dynamic_cast")
return execute(expr->astOperand2());
return unknown();
}
return execute(expr->astOperand1());
}
if (expr->exprId() > 0 && pm->hasValue(expr->exprId())) {
ValueFlow::Value result = utils::as_const(*pm).at(expr->exprId());
if (result.isImpossible() && result.isIntValue() && result.intvalue == 0 && isUsedAsBool(expr, settings)) {
result.intvalue = !result.intvalue;
result.setKnown();
}
return result;
}
if (Token::Match(expr->previous(), ">|%name% {|(")) {
const Token* ftok = expr->previous();
const Function* f = ftok->function();
ValueFlow::Value result = unknown();
if (expr->str() == "(") {
std::vector<const Token*> tokArgs = getArguments(expr);
std::vector<ValueFlow::Value> args(tokArgs.size());
std::transform(
tokArgs.cbegin(), tokArgs.cend(), args.begin(), [&](const Token* tok) {
return execute(tok);
});
if (f) {
if (fdepth >= 0 && !f->isImplicitlyVirtual()) {
ProgramMemory functionState;
for (std::size_t i = 0; i < args.size(); ++i) {
const Variable* const arg = f->getArgumentVar(i);
if (!arg)
return unknown();
functionState.setValue(arg->nameToken(), args[i]);
}
Executor ex = *this;
ex.pm = &functionState;
ex.fdepth--;
auto r = ex.execute(f->functionScope);
if (!r.empty())
result = std::move(r.front());
// TODO: Track values changed by reference
}
} else {
BuiltinLibraryFunction lf = getBuiltinLibraryFunction(ftok->str());
if (lf)
return lf(args);
const std::string& returnValue = settings.library.returnValue(ftok);
if (!returnValue.empty()) {
std::unordered_map<nonneg int, ValueFlow::Value> arg_map;
int argn = 0;
for (const ValueFlow::Value& v : args) {
if (!v.isUninitValue())
arg_map[argn] = v;
argn++;
}
return evaluateLibraryFunction(arg_map, returnValue, settings, ftok->isCpp());
}
}
}
// Check if function modifies argument
visitAstNodes(expr->astOperand2(), [&](const Token* child) {
if (child->exprId() > 0 && pm->hasValue(child->exprId())) {
ValueFlow::Value& v = pm->at(child->exprId());
if (v.valueType == ValueFlow::Value::ValueType::CONTAINER_SIZE) {
if (ValueFlow::isContainerSizeChanged(child, v.indirect, settings))
v = unknown();
} else if (v.valueType != ValueFlow::Value::ValueType::UNINIT) {
if (isVariableChanged(child, v.indirect, settings))
v = unknown();
}
}
return ChildrenToVisit::op1_and_op2;
});
return result;
}
return unknown();
}
static const ValueFlow::Value* getImpossibleValue(const Token* tok)
{
if (!tok)
return nullptr;
std::vector<const ValueFlow::Value*> values;
for (const ValueFlow::Value& v : tok->values()) {
if (!v.isImpossible())
continue;
if (v.isContainerSizeValue() || v.isIntValue()) {
values.push_back(std::addressof(v));
}
}
auto it =
std::max_element(values.begin(), values.end(), [](const ValueFlow::Value* x, const ValueFlow::Value* y) {
return x->intvalue < y->intvalue;
});
if (it == values.end())
return nullptr;
return *it;
}
static bool updateValue(ValueFlow::Value& v, ValueFlow::Value x)
{
const bool returnValue = !x.isUninitValue() && !x.isImpossible();
if (v.isUninitValue() || returnValue)
v = std::move(x);
return returnValue;
}
ValueFlow::Value execute(const Token* expr)
{
depth--;
OnExit onExit{[&] {
depth++;
}};
if (depth < 0)
return unknown();
ValueFlow::Value v = unknown();
if (updateValue(v, executeImpl(expr)))
return v;
if (!expr)
return v;
if (expr->exprId() > 0 && pm->hasValue(expr->exprId())) {
if (updateValue(v, utils::as_const(*pm).at(expr->exprId())))
return v;
}
// Find symbolic values
for (const ValueFlow::Value& value : expr->values()) {
if (!value.isSymbolicValue())
continue;
if (!value.isKnown())
continue;
if (value.tokvalue->exprId() > 0 && !pm->hasValue(value.tokvalue->exprId()))
continue;
const ValueFlow::Value& v_ref = utils::as_const(*pm).at(value.tokvalue->exprId());
if (!v_ref.isIntValue() && value.intvalue != 0)
continue;
ValueFlow::Value v2 = v_ref;
v2.intvalue += value.intvalue;
return v2;
}
if (v.isImpossible() && v.isIntValue())
return v;
if (const ValueFlow::Value* value = getImpossibleValue(expr))
return *value;
return v;
}
std::vector<ValueFlow::Value> execute(const Scope* scope)
{
if (!scope)
return {unknown()};
if (!scope->bodyStart)
return {unknown()};
for (const Token* tok = scope->bodyStart->next(); precedes(tok, scope->bodyEnd); tok = tok->next()) {
const Token* top = tok->astTop();
if (Token::simpleMatch(top, "return") && top->astOperand1())
return {execute(top->astOperand1())};
if (Token::Match(top, "%op%")) {
if (execute(top).isUninitValue())
return {unknown()};
const Token* next = nextAfterAstRightmostLeaf(top);
if (!next)
return {unknown()};
tok = next;
} else if (Token::simpleMatch(top->previous(), "if (")) {
const Token* condTok = top->astOperand2();
ValueFlow::Value v = execute(condTok);
if (!v.isIntValue())
return {unknown()};
const Token* thenStart = top->link()->next();
const Token* next = thenStart->link();
const Token* elseStart = nullptr;
if (Token::simpleMatch(thenStart->link(), "} else {")) {
elseStart = thenStart->link()->tokAt(2);
next = elseStart->link();
}
std::vector<ValueFlow::Value> result;
if (isTrue(v)) {
result = execute(thenStart->scope());
} else if (isFalse(v)) {
if (elseStart)
result = execute(elseStart->scope());
} else {
return {unknown()};
}
if (!result.empty())
return result;
tok = next;
} else {
return {unknown()};
}
}
return {};
}
};
} // namespace
static ValueFlow::Value execute(const Token* expr, ProgramMemory& pm, const Settings& settings)
{
Executor ex{&pm, settings};
return ex.execute(expr);
}
std::vector<ValueFlow::Value> execute(const Scope* scope, ProgramMemory& pm, const Settings& settings)
{
Executor ex{&pm, settings};
return ex.execute(scope);
}
static std::shared_ptr<Token> createTokenFromExpression(const std::string& returnValue,
const Settings& settings,
bool cpp,
std::unordered_map<nonneg int, const Token*>& lookupVarId)
{
std::shared_ptr<TokenList> tokenList = std::make_shared<TokenList>(&settings);
{
const std::string code = "return " + returnValue + ";";
std::istringstream istr(code);
if (!tokenList->createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C))
return nullptr;
}
// TODO: put in a helper?
// combine operators, set links, etc..
std::stack<Token*> lpar;
for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, "[!<>=] =")) {
tok2->str(tok2->str() + "=");
tok2->deleteNext();
} else if (tok2->str() == "(")
lpar.push(tok2);
else if (tok2->str() == ")") {
if (lpar.empty())
return nullptr;
Token::createMutualLinks(lpar.top(), tok2);
lpar.pop();
}
}
if (!lpar.empty())
return nullptr;
// set varids
for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) {
if (!startsWith(tok2->str(), "arg"))
continue;
nonneg int const id = strToInt<nonneg int>(tok2->str().c_str() + 3);
tok2->varId(id);
lookupVarId[id] = tok2;
}
// Evaluate expression
tokenList->createAst();
Token* expr = tokenList->front()->astOperand1();
ValueFlow::valueFlowConstantFoldAST(expr, settings);
return {tokenList, expr};
}
ValueFlow::Value evaluateLibraryFunction(const std::unordered_map<nonneg int, ValueFlow::Value>& args,
const std::string& returnValue,
const Settings& settings,
bool cpp)
{
thread_local static std::unordered_map<std::string,
std::function<ValueFlow::Value(const std::unordered_map<nonneg int, ValueFlow::Value>&, const Settings&)>>
functions = {};
if (functions.count(returnValue) == 0) {
std::unordered_map<nonneg int, const Token*> lookupVarId;
std::shared_ptr<Token> expr = createTokenFromExpression(returnValue, settings, cpp, lookupVarId);
functions[returnValue] =
[lookupVarId, expr](const std::unordered_map<nonneg int, ValueFlow::Value>& xargs, const Settings& settings) {
if (!expr)
return ValueFlow::Value::unknown();
ProgramMemory pm{};
for (const auto& p : xargs) {
auto it = lookupVarId.find(p.first);
if (it != lookupVarId.end())
pm.setValue(it->second, p.second);
}
return execute(expr.get(), pm, settings);
};
}
return functions.at(returnValue)(args, settings);
}
void execute(const Token* expr,
ProgramMemory& programMemory,
MathLib::bigint* result,
bool* error,
const Settings& settings)
{
ValueFlow::Value v = execute(expr, programMemory, settings);
if (!v.isIntValue() || v.isImpossible()) {
if (error)
*error = true;
} else if (result)
*result = v.intvalue;
}
| null |
882 | cpp | cppcheck | addoninfo.cpp | lib/addoninfo.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "addoninfo.h"
#include "path.h"
#include "utils.h"
#include <fstream>
#include <iostream>
#include <string>
#include "json.h"
static std::string getFullPath(const std::string &fileName, const std::string &exename, bool debug = false) {
if (debug)
std::cout << "looking for addon '" << fileName << "'" << std::endl;
if (Path::isFile(fileName))
return fileName;
const std::string exepath = Path::getPathFromFilename(exename);
if (debug)
std::cout << "looking for addon '" << (exepath + fileName) << "'" << std::endl;
if (Path::isFile(exepath + fileName))
return exepath + fileName;
if (debug)
std::cout << "looking for addon '" << (exepath + "addons/" + fileName) << "'" << std::endl;
if (Path::isFile(exepath + "addons/" + fileName))
return exepath + "addons/" + fileName;
#ifdef FILESDIR
if (debug)
std::cout << "looking for addon '" << (FILESDIR + ("/" + fileName)) << "'" << std::endl;
if (Path::isFile(FILESDIR + ("/" + fileName)))
return FILESDIR + ("/" + fileName);
if (debug)
std::cout << "looking for addon '" << (FILESDIR + ("/addons/" + fileName)) << "'" << std::endl;
if (Path::isFile(FILESDIR + ("/addons/" + fileName)))
return FILESDIR + ("/addons/" + fileName);
#endif
return "";
}
static std::string parseAddonInfo(AddonInfo& addoninfo, const picojson::value &json, const std::string &fileName, const std::string &exename) {
const std::string& json_error = picojson::get_last_error();
if (!json_error.empty()) {
return "Loading " + fileName + " failed. " + json_error;
}
if (!json.is<picojson::object>())
return "Loading " + fileName + " failed. JSON is not an object.";
// TODO: remove/complete default value handling for missing fields
const picojson::object& obj = json.get<picojson::object>();
{
const auto it = obj.find("args");
if (it != obj.cend()) {
const auto& val = it->second;
if (!val.is<picojson::array>())
return "Loading " + fileName + " failed. 'args' must be an array.";
for (const picojson::value &v : val.get<picojson::array>()) {
if (!v.is<std::string>())
return "Loading " + fileName + " failed. 'args' entry is not a string.";
addoninfo.args += " " + v.get<std::string>();
}
}
}
{
const auto it = obj.find("ctu");
if (it != obj.cend()) {
const auto& val = it->second;
// ctu is specified in the config file
if (!val.is<bool>())
return "Loading " + fileName + " failed. 'ctu' must be a boolean.";
addoninfo.ctu = val.get<bool>();
}
else {
addoninfo.ctu = false;
}
}
{
const auto it = obj.find("python");
if (it != obj.cend()) {
const auto& val = it->second;
// Python was defined in the config file
if (!val.is<std::string>()) {
return "Loading " + fileName +" failed. 'python' must be a string.";
}
addoninfo.python = val.get<std::string>();
}
else {
addoninfo.python = "";
}
}
{
const auto it = obj.find("executable");
if (it != obj.cend()) {
const auto& val = it->second;
if (!val.is<std::string>())
return "Loading " + fileName + " failed. 'executable' must be a string.";
const std::string e = val.get<std::string>();
addoninfo.executable = getFullPath(e, fileName);
if (addoninfo.executable.empty())
addoninfo.executable = e;
return ""; // <- do not load both "executable" and "script".
}
}
const auto it = obj.find("script");
if (it == obj.cend())
return "Loading " + fileName + " failed. 'script' is missing.";
const auto& val = it->second;
if (!val.is<std::string>())
return "Loading " + fileName + " failed. 'script' must be a string.";
return addoninfo.getAddonInfo(val.get<std::string>(), exename);
}
std::string AddonInfo::getAddonInfo(const std::string &fileName, const std::string &exename, bool debug) {
if (fileName[0] == '{') {
picojson::value json;
const std::string err = picojson::parse(json, fileName);
(void)err; // TODO: report
return parseAddonInfo(*this, json, fileName, exename);
}
if (fileName.find('.') == std::string::npos)
return getAddonInfo(fileName + ".py", exename, debug);
if (endsWith(fileName, ".py")) {
scriptFile = Path::fromNativeSeparators(getFullPath(fileName, exename, debug));
if (scriptFile.empty())
return "Did not find addon " + fileName;
std::string::size_type pos1 = scriptFile.rfind('/');
if (pos1 == std::string::npos)
pos1 = 0;
else
pos1++;
std::string::size_type pos2 = scriptFile.rfind('.');
if (pos2 < pos1)
pos2 = std::string::npos;
name = scriptFile.substr(pos1, pos2 - pos1);
runScript = getFullPath("runaddon.py", exename);
return "";
}
if (!endsWith(fileName, ".json"))
return "Failed to open addon " + fileName;
std::ifstream fin(fileName);
if (!fin.is_open())
return "Failed to open " + fileName;
if (name.empty()) {
name = Path::fromNativeSeparators(fileName);
if (name.find('/') != std::string::npos)
name = name.substr(name.rfind('/') + 1);
}
picojson::value json;
fin >> json;
return parseAddonInfo(*this, json, fileName, exename);
}
| null |
883 | cpp | cppcheck | vfvalue.cpp | lib/vfvalue.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "vfvalue.h"
#include "errortypes.h"
#include "token.h"
#include <sstream>
#include <string>
namespace ValueFlow {
Value::Value(const Token *c, MathLib::bigint val, Bound b)
: bound(b),
safe(false),
conditional(false),
macro(false),
defaultArg(false),
intvalue(val),
varvalue(val),
condition(c) {
errorPath.emplace_back(c, "Assuming that condition '" + c->expressionString() + "' is not redundant");
}
void Value::assumeCondition(const Token *tok) {
condition = tok;
errorPath.emplace_back(tok, "Assuming that condition '" + tok->expressionString() + "' is not redundant");
}
std::string Value::toString() const {
std::stringstream ss;
if (this->isImpossible())
ss << "!";
if (this->bound == Bound::Lower)
ss << ">=";
if (this->bound == Bound::Upper)
ss << "<=";
switch (this->valueType) {
case ValueType::INT:
ss << this->intvalue;
break;
case ValueType::TOK:
ss << this->tokvalue->str();
break;
case ValueType::FLOAT:
ss << this->floatValue;
break;
case ValueType::MOVED:
ss << toString(this->moveKind);
break;
case ValueType::UNINIT:
ss << "Uninit";
break;
case ValueType::BUFFER_SIZE:
case ValueType::CONTAINER_SIZE:
ss << "size=" << this->intvalue;
break;
case ValueType::ITERATOR_START:
ss << "start=" << this->intvalue;
break;
case ValueType::ITERATOR_END:
ss << "end=" << this->intvalue;
break;
case ValueType::LIFETIME:
ss << "lifetime[" << toString(this->lifetimeKind) << "]=("
<< this->tokvalue->expressionString() << ")";
break;
case ValueType::SYMBOLIC:
ss << "symbolic=(" << this->tokvalue->expressionString();
if (this->intvalue > 0)
ss << "+" << this->intvalue;
else if (this->intvalue < 0)
ss << "-" << -this->intvalue;
ss << ")";
break;
}
if (this->indirect > 0)
for (int i = 0; i < this->indirect; i++)
ss << "*";
if (this->path > 0)
ss << "@" << this->path;
return ss.str();
}
std::string Value::infoString() const {
switch (valueType) {
case ValueType::INT:
return std::to_string(intvalue);
case ValueType::TOK:
return tokvalue->str();
case ValueType::FLOAT:
return MathLib::toString(floatValue);
case ValueType::MOVED:
return "<Moved>";
case ValueType::UNINIT:
return "<Uninit>";
case ValueType::BUFFER_SIZE:
case ValueType::CONTAINER_SIZE:
return "size=" + std::to_string(intvalue);
case ValueType::ITERATOR_START:
return "start=" + std::to_string(intvalue);
case ValueType::ITERATOR_END:
return "end=" + std::to_string(intvalue);
case ValueType::LIFETIME:
return "lifetime=" + tokvalue->str();
case ValueType::SYMBOLIC:
{
std::string result = "symbolic=" + tokvalue->expressionString();
if (intvalue > 0)
result += "+" + std::to_string(intvalue);
else if (intvalue < 0)
result += "-" + std::to_string(-intvalue);
return result;
}
}
throw InternalError(nullptr, "Invalid ValueFlow Value type");
}
const char *Value::toString(MoveKind moveKind) {
switch (moveKind) {
case MoveKind::NonMovedVariable:
return "NonMovedVariable";
case MoveKind::MovedVariable:
return "MovedVariable";
case MoveKind::ForwardedVariable:
return "ForwardedVariable";
}
return "";
}
const char *Value::toString(LifetimeKind lifetimeKind) {
switch (lifetimeKind) {
case LifetimeKind::Object:
return "Object";
case LifetimeKind::SubObject:
return "SubObject";
case LifetimeKind::Lambda:
return "Lambda";
case LifetimeKind::Iterator:
return "Iterator";
case LifetimeKind::Address:
return "Address";
}
return "";
}
bool Value::sameToken(const Token *tok1, const Token *tok2) {
if (tok1 == tok2)
return true;
if (!tok1)
return false;
if (tok1->exprId() == 0 || tok2->exprId() == 0)
return false;
return tok1->exprId() == tok2->exprId();
}
const char *Value::toString(LifetimeScope lifetimeScope) {
switch (lifetimeScope) {
case LifetimeScope::Local:
return "Local";
case LifetimeScope::Argument:
return "Argument";
case LifetimeScope::SubFunction:
return "SubFunction";
case LifetimeScope::ThisPointer:
return "ThisPointer";
case LifetimeScope::ThisValue:
return "ThisValue";
}
return "";
}
const char *Value::toString(Bound bound) {
switch (bound) {
case Bound::Point:
return "Point";
case Bound::Upper:
return "Upper";
case Bound::Lower:
return "Lower";
}
return "";
}
}
| null |
884 | cpp | cppcheck | settings.cpp | lib/settings.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include "settings.h"
#include "path.h"
#include "summaries.h"
#include "vfvalue.h"
#include <cctype>
#include <fstream>
#include <iostream>
#include <sstream>
#include <utility>
#include "json.h"
#ifndef _WIN32
#include <unistd.h> // for getpid()
#else
#include <process.h> // for getpid()
#endif
std::atomic<bool> Settings::mTerminated;
const char Settings::SafeChecks::XmlRootName[] = "safe-checks";
const char Settings::SafeChecks::XmlClasses[] = "class-public";
const char Settings::SafeChecks::XmlExternalFunctions[] = "external-functions";
const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions";
const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables";
static int getPid()
{
#ifndef _WIN32
return getpid();
#else
return _getpid();
#endif
}
Settings::Settings()
{
severity.setEnabled(Severity::error, true);
certainty.setEnabled(Certainty::normal, true);
setCheckLevel(Settings::CheckLevel::exhaustive);
executor = defaultExecutor();
pid = getPid();
}
std::string Settings::loadCppcheckCfg(Settings& settings, Suppressions& suppressions, bool debug)
{
// TODO: this always needs to be run *after* the Settings has been filled
static const std::string cfgFilename = "cppcheck.cfg";
std::string fileName;
#ifdef FILESDIR
{
const std::string filesdirCfg = Path::join(FILESDIR, cfgFilename);
if (debug)
std::cout << "looking for '" << filesdirCfg << "'" << std::endl;
if (Path::isFile(filesdirCfg))
fileName = filesdirCfg;
}
#endif
// cppcheck-suppress knownConditionTrueFalse
if (fileName.empty()) {
// TODO: make sure that exename is set
fileName = Path::getPathFromFilename(settings.exename) + cfgFilename;
if (debug)
std::cout << "looking for '" << fileName << "'" << std::endl;
if (!Path::isFile(fileName))
{
if (debug)
std::cout << "no configuration found" << std::endl;
return "";
}
}
std::ifstream fin(fileName);
if (!fin.is_open())
return "could not open file";
picojson::value json;
fin >> json;
{
const std::string& lastErr = picojson::get_last_error();
if (!lastErr.empty())
return "not a valid JSON - " + lastErr;
}
const picojson::object& obj = json.get<picojson::object>();
{
const picojson::object::const_iterator it = obj.find("productName");
if (it != obj.cend()) {
const auto& v = it->second;
if (!v.is<std::string>())
return "'productName' is not a string";
settings.cppcheckCfgProductName = v.get<std::string>();
}
}
{
const picojson::object::const_iterator it = obj.find("about");
if (it != obj.cend()) {
const auto& v = it->second;
if (!v.is<std::string>())
return "'about' is not a string";
settings.cppcheckCfgAbout = v.get<std::string>();
}
}
{
const picojson::object::const_iterator it = obj.find("addons");
if (it != obj.cend()) {
const auto& entry = it->second;
if (!entry.is<picojson::array>())
return "'addons' is not an array";
for (const picojson::value &v : entry.get<picojson::array>())
{
if (!v.is<std::string>())
return "'addons' array entry is not a string";
const std::string &s = v.get<std::string>();
if (!Path::isAbsolute(s))
settings.addons.emplace(Path::join(Path::getPathFromFilename(fileName), s));
else
settings.addons.emplace(s);
}
}
}
{
const picojson::object::const_iterator it = obj.find("suppressions");
if (it != obj.cend()) {
const auto& entry = it->second;
if (!entry.is<picojson::array>())
return "'suppressions' is not an array";
for (const picojson::value &v : entry.get<picojson::array>())
{
if (!v.is<std::string>())
return "'suppressions' array entry is not a string";
const std::string &s = v.get<std::string>();
const std::string err = suppressions.nomsg.addSuppressionLine(s);
if (!err.empty())
return "could not parse suppression '" + s + "' - " + err;
}
}
}
{
const picojson::object::const_iterator it = obj.find("safety");
if (it != obj.cend()) {
const auto& v = it->second;
if (!v.is<bool>())
return "'safety' is not a bool";
settings.safety = settings.safety || v.get<bool>();
}
}
return "";
}
std::pair<std::string, std::string> Settings::getNameAndVersion(const std::string& productName) {
if (productName.empty())
return {};
const std::string::size_type pos1 = productName.rfind(' ');
if (pos1 == std::string::npos)
return {};
if (pos1 + 2 >= productName.length())
return {};
for (auto pos2 = pos1 + 1; pos2 < productName.length(); ++pos2) {
const char c = productName[pos2];
const char prev = productName[pos2-1];
if (std::isdigit(c))
continue;
if (c == '.' && std::isdigit(prev))
continue;
if (c == 's' && pos2 + 1 == productName.length() && std::isdigit(prev))
continue;
return {};
}
return {productName.substr(0, pos1), productName.substr(pos1+1)};
}
std::string Settings::parseEnabled(const std::string &str, std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> &groups)
{
// Enable parameters may be comma separated...
if (str.find(',') != std::string::npos) {
std::string::size_type prevPos = 0;
std::string::size_type pos = 0;
while ((pos = str.find(',', pos)) != std::string::npos) {
if (pos == prevPos)
return std::string("--enable parameter is empty");
std::string errmsg(parseEnabled(str.substr(prevPos, pos - prevPos), groups));
if (!errmsg.empty())
return errmsg;
++pos;
prevPos = pos;
}
if (prevPos >= str.length())
return std::string("--enable parameter is empty");
return parseEnabled(str.substr(prevPos), groups);
}
auto& severity = std::get<0>(groups);
auto& checks = std::get<1>(groups);
if (str == "all") {
// "error" is always enabled and cannot be controlled - so exclude it from "all"
SimpleEnableGroup<Severity> newSeverity;
newSeverity.fill();
newSeverity.disable(Severity::error);
severity.enable(newSeverity);
checks.enable(Checks::missingInclude);
checks.enable(Checks::unusedFunction);
} else if (str == "warning") {
severity.enable(Severity::warning);
} else if (str == "style") {
severity.enable(Severity::style);
} else if (str == "performance") {
severity.enable(Severity::performance);
} else if (str == "portability") {
severity.enable(Severity::portability);
} else if (str == "information") {
severity.enable(Severity::information);
} else if (str == "unusedFunction") {
checks.enable(Checks::unusedFunction);
} else if (str == "missingInclude") {
checks.enable(Checks::missingInclude);
}
#ifdef CHECK_INTERNAL
else if (str == "internal") {
checks.enable(Checks::internalCheck);
}
#endif
else {
// the actual option is prepending in the applyEnabled() call
if (str.empty())
return " parameter is empty";
return " parameter with the unknown name '" + str + "'";
}
return "";
}
std::string Settings::addEnabled(const std::string &str)
{
return applyEnabled(str, true);
}
std::string Settings::removeEnabled(const std::string &str)
{
return applyEnabled(str, false);
}
std::string Settings::applyEnabled(const std::string &str, bool enable)
{
std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> groups;
std::string errmsg = parseEnabled(str, groups);
if (!errmsg.empty())
return (enable ? "--enable" : "--disable") + errmsg;
const auto s = std::get<0>(groups);
const auto c = std::get<1>(groups);
if (enable) {
severity.enable(s);
checks.enable(c);
}
else {
severity.disable(s);
checks.disable(c);
}
// FIXME: hack to make sure "error" is always enabled
severity.enable(Severity::error);
return errmsg;
}
bool Settings::isEnabled(const ValueFlow::Value *value, bool inconclusiveCheck) const
{
if (!severity.isEnabled(Severity::warning) && (value->condition || value->defaultArg))
return false;
if (!certainty.isEnabled(Certainty::inconclusive) && (inconclusiveCheck || value->isInconclusive()))
return false;
return true;
}
void Settings::loadSummaries()
{
Summaries::loadReturn(buildDir, summaryReturn);
}
void Settings::setCheckLevel(CheckLevel level)
{
if (level == CheckLevel::reduced) {
// Checking should finish quickly.
checkLevel = level;
vfOptions.maxSubFunctionArgs = 8;
vfOptions.maxIfCount = 100;
vfOptions.doConditionExpressionAnalysis = false;
vfOptions.maxForwardBranches = 4;
vfOptions.maxIterations = 1;
}
else if (level == CheckLevel::normal) {
// Checking should finish in reasonable time.
checkLevel = level;
vfOptions.maxSubFunctionArgs = 8;
vfOptions.maxIfCount = 100;
vfOptions.doConditionExpressionAnalysis = false;
vfOptions.maxForwardBranches = 4;
}
else if (level == CheckLevel::exhaustive) {
// Checking can take a little while. ~ 10 times slower than normal analysis is OK.
checkLevel = CheckLevel::exhaustive;
vfOptions.maxIfCount = -1;
vfOptions.maxSubFunctionArgs = 256;
vfOptions.doConditionExpressionAnalysis = true;
vfOptions.maxForwardBranches = -1;
}
}
// These tables are auto generated from Cppcheck Premium script
static const std::set<std::string> autosarCheckers{
"accessMoved",
"argumentSize",
"arrayIndexOutOfBounds",
"arrayIndexOutOfBoundsCond",
"arrayIndexThenCheck",
"bufferAccessOutOfBounds",
"comparePointers",
"constParameter",
"cstyleCast",
"ctuOneDefinitionRuleViolation",
"doubleFree",
"duplInheritedMember",
"duplicateBreak",
"exceptThrowInDestructor",
"funcArgNamesDifferent",
"functionConst",
"functionStatic",
"invalidContainer",
"memleak",
"mismatchAllocDealloc",
"missingReturn",
"negativeIndex",
"noExplicitConstructor",
"nullPointer",
"nullPointerArithmetic",
"nullPointerArithmeticRedundantCheck",
"nullPointerDefaultArg",
"nullPointerRedundantCheck",
"objectIndex",
"overlappingWriteFunction",
"overlappingWriteUnion",
"pointerOutOfBounds",
"pointerOutOfBoundsCond",
"preprocessorErrorDirective",
"redundantAssignment",
"redundantInitialization",
"returnDanglingLifetime",
"shadowArgument",
"shadowFunction",
"shadowVariable",
"shiftTooManyBits",
"sizeofFunctionCall",
"throwInNoexceptFunction",
"uninitMemberVar",
"uninitdata",
"unreachableCode",
"unreadVariable",
"unsignedLessThanZero",
"unusedFunction",
"unusedStructMember",
"unusedValue",
"unusedVariable",
"useInitializationList",
"variableScope",
"virtualCallInConstructor",
"zerodiv",
"zerodivcond"
};
static const std::set<std::string> certCCheckers{
"IOWithoutPositioning",
"autoVariables",
"autovarInvalidDeallocation",
"bitwiseOnBoolean",
"comparePointers",
"danglingLifetime",
"deallocret",
"deallocuse",
"doubleFree",
"floatConversionOverflow",
"invalidFunctionArg",
"invalidLengthModifierError",
"invalidLifetime",
"invalidScanfFormatWidth",
"invalidscanf",
"leakReturnValNotUsed",
"leakUnsafeArgAlloc",
"memleak",
"memleakOnRealloc",
"mismatchAllocDealloc",
"missingReturn",
"nullPointer",
"nullPointerArithmetic",
"nullPointerArithmeticRedundantCheck",
"nullPointerDefaultArg",
"nullPointerRedundantCheck",
"preprocessorErrorDirective",
"resourceLeak",
"returnDanglingLifetime",
"sizeofCalculation",
"stringLiteralWrite",
"uninitStructMember",
"uninitdata",
"uninitvar",
"unknownEvaluationOrder",
"useClosedFile",
"wrongPrintfScanfArgNum",
"wrongPrintfScanfParameterPositionError"
};
static const std::set<std::string> certCppCheckers{
"IOWithoutPositioning",
"accessMoved",
"comparePointers",
"containerOutOfBounds",
"ctuOneDefinitionRuleViolation",
"danglingLifetime",
"danglingReference",
"danglingTempReference",
"danglingTemporaryLifetime",
"deallocThrow",
"deallocuse",
"doubleFree",
"eraseDereference",
"exceptThrowInDestructor",
"initializerList",
"invalidContainer",
"memleak",
"mismatchAllocDealloc",
"missingReturn",
"nullPointer",
"operatorEqToSelf",
"returnDanglingLifetime",
"sizeofCalculation",
"uninitvar",
"virtualCallInConstructor",
"virtualDestructor"
};
static const std::set<std::string> misrac2012Checkers{
"argumentSize",
"autovarInvalidDeallocation",
"bufferAccessOutOfBounds",
"comparePointers",
"compareValueOutOfTypeRangeError",
"constParameterPointer",
"danglingLifetime",
"danglingTemporaryLifetime",
"duplicateBreak",
"funcArgNamesDifferent",
"incompatibleFileOpen",
"invalidFunctionArg",
"knownConditionTrueFalse",
"leakNoVarFunctionCall",
"leakReturnValNotUsed",
"memleak",
"memleakOnRealloc",
"missingReturn",
"overlappingWriteFunction",
"overlappingWriteUnion",
"pointerOutOfBounds",
"preprocessorErrorDirective",
"redundantAssignInSwitch",
"redundantAssignment",
"redundantCondition",
"resourceLeak",
"returnDanglingLifetime",
"shadowVariable",
"sizeofCalculation",
"sizeofwithsilentarraypointer",
"syntaxError",
"uninitvar",
"unknownEvaluationOrder",
"unreachableCode",
"unreadVariable",
"unusedLabel",
"unusedVariable",
"useClosedFile",
"writeReadOnlyFile"
};
static const std::set<std::string> misrac2023Checkers{
"argumentSize",
"autovarInvalidDeallocation",
"bufferAccessOutOfBounds",
"comparePointers",
"compareValueOutOfTypeRangeError",
"constParameterPointer",
"danglingLifetime",
"danglingTemporaryLifetime",
"duplicateBreak",
"funcArgNamesDifferent",
"incompatibleFileOpen",
"invalidFunctionArg",
"knownConditionTrueFalse",
"leakNoVarFunctionCall",
"leakReturnValNotUsed",
"memleak",
"memleakOnRealloc",
"missingReturn",
"overlappingWriteFunction",
"overlappingWriteUnion",
"pointerOutOfBounds",
"preprocessorErrorDirective",
"redundantAssignInSwitch",
"redundantAssignment",
"redundantCondition",
"resourceLeak",
"returnDanglingLifetime",
"shadowVariable",
"sizeofCalculation",
"sizeofwithsilentarraypointer",
"syntaxError",
"uninitvar",
"unknownEvaluationOrder",
"unreachableCode",
"unreadVariable",
"unusedLabel",
"unusedVariable",
"useClosedFile",
"writeReadOnlyFile"
};
static const std::set<std::string> misracpp2008Checkers{
"autoVariables",
"comparePointers",
"constParameter",
"constVariable",
"cstyleCast",
"ctuOneDefinitionRuleViolation",
"danglingLifetime",
"duplInheritedMember",
"duplicateBreak",
"exceptThrowInDestructor",
"funcArgNamesDifferent",
"functionConst",
"functionStatic",
"missingReturn",
"noExplicitConstructor",
"overlappingWriteFunction",
"overlappingWriteUnion",
"pointerOutOfBounds",
"preprocessorErrorDirective",
"redundantAssignment",
"redundantInitialization",
"returnReference",
"returnTempReference",
"shadowVariable",
"shiftTooManyBits",
"sizeofFunctionCall",
"uninitDerivedMemberVar",
"uninitDerivedMemberVarPrivate",
"uninitMemberVar",
"uninitMemberVarPrivate",
"uninitStructMember",
"uninitdata",
"uninitvar",
"unknownEvaluationOrder",
"unreachableCode",
"unreadVariable",
"unsignedLessThanZero",
"unusedFunction",
"unusedStructMember",
"unusedVariable",
"variableScope",
"virtualCallInConstructor"
};
static const std::set<std::string> misracpp2023Checkers{
"accessForwarded",
"accessMoved",
"autoVariables",
"compareBoolExpressionWithInt",
"comparePointers",
"compareValueOutOfTypeRangeError",
"constParameter",
"constParameterReference",
"ctuOneDefinitionRuleViolation",
"danglingLifetime",
"identicalConditionAfterEarlyExit",
"identicalInnerCondition",
"ignoredReturnValue",
"invalidFunctionArg",
"invalidFunctionArgBool",
"invalidFunctionArgStr",
"knownConditionTrueFalse",
"missingReturn",
"noExplicitConstructor",
"operatorEqToSelf",
"overlappingWriteUnion",
"pointerOutOfBounds",
"pointerOutOfBoundsCond",
"preprocessorErrorDirective",
"redundantAssignInSwitch",
"redundantAssignment",
"redundantCopy",
"redundantInitialization",
"shadowVariable",
"subtractPointers",
"syntaxError",
"uninitMemberVar",
"uninitvar",
"unknownEvaluationOrder",
"unreachableCode",
"unreadVariable",
"virtualCallInConstructor"
};
bool Settings::isPremiumEnabled(const char id[]) const
{
if (premiumArgs.find("autosar") != std::string::npos && autosarCheckers.count(id))
return true;
if (premiumArgs.find("cert-c-") != std::string::npos && certCCheckers.count(id))
return true;
if (premiumArgs.find("cert-c++") != std::string::npos && certCppCheckers.count(id))
return true;
if (premiumArgs.find("misra-c-") != std::string::npos && (misrac2012Checkers.count(id) || misrac2023Checkers.count(id)))
return true;
if (premiumArgs.find("misra-c++-2008") != std::string::npos && misracpp2008Checkers.count(id))
return true;
if (premiumArgs.find("misra-c++-2023") != std::string::npos && misracpp2023Checkers.count(id))
return true;
return false;
}
void Settings::setMisraRuleTexts(const ExecuteCmdFn& executeCommand)
{
if (premiumArgs.find("--misra-c-20") != std::string::npos) {
const auto it = std::find_if(addonInfos.cbegin(), addonInfos.cend(), [](const AddonInfo& a) {
return a.name == "premiumaddon.json";
});
if (it != addonInfos.cend()) {
std::string arg;
if (premiumArgs.find("--misra-c-2023") != std::string::npos)
arg = "--misra-c-2023-rule-texts";
else
arg = "--misra-c-2012-rule-texts";
std::string output;
executeCommand(it->executable, {std::move(arg)}, "2>&1", output);
setMisraRuleTexts(output);
}
}
}
void Settings::setMisraRuleTexts(const std::string& data)
{
mMisraRuleTexts.clear();
std::istringstream istr(data);
std::string line;
while (std::getline(istr, line)) {
std::string::size_type pos = line.find(' ');
if (pos == std::string::npos)
continue;
std::string id = line.substr(0, pos);
std::string text = line.substr(pos + 1);
if (id.empty() || text.empty())
continue;
if (text[text.size() -1] == '\r')
text.erase(text.size() -1);
mMisraRuleTexts[id] = std::move(text);
}
}
std::string Settings::getMisraRuleText(const std::string& id, const std::string& text) const {
if (id.compare(0, 9, "misra-c20") != 0)
return text;
const auto it = mMisraRuleTexts.find(id.substr(id.rfind('-') + 1));
return it != mMisraRuleTexts.end() ? it->second : text;
}
Settings::ExecutorType Settings::defaultExecutor()
{
static constexpr ExecutorType defaultExecutor =
#if defined(HAS_THREADING_MODEL_FORK)
ExecutorType::Process;
#elif defined(HAS_THREADING_MODEL_THREAD)
ExecutorType::Thread;
#endif
return defaultExecutor;
}
| null |
885 | cpp | cppcheck | check64bit.cpp | lib/check64bit.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2023 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
// 64-bit portability
//---------------------------------------------------------------------------
#include "check64bit.h"
#include "errortypes.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include <vector>
//---------------------------------------------------------------------------
// CWE ids used
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
// Register this check class (by creating a static instance of it)
namespace {
Check64BitPortability instance;
}
void Check64BitPortability::pointerassignment()
{
if (!mSettings->severity.isEnabled(Severity::portability))
return;
logChecker("Check64BitPortability::pointerassignment"); // portability
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
// Check return values
for (const Scope * scope : symbolDatabase->functionScopes) {
if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body
continue;
bool retPointer = false;
if (scope->function->token->strAt(-1) == "*") // Function returns a pointer
retPointer = true;
else if (Token::Match(scope->function->token->previous(), "int|long|DWORD")) // Function returns an integer
;
else
continue;
for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) {
// skip nested functions
if (tok->str() == "{") {
if (tok->scope()->type == Scope::ScopeType::eFunction || tok->scope()->type == Scope::ScopeType::eLambda)
tok = tok->link();
}
if (tok->str() != "return")
continue;
if (!tok->astOperand1() || tok->astOperand1()->isNumber())
continue;
const ValueType * const returnType = tok->astOperand1()->valueType();
if (!returnType)
continue;
if (retPointer && !returnType->typeScope && returnType->pointer == 0U)
returnIntegerError(tok);
if (!retPointer && returnType->pointer >= 1U)
returnPointerError(tok);
}
}
// Check assignments
for (const Scope * scope : symbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() != "=")
continue;
const ValueType *lhstype = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType *rhstype = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr;
if (!lhstype || !rhstype)
continue;
// Assign integer to pointer..
if (lhstype->pointer >= 1U &&
!tok->astOperand2()->isNumber() &&
rhstype->pointer == 0U &&
rhstype->originalTypeName.empty() &&
rhstype->type == ValueType::Type::INT)
assignmentIntegerToAddressError(tok);
// Assign pointer to integer..
if (rhstype->pointer >= 1U &&
lhstype->pointer == 0U &&
lhstype->originalTypeName.empty() &&
lhstype->isIntegral() &&
lhstype->type >= ValueType::Type::CHAR &&
lhstype->type <= ValueType::Type::INT)
assignmentAddressToIntegerError(tok);
}
}
}
void Check64BitPortability::assignmentAddressToIntegerError(const Token *tok)
{
reportError(tok, Severity::portability,
"AssignmentAddressToInteger",
"Assigning a pointer to an integer is not portable.\n"
"Assigning a pointer to an integer (int/long/etc) is not portable across different platforms and "
"compilers. For example in 32-bit Windows and linux they are same width, but in 64-bit Windows and linux "
"they are of different width. In worst case you end up assigning 64-bit address to 32-bit integer. The safe "
"way is to store addresses only in pointer types (or typedefs like uintptr_t).", CWE758, Certainty::normal);
}
void Check64BitPortability::assignmentIntegerToAddressError(const Token *tok)
{
reportError(tok, Severity::portability,
"AssignmentIntegerToAddress",
"Assigning an integer to a pointer is not portable.\n"
"Assigning an integer (int/long/etc) to a pointer is not portable across different platforms and "
"compilers. For example in 32-bit Windows and linux they are same width, but in 64-bit Windows and linux "
"they are of different width. In worst case you end up assigning 64-bit integer to 32-bit pointer. The safe "
"way is to store addresses only in pointer types (or typedefs like uintptr_t).", CWE758, Certainty::normal);
}
void Check64BitPortability::returnPointerError(const Token *tok)
{
reportError(tok, Severity::portability,
"CastAddressToIntegerAtReturn",
"Returning an address value in a function with integer return type is not portable.\n"
"Returning an address value in a function with integer (int/long/etc) return type is not portable across "
"different platforms and compilers. For example in 32-bit Windows and Linux they are same width, but in "
"64-bit Windows and Linux they are of different width. In worst case you end up casting 64-bit address down "
"to 32-bit integer. The safe way is to always return an integer.", CWE758, Certainty::normal);
}
void Check64BitPortability::returnIntegerError(const Token *tok)
{
reportError(tok, Severity::portability,
"CastIntegerToAddressAtReturn",
"Returning an integer in a function with pointer return type is not portable.\n"
"Returning an integer (int/long/etc) in a function with pointer return type is not portable across different "
"platforms and compilers. For example in 32-bit Windows and Linux they are same width, but in 64-bit Windows "
"and Linux they are of different width. In worst case you end up casting 64-bit integer down to 32-bit pointer. "
"The safe way is to always return a pointer.", CWE758, Certainty::normal);
}
| null |
886 | cpp | cppcheck | importproject.h | lib/importproject.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef importprojectH
#define importprojectH
//---------------------------------------------------------------------------
#include "config.h"
#include "filesettings.h"
#include "platform.h"
#include "utils.h"
#include <cstdint>
#include <iosfwd>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
/// @addtogroup Core
/// @{
namespace cppcheck {
struct stricmp {
bool operator()(const std::string &lhs, const std::string &rhs) const {
return caseInsensitiveStringCompare(lhs,rhs) < 0;
}
};
}
class Settings;
/**
* @brief Importing project settings.
*/
class CPPCHECKLIB WARN_UNUSED ImportProject {
public:
enum class Type : std::uint8_t {
NONE,
UNKNOWN,
MISSING,
FAILURE,
COMPILE_DB,
VS_SLN,
VS_VCXPROJ,
BORLAND,
CPPCHECK_GUI
};
static void fsParseCommand(FileSettings& fs, const std::string& command);
static void fsSetDefines(FileSettings& fs, std::string defs);
static void fsSetIncludePaths(FileSettings& fs, const std::string &basepath, const std::list<std::string> &in, std::map<std::string, std::string, cppcheck::stricmp> &variables);
std::list<FileSettings> fileSettings;
Type projectType{Type::NONE};
ImportProject() = default;
virtual ~ImportProject() = default;
ImportProject(const ImportProject&) = default;
ImportProject& operator=(const ImportProject&) & = default;
void selectOneVsConfig(Platform::Type platform);
void selectVsConfigurations(Platform::Type platform, const std::vector<std::string> &configurations);
std::list<std::string> getVSConfigs();
// Cppcheck GUI output
struct {
std::string analyzeAllVsConfigs;
std::vector<std::string> pathNames;
std::list<std::string> libraries;
std::list<std::string> excludedPaths;
std::list<std::string> checkVsConfigs;
std::string projectFile;
std::string platform;
} guiProject;
void ignorePaths(const std::vector<std::string> &ipaths);
void ignoreOtherConfigs(const std::string &cfg);
Type import(const std::string &filename, Settings *settings=nullptr);
protected:
bool importCompileCommands(std::istream &istr);
bool importCppcheckGuiProject(std::istream &istr, Settings *settings);
virtual bool sourceFileExists(const std::string &file);
private:
struct SharedItemsProject {
bool successful = false;
std::string pathToProjectFile;
std::vector<std::string> includePaths;
std::vector<std::string> sourceFiles;
};
bool importSln(std::istream &istr, const std::string &path, const std::vector<std::string> &fileFilters);
static SharedItemsProject importVcxitems(const std::string &filename, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache);
bool importVcxproj(const std::string &filename, std::map<std::string, std::string, cppcheck::stricmp> &variables, const std::string &additionalIncludeDirectories, const std::vector<std::string> &fileFilters, std::vector<SharedItemsProject> &cache);
bool importBcb6Prj(const std::string &projectFilename);
static void printError(const std::string &message);
void setRelativePaths(const std::string &filename);
std::string mPath;
std::set<std::string> mAllVSConfigs;
};
namespace CppcheckXml {
static constexpr char ProjectElementName[] = "project";
static constexpr char ProjectVersionAttrib[] = "version";
static constexpr char ProjectFileVersion[] = "1";
static constexpr char BuildDirElementName[] = "builddir";
static constexpr char ImportProjectElementName[] = "importproject";
static constexpr char AnalyzeAllVsConfigsElementName[] = "analyze-all-vs-configs";
static constexpr char Parser[] = "parser";
static constexpr char IncludeDirElementName[] = "includedir";
static constexpr char DirElementName[] = "dir";
static constexpr char DirNameAttrib[] = "name";
static constexpr char DefinesElementName[] = "defines";
static constexpr char DefineName[] = "define";
static constexpr char DefineNameAttrib[] = "name";
static constexpr char UndefinesElementName[] = "undefines";
static constexpr char UndefineName[] = "undefine";
static constexpr char PathsElementName[] = "paths";
static constexpr char PathName[] = "dir";
static constexpr char PathNameAttrib[] = "name";
static constexpr char RootPathName[] = "root";
static constexpr char RootPathNameAttrib[] = "name";
static constexpr char IgnoreElementName[] = "ignore";
static constexpr char IgnorePathName[] = "path";
static constexpr char IgnorePathNameAttrib[] = "name";
static constexpr char ExcludeElementName[] = "exclude";
static constexpr char ExcludePathName[] = "path";
static constexpr char ExcludePathNameAttrib[] = "name";
static constexpr char FunctionContracts[] = "function-contracts";
static constexpr char VariableContractsElementName[] = "variable-contracts";
static constexpr char LibrariesElementName[] = "libraries";
static constexpr char LibraryElementName[] = "library";
static constexpr char PlatformElementName[] = "platform";
static constexpr char SuppressionsElementName[] = "suppressions";
static constexpr char SuppressionElementName[] = "suppression";
static constexpr char AddonElementName[] = "addon";
static constexpr char AddonsElementName[] = "addons";
static constexpr char ToolElementName[] = "tool";
static constexpr char ToolsElementName[] = "tools";
static constexpr char TagsElementName[] = "tags";
static constexpr char TagElementName[] = "tag";
static constexpr char TagWarningsElementName[] = "tag-warnings";
static constexpr char TagAttributeName[] = "tag";
static constexpr char WarningElementName[] = "warning";
static constexpr char HashAttributeName[] = "hash";
static constexpr char CheckLevelExhaustiveElementName[] = "check-level-exhaustive";
static constexpr char CheckLevelNormalElementName[] = "check-level-normal";
static constexpr char CheckLevelReducedElementName[] = "check-level-reduced";
static constexpr char CheckHeadersElementName[] = "check-headers";
static constexpr char CheckUnusedTemplatesElementName[] = "check-unused-templates";
static constexpr char MaxCtuDepthElementName[] = "max-ctu-depth";
static constexpr char MaxTemplateRecursionElementName[] = "max-template-recursion";
static constexpr char CheckUnknownFunctionReturn[] = "check-unknown-function-return-values";
static constexpr char InlineSuppression[] = "inline-suppression";
static constexpr char ClangTidy[] = "clang-tidy";
static constexpr char Name[] = "name";
static constexpr char VSConfigurationElementName[] = "vs-configurations";
static constexpr char VSConfigurationName[] = "config";
// Cppcheck Premium
static constexpr char BughuntingElementName[] = "bug-hunting";
static constexpr char CodingStandardsElementName[] = "coding-standards";
static constexpr char CodingStandardElementName[] = "coding-standard";
static constexpr char CertIntPrecisionElementName[] = "cert-c-int-precision";
static constexpr char LicenseFileElementName[] = "license-file";
static constexpr char ProjectNameElementName[] = "project-name";
}
/// @}
//---------------------------------------------------------------------------
#endif // importprojectH
| null |
887 | cpp | cppcheck | reverseanalyzer.h | lib/reverseanalyzer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef reverseanalyzerH
#define reverseanalyzerH
struct Analyzer;
class ErrorLogger;
class Settings;
class Token;
class TokenList;
template<class T>
class ValuePtr;
void valueFlowGenericReverse(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings);
#endif
| null |
888 | cpp | cppcheck | check64bit.h | lib/check64bit.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef check64bitH
#define check64bitH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "tokenize.h"
#include <string>
class ErrorLogger;
class Settings;
class Token;
/// @addtogroup Checks
/// @{
/**
* @brief Check for 64-bit portability issues
*/
class CPPCHECKLIB Check64BitPortability : public Check {
friend class Test64BitPortability;
public:
/** This constructor is used when registering the Check64BitPortability */
Check64BitPortability() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
Check64BitPortability(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
Check64BitPortability check64BitPortability(&tokenizer, &tokenizer.getSettings(), errorLogger);
check64BitPortability.pointerassignment();
}
/** Check for pointer assignment */
void pointerassignment();
void assignmentAddressToIntegerError(const Token *tok);
void assignmentIntegerToAddressError(const Token *tok);
void returnIntegerError(const Token *tok);
void returnPointerError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
Check64BitPortability c(nullptr, settings, errorLogger);
c.assignmentAddressToIntegerError(nullptr);
c.assignmentIntegerToAddressError(nullptr);
c.returnIntegerError(nullptr);
c.returnPointerError(nullptr);
}
static std::string myName() {
return "64-bit portability";
}
std::string classInfo() const override {
return "Check if there is 64-bit portability issues:\n"
"- assign address to/from int/long\n"
"- casting address from/to integer when returning from function\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // check64bitH
| null |
889 | cpp | cppcheck | platform.h | lib/platform.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef platformH
#define platformH
//---------------------------------------------------------------------------
#include "config.h"
#include "mathlib.h"
#include "standards.h"
#include <climits>
#include <cstddef>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
/// @addtogroup Core
/// @{
namespace tinyxml2 {
class XMLDocument;
}
/**
* @brief Platform settings
*/
class CPPCHECKLIB Platform {
private:
static long long min_value(int bit) {
if (bit >= 64)
return LLONG_MIN;
return -(1LL << (bit-1));
}
static long long max_value(int bit) {
if (bit >= 64)
return (~0ULL) >> 1;
return (1LL << (bit-1)) - 1LL;
}
static unsigned long long max_value_unsigned(int bit) {
if (bit >= 64)
return ~0ULL;
return (1ULL << bit) - 1ULL;
}
/** provides list of defines specified by the limit.h/climits includes */
std::string getLimitsDefines(bool c99) const;
public:
Platform();
bool isIntValue(MathLib::bigint value) const {
return value >= min_value(int_bit) && value <= max_value(int_bit);
}
bool isIntValue(MathLib::biguint value) const {
const unsigned long long intMax = max_value(int_bit);
return value <= intMax;
}
bool isLongValue(MathLib::bigint value) const {
return value >= min_value(long_bit) && value <= max_value(long_bit);
}
bool isLongValue(MathLib::biguint value) const {
const MathLib::biguint longMax = max_value(long_bit);
return value <= longMax;
}
bool isLongLongValue(MathLib::biguint value) const {
const MathLib::biguint longLongMax = max_value(long_long_bit);
return value <= longLongMax;
}
nonneg int char_bit; /// bits in char
nonneg int short_bit; /// bits in short
nonneg int int_bit; /// bits in int
nonneg int long_bit; /// bits in long
nonneg int long_long_bit; /// bits in long long
/** size of standard types */
std::size_t sizeof_bool;
std::size_t sizeof_short;
std::size_t sizeof_int;
std::size_t sizeof_long;
std::size_t sizeof_long_long;
std::size_t sizeof_float;
std::size_t sizeof_double;
std::size_t sizeof_long_double;
std::size_t sizeof_wchar_t;
std::size_t sizeof_size_t;
std::size_t sizeof_pointer;
char defaultSign; // unsigned:'u', signed:'s', unknown:'\0'
enum Type : std::uint8_t {
Unspecified, // No platform specified
Native, // whatever system this code was compiled on
Win32A,
Win32W,
Win64,
Unix32,
Unix64,
File
};
/** platform type */
Type type;
/** set the platform type for predefined platforms - deprecated use set(const std::string&, std::string&) instead */
bool set(Type t);
/** set the platform type */
bool set(const std::string& platformstr, std::string& errstr, const std::vector<std::string>& paths = {}, bool debug = false);
/**
* load platform file
* @param exename application path
* @param filename platform filename
* @param debug log verbose information about the lookup
* @return returns true if file was loaded successfully
*/
bool loadFromFile(const char exename[], const std::string &filename, bool debug = false);
/** load platform from xml document, primarily for testing */
bool loadFromXmlDocument(const tinyxml2::XMLDocument *doc);
/**
* @brief Returns true if platform type is Windows
* @return true if Windows platform type.
*/
bool isWindows() const {
return type == Type::Win32A ||
type == Type::Win32W ||
type == Type::Win64;
}
const char *toString() const {
return toString(type);
}
static const char *toString(Type pt) {
switch (pt) {
case Type::Unspecified:
return "unspecified";
case Type::Native:
return "native";
case Type::Win32A:
return "win32A";
case Type::Win32W:
return "win32W";
case Type::Win64:
return "win64";
case Type::Unix32:
return "unix32";
case Type::Unix64:
return "unix64";
case Type::File:
return "platformFile";
default:
throw std::runtime_error("unknown platform");
}
}
long long unsignedCharMax() const {
return max_value(char_bit + 1);
}
long long signedCharMax() const {
return max_value(char_bit);
}
long long signedCharMin() const {
return min_value(char_bit);
}
/** provides list of defines specified by the limit.h/climits includes */
std::string getLimitsDefines(Standards::cstd_t cstd) const;
/** provides list of defines specified by the limit.h/climits includes */
std::string getLimitsDefines(Standards::cppstd_t cppstd) const;
};
/// @}
//---------------------------------------------------------------------------
#endif // platformH
| null |
890 | cpp | cppcheck | programmemory.h | lib/programmemory.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef GUARD_PROGRAMMEMORY_H
#define GUARD_PROGRAMMEMORY_H
#include "config.h"
#include "mathlib.h"
#include "vfvalue.h" // needed for alias
#include <cstddef>
#include <functional>
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
class Scope;
class Token;
class Settings;
// Class used to handle heterogeneous lookup in unordered_map(since we can't use C++20 yet)
struct ExprIdToken {
const Token* tok = nullptr;
nonneg int exprid = 0;
ExprIdToken() = default;
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
ExprIdToken(const Token* tok);
// TODO: Make this constructor only available from ProgramMemory
// cppcheck-suppress noExplicitConstructor
// NOLINTNEXTLINE(google-explicit-constructor)
ExprIdToken(nonneg int exprid) : exprid(exprid) {}
nonneg int getExpressionId() const;
bool operator==(const ExprIdToken& rhs) const {
return getExpressionId() == rhs.getExpressionId();
}
bool operator<(const ExprIdToken& rhs) const {
return getExpressionId() < rhs.getExpressionId();
}
template<class T, class U>
friend bool operator!=(const T& lhs, const U& rhs)
{
return !(lhs == rhs);
}
template<class T, class U>
friend bool operator<=(const T& lhs, const U& rhs)
{
return !(lhs > rhs);
}
template<class T, class U>
friend bool operator>(const T& lhs, const U& rhs)
{
return rhs < lhs;
}
template<class T, class U>
friend bool operator>=(const T& lhs, const U& rhs)
{
return !(lhs < rhs);
}
const Token& operator*() const NOEXCEPT {
return *tok;
}
const Token* operator->() const NOEXCEPT {
return tok;
}
struct Hash {
std::size_t operator()(ExprIdToken etok) const;
};
};
struct CPPCHECKLIB ProgramMemory {
using Map = std::unordered_map<ExprIdToken, ValueFlow::Value, ExprIdToken::Hash>;
ProgramMemory() : mValues(new Map()) {}
explicit ProgramMemory(Map values) : mValues(new Map(std::move(values))) {}
void setValue(const Token* expr, const ValueFlow::Value& value);
const ValueFlow::Value* getValue(nonneg int exprid, bool impossible = false) const;
bool getIntValue(nonneg int exprid, MathLib::bigint& result) const;
void setIntValue(const Token* expr, MathLib::bigint value, bool impossible = false);
bool getContainerSizeValue(nonneg int exprid, MathLib::bigint& result) const;
bool getContainerEmptyValue(nonneg int exprid, MathLib::bigint& result) const;
void setContainerSizeValue(const Token* expr, MathLib::bigint value, bool isEqual = true);
void setUnknown(const Token* expr);
bool getTokValue(nonneg int exprid, const Token*& result) const;
bool hasValue(nonneg int exprid);
const ValueFlow::Value& at(nonneg int exprid) const;
ValueFlow::Value& at(nonneg int exprid);
void erase_if(const std::function<bool(const ExprIdToken&)>& pred);
void swap(ProgramMemory &pm) NOEXCEPT;
void clear();
bool empty() const;
void replace(ProgramMemory pm);
Map::const_iterator begin() const {
return mValues->cbegin();
}
Map::const_iterator end() const {
return mValues->cend();
}
friend bool operator==(const ProgramMemory& x, const ProgramMemory& y) {
return x.mValues == y.mValues;
}
friend bool operator!=(const ProgramMemory& x, const ProgramMemory& y) {
return x.mValues != y.mValues;
}
private:
void copyOnWrite();
std::shared_ptr<Map> mValues;
};
struct ProgramMemoryState {
ProgramMemory state;
std::map<nonneg int, const Token*> origins;
const Settings& settings;
explicit ProgramMemoryState(const Settings& s);
void replace(ProgramMemory pm, const Token* origin = nullptr);
void addState(const Token* tok, const ProgramMemory::Map& vars);
void assume(const Token* tok, bool b, bool isEmpty = false);
void removeModifiedVars(const Token* tok);
ProgramMemory get(const Token* tok, const Token* ctx, const ProgramMemory::Map& vars) const;
};
std::vector<ValueFlow::Value> execute(const Scope* scope, ProgramMemory& pm, const Settings& settings);
void execute(const Token* expr,
ProgramMemory& programMemory,
MathLib::bigint* result,
bool* error,
const Settings& settings);
/**
* Is condition always false when variable has given value?
* \param condition top ast token in condition
* \param pm program memory
*/
bool conditionIsFalse(const Token* condition, ProgramMemory pm, const Settings& settings);
/**
* Is condition always true when variable has given value?
* \param condition top ast token in condition
* \param pm program memory
*/
bool conditionIsTrue(const Token* condition, ProgramMemory pm, const Settings& settings);
/**
* Get program memory by looking backwards from given token.
*/
ProgramMemory getProgramMemory(const Token* tok, const Token* expr, const ValueFlow::Value& value, const Settings& settings);
ValueFlow::Value evaluateLibraryFunction(const std::unordered_map<nonneg int, ValueFlow::Value>& args,
const std::string& returnValue,
const Settings& settings,
bool cpp);
#endif
| null |
891 | cpp | cppcheck | findtoken.h | lib/findtoken.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef findtokenH
#define findtokenH
//---------------------------------------------------------------------------
#include <functional>
#include <stack>
#include <string>
#include <type_traits>
#include <vector>
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "smallvector.h"
#include "symboldatabase.h"
#include "token.h"
inline std::vector<MathLib::bigint> evaluateKnownValues(const Token* tok)
{
if (!tok->hasKnownIntValue())
return {};
return {tok->getKnownIntValue()};
}
template<class T, class Predicate, class Found, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
void findTokensImpl(T* start, const Token* end, const Predicate& pred, Found found)
{
for (T* tok = start; precedes(tok, end); tok = tok->next()) {
if (pred(tok)) {
if (found(tok))
break;
}
}
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokens(T* start, const Token* end, const Predicate& pred)
{
std::vector<T*> result;
findTokensImpl(start, end, pred, [&](T* tok) {
result.push_back(tok);
return false;
});
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findToken(T* start, const Token* end, const Predicate& pred)
{
T* result = nullptr;
findTokensImpl(start, end, pred, [&](T* tok) {
result = tok;
return true;
});
return result;
}
template<class T,
class Predicate,
class Found,
class Evaluate,
REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
bool findTokensSkipDeadCodeImpl(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
Found found,
const Evaluate& evaluate,
bool skipUnevaluated)
{
for (T* tok = start; precedes(tok, end); tok = tok->next()) {
if (pred(tok)) {
if (found(tok))
return true;
}
if (Token::Match(tok, "if|for|while (") && Token::simpleMatch(tok->linkAt(1), ") {")) {
const Token* condTok = getCondTok(tok);
if (!condTok)
continue;
auto result = evaluate(condTok);
if (result.empty())
continue;
if (findTokensSkipDeadCodeImpl(library, tok->next(), tok->linkAt(1), pred, found, evaluate, skipUnevaluated))
return true;
T* thenStart = tok->linkAt(1)->next();
T* elseStart = nullptr;
if (Token::simpleMatch(thenStart->link(), "} else {"))
elseStart = thenStart->link()->tokAt(2);
auto r = result.front();
if (r == 0) {
if (elseStart) {
if (findTokensSkipDeadCodeImpl(library, elseStart, elseStart->link(), pred, found, evaluate, skipUnevaluated))
return true;
if (isReturnScope(elseStart->link(), library))
return true;
tok = elseStart->link();
} else {
tok = thenStart->link();
}
} else {
if (findTokensSkipDeadCodeImpl(library, thenStart, thenStart->link(), pred, found, evaluate, skipUnevaluated))
return true;
if (isReturnScope(thenStart->link(), library))
return true;
tok = thenStart->link();
}
} else if (Token::Match(tok->astParent(), "&&|?|%oror%") && astIsLHS(tok)) {
auto result = evaluate(tok);
if (result.empty())
continue;
const bool cond = result.front() != 0;
T* next = nullptr;
if ((cond && Token::simpleMatch(tok->astParent(), "||")) ||
(!cond && Token::simpleMatch(tok->astParent(), "&&"))) {
next = nextAfterAstRightmostLeaf(tok->astParent());
} else if (Token::simpleMatch(tok->astParent(), "?")) {
T* colon = tok->astParent()->astOperand2();
if (!cond) {
next = colon;
} else {
if (findTokensSkipDeadCodeImpl(library, tok->astParent()->next(), colon, pred, found, evaluate, skipUnevaluated))
return true;
next = nextAfterAstRightmostLeaf(colon);
}
}
if (next)
tok = next;
} else if (Token::simpleMatch(tok, "} else {")) {
const Token* condTok = getCondTokFromEnd(tok);
if (!condTok)
continue;
auto result = evaluate(condTok);
if (result.empty())
continue;
if (isReturnScope(tok->link(), library))
return true;
auto r = result.front();
if (r != 0) {
tok = tok->linkAt(2);
}
} else if (Token::simpleMatch(tok, "[") && Token::Match(tok->link(), "] (|{")) {
T* afterCapture = tok->link()->next();
if (Token::simpleMatch(afterCapture, "(") && afterCapture->link())
tok = afterCapture->link()->next();
else
tok = afterCapture;
}
if (skipUnevaluated && isUnevaluated(tok)) {
T *next = tok->linkAt(1);
if (!next)
continue;
tok = next;
}
}
return false;
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadCode(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
const Evaluate& evaluate)
{
std::vector<T*> result;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result.push_back(tok);
return false;
},
evaluate,
false);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokensSkipDeadCode(library, start, end, pred, &evaluateKnownValues);
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadAndUnevaluatedCode(const Library& library,
T* start,
const Token* end,
const Predicate& pred,
const Evaluate& evaluate)
{
std::vector<T*> result;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result.push_back(tok);
return false;
},
evaluate,
true);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
std::vector<T*> findTokensSkipDeadAndUnevaluatedCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokensSkipDeadAndUnevaluatedCode(library, start, end, pred, &evaluateKnownValues);
}
template<class T, class Predicate, class Evaluate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findTokenSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred, const Evaluate& evaluate)
{
T* result = nullptr;
(void)findTokensSkipDeadCodeImpl(
library,
start,
end,
pred,
[&](T* tok) {
result = tok;
return true;
},
evaluate,
false);
return result;
}
template<class T, class Predicate, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
T* findTokenSkipDeadCode(const Library& library, T* start, const Token* end, const Predicate& pred)
{
return findTokenSkipDeadCode(library, start, end, pred, &evaluateKnownValues);
}
#endif // findtokenH
| null |
892 | cpp | cppcheck | checkfunctions.h | lib/checkfunctions.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkfunctionsH
#define checkfunctionsH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "library.h"
#include "settings.h"
#include "tokenize.h"
#include <map>
#include <string>
class Token;
class ErrorLogger;
namespace ValueFlow {
class Value;
} // namespace ValueFlow
/// @addtogroup Checks
/// @{
/**
* @brief Check for bad function usage
*/
class CPPCHECKLIB CheckFunctions : public Check {
public:
/** This constructor is used when registering the CheckFunctions */
CheckFunctions() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckFunctions(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckFunctions checkFunctions(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkFunctions.checkIgnoredReturnValue();
checkFunctions.checkMissingReturn(); // Missing "return" in exit path
// --check-library : functions with nonmatching configuration
checkFunctions.checkLibraryMatchFunctions();
checkFunctions.checkProhibitedFunctions();
checkFunctions.invalidFunctionUsage();
checkFunctions.checkMathFunctions();
checkFunctions.memsetZeroBytes();
checkFunctions.memsetInvalid2ndParam();
checkFunctions.returnLocalStdMove();
checkFunctions.useStandardLibrary();
}
/** Check for functions that should not be used */
void checkProhibitedFunctions();
/**
* @brief Invalid function usage (invalid input value / overlapping data)
*
* %Check that given function parameters are valid according to the standard
* - wrong radix given for strtol/strtoul
* - overlapping data when using sprintf/snprintf
* - wrong input value according to library
*/
void invalidFunctionUsage();
/** @brief %Check for ignored return values. */
void checkIgnoredReturnValue();
/** @brief %Check for parameters given to math function that do not make sense*/
void checkMathFunctions();
/** @brief %Check for filling zero bytes with memset() */
void memsetZeroBytes();
/** @brief %Check for invalid 2nd parameter of memset() */
void memsetInvalid2ndParam();
/** @brief %Check for copy elision by RVO|NRVO */
void returnLocalStdMove();
void useStandardLibrary();
/** @brief --check-library: warn for unconfigured function calls */
void checkLibraryMatchFunctions();
/** @brief %Check for missing "return" */
void checkMissingReturn();
void invalidFunctionArgError(const Token *tok, const std::string &functionName, int argnr, const ValueFlow::Value *invalidValue, const std::string &validstr);
void invalidFunctionArgBoolError(const Token *tok, const std::string &functionName, int argnr);
void invalidFunctionArgStrError(const Token *tok, const std::string &functionName, nonneg int argnr);
void ignoredReturnValueError(const Token* tok, const std::string& function);
void ignoredReturnErrorCode(const Token* tok, const std::string& function);
void mathfunctionCallWarning(const Token *tok, nonneg int numParam = 1);
void mathfunctionCallWarning(const Token *tok, const std::string& oldexp, const std::string& newexp);
void memsetZeroBytesError(const Token *tok);
void memsetFloatError(const Token *tok, const std::string &var_value);
void memsetValueOutOfRangeError(const Token *tok, const std::string &value);
void missingReturnError(const Token *tok);
void copyElisionError(const Token *tok);
void useStandardLibraryError(const Token *tok, const std::string& expected);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckFunctions c(nullptr, settings, errorLogger);
for (std::map<std::string, Library::WarnInfo>::const_iterator i = settings->library.functionwarn().cbegin(); i != settings->library.functionwarn().cend(); ++i) {
c.reportError(nullptr, Severity::style, i->first+"Called", i->second.message);
}
c.invalidFunctionArgError(nullptr, "func_name", 1, nullptr,"1:4");
c.invalidFunctionArgBoolError(nullptr, "func_name", 1);
c.invalidFunctionArgStrError(nullptr, "func_name", 1);
c.ignoredReturnValueError(nullptr, "malloc");
c.mathfunctionCallWarning(nullptr);
c.mathfunctionCallWarning(nullptr, "1 - erf(x)", "erfc(x)");
c.memsetZeroBytesError(nullptr);
c.memsetFloatError(nullptr, "varname");
c.memsetValueOutOfRangeError(nullptr, "varname");
c.missingReturnError(nullptr);
c.copyElisionError(nullptr);
c.useStandardLibraryError(nullptr, "memcpy");
}
static std::string myName() {
return "Check function usage";
}
std::string classInfo() const override {
return "Check function usage:\n"
"- missing 'return' in non-void function\n"
"- return value of certain functions not used\n"
"- invalid input values for functions\n"
"- Warn if a function is called whose usage is discouraged\n"
"- memset() third argument is zero\n"
"- memset() with a value out of range as the 2nd parameter\n"
"- memset() with a float as the 2nd parameter\n"
"- copy elision optimization for returning value affected by std::move\n"
"- use memcpy()/memset() instead of for loop\n";
}
};
/// @}
//---------------------------------------------------------------------------
#endif // checkfunctionsH
| null |
893 | cpp | cppcheck | checktype.cpp | lib/checktype.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checktype.h"
#include "astutils.h"
#include "errortypes.h"
#include "mathlib.h"
#include "platform.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenize.h"
#include "valueflow.h"
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <iterator>
#include <list>
#include <sstream>
#include <utility>
#include <vector>
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckType instance;
}
//---------------------------------------------------------------------------
// Checking for shift by too many bits
//---------------------------------------------------------------------------
//
// CWE ids used:
static const CWE CWE195(195U); // Signed to Unsigned Conversion Error
static const CWE CWE197(197U); // Numeric Truncation Error
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE190(190U); // Integer Overflow or Wraparound
void CheckType::checkTooBigBitwiseShift()
{
// unknown sizeof(int) => can't run this checker
if (mSettings->platform.type == Platform::Type::Unspecified)
return;
logChecker("CheckType::checkTooBigBitwiseShift"); // platform
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
// C++ and macro: OUT(x<<y)
if (tok->isCpp() && Token::Match(tok, "[;{}] %name% (") && Token::simpleMatch(tok->linkAt(2), ") ;") && tok->next()->isUpperCaseName() && !tok->next()->function())
tok = tok->linkAt(2);
tok = skipUnreachableBranch(tok);
if (!tok->astOperand1() || !tok->astOperand2())
continue;
if (!Token::Match(tok, "<<|>>|<<=|>>="))
continue;
// get number of bits of lhs
const ValueType * const lhstype = tok->astOperand1()->valueType();
if (!lhstype || !lhstype->isIntegral() || lhstype->pointer >= 1)
continue;
// C11 Standard, section 6.5.7 Bitwise shift operators, states:
// The integer promotions are performed on each of the operands.
// The type of the result is that of the promoted left operand.
int lhsbits;
if ((lhstype->type == ValueType::Type::CHAR) ||
(lhstype->type == ValueType::Type::SHORT) ||
(lhstype->type == ValueType::Type::WCHAR_T) ||
(lhstype->type == ValueType::Type::BOOL) ||
(lhstype->type == ValueType::Type::INT))
lhsbits = mSettings->platform.int_bit;
else if (lhstype->type == ValueType::Type::LONG)
lhsbits = mSettings->platform.long_bit;
else if (lhstype->type == ValueType::Type::LONGLONG)
lhsbits = mSettings->platform.long_long_bit;
else
continue;
// Get biggest rhs value. preferably a value which doesn't have 'condition'.
const ValueFlow::Value * value = tok->astOperand2()->getValueGE(lhsbits, *mSettings);
if (value && mSettings->isEnabled(value, false))
tooBigBitwiseShiftError(tok, lhsbits, *value);
else if (lhstype->sign == ValueType::Sign::SIGNED) {
value = tok->astOperand2()->getValueGE(lhsbits-1, *mSettings);
if (value && mSettings->isEnabled(value, false))
tooBigSignedBitwiseShiftError(tok, lhsbits, *value);
}
}
}
void CheckType::tooBigBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits)
{
constexpr char id[] = "shiftTooManyBits";
if (!tok) {
reportError(tok, Severity::error, id, "Shifting 32-bit value by 40 bits is undefined behaviour", CWE758, Certainty::normal);
return;
}
const ErrorPath errorPath = getErrorPath(tok, &rhsbits, "Shift");
std::ostringstream errmsg;
errmsg << "Shifting " << lhsbits << "-bit value by " << rhsbits.intvalue << " bits is undefined behaviour";
if (rhsbits.condition)
errmsg << ". See condition at line " << rhsbits.condition->linenr() << ".";
reportError(errorPath, rhsbits.errorSeverity() ? Severity::error : Severity::warning, id, errmsg.str(), CWE758, rhsbits.isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
void CheckType::tooBigSignedBitwiseShiftError(const Token *tok, int lhsbits, const ValueFlow::Value &rhsbits)
{
constexpr char id[] = "shiftTooManyBitsSigned";
const bool cpp14 = ((tok && tok->isCpp()) || (mTokenizer && mTokenizer->isCPP())) && (mSettings->standards.cpp >= Standards::CPP14);
std::string behaviour = "undefined";
if (cpp14)
behaviour = "implementation-defined";
if (!tok) {
reportError(tok, Severity::error, id, "Shifting signed 32-bit value by 31 bits is " + behaviour + " behaviour", CWE758, Certainty::normal);
return;
}
Severity severity = rhsbits.errorSeverity() ? Severity::error : Severity::warning;
if (cpp14)
severity = Severity::portability;
if ((severity == Severity::portability) && !mSettings->severity.isEnabled(Severity::portability))
return;
const ErrorPath errorPath = getErrorPath(tok, &rhsbits, "Shift");
std::ostringstream errmsg;
errmsg << "Shifting signed " << lhsbits << "-bit value by " << rhsbits.intvalue << " bits is " + behaviour + " behaviour";
if (rhsbits.condition)
errmsg << ". See condition at line " << rhsbits.condition->linenr() << ".";
reportError(errorPath, severity, id, errmsg.str(), CWE758, rhsbits.isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// Checking for integer overflow
//---------------------------------------------------------------------------
void CheckType::checkIntegerOverflow()
{
// unknown sizeof(int) => can't run this checker
if (mSettings->platform.type == Platform::Type::Unspecified || mSettings->platform.int_bit >= MathLib::bigint_bits)
return;
logChecker("CheckType::checkIntegerOverflow"); // platform
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp())
continue;
// is result signed integer?
const ValueType *vt = tok->valueType();
if (!vt || !vt->isIntegral() || vt->sign != ValueType::Sign::SIGNED)
continue;
unsigned int bits;
if (vt->type == ValueType::Type::INT)
bits = mSettings->platform.int_bit;
else if (vt->type == ValueType::Type::LONG)
bits = mSettings->platform.long_bit;
else if (vt->type == ValueType::Type::LONGLONG)
bits = mSettings->platform.long_long_bit;
else
continue;
if (bits >= MathLib::bigint_bits)
continue;
// max value according to platform settings.
const MathLib::bigint maxvalue = (((MathLib::biguint)1) << (bits - 1)) - 1;
// is there a overflow result value
bool isOverflow = true;
const ValueFlow::Value *value = tok->getValueGE(maxvalue + 1, *mSettings);
if (!value) {
value = tok->getValueLE(-maxvalue - 2, *mSettings);
isOverflow = false;
}
if (!value || !mSettings->isEnabled(value,false))
continue;
// For left shift, it's common practice to shift into the sign bit
if (tok->str() == "<<" && value->intvalue > 0 && value->intvalue < (((MathLib::bigint)1) << bits))
continue;
integerOverflowError(tok, *value, isOverflow);
}
}
void CheckType::integerOverflowError(const Token *tok, const ValueFlow::Value &value, bool isOverflow)
{
const std::string expr(tok ? tok->expressionString() : "");
const std::string type = isOverflow ? "overflow" : "underflow";
std::string msg;
if (value.condition)
msg = ValueFlow::eitherTheConditionIsRedundant(value.condition) +
" or there is signed integer " + type + " for expression '" + expr + "'.";
else
msg = "Signed integer " + type + " for expression '" + expr + "'.";
if (value.safe)
msg = "Safe checks: " + msg;
reportError(getErrorPath(tok, &value, "Integer " + type),
value.errorSeverity() ? Severity::error : Severity::warning,
getMessageId(value, "integerOverflow").c_str(),
msg,
CWE190,
value.isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// Checking for sign conversion when operand can be negative
//---------------------------------------------------------------------------
void CheckType::checkSignConversion()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckType::checkSignConversion"); // warning
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (!tok->isArithmeticalOp() || Token::Match(tok,"+|-"))
continue;
// Is result unsigned?
if (!(tok->valueType() && tok->valueType()->sign == ValueType::Sign::UNSIGNED))
continue;
// Check if an operand can be negative..
const Token * astOperands[] = { tok->astOperand1(), tok->astOperand2() };
for (const Token * tok1 : astOperands) {
if (!tok1)
continue;
const ValueFlow::Value* negativeValue =
ValueFlow::findValue(tok1->values(), *mSettings, [&](const ValueFlow::Value& v) {
return !v.isImpossible() && v.isIntValue() && (v.intvalue <= -1 || v.wideintvalue <= -1);
});
if (!negativeValue)
continue;
if (tok1->valueType() && tok1->valueType()->sign != ValueType::Sign::UNSIGNED)
signConversionError(tok1, negativeValue, tok1->isNumber());
}
}
}
void CheckType::signConversionError(const Token *tok, const ValueFlow::Value *negativeValue, const bool constvalue)
{
const std::string expr(tok ? tok->expressionString() : "var");
std::ostringstream msg;
if (tok && tok->isName())
msg << "$symbol:" << expr << "\n";
if (constvalue)
msg << "Expression '" << expr << "' has a negative value. That is converted to an unsigned value and used in an unsigned calculation.";
else
msg << "Expression '" << expr << "' can have a negative value. That is converted to an unsigned value and used in an unsigned calculation.";
if (!negativeValue)
reportError(tok, Severity::warning, "signConversion", msg.str(), CWE195, Certainty::normal);
else {
const ErrorPath &errorPath = getErrorPath(tok,negativeValue,"Negative value is converted to an unsigned value");
reportError(errorPath,
Severity::warning,
Check::getMessageId(*negativeValue, "signConversion").c_str(),
msg.str(),
CWE195,
negativeValue->isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
}
//---------------------------------------------------------------------------
// Checking for long cast of int result const long x = var1 * var2;
//---------------------------------------------------------------------------
static bool checkTypeCombination(ValueType src, ValueType tgt, const Settings& settings)
{
static const std::pair<ValueType::Type, ValueType::Type> typeCombinations[] = {
{ ValueType::Type::INT, ValueType::Type::LONG },
{ ValueType::Type::INT, ValueType::Type::LONGLONG },
{ ValueType::Type::LONG, ValueType::Type::LONGLONG },
{ ValueType::Type::FLOAT, ValueType::Type::DOUBLE },
{ ValueType::Type::FLOAT, ValueType::Type::LONGDOUBLE },
{ ValueType::Type::DOUBLE, ValueType::Type::LONGDOUBLE },
};
src.reference = Reference::None;
tgt.reference = Reference::None;
const std::size_t sizeSrc = ValueFlow::getSizeOf(src, settings);
const std::size_t sizeTgt = ValueFlow::getSizeOf(tgt, settings);
if (!(sizeSrc > 0 && sizeTgt > 0 && sizeSrc < sizeTgt))
return false;
return std::any_of(std::begin(typeCombinations), std::end(typeCombinations), [&](const std::pair<ValueType::Type, ValueType::Type>& p) {
return src.type == p.first && tgt.type == p.second;
});
}
void CheckType::checkLongCast()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("truncLongCastAssignment"))
return;
logChecker("CheckType::checkLongCast"); // style
// Assignments..
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (tok->str() != "=" || !Token::Match(tok->astOperand2(), "*|<<") || tok->astOperand2()->isUnaryOp("*"))
continue;
if (tok->astOperand2()->hasKnownIntValue()) {
const ValueFlow::Value &v = tok->astOperand2()->values().front();
if (mSettings->platform.isIntValue(v.intvalue))
continue;
}
const ValueType *lhstype = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr;
const ValueType *rhstype = tok->astOperand2()->valueType();
if (!lhstype || !rhstype)
continue;
if (!checkTypeCombination(*rhstype, *lhstype, *mSettings))
continue;
// assign int result to long/longlong const nonpointer?
if (rhstype->pointer == 0U &&
rhstype->originalTypeName.empty() &&
lhstype->pointer == 0U &&
lhstype->originalTypeName.empty())
longCastAssignError(tok, rhstype, lhstype);
}
// Return..
const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase();
for (const Scope * scope : symbolDatabase->functionScopes) {
// function must return long data
const Token * def = scope->classDef;
if (!Token::Match(def, "%name% (") || !def->next()->valueType())
continue;
const ValueType* retVt = def->next()->valueType();
// return statements
const Token *ret = nullptr;
for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (tok->str() == "return") {
if (Token::Match(tok->astOperand1(), "<<|*")) {
const ValueType *type = tok->astOperand1()->valueType();
if (type && checkTypeCombination(*type, *retVt, *mSettings) &&
type->pointer == 0U &&
type->originalTypeName.empty())
ret = tok;
}
// All return statements must have problem otherwise no warning
if (ret != tok) {
ret = nullptr;
break;
}
}
}
if (ret)
longCastReturnError(ret, ret->astOperand1()->valueType(), retVt);
}
}
static void makeBaseTypeString(std::string& typeStr)
{
const auto pos = typeStr.find("signed");
if (pos != std::string::npos)
typeStr.erase(typeStr.begin(), typeStr.begin() + pos + 6 + 1);
}
void CheckType::longCastAssignError(const Token *tok, const ValueType* src, const ValueType* tgt)
{
std::string srcStr = src ? src->str() : "int";
makeBaseTypeString(srcStr);
std::string tgtStr = tgt ? tgt->str() : "long";
makeBaseTypeString(tgtStr);
reportError(tok,
Severity::style,
"truncLongCastAssignment",
srcStr + " result is assigned to " + tgtStr + " variable. If the variable is " + tgtStr + " to avoid loss of information, then you have loss of information.\n" +
srcStr + " result is assigned to " + tgtStr + " variable. If the variable is " + tgtStr + " to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to " + tgtStr + ", for example 'l = a * b;' => 'l = (" + tgtStr + ")a * b;'.", CWE197, Certainty::normal);
}
void CheckType::longCastReturnError(const Token *tok, const ValueType* src, const ValueType* tgt)
{
std::string srcStr = src ? src->str() : "int";
makeBaseTypeString(srcStr);
std::string tgtStr = tgt ? tgt->str() : "long";
makeBaseTypeString(tgtStr);
reportError(tok,
Severity::style,
"truncLongCastReturn",
srcStr +" result is returned as " + tgtStr + " value. If the return value is " + tgtStr + " to avoid loss of information, then you have loss of information.\n" +
srcStr +" result is returned as " + tgtStr + " value. If the return value is " + tgtStr + " to avoid loss of information, then there is loss of information. To avoid loss of information you must cast a calculation operand to long, for example 'return a*b;' => 'return (long)a*b'.", CWE197, Certainty::normal);
}
//---------------------------------------------------------------------------
// Checking for float to integer overflow
//---------------------------------------------------------------------------
void CheckType::checkFloatToIntegerOverflow()
{
logChecker("CheckType::checkFloatToIntegerOverflow");
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
const ValueType *vtint, *vtfloat;
// Explicit cast
if (Token::Match(tok, "( %name%") && tok->astOperand1() && !tok->astOperand2()) {
if (isUnreachableOperand(tok))
continue;
vtint = tok->valueType();
vtfloat = tok->astOperand1()->valueType();
checkFloatToIntegerOverflow(tok, vtint, vtfloat, tok->astOperand1()->values());
}
// Assignment
else if (tok->str() == "=" && tok->astOperand1() && tok->astOperand2()) {
if (isUnreachableOperand(tok))
continue;
vtint = tok->astOperand1()->valueType();
vtfloat = tok->astOperand2()->valueType();
checkFloatToIntegerOverflow(tok, vtint, vtfloat, tok->astOperand2()->values());
}
else if (tok->str() == "return" && tok->astOperand1() && tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->isFloat()) {
if (isUnreachableOperand(tok))
continue;
const Scope *scope = tok->scope();
while (scope && scope->type != Scope::ScopeType::eLambda && scope->type != Scope::ScopeType::eFunction)
scope = scope->nestedIn;
if (scope && scope->type == Scope::ScopeType::eFunction && scope->function && scope->function->retDef) {
const ValueType &valueType = ValueType::parseDecl(scope->function->retDef, *mSettings);
vtfloat = tok->astOperand1()->valueType();
checkFloatToIntegerOverflow(tok, &valueType, vtfloat, tok->astOperand1()->values());
}
}
}
}
void CheckType::checkFloatToIntegerOverflow(const Token *tok, const ValueType *vtint, const ValueType *vtfloat, const std::list<ValueFlow::Value> &floatValues)
{
// Conversion of float to integer?
if (!vtint || !vtint->isIntegral())
return;
if (!vtfloat || !vtfloat->isFloat())
return;
for (const ValueFlow::Value &f : floatValues) {
if (f.valueType != ValueFlow::Value::ValueType::FLOAT)
continue;
if (!mSettings->isEnabled(&f, false))
continue;
if (f.floatValue >= std::exp2(mSettings->platform.long_long_bit))
floatToIntegerOverflowError(tok, f);
else if ((-f.floatValue) > std::exp2(mSettings->platform.long_long_bit - 1))
floatToIntegerOverflowError(tok, f);
else if (mSettings->platform.type != Platform::Type::Unspecified) {
int bits = 0;
if (vtint->type == ValueType::Type::CHAR)
bits = mSettings->platform.char_bit;
else if (vtint->type == ValueType::Type::SHORT)
bits = mSettings->platform.short_bit;
else if (vtint->type == ValueType::Type::INT)
bits = mSettings->platform.int_bit;
else if (vtint->type == ValueType::Type::LONG)
bits = mSettings->platform.long_bit;
else if (vtint->type == ValueType::Type::LONGLONG)
bits = mSettings->platform.long_long_bit;
else
continue;
if (bits < MathLib::bigint_bits && f.floatValue >= (((MathLib::biguint)1) << bits))
floatToIntegerOverflowError(tok, f);
}
}
}
void CheckType::floatToIntegerOverflowError(const Token *tok, const ValueFlow::Value &value)
{
std::ostringstream errmsg;
errmsg << "Undefined behaviour: float (" << value.floatValue << ") to integer conversion overflow.";
reportError(getErrorPath(tok, &value, "float to integer conversion"),
value.errorSeverity() ? Severity::error : Severity::warning,
"floatConversionOverflow",
errmsg.str(), CWE190, value.isInconclusive() ? Certainty::inconclusive : Certainty::normal);
}
| null |
894 | cpp | cppcheck | platform.cpp | lib/platform.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform.h"
#include "path.h"
#include <cstring>
#include <iostream>
#include <limits>
#include <vector>
#include "xml.h"
Platform::Platform()
{
set(Type::Native);
}
bool Platform::set(Type t)
{
switch (t) {
case Type::Unspecified: // unknown type sizes (sizes etc are set but are not known)
case Type::Native: // same as system this code was compile on
type = t;
sizeof_bool = sizeof(bool);
sizeof_short = sizeof(short);
sizeof_int = sizeof(int);
sizeof_long = sizeof(long);
sizeof_long_long = sizeof(long long);
sizeof_float = sizeof(float);
sizeof_double = sizeof(double);
sizeof_long_double = sizeof(long double);
sizeof_wchar_t = sizeof(wchar_t);
sizeof_size_t = sizeof(std::size_t);
sizeof_pointer = sizeof(void *);
if (type == Type::Unspecified) {
defaultSign = '\0';
} else {
defaultSign = std::numeric_limits<char>::is_signed ? 's' : 'u';
}
char_bit = 8;
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
return true;
case Type::Win32W:
case Type::Win32A:
type = t;
sizeof_bool = 1; // 4 in Visual C++ 4.2
sizeof_short = 2;
sizeof_int = 4;
sizeof_long = 4;
sizeof_long_long = 8;
sizeof_float = 4;
sizeof_double = 8;
sizeof_long_double = 8;
sizeof_wchar_t = 2;
sizeof_size_t = 4;
sizeof_pointer = 4;
defaultSign = '\0';
char_bit = 8;
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
return true;
case Type::Win64:
type = t;
sizeof_bool = 1;
sizeof_short = 2;
sizeof_int = 4;
sizeof_long = 4;
sizeof_long_long = 8;
sizeof_float = 4;
sizeof_double = 8;
sizeof_long_double = 8;
sizeof_wchar_t = 2;
sizeof_size_t = 8;
sizeof_pointer = 8;
defaultSign = '\0';
char_bit = 8;
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
return true;
case Type::Unix32:
type = t;
sizeof_bool = 1;
sizeof_short = 2;
sizeof_int = 4;
sizeof_long = 4;
sizeof_long_long = 8;
sizeof_float = 4;
sizeof_double = 8;
sizeof_long_double = 12;
sizeof_wchar_t = 4;
sizeof_size_t = 4;
sizeof_pointer = 4;
defaultSign = '\0';
char_bit = 8;
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
return true;
case Type::Unix64:
type = t;
sizeof_bool = 1;
sizeof_short = 2;
sizeof_int = 4;
sizeof_long = 8;
sizeof_long_long = 8;
sizeof_float = 4;
sizeof_double = 8;
sizeof_long_double = 16;
sizeof_wchar_t = 4;
sizeof_size_t = 8;
sizeof_pointer = 8;
defaultSign = '\0';
char_bit = 8;
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
return true;
case Type::File:
// sizes are not set.
return false;
}
// unsupported platform
return false;
}
bool Platform::set(const std::string& platformstr, std::string& errstr, const std::vector<std::string>& paths, bool debug)
{
if (platformstr == "win32A")
set(Type::Win32A);
else if (platformstr == "win32W")
set(Type::Win32W);
else if (platformstr == "win64")
set(Type::Win64);
else if (platformstr == "unix32")
set(Type::Unix32);
else if (platformstr == "unix64")
set(Type::Unix64);
else if (platformstr == "native")
set(Type::Native);
else if (platformstr == "unspecified")
set(Type::Unspecified);
else if (paths.empty()) {
errstr = "unrecognized platform: '" + platformstr + "' (no lookup).";
return false;
}
else {
bool found = false;
for (const std::string& path : paths) {
if (debug)
std::cout << "looking for platform '" + platformstr + "' in '" + path + "'" << std::endl;
if (loadFromFile(path.c_str(), platformstr, debug)) {
found = true;
break;
}
}
if (!found) {
errstr = "unrecognized platform: '" + platformstr + "'.";
return false;
}
}
return true;
}
bool Platform::loadFromFile(const char exename[], const std::string &filename, bool debug)
{
// TODO: only append .xml if missing
// TODO: use native separators
std::vector<std::string> filenames{
filename,
filename + ".xml",
"platforms/" + filename,
"platforms/" + filename + ".xml"
};
if (exename && (std::string::npos != Path::fromNativeSeparators(exename).find('/'))) {
filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + filename);
filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + "platforms/" + filename);
filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + "platforms/" + filename + ".xml");
}
#ifdef FILESDIR
std::string filesdir = FILESDIR;
if (!filesdir.empty() && filesdir[filesdir.size()-1] != '/')
filesdir += '/';
filenames.push_back(filesdir + ("platforms/" + filename));
filenames.push_back(filesdir + ("platforms/" + filename + ".xml"));
#endif
// open file..
tinyxml2::XMLDocument doc;
bool success = false;
for (const std::string & f : filenames) {
if (debug)
std::cout << "try to load platform file '" << f << "' ... ";
if (doc.LoadFile(f.c_str()) == tinyxml2::XML_SUCCESS) {
if (debug)
std::cout << "Success" << std::endl;
success = true;
break;
}
if (debug)
std::cout << doc.ErrorStr() << std::endl;
}
if (!success)
return false;
return loadFromXmlDocument(&doc);
}
static unsigned int xmlTextAsUInt(const tinyxml2::XMLElement* node, bool& error)
{
unsigned int retval = 0;
if (node->QueryUnsignedText(&retval) != tinyxml2::XML_SUCCESS)
error = true;
return retval;
}
bool Platform::loadFromXmlDocument(const tinyxml2::XMLDocument *doc)
{
const tinyxml2::XMLElement * const rootnode = doc->FirstChildElement();
if (!rootnode || std::strcmp(rootnode->Name(), "platform") != 0)
return false;
bool error = false;
for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) {
const char* name = node->Name();
if (std::strcmp(name, "default-sign") == 0) {
const char* str = node->GetText();
if (str)
defaultSign = *str;
else
error = true;
} else if (std::strcmp(name, "char_bit") == 0)
char_bit = xmlTextAsUInt(node, error);
else if (std::strcmp(name, "sizeof") == 0) {
for (const tinyxml2::XMLElement *sz = node->FirstChildElement(); sz; sz = sz->NextSiblingElement()) {
const char* szname = sz->Name();
if (std::strcmp(szname, "short") == 0)
sizeof_short = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "bool") == 0)
sizeof_bool = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "int") == 0)
sizeof_int = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "long") == 0)
sizeof_long = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "long-long") == 0)
sizeof_long_long = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "float") == 0)
sizeof_float = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "double") == 0)
sizeof_double = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "long-double") == 0)
sizeof_long_double = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "pointer") == 0)
sizeof_pointer = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "size_t") == 0)
sizeof_size_t = xmlTextAsUInt(sz, error);
else if (std::strcmp(szname, "wchar_t") == 0)
sizeof_wchar_t = xmlTextAsUInt(sz, error);
}
}
}
short_bit = char_bit * sizeof_short;
int_bit = char_bit * sizeof_int;
long_bit = char_bit * sizeof_long;
long_long_bit = char_bit * sizeof_long_long;
type = Type::File;
return !error;
}
std::string Platform::getLimitsDefines(bool c99) const
{
std::string s;
// climits / limits.h
s += "CHAR_BIT=";
s += std::to_string(char_bit);
s += ";SCHAR_MIN=";
s += std::to_string(min_value(char_bit));
s += ";SCHAR_MAX=";
s += std::to_string(max_value(char_bit));
s += ";UCHAR_MAX=";
s += std::to_string(max_value(char_bit+1));
s += ";CHAR_MIN=";
if (defaultSign == 'u')
s += std::to_string(min_value(char_bit));
else
s += std::to_string(0);
s += ";CHAR_MAX=";
if (defaultSign == 'u')
s += std::to_string(max_value(char_bit+1));
else
s += std::to_string(max_value(char_bit));
// TODO
//s += ";MB_LEN_MAX=";
s += ";SHRT_MIN=";
s += std::to_string(min_value(short_bit));
s += ";SHRT_MAX=";
s += std::to_string(max_value(short_bit));
s += ";USHRT_MAX=";
s += std::to_string(max_value(short_bit+1));
s += ";INT_MIN=";
s += "(-" + std::to_string(max_value(int_bit)) + " - 1)";
s += ";INT_MAX=";
s += std::to_string(max_value(int_bit));
s += ";UINT_MAX=";
s += std::to_string(max_value(int_bit+1));
s += ";LONG_MIN=";
s += "(-" + std::to_string(max_value(long_bit)) + "L - 1L)";
s += ";LONG_MAX=";
s += std::to_string(max_value(long_bit)) + "L";
s += ";ULONG_MAX=";
s += std::to_string(max_value_unsigned(long_bit)) + "UL";
if (c99) {
s += ";LLONG_MIN=";
s += "(-" + std::to_string(max_value(long_long_bit)) + "LL - 1LL)";
s += ";LLONG_MAX=";
s += std::to_string(max_value(long_long_bit)) + "LL";
s += ";ULLONG_MAX=";
s += std::to_string(max_value_unsigned(long_long_bit)) + "ULL";
}
// cstdint / stdint.h
// FIXME: these are currently hard-coded in std.cfg
/*
INTMAX_MIN
INTMAX_MAX
UINTMAX_MAX
INTN_MIN
INTN_MAX
UINTN_MAX
INT_LEASTN_MIN
INT_LEASTN_MAX
UINT_LEASTN_MAX
INT_FASTN_MIN
INT_FASTN_MAX
UINT_FASTN_MAX
INTPTR_MIN
INTPTR_MAX
UINTPTR_MAX
SIZE_MAX
PTRDIFF_MIN
PTRDIFF_MAX
SIG_ATOMIC_MIN
SIG_ATOMIC_MAX
WCHAR_MIN
WCHAR_MAX
WINT_MIN
WINT_MAX
// function-like macros
// implemented in std.cfg
INTMAX_C
UINTMAX_C
INTN_C
UINTN_C
*/
// cfloat / float.h
/*
// TODO: implement
FLT_RADIX
FLT_MANT_DIG
DBL_MANT_DIG
LDBL_MANT_DIG
FLT_DIG
DBL_DIG
LDBL_DIG
FLT_MIN_EXP
DBL_MIN_EXP
LDBL_MIN_EXP
FLT_MIN_10_EXP
DBL_MIN_10_EXP
LDBL_MIN_10_EXP
FLT_MAX_EXP
DBL_MAX_EXP
LDBL_MAX_EXP
FLT_MAX_10_EXP
DBL_MAX_10_EXP
LDBL_MAX_10_EXP
FLT_MAX
DBL_MAX
LDBL_MAX
FLT_EPSILON
DBL_EPSILON
LDBL_EPSILON
FLT_MIN
DBL_MIN
LDBL_MIN
FLT_ROUNDS
// C99 / C++11 only
FLT_EVAL_METHOD
DECIMAL_DIG
*/
return s;
}
std::string Platform::getLimitsDefines(Standards::cstd_t cstd) const
{
return getLimitsDefines(cstd >= Standards::cstd_t::C99);
}
std::string Platform::getLimitsDefines(Standards::cppstd_t cppstd) const
{
return getLimitsDefines(cppstd >= Standards::cppstd_t::CPP11);
}
| null |
895 | cpp | cppcheck | analyzer.h | lib/analyzer.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef analyzerH
#define analyzerH
#include "config.h"
#include "mathlib.h"
#include <cstdint>
#include <string>
#include <type_traits>
#include <vector>
class Token;
template<class T>
class ValuePtr;
struct Analyzer {
struct Action {
Action() = default;
Action(const Action&) = default;
Action& operator=(const Action& rhs) & = default;
template<class T,
REQUIRES("T must be convertible to unsigned int", std::is_convertible<T, unsigned int> ),
REQUIRES("T must not be a bool", !std::is_same<T, bool> )>
// NOLINTNEXTLINE(google-explicit-constructor)
Action(T f) : mFlag(f) // cppcheck-suppress noExplicitConstructor
{}
enum : std::uint16_t {
None = 0,
Read = (1 << 0),
Write = (1 << 1),
Invalid = (1 << 2),
Inconclusive = (1 << 3),
Match = (1 << 4),
Idempotent = (1 << 5),
Incremental = (1 << 6),
SymbolicMatch = (1 << 7),
Internal = (1 << 8),
};
void set(unsigned int f, bool state = true) {
mFlag = state ? mFlag | f : mFlag & ~f;
}
bool get(unsigned int f) const {
return ((mFlag & f) != 0);
}
bool isRead() const {
return get(Read);
}
bool isWrite() const {
return get(Write);
}
bool isInvalid() const {
return get(Invalid);
}
bool isInconclusive() const {
return get(Inconclusive);
}
bool isNone() const {
return mFlag == None;
}
bool isModified() const {
return isWrite() || isInvalid();
}
bool isIdempotent() const {
return get(Idempotent);
}
bool isIncremental() const {
return get(Incremental);
}
bool isSymbolicMatch() const {
return get(SymbolicMatch);
}
bool isInternal() const {
return get(Internal);
}
bool matches() const {
return get(Match);
}
Action& operator|=(Action a) {
set(a.mFlag);
return *this;
}
friend Action operator|(Action a, Action b) {
a |= b;
return a;
}
friend bool operator==(Action a, Action b) {
return a.mFlag == b.mFlag;
}
friend bool operator!=(Action a, Action b) {
return a.mFlag != b.mFlag;
}
private:
unsigned int mFlag{};
};
enum class Terminate : std::uint8_t { None, Bail, Escape, Modified, Inconclusive, Conditional };
struct Result {
explicit Result(Action action = Action::None, Terminate terminate = Terminate::None)
: action(action), terminate(terminate)
{}
Action action;
Terminate terminate;
void update(Result rhs) {
if (terminate == Terminate::None)
terminate = rhs.terminate;
action |= rhs.action;
}
};
enum class Direction : std::uint8_t { Forward, Reverse };
struct Assume {
enum Flags : std::uint8_t {
None = 0,
Quiet = (1 << 0),
Absolute = (1 << 1),
ContainerEmpty = (1 << 2),
};
};
enum class Evaluate : std::uint8_t { Integral, ContainerEmpty };
/// Analyze a token
virtual Action analyze(const Token* tok, Direction d) const = 0;
/// Update the state of the value
virtual void update(Token* tok, Action a, Direction d) = 0;
/// Try to evaluate the value of a token(most likely a condition)
virtual std::vector<MathLib::bigint> evaluate(Evaluate e, const Token* tok, const Token* ctx = nullptr) const = 0;
std::vector<MathLib::bigint> evaluate(const Token* tok, const Token* ctx = nullptr) const
{
return evaluate(Evaluate::Integral, tok, ctx);
}
/// Lower any values to possible
virtual bool lowerToPossible() = 0;
/// Lower any values to inconclusive
virtual bool lowerToInconclusive() = 0;
/// If the analysis is unsure whether to update a scope, this will return true if the analysis should bifurcate the scope
virtual bool updateScope(const Token* endBlock, bool modified) const = 0;
/// If the value is conditional
virtual bool isConditional() const = 0;
/// If analysis should stop on the condition
virtual bool stopOnCondition(const Token* condTok) const = 0;
/// The condition that will be assumed during analysis
virtual void assume(const Token* tok, bool state, unsigned int flags = 0) = 0;
/// Update the state of the program at the token
virtual void updateState(const Token* tok) = 0;
/// Return analyzer for expression at token
virtual ValuePtr<Analyzer> reanalyze(Token* tok, const std::string& msg = emptyString) const = 0;
virtual bool invalid() const {
return false;
}
virtual ~Analyzer() = default;
Analyzer(const Analyzer&) = default;
protected:
Analyzer() = default;
};
#endif
| null |
896 | cpp | cppcheck | checkautovariables.h | lib/checkautovariables.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkautovariablesH
#define checkautovariablesH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "tokenize.h"
#include <string>
#include <set>
class Settings;
class Token;
class ErrorLogger;
class Variable;
namespace ValueFlow {
class Value;
}
/// @addtogroup Checks
/** @brief Various small checks for automatic variables */
/// @{
class CPPCHECKLIB CheckAutoVariables : public Check {
public:
/** This constructor is used when registering the CheckClass */
CheckAutoVariables() : Check(myName()) {}
private:
/** This constructor is used when running checks. */
CheckAutoVariables(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckAutoVariables checkAutoVariables(&tokenizer, &tokenizer.getSettings(), errorLogger);
checkAutoVariables.assignFunctionArg();
checkAutoVariables.checkVarLifetime();
checkAutoVariables.autoVariables();
}
/** assign function argument */
void assignFunctionArg();
/** Check auto variables */
void autoVariables();
/**
* Check variable assignment.. value must be changed later or there will be a error reported
* @return true if error is reported */
bool checkAutoVariableAssignment(const Token *expr, bool inconclusive, const Token *startToken = nullptr);
void checkVarLifetime();
void checkVarLifetimeScope(const Token * start, const Token * end);
void errorAutoVariableAssignment(const Token *tok, bool inconclusive);
void errorReturnDanglingLifetime(const Token *tok, const ValueFlow::Value* val);
void errorInvalidLifetime(const Token *tok, const ValueFlow::Value* val);
void errorDanglngLifetime(const Token *tok, const ValueFlow::Value *val);
void errorDanglingTemporaryLifetime(const Token* tok, const ValueFlow::Value* val, const Token* tempTok);
void errorReturnReference(const Token* tok, ErrorPath errorPath, bool inconclusive);
void errorDanglingReference(const Token *tok, const Variable *var, ErrorPath errorPath);
void errorDanglingTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive);
void errorReturnTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive);
void errorInvalidDeallocation(const Token *tok, const ValueFlow::Value *val);
void errorUselessAssignmentArg(const Token *tok);
void errorUselessAssignmentPtrArg(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckAutoVariables c(nullptr,settings,errorLogger);
c.errorAutoVariableAssignment(nullptr, false);
c.errorReturnReference(nullptr, ErrorPath{}, false);
c.errorDanglingReference(nullptr, nullptr, ErrorPath{});
c.errorReturnTempReference(nullptr, ErrorPath{}, false);
c.errorDanglingTempReference(nullptr, ErrorPath{}, false);
c.errorInvalidDeallocation(nullptr, nullptr);
c.errorUselessAssignmentArg(nullptr);
c.errorUselessAssignmentPtrArg(nullptr);
c.errorReturnDanglingLifetime(nullptr, nullptr);
c.errorInvalidLifetime(nullptr, nullptr);
c.errorDanglngLifetime(nullptr, nullptr);
c.errorDanglingTemporaryLifetime(nullptr, nullptr, nullptr);
}
static std::string myName() {
return "Auto Variables";
}
std::string classInfo() const override {
return "A pointer to a variable is only valid as long as the variable is in scope.\n"
"Check:\n"
"- returning a pointer to auto or temporary variable\n"
"- assigning address of an variable to an effective parameter of a function\n"
"- returning reference to local/temporary variable\n"
"- returning address of function parameter\n"
"- suspicious assignment of pointer argument\n"
"- useless assignment of function argument\n";
}
/** returns true if tokvalue has already been diagnosed */
bool diag(const Token* tokvalue);
std::set<const Token*> mDiagDanglingTemp;
};
/// @}
//---------------------------------------------------------------------------
#endif // checkautovariablesH
| null |
897 | cpp | cppcheck | suppressions.cpp | lib/suppressions.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "suppressions.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "filesettings.h"
#include "path.h"
#include "utils.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include <algorithm>
#include <cctype> // std::isdigit, std::isalnum, etc
#include <cstring>
#include <functional> // std::bind, std::placeholders
#include <sstream>
#include <utility>
#include "xml.h"
static const char ID_UNUSEDFUNCTION[] = "unusedFunction";
static const char ID_CHECKERSREPORT[] = "checkersReport";
SuppressionList::ErrorMessage SuppressionList::ErrorMessage::fromErrorMessage(const ::ErrorMessage &msg, const std::set<std::string> ¯oNames)
{
SuppressionList::ErrorMessage ret;
ret.hash = msg.hash;
ret.errorId = msg.id;
if (!msg.callStack.empty()) {
ret.setFileName(msg.callStack.back().getfile(false));
ret.lineNumber = msg.callStack.back().line;
} else {
ret.lineNumber = SuppressionList::Suppression::NO_LINE;
}
ret.certainty = msg.certainty;
ret.symbolNames = msg.symbolNames();
ret.macroNames = macroNames;
return ret;
}
static bool isAcceptedErrorIdChar(char c)
{
switch (c) {
case '_':
case '-':
case '.':
case '*':
return true;
default:
return c > 0 && std::isalnum(c);
}
}
std::string SuppressionList::parseFile(std::istream &istr)
{
// Change '\r' to '\n' in the istr
std::string filedata;
std::string line;
while (std::getline(istr, line))
filedata += line + "\n";
std::replace(filedata.begin(), filedata.end(), '\r', '\n');
// Parse filedata..
std::istringstream istr2(filedata);
while (std::getline(istr2, line)) {
// Skip empty lines
if (line.empty())
continue;
std::string::size_type pos = 0;
while (pos < line.size() && std::isspace(line[pos]))
++pos;
if (pos == line.size())
continue;
// Skip comments
if (line[pos] == '#')
continue;
if (pos < line.size() - 1 && line[pos] == '/' && line[pos + 1] == '/')
continue;
const std::string errmsg(addSuppressionLine(line));
if (!errmsg.empty())
return errmsg;
}
return "";
}
std::string SuppressionList::parseXmlFile(const char *filename)
{
tinyxml2::XMLDocument doc;
const tinyxml2::XMLError error = doc.LoadFile(filename);
if (error != tinyxml2::XML_SUCCESS)
return std::string("failed to load suppressions XML '") + filename + "' (" + tinyxml2::XMLDocument::ErrorIDToName(error) + ").";
const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement();
if (!rootnode)
return std::string("failed to load suppressions XML '") + filename + "' (no root node found).";
// TODO: check for proper root node 'suppressions'
for (const tinyxml2::XMLElement * e = rootnode->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "suppress") != 0)
return std::string("invalid suppression xml file '") + filename + "', expected 'suppress' element but got a '" + e->Name() + "'.";
Suppression s;
for (const tinyxml2::XMLElement * e2 = e->FirstChildElement(); e2; e2 = e2->NextSiblingElement()) {
const char *name = e2->Name();
const char *text = empty_if_null(e2->GetText());
if (std::strcmp(name, "id") == 0)
s.errorId = text;
else if (std::strcmp(name, "fileName") == 0)
s.fileName = text;
else if (std::strcmp(name, "lineNumber") == 0)
s.lineNumber = strToInt<int>(text);
else if (std::strcmp(name, "symbolName") == 0)
s.symbolName = text;
else if (*text && std::strcmp(name, "hash") == 0)
s.hash = strToInt<std::size_t>(text);
else
return std::string("unknown element '") + name + "' in suppressions XML '" + filename + "', expected id/fileName/lineNumber/symbolName/hash.";
}
const std::string err = addSuppression(std::move(s));
if (!err.empty())
return err;
}
return "";
}
std::vector<SuppressionList::Suppression> SuppressionList::parseMultiSuppressComment(const std::string &comment, std::string *errorMessage)
{
std::vector<Suppression> suppressions;
// If this function is called we assume that comment starts with "cppcheck-suppress[".
const std::string::size_type start_position = comment.find('[');
const std::string::size_type end_position = comment.find(']', start_position);
if (end_position == std::string::npos) {
if (errorMessage && errorMessage->empty())
*errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]";
return suppressions;
}
// parse all suppressions
for (std::string::size_type pos = start_position; pos < end_position;) {
const std::string::size_type pos1 = pos + 1;
pos = comment.find(',', pos1);
const std::string::size_type pos2 = (pos < end_position) ? pos : end_position;
if (pos1 == pos2)
continue;
Suppression s;
std::istringstream iss(comment.substr(pos1, pos2-pos1));
iss >> s.errorId;
if (!iss) {
if (errorMessage && errorMessage->empty())
*errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]";
suppressions.clear();
return suppressions;
}
const std::string symbolNameString = "symbolName=";
while (iss) {
std::string word;
iss >> word;
if (!iss)
break;
if (word.find_first_not_of("+-*/%#;") == std::string::npos)
break;
if (startsWith(word, symbolNameString)) {
s.symbolName = word.substr(symbolNameString.size());
} else {
if (errorMessage && errorMessage->empty())
*errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]";
suppressions.clear();
return suppressions;
}
}
suppressions.push_back(std::move(s));
}
return suppressions;
}
std::string SuppressionList::addSuppressionLine(const std::string &line)
{
std::istringstream lineStream;
SuppressionList::Suppression suppression;
// Strip any end of line comments
std::string::size_type endpos = std::min(line.find('#'), line.find("//"));
if (endpos != std::string::npos) {
while (endpos > 0 && std::isspace(line[endpos-1])) {
endpos--;
}
lineStream.str(line.substr(0, endpos));
} else {
lineStream.str(line);
}
if (std::getline(lineStream, suppression.errorId, ':')) {
if (std::getline(lineStream, suppression.fileName)) {
// If there is not a dot after the last colon in "file" then
// the colon is a separator and the contents after the colon
// is a line number..
// Get position of last colon
const std::string::size_type pos = suppression.fileName.rfind(':');
// if a colon is found and there is no dot after it..
if (pos != std::string::npos &&
suppression.fileName.find('.', pos) == std::string::npos) {
// Try to parse out the line number
try {
std::istringstream istr1(suppression.fileName.substr(pos+1));
istr1 >> suppression.lineNumber;
} catch (...) {
suppression.lineNumber = SuppressionList::Suppression::NO_LINE;
}
if (suppression.lineNumber != SuppressionList::Suppression::NO_LINE) {
suppression.fileName.erase(pos);
}
}
}
}
suppression.fileName = Path::simplifyPath(suppression.fileName);
return addSuppression(std::move(suppression));
}
std::string SuppressionList::addSuppression(SuppressionList::Suppression suppression)
{
// Check if suppression is already in list
auto foundSuppression = std::find_if(mSuppressions.begin(), mSuppressions.end(),
std::bind(&Suppression::isSameParameters, &suppression, std::placeholders::_1));
if (foundSuppression != mSuppressions.end()) {
// Update matched state of existing global suppression
if (!suppression.isLocal() && suppression.matched)
foundSuppression->matched = suppression.matched;
return "";
}
// Check that errorId is valid..
if (suppression.errorId.empty() && suppression.hash == 0)
return "Failed to add suppression. No id.";
for (std::string::size_type pos = 0; pos < suppression.errorId.length(); ++pos) {
if (!isAcceptedErrorIdChar(suppression.errorId[pos])) {
return "Failed to add suppression. Invalid id \"" + suppression.errorId + "\"";
}
if (pos == 0 && std::isdigit(suppression.errorId[pos])) {
return "Failed to add suppression. Invalid id \"" + suppression.errorId + "\"";
}
}
if (!isValidGlobPattern(suppression.errorId))
return "Failed to add suppression. Invalid glob pattern '" + suppression.errorId + "'.";
if (!isValidGlobPattern(suppression.fileName))
return "Failed to add suppression. Invalid glob pattern '" + suppression.fileName + "'.";
mSuppressions.push_back(std::move(suppression));
return "";
}
std::string SuppressionList::addSuppressions(std::list<Suppression> suppressions)
{
for (auto &newSuppression : suppressions) {
auto errmsg = addSuppression(std::move(newSuppression));
if (!errmsg.empty())
return errmsg;
}
return "";
}
void SuppressionList::ErrorMessage::setFileName(std::string s)
{
mFileName = Path::simplifyPath(std::move(s));
}
bool SuppressionList::Suppression::parseComment(std::string comment, std::string *errorMessage)
{
if (comment.size() < 2)
return false;
if (comment.find(';') != std::string::npos)
comment.erase(comment.find(';'));
if (comment.find("//", 2) != std::string::npos)
comment.erase(comment.find("//",2));
if (comment.compare(comment.size() - 2, 2, "*/") == 0)
comment.erase(comment.size() - 2, 2);
const std::set<std::string> cppchecksuppress{
"cppcheck-suppress",
"cppcheck-suppress-begin",
"cppcheck-suppress-end",
"cppcheck-suppress-file",
"cppcheck-suppress-macro"
};
std::istringstream iss(comment.substr(2));
std::string word;
iss >> word;
if (!cppchecksuppress.count(word))
return false;
iss >> errorId;
if (!iss)
return false;
const std::string symbolNameString = "symbolName=";
while (iss) {
iss >> word;
if (!iss)
break;
if (word.find_first_not_of("+-*/%#;") == std::string::npos)
break;
if (startsWith(word, symbolNameString))
symbolName = word.substr(symbolNameString.size());
else if (errorMessage && errorMessage->empty())
*errorMessage = "Bad suppression attribute '" + word + "'. You can write comments in the comment after a ; or //. Valid suppression attributes; symbolName=sym";
}
return true;
}
bool SuppressionList::Suppression::isSuppressed(const SuppressionList::ErrorMessage &errmsg) const
{
if (hash > 0 && hash != errmsg.hash)
return false;
if (!errorId.empty() && !matchglob(errorId, errmsg.errorId))
return false;
if (type == SuppressionList::Type::macro) {
if (errmsg.macroNames.count(macroName) == 0)
return false;
} else {
if (!fileName.empty() && !matchglob(fileName, errmsg.getFileName()))
return false;
if ((SuppressionList::Type::unique == type) && (lineNumber != NO_LINE) && (lineNumber != errmsg.lineNumber)) {
if (!thisAndNextLine || lineNumber + 1 != errmsg.lineNumber)
return false;
}
if ((SuppressionList::Type::block == type) && ((errmsg.lineNumber < lineBegin) || (errmsg.lineNumber > lineEnd)))
return false;
}
if (!symbolName.empty()) {
for (std::string::size_type pos = 0; pos < errmsg.symbolNames.size();) {
const std::string::size_type pos2 = errmsg.symbolNames.find('\n',pos);
std::string symname;
if (pos2 == std::string::npos) {
symname = errmsg.symbolNames.substr(pos);
pos = pos2;
} else {
symname = errmsg.symbolNames.substr(pos,pos2-pos);
pos = pos2+1;
}
if (matchglob(symbolName, symname))
return true;
}
return false;
}
return true;
}
bool SuppressionList::Suppression::isMatch(const SuppressionList::ErrorMessage &errmsg)
{
if (!isSuppressed(errmsg))
return false;
matched = true;
checked = true;
return true;
}
// cppcheck-suppress unusedFunction - used by GUI only
std::string SuppressionList::Suppression::getText() const
{
std::string ret;
if (!errorId.empty())
ret = errorId;
if (!fileName.empty())
ret += " fileName=" + fileName;
if (lineNumber != NO_LINE)
ret += " lineNumber=" + std::to_string(lineNumber);
if (!symbolName.empty())
ret += " symbolName=" + symbolName;
if (hash > 0)
ret += " hash=" + std::to_string(hash);
if (startsWith(ret," "))
return ret.substr(1);
return ret;
}
bool SuppressionList::isSuppressed(const SuppressionList::ErrorMessage &errmsg, bool global)
{
const bool unmatchedSuppression(errmsg.errorId == "unmatchedSuppression");
bool returnValue = false;
for (Suppression &s : mSuppressions) {
if (!global && !s.isLocal())
continue;
if (unmatchedSuppression && s.errorId != errmsg.errorId)
continue;
if (s.isMatch(errmsg))
returnValue = true;
}
return returnValue;
}
bool SuppressionList::isSuppressedExplicitly(const SuppressionList::ErrorMessage &errmsg, bool global)
{
for (Suppression &s : mSuppressions) {
if (!global && !s.isLocal())
continue;
if (s.errorId != errmsg.errorId) // Error id must match exactly
continue;
if (s.isMatch(errmsg))
return true;
}
return false;
}
bool SuppressionList::isSuppressed(const ::ErrorMessage &errmsg, const std::set<std::string>& macroNames)
{
if (mSuppressions.empty())
return false;
return isSuppressed(SuppressionList::ErrorMessage::fromErrorMessage(errmsg, macroNames));
}
void SuppressionList::dump(std::ostream & out) const
{
out << " <suppressions>" << std::endl;
for (const Suppression &suppression : mSuppressions) {
out << " <suppression";
out << " errorId=\"" << ErrorLogger::toxml(suppression.errorId) << '"';
if (!suppression.fileName.empty())
out << " fileName=\"" << ErrorLogger::toxml(suppression.fileName) << '"';
if (suppression.lineNumber != Suppression::NO_LINE)
out << " lineNumber=\"" << suppression.lineNumber << '"';
if (!suppression.symbolName.empty())
out << " symbolName=\"" << ErrorLogger::toxml(suppression.symbolName) << '\"';
if (suppression.hash > 0)
out << " hash=\"" << suppression.hash << '\"';
if (suppression.lineBegin != Suppression::NO_LINE)
out << " lineBegin=\"" << suppression.lineBegin << '"';
if (suppression.lineEnd != Suppression::NO_LINE)
out << " lineEnd=\"" << suppression.lineEnd << '"';
if (suppression.type == SuppressionList::Type::file)
out << " type=\"file\"";
else if (suppression.type == SuppressionList::Type::block)
out << " type=\"block\"";
else if (suppression.type == SuppressionList::Type::blockBegin)
out << " type=\"blockBegin\"";
else if (suppression.type == SuppressionList::Type::blockEnd)
out << " type=\"blockEnd\"";
else if (suppression.type == SuppressionList::Type::macro)
out << " type=\"macro\"";
out << " />" << std::endl;
}
out << " </suppressions>" << std::endl;
}
std::list<SuppressionList::Suppression> SuppressionList::getUnmatchedLocalSuppressions(const FileWithDetails &file, const bool unusedFunctionChecking) const
{
std::list<Suppression> result;
for (const Suppression &s : mSuppressions) {
if (s.matched || ((s.lineNumber != Suppression::NO_LINE) && !s.checked))
continue;
if (s.type == SuppressionList::Type::macro)
continue;
if (s.hash > 0)
continue;
if (s.errorId == ID_CHECKERSREPORT)
continue;
if (!unusedFunctionChecking && s.errorId == ID_UNUSEDFUNCTION)
continue;
if (!s.isLocal() || s.fileName != file.spath())
continue;
result.push_back(s);
}
return result;
}
std::list<SuppressionList::Suppression> SuppressionList::getUnmatchedGlobalSuppressions(const bool unusedFunctionChecking) const
{
std::list<Suppression> result;
for (const Suppression &s : mSuppressions) {
if (s.matched || ((s.lineNumber != Suppression::NO_LINE) && !s.checked))
continue;
if (s.hash > 0)
continue;
if (!unusedFunctionChecking && s.errorId == ID_UNUSEDFUNCTION)
continue;
if (s.errorId == ID_CHECKERSREPORT)
continue;
if (s.isLocal())
continue;
result.push_back(s);
}
return result;
}
const std::list<SuppressionList::Suppression> &SuppressionList::getSuppressions() const
{
return mSuppressions;
}
void SuppressionList::markUnmatchedInlineSuppressionsAsChecked(const Tokenizer &tokenizer) {
int currLineNr = -1;
int currFileIdx = -1;
for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) {
if (currFileIdx != tok->fileIndex() || currLineNr != tok->linenr()) {
currLineNr = tok->linenr();
currFileIdx = tok->fileIndex();
for (auto &suppression : mSuppressions) {
if (suppression.type == SuppressionList::Type::unique) {
if (!suppression.checked && (suppression.lineNumber == currLineNr) && (suppression.fileName == tokenizer.list.file(tok))) {
suppression.checked = true;
}
} else if (suppression.type == SuppressionList::Type::block) {
if ((!suppression.checked && (suppression.lineBegin <= currLineNr) && (suppression.lineEnd >= currLineNr) && (suppression.fileName == tokenizer.list.file(tok)))) {
suppression.checked = true;
}
} else if (!suppression.checked && suppression.fileName == tokenizer.list.file(tok)) {
suppression.checked = true;
}
}
}
}
}
bool SuppressionList::reportUnmatchedSuppressions(const std::list<SuppressionList::Suppression> &unmatched, ErrorLogger &errorLogger)
{
bool err = false;
// Report unmatched suppressions
for (const SuppressionList::Suppression &s : unmatched) {
// don't report "unmatchedSuppression" as unmatched
if (s.errorId == "unmatchedSuppression")
continue;
// check if this unmatched suppression is suppressed
bool suppressed = false;
for (const SuppressionList::Suppression &s2 : unmatched) {
if (s2.errorId == "unmatchedSuppression") {
if ((s2.fileName.empty() || s2.fileName == "*" || s2.fileName == s.fileName) &&
(s2.lineNumber == SuppressionList::Suppression::NO_LINE || s2.lineNumber == s.lineNumber)) {
suppressed = true;
break;
}
}
}
if (suppressed)
continue;
std::list<::ErrorMessage::FileLocation> callStack;
if (!s.fileName.empty())
callStack.emplace_back(s.fileName, s.lineNumber, 0);
errorLogger.reportErr(::ErrorMessage(std::move(callStack), emptyString, Severity::information, "Unmatched suppression: " + s.errorId, "unmatchedSuppression", Certainty::normal));
err = true;
}
return err;
}
| null |
898 | cpp | cppcheck | checkclass.cpp | lib/checkclass.cpp | null | /*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#include "checkclass.h"
#include "astutils.h"
#include "library.h"
#include "settings.h"
#include "standards.h"
#include "symboldatabase.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "platform.h"
#include "token.h"
#include "tokenize.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueflow.h"
#include <algorithm>
#include <cctype>
#include <cstring>
#include <iterator>
#include <utility>
#include <unordered_map>
#include "xml.h"
//---------------------------------------------------------------------------
// Register CheckClass..
namespace {
CheckClass instance;
}
static const CWE CWE398(398U); // Indicator of Poor Code Quality
static const CWE CWE404(404U); // Improper Resource Shutdown or Release
static const CWE CWE665(665U); // Improper Initialization
static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
static const CWE CWE762(762U); // Mismatched Memory Management Routines
static const CWE CWE_ONE_DEFINITION_RULE(758U);
static const char * getFunctionTypeName(Function::Type type)
{
switch (type) {
case Function::eConstructor:
return "constructor";
case Function::eCopyConstructor:
return "copy constructor";
case Function::eMoveConstructor:
return "move constructor";
case Function::eDestructor:
return "destructor";
case Function::eFunction:
return "function";
case Function::eOperatorEqual:
return "operator=";
case Function::eLambda:
return "lambda";
}
return "";
}
static bool isVariableCopyNeeded(const Variable &var, Function::Type type)
{
bool isOpEqual = false;
switch (type) {
case Function::eOperatorEqual:
isOpEqual = true;
break;
case Function::eCopyConstructor:
case Function::eMoveConstructor:
break;
default:
return true;
}
return (!var.hasDefault() || isOpEqual) && // default init does not matter for operator=
(var.isPointer() ||
(var.type() && var.type()->needInitialization == Type::NeedInitialization::True) ||
(var.valueType() && var.valueType()->type >= ValueType::Type::CHAR));
}
static bool isVclTypeInit(const Type *type)
{
if (!type)
return false;
return std::any_of(type->derivedFrom.begin(), type->derivedFrom.end(), [&](const Type::BaseInfo& baseInfo) {
if (!baseInfo.type)
return true;
if (isVclTypeInit(baseInfo.type))
return true;
return false;
});
}
//---------------------------------------------------------------------------
CheckClass::CheckClass(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger),
mSymbolDatabase(tokenizer?tokenizer->getSymbolDatabase():nullptr)
{}
//---------------------------------------------------------------------------
// ClassCheck: Check that all class constructors are ok.
//---------------------------------------------------------------------------
void CheckClass::constructors()
{
const bool printStyle = mSettings->severity.isEnabled(Severity::style);
const bool printWarnings = mSettings->severity.isEnabled(Severity::warning);
if (!printStyle && !printWarnings && !mSettings->isPremiumEnabled("uninitMemberVar"))
return;
logChecker("CheckClass::checkConstructors"); // style,warning
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
if (mSettings->hasLib("vcl") && isVclTypeInit(scope->definedType))
continue;
const bool unusedTemplate = Token::simpleMatch(scope->classDef->previous(), ">");
const bool usedInUnion = std::any_of(mSymbolDatabase->scopeList.cbegin(), mSymbolDatabase->scopeList.cend(), [&](const Scope& unionScope) {
if (unionScope.type != Scope::eUnion)
return false;
return std::any_of(unionScope.varlist.cbegin(), unionScope.varlist.cend(), [&](const Variable& var) {
return var.type() && var.type()->classScope == scope;
});
});
// There are no constructors.
if (scope->numConstructors == 0 && printStyle && !usedInUnion) {
// If there is a private variable, there should be a constructor..
int needInit = 0, haveInit = 0;
std::vector<const Variable*> uninitVars;
for (const Variable &var : scope->varlist) {
if (var.isPrivate() && !var.isStatic() &&
(!var.isClass() || (var.type() && var.type()->needInitialization == Type::NeedInitialization::True))) {
++needInit;
if (!var.isInit() && !var.hasDefault() && var.nameToken()->scope() == scope) // don't warn for anonymous union members
uninitVars.emplace_back(&var);
else
++haveInit;
}
}
if (needInit > haveInit) {
if (haveInit == 0)
noConstructorError(scope->classDef, scope->className, scope->classDef->str() == "struct");
else
for (const Variable* uv : uninitVars)
uninitVarError(uv->typeStartToken(), uv->scope()->className, uv->name());
}
}
if (!printWarnings)
continue;
// #3196 => bailout if there are nested unions
// TODO: handle union variables better
{
const bool bailout = std::any_of(scope->nestedList.cbegin(), scope->nestedList.cend(), [](const Scope* nestedScope) {
return nestedScope->type == Scope::eUnion;
});
if (bailout)
continue;
}
std::vector<Usage> usageList = createUsageList(scope);
for (const Function &func : scope->functionList) {
if (!(func.isConstructor() && (func.hasBody() || (func.isDefault() && func.type == Function::eConstructor))) &&
!(func.type == Function::eOperatorEqual && func.hasBody()))
continue; // a defaulted constructor does not initialize primitive members
// Bail: If initializer list is not recognized as a variable or type then skip since parsing is incomplete
if (unusedTemplate && func.type == Function::eConstructor) {
const Token *initList = func.constructorMemberInitialization();
if (Token::Match(initList, ": %name% (") && initList->next()->tokType() == Token::eName)
break;
}
// Mark all variables not used
clearAllVar(usageList);
// Variables with default initializers
for (Usage &usage : usageList) {
const Variable& var = *usage.var;
// check for C++11 initializer
if (var.hasDefault() && func.type != Function::eOperatorEqual && func.type != Function::eCopyConstructor) { // variable still needs to be copied
usage.init = true;
}
}
std::list<const Function *> callstack;
initializeVarList(func, callstack, scope, usageList);
// Assign 1 union member => assign all union members
for (const Usage &usage : usageList) {
const Variable& var = *usage.var;
if (!usage.assign && !usage.init)
continue;
const Scope* varScope1 = var.nameToken()->scope();
while (varScope1->type == Scope::ScopeType::eStruct)
varScope1 = varScope1->nestedIn;
if (varScope1->type == Scope::ScopeType::eUnion) {
for (Usage &usage2 : usageList) {
const Variable& var2 = *usage2.var;
if (usage2.assign || usage2.init || var2.isStatic())
continue;
const Scope* varScope2 = var2.nameToken()->scope();
while (varScope2->type == Scope::ScopeType::eStruct)
varScope2 = varScope2->nestedIn;
if (varScope1 == varScope2)
usage2.assign = true;
}
}
}
// Check if any variables are uninitialized
for (const Usage &usage : usageList) {
const Variable& var = *usage.var;
if (usage.assign || usage.init || var.isStatic())
continue;
if (var.valueType() && var.valueType()->pointer == 0 && var.type() && var.type()->needInitialization == Type::NeedInitialization::False && var.type()->derivedFrom.empty())
continue;
if (var.isConst() && func.isOperator()) // We can't set const members in assignment operator
continue;
// Check if this is a class constructor
if (!var.isPointer() && !var.isPointerArray() && var.isClass() && func.type == Function::eConstructor) {
// Unknown type so assume it is initialized
if (!var.type()) {
if (var.isStlType() && var.valueType() && var.valueType()->containerTypeToken && var.getTypeName() == "std::array") {
const Token* ctt = var.valueType()->containerTypeToken;
if (!ctt->isStandardType() &&
(!ctt->type() || ctt->type()->needInitialization != Type::NeedInitialization::True) &&
!mSettings->library.podtype(ctt->str())) // TODO: handle complex type expression
continue;
}
else
continue;
}
// Known type that doesn't need initialization or
// known type that has member variables of an unknown type
else if (var.type()->needInitialization != Type::NeedInitialization::True)
continue;
}
// Check if type can't be copied
if (!var.isPointer() && !var.isPointerArray() && var.typeScope()) {
if (func.type == Function::eMoveConstructor) {
if (canNotMove(var.typeScope()))
continue;
} else {
if (canNotCopy(var.typeScope()))
continue;
}
}
// Is there missing member copy in copy/move constructor or assignment operator?
bool missingCopy = false;
// Don't warn about unknown types in copy constructors since we
// don't know if they can be copied or not..
if (!isVariableCopyNeeded(var, func.type)) {
if (!printInconclusive)
continue;
missingCopy = true;
}
// It's non-static and it's not initialized => error
if (func.type == Function::eOperatorEqual) {
const Token *operStart = func.arg;
bool classNameUsed = false;
for (const Token *operTok = operStart; operTok != operStart->link(); operTok = operTok->next()) {
if (operTok->str() == scope->className) {
classNameUsed = true;
break;
}
}
if (classNameUsed && mSettings->library.getTypeCheck("operatorEqVarError", var.getTypeName()) != Library::TypeCheck::suppress)
operatorEqVarError(func.token, scope->className, var.name(), missingCopy);
} else if (func.access != AccessControl::Private || mSettings->standards.cpp >= Standards::CPP11) {
// If constructor is not in scope then we maybe using a constructor from a different template specialization
if (!precedes(scope->bodyStart, func.tokenDef))
continue;
const Scope *varType = var.typeScope();
if (!varType || varType->type != Scope::eUnion) {
const bool derived = scope != var.scope();
if (func.type == Function::eConstructor &&
func.nestedIn && (func.nestedIn->numConstructors - func.nestedIn->numCopyOrMoveConstructors) > 1 &&
func.argCount() == 0 && func.functionScope &&
func.arg && func.arg->link()->next() == func.functionScope->bodyStart &&
func.functionScope->bodyStart->link() == func.functionScope->bodyStart->next()) {
// don't warn about user defined default constructor when there are other constructors
if (printInconclusive)
uninitVarError(func.token, func.access == AccessControl::Private, func.type, var.scope()->className, var.name(), derived, true);
} else if (missingCopy)
missingMemberCopyError(func.token, func.type, var.scope()->className, var.name());
else
uninitVarError(func.token, func.access == AccessControl::Private, func.type, var.scope()->className, var.name(), derived, false);
}
}
}
}
}
}
void CheckClass::checkExplicitConstructors()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("noExplicitConstructor"))
return;
logChecker("CheckClass::checkExplicitConstructors"); // style
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// Do not perform check, if the class/struct has not any constructors
if (scope->numConstructors == 0)
continue;
// Is class abstract? Maybe this test is over-simplification, but it will suffice for simple cases,
// and it will avoid false positives.
const bool isAbstractClass = std::any_of(scope->functionList.cbegin(), scope->functionList.cend(), [](const Function& func) {
return func.isPure();
});
// Abstract classes can't be instantiated. But if there is C++11
// "misuse" by derived classes then these constructors must be explicit.
if (isAbstractClass && mSettings->standards.cpp >= Standards::CPP11)
continue;
for (const Function &func : scope->functionList) {
// We are looking for constructors, which are meeting following criteria:
// 1) Constructor is declared with a single parameter
// 2) Constructor is not declared as explicit
// 3) It is not a copy/move constructor of non-abstract class
// 4) Constructor is not marked as delete (programmer can mark the default constructor as deleted, which is ok)
if (!func.isConstructor() || func.isDelete() || (!func.hasBody() && func.access == AccessControl::Private))
continue;
if (!func.isExplicit() &&
func.argCount() > 0 && func.minArgCount() < 2 &&
func.type != Function::eCopyConstructor &&
func.type != Function::eMoveConstructor &&
!(func.templateDef && Token::simpleMatch(func.argumentList.front().typeEndToken(), "...")) &&
func.argumentList.front().getTypeName() != "std::initializer_list") {
noExplicitConstructorError(func.tokenDef, scope->className, scope->type == Scope::eStruct);
}
}
}
}
static bool hasNonCopyableBase(const Scope *scope, bool *unknown)
{
// check if there is base class that is not copyable
for (const Type::BaseInfo &baseInfo : scope->definedType->derivedFrom) {
if (!baseInfo.type || !baseInfo.type->classScope) {
*unknown = true;
continue;
}
if (hasNonCopyableBase(baseInfo.type->classScope, unknown))
return true;
for (const Function &func : baseInfo.type->classScope->functionList) {
if (func.type != Function::eCopyConstructor)
continue;
if (func.access == AccessControl::Private || func.isDelete()) {
*unknown = false;
return true;
}
}
}
return false;
}
void CheckClass::copyconstructors()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckClass::checkCopyConstructors"); // warning
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
std::map<int, const Token*> allocatedVars;
for (const Function &func : scope->functionList) {
if (func.type != Function::eConstructor || !func.functionScope)
continue;
const Token* tok = func.token->linkAt(1);
for (const Token* const end = func.functionScope->bodyStart; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% ( new") ||
(Token::Match(tok, "%var% ( %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)))) {
const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope)
allocatedVars[tok->varId()] = tok;
}
}
for (const Token* const end = func.functionScope->bodyEnd; tok != end; tok = tok->next()) {
if (Token::Match(tok, "%var% = new") ||
(Token::Match(tok, "%var% = %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)))) {
const Variable* var = tok->variable();
if (var && var->isPointer() && var->scope() == scope && !var->isStatic())
allocatedVars[tok->varId()] = tok;
}
}
}
if (!allocatedVars.empty()) {
const Function *funcCopyCtor = nullptr;
const Function *funcOperatorEq = nullptr;
const Function *funcDestructor = nullptr;
for (const Function &func : scope->functionList) {
if (func.type == Function::eCopyConstructor)
funcCopyCtor = &func;
else if (func.type == Function::eOperatorEqual)
funcOperatorEq = &func;
else if (func.type == Function::eDestructor)
funcDestructor = &func;
}
if (!funcCopyCtor || funcCopyCtor->isDefault()) {
bool unknown = false;
if (!hasNonCopyableBase(scope, &unknown) && !unknown)
noCopyConstructorError(scope, funcCopyCtor, allocatedVars.cbegin()->second, unknown);
}
if (!funcOperatorEq || funcOperatorEq->isDefault()) {
bool unknown = false;
if (!hasNonCopyableBase(scope, &unknown) && !unknown)
noOperatorEqError(scope, funcOperatorEq, allocatedVars.cbegin()->second, unknown);
}
if (!funcDestructor || funcDestructor->isDefault()) {
const Token * mustDealloc = nullptr;
for (std::map<int, const Token*>::const_iterator it = allocatedVars.cbegin(); it != allocatedVars.cend(); ++it) {
if (!Token::Match(it->second, "%var% [(=] new %type%")) {
mustDealloc = it->second;
break;
}
if (it->second->valueType() && it->second->valueType()->isIntegral()) {
mustDealloc = it->second;
break;
}
const Variable *var = it->second->variable();
if (var && var->typeScope() && var->typeScope()->functionList.empty() && var->type()->derivedFrom.empty()) {
mustDealloc = it->second;
break;
}
}
if (mustDealloc)
noDestructorError(scope, funcDestructor, mustDealloc);
}
}
std::set<const Token*> copiedVars;
const Token* copyCtor = nullptr;
for (const Function &func : scope->functionList) {
if (func.type != Function::eCopyConstructor)
continue;
copyCtor = func.tokenDef;
if (!func.functionScope) {
allocatedVars.clear();
break;
}
const Token* tok = func.tokenDef->linkAt(1)->next();
if (tok->str()==":") {
tok=tok->next();
while (Token::Match(tok, "%name% (")) {
if (allocatedVars.find(tok->varId()) != allocatedVars.end()) {
if (tok->varId() && Token::Match(tok->tokAt(2), "%name% . %name% )"))
copiedVars.insert(tok);
else if (!Token::Match(tok->tokAt(2), "%any% )"))
allocatedVars.erase(tok->varId()); // Assume memory is allocated
}
tok = tok->linkAt(1)->tokAt(2);
}
}
for (tok = func.functionScope->bodyStart; tok != func.functionScope->bodyEnd; tok = tok->next()) {
if ((tok->isCpp() && Token::Match(tok, "%var% = new")) ||
(Token::Match(tok, "%var% = %name% (") && (mSettings->library.getAllocFuncInfo(tok->tokAt(2)) || mSettings->library.getReallocFuncInfo(tok->tokAt(2))))) {
allocatedVars.erase(tok->varId());
} else if (Token::Match(tok, "%var% = %name% . %name% ;") && allocatedVars.find(tok->varId()) != allocatedVars.end()) {
copiedVars.insert(tok);
}
}
break;
}
if (copyCtor && !copiedVars.empty()) {
for (const Token *cv : copiedVars)
copyConstructorShallowCopyError(cv, cv->str());
// throw error if count mismatch
/* FIXME: This doesn't work. See #4154
for (std::map<int, const Token*>::const_iterator i = allocatedVars.begin(); i != allocatedVars.end(); ++i) {
copyConstructorMallocError(copyCtor, i->second, i->second->str());
}
*/
}
}
}
/* This doesn't work. See #4154
void CheckClass::copyConstructorMallocError(const Token *cctor, const Token *alloc, const std::string& varname)
{
std::list<const Token*> callstack;
callstack.push_back(cctor);
callstack.push_back(alloc);
reportError(callstack, Severity::warning, "copyCtorNoAllocation", "Copy constructor does not allocate memory for member '" + varname + "' although memory has been allocated in other constructors.");
}
*/
void CheckClass::copyConstructorShallowCopyError(const Token *tok, const std::string& varname)
{
reportError(tok, Severity::warning, "copyCtorPointerCopying",
"$symbol:" + varname + "\nValue of pointer '$symbol', which points to allocated memory, is copied in copy constructor instead of allocating new memory.", CWE398, Certainty::normal);
}
static std::string noMemberErrorMessage(const Scope *scope, const char function[], bool isdefault)
{
const std::string &classname = scope ? scope->className : "class";
const std::string type = (scope && scope->type == Scope::eStruct) ? "Struct" : "Class";
const bool isDestructor = (function[0] == 'd');
std::string errmsg = "$symbol:" + classname + '\n';
if (isdefault) {
errmsg += type + " '$symbol' has dynamic memory/resource allocation(s). The " + function + " is explicitly defaulted but the default " + function + " does not work well.";
if (isDestructor)
errmsg += " It is recommended to define the " + std::string(function) + '.';
else
errmsg += " It is recommended to define or delete the " + std::string(function) + '.';
} else {
errmsg += type + " '$symbol' does not have a " + function + " which is recommended since it has dynamic memory/resource allocation(s).";
}
return errmsg;
}
void CheckClass::noCopyConstructorError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive)
{
reportError(alloc, Severity::warning, "noCopyConstructor", noMemberErrorMessage(scope, "copy constructor", isdefault), CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckClass::noOperatorEqError(const Scope *scope, bool isdefault, const Token *alloc, bool inconclusive)
{
reportError(alloc, Severity::warning, "noOperatorEq", noMemberErrorMessage(scope, "operator=", isdefault), CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckClass::noDestructorError(const Scope *scope, bool isdefault, const Token *alloc)
{
reportError(alloc, Severity::warning, "noDestructor", noMemberErrorMessage(scope, "destructor", isdefault), CWE398, Certainty::normal);
}
bool CheckClass::canNotCopy(const Scope *scope)
{
bool constructor = false;
bool publicAssign = false;
bool publicCopy = false;
for (const Function &func : scope->functionList) {
if (func.isConstructor())
constructor = true;
if (func.access != AccessControl::Public)
continue;
if (func.type == Function::eCopyConstructor) {
publicCopy = true;
break;
}
if (func.type == Function::eOperatorEqual) {
publicAssign = true;
break;
}
}
return constructor && !(publicAssign || publicCopy);
}
bool CheckClass::canNotMove(const Scope *scope)
{
bool constructor = false;
bool publicAssign = false;
bool publicCopy = false;
bool publicMove = false;
for (const Function &func : scope->functionList) {
if (func.isConstructor())
constructor = true;
if (func.access != AccessControl::Public)
continue;
if (func.type == Function::eCopyConstructor) {
publicCopy = true;
break;
}
if (func.type == Function::eMoveConstructor) {
publicMove = true;
break;
}
if (func.type == Function::eOperatorEqual) {
publicAssign = true;
break;
}
}
return constructor && !(publicAssign || publicCopy || publicMove);
}
static void getAllVariableMembers(const Scope *scope, std::vector<const Variable *>& varList)
{
std::transform(scope->varlist.cbegin(), scope->varlist.cend(), std::back_inserter(varList), [](const Variable& var) {
return &var;
});
if (scope->definedType) {
for (const Type::BaseInfo& baseInfo: scope->definedType->derivedFrom) {
if (scope->definedType == baseInfo.type)
continue;
const Scope *baseClass = baseInfo.type ? baseInfo.type->classScope : nullptr;
if (baseClass && baseClass->isClassOrStruct() && baseClass->numConstructors == 0)
getAllVariableMembers(baseClass, varList);
}
}
}
std::vector<CheckClass::Usage> CheckClass::createUsageList(const Scope *scope)
{
std::vector<Usage> ret;
std::vector<const Variable *> varlist;
getAllVariableMembers(scope, varlist);
ret.reserve(varlist.size());
std::transform(varlist.cbegin(), varlist.cend(), std::back_inserter(ret), [](const Variable* var) {
return Usage(var);
});
return ret;
}
void CheckClass::assignVar(std::vector<Usage> &usageList, nonneg int varid)
{
auto it = std::find_if(usageList.begin(), usageList.end(), [varid](const Usage& usage) {
return usage.var->declarationId() == varid;
});
if (it != usageList.end())
it->assign = true;
}
void CheckClass::assignVar(std::vector<Usage> &usageList, const Token* vartok)
{
if (vartok->varId() > 0) {
assignVar(usageList, vartok->varId());
return;
}
auto it = std::find_if(usageList.begin(), usageList.end(), [vartok](const Usage& usage) {
// FIXME: This is a workaround when varid is not set for a derived member
return usage.var->name() == vartok->str();
});
if (it != usageList.end())
it->assign = true;
}
void CheckClass::initVar(std::vector<Usage> &usageList, nonneg int varid)
{
auto it = std::find_if(usageList.begin(), usageList.end(), [varid](const Usage& usage) {
return usage.var->declarationId() == varid;
});
if (it != usageList.end())
it->init = true;
}
void CheckClass::assignAllVar(std::vector<Usage> &usageList)
{
for (Usage & i : usageList)
i.assign = true;
}
void CheckClass::assignAllVarsVisibleFromScope(std::vector<Usage>& usageList, const Scope* scope)
{
for (Usage& usage : usageList) {
if (usage.var->scope() == scope)
usage.assign = true;
}
// Iterate through each base class...
for (const Type::BaseInfo& i : scope->definedType->derivedFrom) {
const Type *derivedFrom = i.type;
if (derivedFrom && derivedFrom->classScope)
assignAllVarsVisibleFromScope(usageList, derivedFrom->classScope);
}
}
void CheckClass::clearAllVar(std::vector<Usage> &usageList)
{
for (Usage & i : usageList) {
i.assign = false;
i.init = false;
}
}
bool CheckClass::isBaseClassMutableMemberFunc(const Token *tok, const Scope *scope)
{
// Iterate through each base class...
for (const Type::BaseInfo & i : scope->definedType->derivedFrom) {
const Type *derivedFrom = i.type;
// Check if base class exists in database
if (derivedFrom && derivedFrom->classScope) {
const std::list<Function>& functionList = derivedFrom->classScope->functionList;
if (std::any_of(functionList.cbegin(), functionList.cend(), [&](const Function& func) {
return func.tokenDef->str() == tok->str() && !func.isStatic() && !func.isConst();
}))
return true;
if (isBaseClassMutableMemberFunc(tok, derivedFrom->classScope))
return true;
}
// Base class not found so assume it is in it.
else
return true;
}
return false;
}
void CheckClass::initializeVarList(const Function &func, std::list<const Function *> &callstack, const Scope *scope, std::vector<Usage> &usage) const
{
if (!func.functionScope)
return;
bool initList = func.isConstructor();
const Token *ftok = func.arg->link()->next();
int level = 0;
for (; ftok && ftok != func.functionScope->bodyEnd; ftok = ftok->next()) {
// Class constructor.. initializing variables like this
// clKalle::clKalle() : var(value) { }
if (initList) {
if (level == 0 && Token::Match(ftok, "%name% {|(") && Token::Match(ftok->linkAt(1), "}|) ,|{")) {
if (ftok->str() != func.name()) {
if (ftok->varId())
initVar(usage, ftok->varId());
else { // base class constructor
for (Usage& u : usage) {
if (u.var->scope() != scope) // assume that all variables are initialized in base class
u.init = true;
}
}
} else { // c++11 delegate constructor
const Function *member = ftok->function();
// member function not found => assume it initializes all members
if (!member) {
assignAllVar(usage);
return;
}
// recursive call
// assume that all variables are initialized
if (std::find(callstack.cbegin(), callstack.cend(), member) != callstack.cend()) {
/** @todo false negative: just bail */
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
}
// there is a called member function, but it has no implementation, so we assume it initializes everything
else {
assignAllVar(usage);
}
}
} else if (level != 0 && Token::Match(ftok, "%name% =")) // assignment in the initializer: var(value = x)
assignVar(usage, ftok->varId());
// Level handling
if (ftok->link() && Token::Match(ftok, "(|<"))
level++;
else if (ftok->str() == "{") {
if (level != 0 ||
(Token::Match(ftok->previous(), "%name%|>") && Token::Match(ftok->link(), "} ,|{")))
level++;
else
initList = false;
} else if (ftok->link() && Token::Match(ftok, ")|>|}"))
level--;
}
if (initList)
continue;
// Variable getting value from stream?
if (Token::Match(ftok, ">>|& %name%") && isLikelyStreamRead(ftok)) {
assignVar(usage, ftok->next()->varId());
}
// If assignment comes after an && or || this is really inconclusive because of short circuiting
if (Token::Match(ftok, "%oror%|&&"))
continue;
if (Token::simpleMatch(ftok, "( !"))
ftok = ftok->next();
// Using the operator= function to initialize all variables..
if (Token::Match(ftok->next(), "return| (| * this )| =")) {
assignAllVar(usage);
break;
}
// Using swap to assign all variables..
if (func.type == Function::eOperatorEqual && Token::Match(ftok, "[;{}] %name% (") && Token::Match(ftok->linkAt(2), ") . %name% ( *| this ) ;")) {
assignAllVar(usage);
break;
}
// Calling member variable function?
if (Token::Match(ftok->next(), "%var% . %name% (") && !(ftok->next()->valueType() && ftok->next()->valueType()->pointer)) {
if (std::any_of(scope->varlist.cbegin(), scope->varlist.cend(), [&](const Variable& var) {
return var.declarationId() == ftok->next()->varId();
}))
/** @todo false negative: we assume function changes variable state */
assignVar(usage, ftok->next()->varId());
ftok = ftok->tokAt(2);
}
if (!Token::Match(ftok->next(), "::| %name%") &&
!Token::Match(ftok->next(), "*| this . %name%") &&
!Token::Match(ftok->next(), "* %name% =") &&
!Token::Match(ftok->next(), "( * this ) . %name%") &&
!Token::Match(ftok->next(), "( * %name% ) =") &&
!Token::Match(ftok->next(), "* ( %name% ) ="))
continue;
// Goto the first token in this statement..
ftok = ftok->next();
// skip "return"
if (ftok->str() == "return")
ftok = ftok->next();
// Skip "( * this )"
if (Token::simpleMatch(ftok, "( * this ) .")) {
ftok = ftok->tokAt(5);
}
// Skip "this->"
if (Token::simpleMatch(ftok, "this ."))
ftok = ftok->tokAt(2);
// Skip "classname :: "
if (Token::Match(ftok, ":: %name%"))
ftok = ftok->next();
while (Token::Match(ftok, "%name% ::"))
ftok = ftok->tokAt(2);
// Clearing all variables..
if (Token::Match(ftok, "::| memset ( this ,")) {
assignAllVar(usage);
return;
}
// Ticket #7068
if (Token::Match(ftok, "::| memset ( &| this . %name%")) {
if (ftok->str() == "::")
ftok = ftok->next();
int offsetToMember = 4;
if (ftok->strAt(2) == "&")
++offsetToMember;
assignVar(usage, ftok->tokAt(offsetToMember)->varId());
ftok = ftok->linkAt(1);
continue;
}
// Clearing array..
if (Token::Match(ftok, "::| memset ( %name% ,")) {
if (ftok->str() == "::")
ftok = ftok->next();
assignVar(usage, ftok->tokAt(2)->varId());
ftok = ftok->linkAt(1);
continue;
}
// Calling member function?
if (Token::simpleMatch(ftok, "operator= (")) {
if (ftok->function()) {
const Function *member = ftok->function();
// recursive call
// assume that all variables are initialized
if (std::find(callstack.cbegin(), callstack.cend(), member) != callstack.cend()) {
/** @todo false negative: just bail */
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
}
// assume that a base class call to operator= assigns all its base members (but not more)
else if (func.tokenDef->str() == ftok->str() && isBaseClassMutableMemberFunc(ftok, scope)) {
if (member->nestedIn)
assignAllVarsVisibleFromScope(usage, member->nestedIn->definedType->classScope);
}
// there is a called member function, but it has no implementation, so we assume it initializes everything
else {
assignAllVar(usage);
}
}
// using default operator =, assume everything initialized
else {
assignAllVar(usage);
}
} else if (Token::Match(ftok, "::| %name% (") && !Token::Match(ftok, "if|while|for")) {
if (ftok->str() == "::")
ftok = ftok->next();
// Passing "this" => assume that everything is initialized
for (const Token *tok2 = ftok->linkAt(1); tok2 && tok2 != ftok; tok2 = tok2->previous()) {
if (tok2->str() == "this") {
assignAllVar(usage);
return;
}
}
// check if member function
if (ftok->function() && ftok->function()->nestedIn == scope &&
!ftok->function()->isConstructor()) {
const Function *member = ftok->function();
// recursive call
// assume that all variables are initialized
if (std::find(callstack.cbegin(), callstack.cend(), member) != callstack.cend()) {
assignAllVar(usage);
return;
}
// member function has implementation
if (member->hasBody()) {
// initialize variable use list using member function
callstack.push_back(member);
initializeVarList(*member, callstack, scope, usage);
callstack.pop_back();
// Assume that variables that are passed to it are initialized..
for (const Token *tok2 = ftok; tok2; tok2 = tok2->next()) {
if (Token::Match(tok2, "[;{}]"))
break;
if (Token::Match(tok2, "[(,] &| %name% [,)]")) {
tok2 = tok2->next();
if (tok2->str() == "&")
tok2 = tok2->next();
if (isVariableChangedByFunctionCall(tok2, tok2->strAt(-1) == "&", tok2->varId(), *mSettings, nullptr))
assignVar(usage, tok2->varId());
}
}
}
// there is a called member function, but it has no implementation, so we assume it initializes everything (if it can mutate state)
else if (!member->isConst() && !member->isStatic()) {
assignAllVar(usage);
}
// const method, assume it assigns all mutable members
else if (member->isConst()) {
for (Usage& i: usage) {
if (i.var->isMutable())
i.assign = true;
}
}
}
// not member function
else {
// could be a base class virtual function, so we assume it initializes everything
if (!func.isConstructor() && isBaseClassMutableMemberFunc(ftok, scope)) {
/** @todo False Negative: we should look at the base class functions to see if they
* call any derived class virtual functions that change the derived class state
*/
assignAllVar(usage);
}
// has friends, so we assume it initializes everything
if (!scope->definedType->friendList.empty())
assignAllVar(usage);
// the function is external and it's neither friend nor inherited virtual function.
// assume all variables that are passed to it are initialized..
else {
for (const Token *tok = ftok->tokAt(2); tok && tok != ftok->linkAt(1); tok = tok->next()) {
if (tok->isName()) {
assignVar(usage, tok->varId());
}
}
}
}
}
// Assignment of member variable?
else if (Token::Match(ftok, "%name% =")) {
assignVar(usage, ftok);
bool bailout = ftok->variable() && ftok->variable()->isReference();
const Token* tok2 = ftok->tokAt(2);
if (tok2->str() == "&") {
tok2 = tok2->next();
bailout = true;
}
if (tok2->variable() && (bailout || tok2->variable()->isArray()) && tok2->strAt(1) != "[")
assignVar(usage, tok2->varId());
}
// Assignment of array item of member variable?
else if (Token::Match(ftok, "%name% [|.")) {
const Token *tok2 = ftok;
while (tok2) {
if (tok2->strAt(1) == "[")
tok2 = tok2->linkAt(1);
else if (Token::Match(tok2->next(), ". %name%"))
tok2 = tok2->tokAt(2);
else
break;
}
if (tok2 && tok2->strAt(1) == "=")
assignVar(usage, ftok->varId());
}
// Assignment of array item of member variable?
else if (Token::Match(ftok, "* %name% =")) {
assignVar(usage, ftok->next()->varId());
} else if (Token::Match(ftok, "( * %name% ) =")) {
assignVar(usage, ftok->tokAt(2)->varId());
} else if (Token::Match(ftok, "* ( %name% ) =")) {
assignVar(usage, ftok->tokAt(2)->varId());
} else if (Token::Match(ftok, "* this . %name% =")) {
assignVar(usage, ftok->tokAt(3)->varId());
} else if (astIsRangeBasedForDecl(ftok)) {
if (const Variable* rangeVar = ftok->astParent()->astOperand1()->variable()) {
if (rangeVar->isReference() && !rangeVar->isConst())
assignVar(usage, ftok->varId());
}
}
// The functions 'clear' and 'Clear' are supposed to initialize variable.
if (Token::Match(ftok, "%name% . clear|Clear (")) {
assignVar(usage, ftok->varId());
}
}
}
void CheckClass::noConstructorError(const Token *tok, const std::string &classname, bool isStruct)
{
// For performance reasons the constructor might be intentionally missing. Therefore this is not a "warning"
const std::string message {"The " + std::string(isStruct ? "struct" : "class") + " '$symbol' does not declare a constructor although it has private member variables which likely require initialization."};
const std::string verbose {message + " Member variables of native types, pointers, or references are left uninitialized when the class is instantiated. That may cause bugs or undefined behavior."};
reportError(tok, Severity::style, "noConstructor", "$symbol:" + classname + '\n' + message + '\n' + verbose, CWE398, Certainty::normal);
}
void CheckClass::noExplicitConstructorError(const Token *tok, const std::string &classname, bool isStruct)
{
const std::string message(std::string(isStruct ? "Struct" : "Class") + " '$symbol' has a constructor with 1 argument that is not explicit.");
const std::string verbose(message + " Such, so called \"Converting constructors\", should in general be explicit for type safety reasons as that prevents unintended implicit conversions.");
reportError(tok, Severity::style, "noExplicitConstructor", "$symbol:" + classname + '\n' + message + '\n' + verbose, CWE398, Certainty::normal);
}
void CheckClass::uninitVarError(const Token *tok, bool isprivate, Function::Type functionType, const std::string &classname, const std::string &varname, bool derived, bool inconclusive)
{
std::string ctor;
if (functionType == Function::eCopyConstructor)
ctor = "copy ";
else if (functionType == Function::eMoveConstructor)
ctor = "move ";
std::string message("Member variable '$symbol' is not initialized in the " + ctor + "constructor.");
if (derived)
message += " Maybe it should be initialized directly in the class " + classname + "?";
std::string id = std::string("uninit") + (derived ? "Derived" : "") + "MemberVar" + (isprivate ? "Private" : "");
const std::string verbose {message + " Member variables of native types, pointers, or references are left uninitialized when the class is instantiated. That may cause bugs or undefined behavior."};
reportError(tok, Severity::warning, id, "$symbol:" + classname + "::" + varname + '\n' + message + '\n' + verbose, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
void CheckClass::uninitVarError(const Token *tok, const std::string &classname, const std::string &varname)
{
const std::string message("Member variable '$symbol' is not initialized."); // report missing in-class initializer
const std::string verbose {message + " Member variables of native types, pointers, or references are left uninitialized when the class is instantiated. That may cause bugs or undefined behavior."};
const std::string id = std::string("uninitMemberVarPrivate");
reportError(tok, Severity::warning, id, "$symbol:" + classname + "::" + varname + '\n' + message + '\n' + verbose, CWE398, Certainty::normal);
}
void CheckClass::missingMemberCopyError(const Token *tok, Function::Type functionType, const std::string& classname, const std::string& varname)
{
const std::string ctor(functionType == Function::Type::eCopyConstructor ? "copy" : "move");
const std::string action(functionType == Function::Type::eCopyConstructor ? "copied?" : "moved?");
const std::string message =
"$symbol:" + classname + "::" + varname + "\n" +
"Member variable '$symbol' is not assigned in the " + ctor + " constructor. Should it be " + action;
reportError(tok, Severity::warning, "missingMemberCopy", message, CWE398, Certainty::inconclusive);
}
void CheckClass::operatorEqVarError(const Token *tok, const std::string &classname, const std::string &varname, bool inconclusive)
{
reportError(tok, Severity::warning, "operatorEqVarError", "$symbol:" + classname + "::" + varname + "\nMember variable '$symbol' is not assigned a value in '" + classname + "::operator='.", CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal);
}
//---------------------------------------------------------------------------
// ClassCheck: Use initialization list instead of assignment
//---------------------------------------------------------------------------
void CheckClass::initializationListUsage()
{
if (!mSettings->severity.isEnabled(Severity::performance))
return;
logChecker("CheckClass::initializationListUsage"); // performance
for (const Scope *scope : mSymbolDatabase->functionScopes) {
// Check every constructor
if (!scope->function || !scope->function->isConstructor())
continue;
// Do not warn when a delegate constructor is called
if (const Token *initList = scope->function->constructorMemberInitialization()) {
if (Token::Match(initList, ": %name% {|(") && initList->strAt(1) == scope->className)
continue;
}
const Scope* owner = scope->functionOf;
for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%name% (")) // Assignments might depend on this function call or if/for/while/switch statement from now on.
break;
if (Token::Match(tok, "try|do {"))
break;
if (!Token::Match(tok, "%var% =") || tok->strAt(-1) == "*" || tok->strAt(-1) == ".")
continue;
const Variable* var = tok->variable();
if (!var || var->scope() != owner || var->isStatic())
continue;
if (var->isPointer() || var->isReference() || var->isEnumType())
continue;
if (!WRONG_DATA(!var->valueType(), tok) && var->valueType()->type > ValueType::Type::ITERATOR)
continue;
// bailout: multi line lambda in rhs => do not warn
if (findLambdaEndToken(tok->tokAt(2)) && tok->tokAt(2)->findExpressionStartEndTokens().second->linenr() > tok->tokAt(2)->linenr())
continue;
// Access local var member in rhs => do not warn
bool localmember = false;
visitAstNodes(tok->next()->astOperand2(),
[&](const Token *rhs) {
if (rhs->str() == "." && rhs->astOperand1() && rhs->astOperand1()->variable() && rhs->astOperand1()->variable()->isLocal())
localmember = true;
return ChildrenToVisit::op1_and_op2;
});
if (localmember)
continue;
bool allowed = true;
visitAstNodes(tok->next()->astOperand2(),
[&](const Token *tok2) {
const Variable* var2 = tok2->variable();
if (var2) {
if (var2->scope() == owner && tok2->strAt(-1)!=".") { // Is there a dependency between two member variables?
allowed = false;
return ChildrenToVisit::done;
}
if (var2->isArray() && var2->isLocal()) { // Can't initialize with a local array
allowed = false;
return ChildrenToVisit::done;
}
} else if (tok2->str() == "this") { // 'this' instance is not completely constructed in initialization list
allowed = false;
return ChildrenToVisit::done;
} else if (Token::Match(tok2, "%name% (") && tok2->strAt(-1) != "." && isMemberFunc(owner, tok2)) { // Member function called?
allowed = false;
return ChildrenToVisit::done;
}
return ChildrenToVisit::op1_and_op2;
});
if (!allowed)
continue;
suggestInitializationList(tok, tok->str());
}
}
}
void CheckClass::suggestInitializationList(const Token* tok, const std::string& varname)
{
reportError(tok, Severity::performance, "useInitializationList", "$symbol:" + varname + "\nVariable '$symbol' is assigned in constructor body. Consider performing initialization in initialization list.\n"
"When an object of a class is created, the constructors of all member variables are called consecutively "
"in the order the variables are declared, even if you don't explicitly write them to the initialization list. You "
"could avoid assigning '$symbol' a value by passing the value to the constructor in the initialization list.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// ClassCheck: Unused private functions
//---------------------------------------------------------------------------
static bool checkFunctionUsage(const Function *privfunc, const Scope* scope)
{
if (!scope)
return true; // Assume it is used, if scope is not seen
for (std::list<Function>::const_iterator func = scope->functionList.cbegin(); func != scope->functionList.cend(); ++func) {
if (func->functionScope) {
if (Token::Match(func->tokenDef, "%name% (")) {
for (const Token *ftok = func->tokenDef->tokAt(2); ftok && ftok->str() != ")"; ftok = ftok->next()) {
if (Token::Match(ftok, "= %name% [(,)]") && ftok->strAt(1) == privfunc->name())
return true;
if (ftok->str() == "(")
ftok = ftok->link();
}
}
for (const Token *ftok = func->functionScope->classDef->linkAt(1); ftok != func->functionScope->bodyEnd; ftok = ftok->next()) {
if (ftok->function() == privfunc)
return true;
if (ftok->varId() == 0U && ftok->str() == privfunc->name()) // TODO: This condition should be redundant
return true;
}
} else if ((func->type != Function::eCopyConstructor &&
func->type != Function::eOperatorEqual) ||
func->access != AccessControl::Private) // Assume it is used, if a function implementation isn't seen, but empty private copy constructors and assignment operators are OK
return true;
}
const std::map<std::string, Type*>::const_iterator end = scope->definedTypesMap.cend();
for (std::map<std::string, Type*>::const_iterator iter = scope->definedTypesMap.cbegin(); iter != end; ++iter) {
const Type *type = iter->second;
if (type->enclosingScope == scope && checkFunctionUsage(privfunc, type->classScope))
return true;
}
for (const Variable &var : scope->varlist) {
if (var.isStatic()) {
const Token* tok = Token::findmatch(scope->bodyStart, "%varid% =|(|{", var.declarationId());
if (tok)
tok = tok->tokAt(2);
while (tok && tok->str() != ";") {
if (tok->function() == privfunc)
return true;
tok = tok->next();
}
}
}
return false; // Unused in this scope
}
void CheckClass::privateFunctions()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedPrivateFunction"))
return;
logChecker("CheckClass::privateFunctions"); // style
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// do not check borland classes with properties..
if (Token::findsimplematch(scope->bodyStart, "; __property ;", scope->bodyEnd))
continue;
std::list<const Function*> privateFuncs;
for (const Function &func : scope->functionList) {
// Get private functions..
if (func.type == Function::eFunction && func.access == AccessControl::Private && !func.isOperator()) // TODO: There are smarter ways to check private operator usage
privateFuncs.push_back(&func);
}
// Bailout for overridden virtual functions of base classes
if (!scope->definedType->derivedFrom.empty()) {
// Check virtual functions
for (std::list<const Function*>::const_iterator it = privateFuncs.cbegin(); it != privateFuncs.cend();) {
if ((*it)->isImplicitlyVirtual(true)) // Give true as default value to be returned if we don't see all base classes
it = privateFuncs.erase(it);
else
++it;
}
}
while (!privateFuncs.empty()) {
const auto& pf = privateFuncs.front();
if (pf->retDef && pf->retDef->isAttributeMaybeUnused()) {
privateFuncs.pop_front();
continue;
}
// Check that all private functions are used
bool used = checkFunctionUsage(pf, scope); // Usage in this class
// Check in friend classes
const std::vector<Type::FriendInfo>& friendList = scope->definedType->friendList;
for (std::size_t i = 0; i < friendList.size() && !used; i++) {
if (friendList[i].type)
used = checkFunctionUsage(pf, friendList[i].type->classScope);
else
used = true; // Assume, it is used if we do not see friend class
}
if (!used)
unusedPrivateFunctionError(pf->tokenDef, scope->className, pf->name());
privateFuncs.pop_front();
}
}
}
void CheckClass::unusedPrivateFunctionError(const Token *tok, const std::string &classname, const std::string &funcname)
{
reportError(tok, Severity::style, "unusedPrivateFunction", "$symbol:" + classname + "::" + funcname + "\nUnused private function: '$symbol'", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// ClassCheck: Check that memset is not used on classes
//---------------------------------------------------------------------------
static const Scope* findFunctionOf(const Scope* scope)
{
while (scope) {
if (scope->type == Scope::eFunction)
return scope->functionOf;
scope = scope->nestedIn;
}
return nullptr;
}
void CheckClass::checkMemset()
{
logChecker("CheckClass::checkMemset");
const bool printWarnings = mSettings->severity.isEnabled(Severity::warning);
for (const Scope *scope : mSymbolDatabase->functionScopes) {
for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "memset|memcpy|memmove (")) {
const Token* arg1 = tok->tokAt(2);
const Token* arg3 = arg1->nextArgument();
if (arg3)
arg3 = arg3->nextArgument();
if (!arg3)
// weird, shouldn't happen: memset etc should have
// 3 arguments.
continue;
const Token *typeTok = nullptr;
const Scope *type = nullptr;
const Token* sizeofTok = arg3->previous()->astOperand2(); // try to find sizeof() in argument expression
if (sizeofTok && sizeofTok->astOperand1() && Token::simpleMatch(sizeofTok->astOperand1()->previous(), "sizeof ("))
sizeofTok = sizeofTok->astOperand1();
else if (sizeofTok && sizeofTok->astOperand2() && Token::simpleMatch(sizeofTok->astOperand2()->previous(), "sizeof ("))
sizeofTok = sizeofTok->astOperand2();
if (Token::simpleMatch(sizeofTok, "("))
sizeofTok = sizeofTok->previous();
if (Token::Match(sizeofTok, "sizeof ( %type% )"))
typeTok = sizeofTok->tokAt(2);
else if (Token::Match(sizeofTok, "sizeof ( %type% :: %type% )"))
typeTok = sizeofTok->tokAt(4);
else if (Token::Match(sizeofTok, "sizeof ( struct %type% )"))
typeTok = sizeofTok->tokAt(3);
else if (Token::simpleMatch(sizeofTok, "sizeof ( * this )") || Token::simpleMatch(arg1, "this ,")) {
type = findFunctionOf(sizeofTok->scope());
} else if (Token::Match(arg1, "&|*|%var%")) {
int numIndirToVariableType = 0; // Offset to the actual type in terms of dereference/addressof
for (;; arg1 = arg1->next()) {
if (arg1->str() == "&")
++numIndirToVariableType;
else if (arg1->str() == "*")
--numIndirToVariableType;
else
break;
}
const Variable * const var = arg1->variable();
if (var && arg1->strAt(1) == ",") {
if (var->isArrayOrPointer()) {
const Token *endTok = var->typeEndToken();
while (Token::simpleMatch(endTok, "*")) {
++numIndirToVariableType;
endTok = endTok->previous();
}
}
if (var->isArray())
numIndirToVariableType += int(var->dimensions().size());
if (numIndirToVariableType == 1)
type = var->typeScope();
if (!type && !var->isPointer() && !Token::simpleMatch(var->typeStartToken(), "std :: array") &&
mSettings->library.detectContainerOrIterator(var->typeStartToken())) {
memsetError(tok, tok->str(), var->getTypeName(), {}, /*isContainer*/ true);
}
}
}
// No type defined => The tokens didn't match
if (!typeTok && !type)
continue;
if (typeTok && typeTok->str() == "(")
typeTok = typeTok->next();
if (!type && typeTok->type())
type = typeTok->type()->classScope;
if (type) {
const std::set<const Scope *> parsedTypes;
checkMemsetType(scope, tok, type, false, parsedTypes);
}
} else if (tok->variable() && tok->variable()->isPointer() && tok->variable()->typeScope() && Token::Match(tok, "%var% = %name% (")) {
const Library::AllocFunc* alloc = mSettings->library.getAllocFuncInfo(tok->tokAt(2));
if (!alloc)
alloc = mSettings->library.getReallocFuncInfo(tok->tokAt(2));
if (!alloc || alloc->bufferSize == Library::AllocFunc::BufferSize::none)
continue;
const std::set<const Scope *> parsedTypes;
checkMemsetType(scope, tok->tokAt(2), tok->variable()->typeScope(), true, parsedTypes);
if (printWarnings && tok->variable()->typeScope()->numConstructors > 0)
mallocOnClassWarning(tok, tok->strAt(2), tok->variable()->typeScope()->classDef);
}
}
}
}
void CheckClass::checkMemsetType(const Scope *start, const Token *tok, const Scope *type, bool allocation, std::set<const Scope *> parsedTypes)
{
// If type has been checked there is no need to check it again
if (parsedTypes.find(type) != parsedTypes.end())
return;
parsedTypes.insert(type);
const bool printPortability = mSettings->severity.isEnabled(Severity::portability);
// recursively check all parent classes
for (const Type::BaseInfo & i : type->definedType->derivedFrom) {
const Type* derivedFrom = i.type;
if (derivedFrom && derivedFrom->classScope)
checkMemsetType(start, tok, derivedFrom->classScope, allocation, parsedTypes);
}
// Warn if type is a class that contains any virtual functions
for (const Function &func : type->functionList) {
if (func.hasVirtualSpecifier()) {
if (allocation)
mallocOnClassError(tok, tok->str(), type->classDef, "virtual function");
else
memsetError(tok, tok->str(), "virtual function", type->classDef->str());
}
}
// Warn if type is a class or struct that contains any std::* variables
for (const Variable &var : type->varlist) {
if (var.isReference() && !var.isStatic()) {
memsetErrorReference(tok, tok->str(), type->classDef->str());
continue;
}
// don't warn if variable static or const, pointer or array of pointers
if (!var.isStatic() && !var.isConst() && !var.isPointer() && (!var.isArray() || var.typeEndToken()->str() != "*")) {
const Token *tok1 = var.typeStartToken();
const Scope *typeScope = var.typeScope();
std::string typeName;
if (Token::Match(tok1, "%type% ::")) {
const Token *typeTok = tok1;
while (Token::Match(typeTok, "%type% ::")) {
typeName += typeTok->str() + "::";
typeTok = typeTok->tokAt(2);
}
typeName += typeTok->str();
}
// check for std:: type
if (var.isStlType() && typeName != "std::array" && !mSettings->library.podtype(typeName)) {
if (allocation)
mallocOnClassError(tok, tok->str(), type->classDef, "'" + typeName + "'");
else
memsetError(tok, tok->str(), "'" + typeName + "'", type->classDef->str());
}
// check for known type
else if (typeScope && typeScope != type)
checkMemsetType(start, tok, typeScope, allocation, parsedTypes);
// check for float
else if (printPortability && var.isFloatingType() && tok->str() == "memset")
memsetErrorFloat(tok, type->classDef->str());
}
}
}
void CheckClass::mallocOnClassWarning(const Token* tok, const std::string &memfunc, const Token* classTok)
{
std::list<const Token *> toks = { tok, classTok };
reportError(toks, Severity::warning, "mallocOnClassWarning",
"$symbol:" + memfunc +"\n"
"Memory for class instance allocated with $symbol(), but class provides constructors.\n"
"Memory for class instance allocated with $symbol(), but class provides constructors. This is unsafe, "
"since no constructor is called and class members remain uninitialized. Consider using 'new' instead.", CWE762, Certainty::normal);
}
void CheckClass::mallocOnClassError(const Token* tok, const std::string &memfunc, const Token* classTok, const std::string &classname)
{
std::list<const Token *> toks = { tok, classTok };
reportError(toks, Severity::error, "mallocOnClassError",
"$symbol:" + memfunc +"\n"
"$symbol:" + classname +"\n"
"Memory for class instance allocated with " + memfunc + "(), but class contains a " + classname + ".\n"
"Memory for class instance allocated with " + memfunc + "(), but class a " + classname + ". This is unsafe, "
"since no constructor is called and class members remain uninitialized. Consider using 'new' instead.", CWE665, Certainty::normal);
}
void CheckClass::memsetError(const Token *tok, const std::string &memfunc, const std::string &classname, const std::string &type, bool isContainer)
{
const std::string typeStr = isContainer ? std::string() : (type + " that contains a ");
const std::string msg = "$symbol:" + memfunc + "\n"
"$symbol:" + classname + "\n"
"Using '" + memfunc + "' on " + typeStr + classname + ".\n"
"Using '" + memfunc + "' on " + typeStr + classname + " is unsafe, because constructor, destructor "
"and copy operator calls are omitted. These are necessary for this non-POD type to ensure that a valid object "
"is created.";
reportError(tok, Severity::error, "memsetClass", msg, CWE762, Certainty::normal);
}
void CheckClass::memsetErrorReference(const Token *tok, const std::string &memfunc, const std::string &type)
{
reportError(tok, Severity::error, "memsetClassReference",
"$symbol:" + memfunc +"\n"
"Using '" + memfunc + "' on " + type + " that contains a reference.", CWE665, Certainty::normal);
}
void CheckClass::memsetErrorFloat(const Token *tok, const std::string &type)
{
reportError(tok, Severity::portability, "memsetClassFloat", "Using memset() on " + type + " which contains a floating point number.\n"
"Using memset() on " + type + " which contains a floating point number."
" This is not portable because memset() sets each byte of a block of memory to a specific value and"
" the actual representation of a floating-point value is implementation defined."
" Note: In case of an IEEE754-1985 compatible implementation setting all bits to zero results in the value 0.0.", CWE758, Certainty::normal);
}
//---------------------------------------------------------------------------
// ClassCheck: "C& operator=(const C&) { ... return *this; }"
// operator= should return a reference to *this
//---------------------------------------------------------------------------
void CheckClass::operatorEqRetRefThis()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("operatorEqRetRefThis"))
return;
logChecker("CheckClass::operatorEqRetRefThis"); // style
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
for (std::list<Function>::const_iterator func = scope->functionList.cbegin(); func != scope->functionList.cend(); ++func) {
if (func->type == Function::eOperatorEqual && func->hasBody()) {
// make sure return signature is correct
if (func->retType == func->nestedIn->definedType && func->tokenDef->strAt(-1) == "&") {
checkReturnPtrThis(scope, &(*func), func->functionScope->bodyStart, func->functionScope->bodyEnd);
}
}
}
}
}
void CheckClass::checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last)
{
std::set<const Function*> analyzedFunctions;
checkReturnPtrThis(scope, func, tok, last, analyzedFunctions);
}
void CheckClass::checkReturnPtrThis(const Scope *scope, const Function *func, const Token *tok, const Token *last, std::set<const Function*>& analyzedFunctions)
{
bool foundReturn = false;
const Token* const startTok = tok;
for (; tok && tok != last; tok = tok->next()) {
// check for return of reference to this
if (const Token* lScope = isLambdaCaptureList(tok)) // skip lambda
tok = lScope->link();
if (tok->str() != "return")
continue;
foundReturn = true;
const Token *retExpr = tok->astOperand1();
if (retExpr && retExpr->str() == "=")
retExpr = retExpr->astOperand1();
if (retExpr && retExpr->isUnaryOp("*") && Token::simpleMatch(retExpr->astOperand1(), "this"))
continue;
std::string cast("( " + scope->className + " & )");
if (Token::simpleMatch(tok->next(), cast.c_str(), cast.size()))
tok = tok->tokAt(4);
// check if a function is called
if (tok->strAt(2) == "(" &&
tok->linkAt(2)->strAt(1) == ";") {
// check if it is a member function
for (std::list<Function>::const_iterator it = scope->functionList.cbegin(); it != scope->functionList.cend(); ++it) {
// check for a regular function with the same name and a body
if (it->type == Function::eFunction && it->hasBody() &&
it->token->str() == tok->strAt(1)) {
// check for the proper return type
if (it->tokenDef->strAt(-1) == "&" &&
it->tokenDef->strAt(-2) == scope->className) {
// make sure it's not a const function
if (!it->isConst()) {
/** @todo make sure argument types match */
// avoid endless recursions
if (analyzedFunctions.find(&*it) == analyzedFunctions.end()) {
analyzedFunctions.insert(&*it);
checkReturnPtrThis(scope, &*it, it->arg->link()->next(), it->arg->link()->linkAt(1),
analyzedFunctions);
}
// just bail for now
else
return;
}
}
}
}
}
// check if *this is returned
else if (!(Token::simpleMatch(tok->next(), "operator= (") ||
Token::simpleMatch(tok->next(), "this . operator= (") ||
(Token::Match(tok->next(), "%type% :: operator= (") &&
tok->strAt(1) == scope->className)))
operatorEqRetRefThisError(func->token);
}
if (foundReturn) {
return;
}
if (startTok->next() == last) {
const std::string tmp("( const " + scope->className + " &");
if (Token::simpleMatch(func->argDef, tmp.c_str(), tmp.size())) {
// Typical wrong way to suppress default assignment operator by declaring it and leaving empty
operatorEqMissingReturnStatementError(func->token, func->access == AccessControl::Public);
} else {
operatorEqMissingReturnStatementError(func->token, true);
}
return;
}
if (mSettings->library.isScopeNoReturn(last, nullptr)) {
// Typical wrong way to prohibit default assignment operator
// by always throwing an exception or calling a noreturn function
operatorEqShouldBeLeftUnimplementedError(func->token);
return;
}
operatorEqMissingReturnStatementError(func->token, func->access == AccessControl::Public);
}
void CheckClass::operatorEqRetRefThisError(const Token *tok)
{
reportError(tok, Severity::style, "operatorEqRetRefThis", "'operator=' should return reference to 'this' instance.", CWE398, Certainty::normal);
}
void CheckClass::operatorEqShouldBeLeftUnimplementedError(const Token *tok)
{
reportError(tok, Severity::style, "operatorEqShouldBeLeftUnimplemented", "'operator=' should either return reference to 'this' instance or be declared private and left unimplemented.", CWE398, Certainty::normal);
}
void CheckClass::operatorEqMissingReturnStatementError(const Token *tok, bool error)
{
if (error) {
reportError(tok, Severity::error, "operatorEqMissingReturnStatement", "No 'return' statement in non-void function causes undefined behavior.", CWE398, Certainty::normal);
} else {
operatorEqRetRefThisError(tok);
}
}
//---------------------------------------------------------------------------
// ClassCheck: "C& operator=(const C& rhs) { if (this == &rhs) ... }"
// operator= should check for assignment to self
//
// For simple classes, an assignment to self check is only a potential optimization.
//
// For classes that allocate dynamic memory, assignment to self can be a real error
// if it is deallocated and allocated again without being checked for.
//
// This check is not valid for classes with multiple inheritance because a
// class can have multiple addresses so there is no trivial way to check for
// assignment to self.
//---------------------------------------------------------------------------
void CheckClass::operatorEqToSelf()
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("operatorEqToSelf"))
return;
logChecker("CheckClass::operatorEqToSelf"); // warning
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// skip classes with multiple inheritance
if (scope->definedType->derivedFrom.size() > 1)
continue;
for (const Function &func : scope->functionList) {
if (func.type == Function::eOperatorEqual && func.hasBody()) {
// make sure that the operator takes an object of the same type as *this, otherwise we can't detect self-assignment checks
if (func.argumentList.empty())
continue;
const Token* typeTok = func.argumentList.front().typeEndToken();
while (typeTok->str() == "const" || typeTok->str() == "&" || typeTok->str() == "*")
typeTok = typeTok->previous();
if (typeTok->str() != scope->className)
continue;
// make sure return signature is correct
if (Token::Match(func.retDef, "%type% &") && func.retDef->str() == scope->className) {
// find the parameter name
const Token *rhs = func.argumentList.cbegin()->nameToken();
const Token* out_ifStatementScopeStart = nullptr;
if (!hasAssignSelf(&func, rhs, out_ifStatementScopeStart)) {
if (hasAllocation(&func, scope))
operatorEqToSelfError(func.token);
} else if (out_ifStatementScopeStart != nullptr) {
if (hasAllocationInIfScope(&func, scope, out_ifStatementScopeStart))
operatorEqToSelfError(func.token);
}
}
}
}
}
}
bool CheckClass::hasAllocationInIfScope(const Function *func, const Scope* scope, const Token *ifStatementScopeStart) const
{
const Token *end;
if (ifStatementScopeStart->str() == "{")
end = ifStatementScopeStart->link();
else
end = func->functionScope->bodyEnd;
return hasAllocation(func, scope, ifStatementScopeStart, end);
}
bool CheckClass::hasAllocation(const Function *func, const Scope* scope) const
{
return hasAllocation(func, scope, func->functionScope->bodyStart, func->functionScope->bodyEnd);
}
bool CheckClass::hasAllocation(const Function *func, const Scope* scope, const Token *start, const Token *end) const
{
if (!end)
end = func->functionScope->bodyEnd;
for (const Token *tok = start; tok && (tok != end); tok = tok->next()) {
if (((tok->isCpp() && Token::Match(tok, "%var% = new")) ||
(Token::Match(tok, "%var% = %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)))) &&
isMemberVar(scope, tok))
return true;
// check for deallocating memory
const Token *var;
if (Token::Match(tok, "%name% ( %var%") && mSettings->library.getDeallocFuncInfo(tok))
var = tok->tokAt(2);
else if (tok->isCpp() && Token::Match(tok, "delete [ ] %var%"))
var = tok->tokAt(3);
else if (tok->isCpp() && Token::Match(tok, "delete %var%"))
var = tok->next();
else
continue;
// Check for assignment to the deleted pointer (only if its a member of the class)
if (isMemberVar(scope, var)) {
for (const Token *tok1 = var->next(); tok1 && (tok1 != end); tok1 = tok1->next()) {
if (Token::Match(tok1, "%varid% =", var->varId()))
return true;
}
}
}
return false;
}
static bool isTrueKeyword(const Token* tok)
{
return tok->hasKnownIntValue() && tok->getKnownIntValue() == 1;
}
static bool isFalseKeyword(const Token* tok)
{
return tok->hasKnownIntValue() && tok->getKnownIntValue() == 0;
}
/*
* Checks if self-assignment test is inverse
* For example 'if (this == &rhs)'
*/
CheckClass::Bool CheckClass::isInverted(const Token *tok, const Token *rhs)
{
bool res = true;
for (const Token *itr = tok; itr && itr->str()!="("; itr=itr->astParent()) {
if (Token::simpleMatch(itr, "!=") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) {
res = !res;
} else if (Token::simpleMatch(itr, "!=") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size()))
|| (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) {
res = !res;
} else if (Token::simpleMatch(itr, "!=") && (isFalseKeyword(itr->astOperand1()) || isFalseKeyword(itr->astOperand2()))) {
//Do nothing
} else if (Token::simpleMatch(itr, "!")) {
res = !res;
} else if (Token::simpleMatch(itr, "==") && (isFalseKeyword(itr->astOperand1()) || isFalseKeyword(itr->astOperand2()))) {
res = !res;
} else if (Token::simpleMatch(itr, "==") && (isTrueKeyword(itr->astOperand1()) || isTrueKeyword(itr->astOperand2()))) {
//Do nothing
} else if (Token::simpleMatch(itr, "==") && ((Token::simpleMatch(itr->astOperand1(), "this") && Token::simpleMatch(itr->astOperand2(), "&") && Token::simpleMatch(itr->astOperand2()->next(), rhs->str().c_str(), rhs->str().size()))
|| (Token::simpleMatch(itr->astOperand2(), "this") && Token::simpleMatch(itr->astOperand1(), "&") && Token::simpleMatch(itr->astOperand1()->next(), rhs->str().c_str(), rhs->str().size())))) {
//Do nothing
} else {
return Bool::BAILOUT;
}
}
if (res)
return Bool::TRUE;
return Bool::FALSE;
}
const Token * CheckClass::getIfStmtBodyStart(const Token *tok, const Token *rhs)
{
const Token *top = tok->astTop();
if (Token::simpleMatch(top->link(), ") {")) {
switch (isInverted(tok->astParent(), rhs)) {
case Bool::BAILOUT:
return nullptr;
case Bool::TRUE:
return top->link()->next();
case Bool::FALSE:
return top->link()->linkAt(1);
}
}
return nullptr;
}
bool CheckClass::hasAssignSelf(const Function *func, const Token *rhs, const Token *&out_ifStatementScopeStart)
{
if (!rhs)
return false;
const Token *last = func->functionScope->bodyEnd;
for (const Token *tok = func->functionScope->bodyStart; tok && tok != last; tok = tok->next()) {
if (!Token::simpleMatch(tok, "if ("))
continue;
bool ret = false;
visitAstNodes(tok->next()->astOperand2(),
[&](const Token *tok2) {
if (!Token::Match(tok2, "==|!="))
return ChildrenToVisit::op1_and_op2;
if (Token::simpleMatch(tok2->astOperand1(), "this"))
tok2 = tok2->astOperand2();
else if (Token::simpleMatch(tok2->astOperand2(), "this"))
tok2 = tok2->astOperand1();
else
return ChildrenToVisit::op1_and_op2;
if (tok2 && tok2->isUnaryOp("&") && tok2->astOperand1()->str() == rhs->str())
ret = true;
if (ret) {
out_ifStatementScopeStart = getIfStmtBodyStart(tok2, rhs);
}
return ret ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2;
});
if (ret)
return ret;
}
return false;
}
void CheckClass::operatorEqToSelfError(const Token *tok)
{
reportError(tok, Severity::warning, "operatorEqToSelf",
"'operator=' should check for assignment to self to avoid problems with dynamic memory.\n"
"'operator=' should check for assignment to self to ensure that each block of dynamically "
"allocated memory is owned and managed by only one instance of the class.", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// A destructor in a base class should be virtual
//---------------------------------------------------------------------------
void CheckClass::virtualDestructor()
{
// This error should only be given if:
// * base class doesn't have virtual destructor
// * derived class has non-empty destructor (only c++03, in c++11 it's UB see paragraph 3 in [expr.delete])
// * base class is deleted
// unless inconclusive in which case:
// * A class with any virtual functions should have a destructor that is either public and virtual or protected
const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive);
std::list<const Function *> inconclusiveErrors;
logChecker("CheckClass::virtualDestructor");
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// Skip base classes (unless inconclusive)
if (scope->definedType->derivedFrom.empty()) {
if (printInconclusive) {
const Function *destructor = scope->getDestructor();
if (destructor && !destructor->hasVirtualSpecifier() && destructor->access == AccessControl::Public) {
if (std::any_of(scope->functionList.cbegin(), scope->functionList.cend(), [](const Function& func) {
return func.hasVirtualSpecifier();
}))
inconclusiveErrors.push_back(destructor);
}
}
continue;
}
// Check if destructor is empty and non-empty ..
if (mSettings->standards.cpp <= Standards::CPP03) {
// Find the destructor
const Function *destructor = scope->getDestructor();
// Check for destructor with implementation
if (!destructor || !destructor->hasBody())
continue;
// Empty destructor
if (destructor->token->linkAt(3) == destructor->token->tokAt(4))
continue;
}
const Token *derived = scope->classDef;
const Token *derivedClass = derived->next();
// Iterate through each base class...
for (const Type::BaseInfo & j : scope->definedType->derivedFrom) {
// Check if base class is public and exists in database
if (j.access != AccessControl::Private && j.type) {
const Type *derivedFrom = j.type;
const Scope *derivedFromScope = derivedFrom->classScope;
if (!derivedFromScope)
continue;
// Check for this pattern:
// 1. Base class pointer is given the address of derived class instance
// 2. Base class pointer is deleted
//
// If this pattern is not seen then bailout the checking of these base/derived classes
{
// pointer variables of type 'Base *'
std::set<int> baseClassPointers;
for (const Variable* var : mSymbolDatabase->variableList()) {
if (var && var->isPointer() && var->type() == derivedFrom)
baseClassPointers.insert(var->declarationId());
}
// pointer variables of type 'Base *' that should not be deleted
std::set<int> dontDelete;
// No deletion of derived class instance through base class pointer found => the code is ok
bool ok = true;
for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) {
if (Token::Match(tok, "[;{}] %var% =") &&
baseClassPointers.find(tok->next()->varId()) != baseClassPointers.end()) {
// new derived class..
const std::string tmp("new " + derivedClass->str());
if (Token::simpleMatch(tok->tokAt(3), tmp.c_str(), tmp.size())) {
dontDelete.insert(tok->next()->varId());
}
}
// Delete base class pointer that might point at derived class
else if (Token::Match(tok, "delete %var% ;") &&
dontDelete.find(tok->next()->varId()) != dontDelete.end()) {
ok = false;
break;
}
}
// No base class pointer that points at a derived class is deleted
if (ok)
continue;
}
// Find the destructor declaration for the base class.
const Function *baseDestructor = derivedFromScope->getDestructor();
// Check that there is a destructor..
if (!baseDestructor) {
if (derivedFrom->derivedFrom.empty()) {
virtualDestructorError(derivedFrom->classDef, derivedFrom->name(), derivedClass->str(), false);
}
} else if (!baseDestructor->hasVirtualSpecifier()) {
// TODO: This is just a temporary fix, better solution is needed.
// Skip situations where base class has base classes of its own, because
// some of the base classes might have virtual destructor.
// Proper solution is to check all of the base classes. If base class is not
// found or if one of the base classes has virtual destructor, error should not
// be printed. See TODO test case "virtualDestructorInherited"
if (derivedFrom->derivedFrom.empty()) {
// Make sure that the destructor is public (protected or private
// would not compile if inheritance is used in a way that would
// cause the bug we are trying to find here.)
if (baseDestructor->access == AccessControl::Public) {
virtualDestructorError(baseDestructor->token, derivedFrom->name(), derivedClass->str(), false);
// check for duplicate error and remove it if found
const std::list<const Function *>::const_iterator found = std::find(inconclusiveErrors.cbegin(), inconclusiveErrors.cend(), baseDestructor);
if (found != inconclusiveErrors.cend())
inconclusiveErrors.erase(found);
}
}
}
}
}
}
for (const Function *func : inconclusiveErrors)
virtualDestructorError(func->tokenDef, func->name(), emptyString, true);
}
void CheckClass::virtualDestructorError(const Token *tok, const std::string &Base, const std::string &Derived, bool inconclusive)
{
if (inconclusive) {
if (mSettings->severity.isEnabled(Severity::warning))
reportError(tok, Severity::warning, "virtualDestructor", "$symbol:" + Base + "\nClass '$symbol' which has virtual members does not have a virtual destructor.", CWE404, Certainty::inconclusive);
} else {
reportError(tok, Severity::error, "virtualDestructor",
"$symbol:" + Base +"\n"
"$symbol:" + Derived +"\n"
"Class '" + Base + "' which is inherited by class '" + Derived + "' does not have a virtual destructor.\n"
"Class '" + Base + "' which is inherited by class '" + Derived + "' does not have a virtual destructor. "
"If you destroy instances of the derived class by deleting a pointer that points to the base class, only "
"the destructor of the base class is executed. Thus, dynamic memory that is managed by the derived class "
"could leak. This can be avoided by adding a virtual destructor to the base class.", CWE404, Certainty::normal);
}
}
//---------------------------------------------------------------------------
// warn for "this-x". The indented code may be "this->x"
//---------------------------------------------------------------------------
void CheckClass::thisSubtraction()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckClass::thisSubtraction"); // warning
const Token *tok = mTokenizer->tokens();
for (;;) {
tok = Token::findmatch(tok, "this - %name%");
if (!tok)
break;
if (tok->strAt(-1) != "*")
thisSubtractionError(tok);
tok = tok->next();
}
}
void CheckClass::thisSubtractionError(const Token *tok)
{
reportError(tok, Severity::warning, "thisSubtraction", "Suspicious pointer subtraction. Did you intend to write '->'?", CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// can member function be const?
//---------------------------------------------------------------------------
void CheckClass::checkConst()
{
// This is an inconclusive check. False positives: #3322.
if (!mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
if (!mSettings->severity.isEnabled(Severity::style) &&
!mSettings->isPremiumEnabled("functionConst") &&
!mSettings->isPremiumEnabled("functionStatic"))
return;
logChecker("CheckClass::checkConst"); // style,inconclusive
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
for (const Function &func : scope->functionList) {
// does the function have a body?
if (func.type != Function::eFunction || !func.hasBody())
continue;
// don't warn for friend/static/virtual functions
if (func.isFriend() || func.isStatic() || func.hasVirtualSpecifier())
continue;
if (func.functionPointerUsage)
continue;
if (func.hasRvalRefQualifier())
continue;
// don't suggest const when returning non-const pointer/reference, but still suggest static
auto isPointerOrReference = [this](const Token* start, const Token* end) -> bool {
bool inTemplArgList = false, isConstTemplArg = false;
for (const Token* tok = start; tok != end; tok = tok->next()) {
if (tok->str() == "{") // end of trailing return type
return false;
if (tok->str() == "<") {
if (!tok->link())
mSymbolDatabase->debugMessage(tok, "debug", "CheckClass::checkConst found unlinked template argument list '" + tok->expressionString() + "'.");
inTemplArgList = true;
}
else if (tok->str() == ">") {
inTemplArgList = false;
isConstTemplArg = false;
}
else if (tok->str() == "const") {
if (!inTemplArgList)
return false;
isConstTemplArg = true;
}
else if (!isConstTemplArg && Token::Match(tok, "*|&"))
return true;
}
return false;
};
const bool returnsPtrOrRef = isPointerOrReference(func.retDef, func.tokenDef);
if (Function::returnsPointer(&func, /*unknown*/ true) || Function::returnsReference(&func, /*unknown*/ true, /*includeRValueRef*/ true)) { // returns const/non-const depending on template arg
bool isTemplateArg = false;
for (const Token* tok2 = func.retDef; precedes(tok2, func.token); tok2 = tok2->next())
if (tok2->isTemplateArg() && tok2->str() == "const") {
isTemplateArg = true;
break;
}
if (isTemplateArg)
continue;
}
if (func.isOperator()) { // Operator without return type: conversion operator
const std::string& opName = func.tokenDef->str();
if (opName.compare(8, 5, "const") != 0 && (endsWith(opName,'&') || endsWith(opName,'*')))
continue;
} else if (mSettings->library.isSmartPointer(func.retDef)) {
// Don't warn if a std::shared_ptr etc is returned
continue;
} else {
// don't warn for unknown types..
// LPVOID, HDC, etc
if (func.retDef->str().size() > 2 && !func.retDef->type() && func.retDef->isUpperCaseName())
continue;
}
// check if base class function is virtual
bool foundAllBaseClasses = true;
if (!scope->definedType->derivedFrom.empty() && func.isImplicitlyVirtual(true, &foundAllBaseClasses) && foundAllBaseClasses)
continue;
MemberAccess memberAccessed = MemberAccess::NONE;
// if nothing non-const was found. write error..
if (!checkConstFunc(scope, &func, memberAccessed))
continue;
const bool suggestStatic = memberAccessed != MemberAccess::MEMBER && !func.isOperator();
if ((returnsPtrOrRef || func.isConst() || func.hasLvalRefQualifier()) && !suggestStatic)
continue;
std::string classname = scope->className;
const Scope *nest = scope->nestedIn;
while (nest && nest->type != Scope::eGlobal) {
classname = nest->className + "::" + classname;
nest = nest->nestedIn;
}
// get function name
std::string functionName = (func.tokenDef->isName() ? "" : "operator") + func.tokenDef->str();
if (func.tokenDef->str() == "(")
functionName += ")";
else if (func.tokenDef->str() == "[")
functionName += "]";
if (func.isInline())
checkConstError(func.token, classname, functionName, suggestStatic, foundAllBaseClasses);
else // not inline
checkConstError2(func.token, func.tokenDef, classname, functionName, suggestStatic, foundAllBaseClasses);
}
}
}
// tok should point at "this"
static const Token* getFuncTokFromThis(const Token* tok) {
if (!Token::simpleMatch(tok->next(), "."))
return nullptr;
tok = tok->tokAt(2);
while (Token::Match(tok, "%name% ::"))
tok = tok->tokAt(2);
return Token::Match(tok, "%name% (") ? tok : nullptr;
}
bool CheckClass::isMemberVar(const Scope *scope, const Token *tok) const
{
bool again = false;
// try to find the member variable
do {
again = false;
if (tok->str() == "this")
return !getFuncTokFromThis(tok); // function calls are handled elsewhere
if (Token::simpleMatch(tok->tokAt(-3), "( * this )"))
return true;
if (Token::Match(tok->tokAt(-3), "%name% ) . %name%")) {
tok = tok->tokAt(-3);
again = true;
} else if (Token::Match(tok->tokAt(-2), "%name% . %name%")) {
tok = tok->tokAt(-2);
again = true;
} else if (Token::Match(tok->tokAt(-2), "] . %name%")) {
tok = tok->linkAt(-2)->previous();
again = true;
} else if (tok->str() == "]") {
tok = tok->link()->previous();
again = true;
}
} while (again);
if (tok->isKeyword() || tok->isStandardType())
return false;
for (const Variable& var : scope->varlist) {
if (var.name() == tok->str()) {
if (Token::Match(tok, "%name% ::"))
continue;
const Token* fqTok = tok;
while (Token::Match(fqTok->tokAt(-2), "%name% ::"))
fqTok = fqTok->tokAt(-2);
if (fqTok->strAt(-1) == "::")
fqTok = fqTok->previous();
bool isMember = tok == fqTok;
std::string scopeStr;
const Scope* curScope = scope;
while (!isMember && curScope && curScope->type != Scope::ScopeType::eGlobal) {
scopeStr.insert(0, curScope->className + " :: ");
isMember = Token::Match(fqTok, scopeStr.c_str());
curScope = curScope->nestedIn;
}
if (isMember) {
if (tok->varId() == 0)
mSymbolDatabase->debugMessage(tok, "varid0", "CheckClass::isMemberVar found used member variable \'" + tok->str() + "\' with varid 0");
return !var.isStatic();
}
}
}
// not found in this class
if (!scope->definedType->derivedFrom.empty()) {
// check each base class
bool foundAllBaseClasses = true;
for (const Type::BaseInfo & i : scope->definedType->derivedFrom) {
// find the base class
const Type *derivedFrom = i.type;
if (!derivedFrom || !derivedFrom->classScope)
foundAllBaseClasses = false;
// find the function in the base class
if (derivedFrom && derivedFrom->classScope && derivedFrom->classScope != scope) {
if (isMemberVar(derivedFrom->classScope, tok))
return true;
}
}
if (!foundAllBaseClasses)
return true;
}
return false;
}
bool CheckClass::isMemberFunc(const Scope *scope, const Token *tok)
{
if (!tok->function()) {
for (const Function &func : scope->functionList) {
if (func.name() == tok->str()) {
const Token* tok2 = tok->tokAt(2);
int argsPassed = tok2->str() == ")" ? 0 : 1;
for (;;) {
tok2 = tok2->nextArgument();
if (tok2)
argsPassed++;
else
break;
}
if (argsPassed == func.argCount() ||
(func.isVariadic() && argsPassed >= (func.argCount() - 1)) ||
(argsPassed < func.argCount() && argsPassed >= func.minArgCount()))
return true;
}
}
} else if (tok->function()->nestedIn == scope)
return !tok->function()->isStatic();
// not found in this class
if (!scope->definedType->derivedFrom.empty()) {
// check each base class
for (const Type::BaseInfo & i : scope->definedType->derivedFrom) {
// find the base class
const Type *derivedFrom = i.type;
// find the function in the base class
if (derivedFrom && derivedFrom->classScope && derivedFrom->classScope != scope) {
if (isMemberFunc(derivedFrom->classScope, tok))
return true;
}
}
}
return false;
}
bool CheckClass::isConstMemberFunc(const Scope *scope, const Token *tok)
{
if (!tok->function())
return false;
if (tok->function()->nestedIn == scope)
return tok->function()->isConst();
// not found in this class
if (!scope->definedType->derivedFrom.empty()) {
// check each base class
for (const Type::BaseInfo & i : scope->definedType->derivedFrom) {
// find the base class
const Type *derivedFrom = i.type;
// find the function in the base class
if (derivedFrom && derivedFrom->classScope) {
if (isConstMemberFunc(derivedFrom->classScope, tok))
return true;
}
}
}
return false;
}
const std::set<std::string> CheckClass::stl_containers_not_const = { "map", "unordered_map", "std :: map|unordered_map <" }; // start pattern
bool CheckClass::checkConstFunc(const Scope *scope, const Function *func, MemberAccess& memberAccessed) const
{
if (mTokenizer->hasIfdef(func->functionScope->bodyStart, func->functionScope->bodyEnd))
return false;
auto getFuncTok = [](const Token* tok) -> const Token* {
if (Token::simpleMatch(tok, "this"))
tok = getFuncTokFromThis(tok);
bool isReturn = false;
if ((Token::Match(tok, "%name% (|{") || (isReturn = Token::simpleMatch(tok->astParent(), "return {"))) && !tok->isStandardType() && !tok->isKeyword()) {
if (isReturn)
tok = tok->astParent();
return tok;
}
return nullptr;
};
auto checkFuncCall = [this, &memberAccessed](const Token* funcTok, const Scope* scope, const Function* func) {
if (isMemberFunc(scope, funcTok) && (funcTok->strAt(-1) != "." || Token::simpleMatch(funcTok->tokAt(-2), "this ."))) {
const bool isSelf = func == funcTok->function();
if (!isConstMemberFunc(scope, funcTok) && !isSelf)
return false;
memberAccessed = (isSelf && memberAccessed != MemberAccess::MEMBER) ? MemberAccess::SELF : MemberAccess::MEMBER;
}
if (const Function* f = funcTok->function()) { // check known function
const std::vector<const Token*> args = getArguments(funcTok);
const auto argMax = std::min<nonneg int>(args.size(), f->argCount());
for (nonneg int argIndex = 0; argIndex < argMax; ++argIndex) {
const Variable* const argVar = f->getArgumentVar(argIndex);
if (!argVar || ((argVar->isArrayOrPointer() || argVar->isReference()) &&
!(argVar->valueType() && argVar->valueType()->isConst(argVar->valueType()->pointer)))) { // argument might be modified
const Token* arg = args[argIndex];
// Member variable given as parameter
const Token* varTok = previousBeforeAstLeftmostLeaf(arg);
if (!varTok)
return false;
varTok = varTok->next();
if ((varTok->isName() && isMemberVar(scope, varTok)) || (varTok->isUnaryOp("&") && (varTok = varTok->astOperand1()) && isMemberVar(scope, varTok))) {
const Variable* var = varTok->variable();
if (!var || (!var->isMutable() && !var->isConst()))
return false;
}
}
}
return true;
}
if (const Library::Function* fLib = mSettings->library.getFunction(funcTok))
if (fLib->isconst || fLib->ispure)
return true;
// Member variable given as parameter to unknown function
const Token *lpar = funcTok->next();
if (Token::simpleMatch(lpar, "( ) ("))
lpar = lpar->tokAt(2);
for (const Token* tok = lpar->next(); tok && tok != funcTok->linkAt(1); tok = tok->next()) {
if (tok->str() == "(")
tok = tok->link();
else if ((tok->isName() && isMemberVar(scope, tok)) || (tok->isUnaryOp("&") && (tok = tok->astOperand1()) && isMemberVar(scope, tok))) {
const Variable* var = tok->variable();
if (!var || (!var->isMutable() && !var->isConst()))
return false;
}
}
return true;
};
// if the function doesn't have any assignment nor function call,
// it can be a const function..
for (const Token *tok1 = func->functionScope->bodyStart; tok1 && tok1 != func->functionScope->bodyEnd; tok1 = tok1->next()) {
if (tok1->isName() && isMemberVar(scope, tok1)) {
memberAccessed = MemberAccess::MEMBER;
const Variable* v = tok1->variable();
if (v && v->isMutable())
continue;
if (tok1->str() == "this") {
if (tok1->previous()->isAssignmentOp())
return false;
if (Token::Match(tok1->previous(), "( this . * %var% )")) // call using ptr to member function TODO: check constness
return false;
if (Token::simpleMatch(tok1->astParent(), "*") && tok1->astParent()->astParent() && tok1->astParent()->astParent()->isIncDecOp())
return false;
}
// non const pointer cast
if (tok1->valueType() && tok1->valueType()->pointer > 0 && tok1->astParent() && tok1->astParent()->isCast() &&
!(tok1->astParent()->valueType() &&
(tok1->astParent()->valueType()->pointer == 0 || tok1->astParent()->valueType()->isConst(tok1->astParent()->valueType()->pointer))))
return false;
const Token* lhs = tok1->previous();
if (lhs->str() == "(" && tok1->astParent() && tok1->astParent()->astParent())
lhs = tok1->astParent()->astParent();
else if (lhs->str() == "?" && lhs->astParent())
lhs = lhs->astParent();
else if (lhs->str() == ":" && lhs->astParent() && lhs->astParent()->astParent() && lhs->astParent()->str() == "?")
lhs = lhs->astParent()->astParent();
if (lhs->str() == "&") {
const Token* const top = lhs->astTop();
if (top->isAssignmentOp()) {
if (Token::simpleMatch(top->astOperand2(), "{") && !top->astOperand2()->previous()->function()) // TODO: check usage in init list
return false;
if (top->previous()->variable()) {
if (top->previous()->variable()->typeStartToken()->strAt(-1) != "const" && top->previous()->variable()->isPointer())
return false;
}
}
} else if (lhs->str() == ":" && lhs->astParent() && lhs->astParent()->str() == "(") { // range-based for-loop (C++11)
// TODO: We could additionally check what is done with the elements to avoid false negatives. Here we just rely on "const" keyword being used.
if (lhs->astParent()->strAt(1) != "const")
return false;
} else {
if (lhs->isAssignmentOp()) {
const Variable* lhsVar = lhs->previous()->variable();
if (lhsVar && !lhsVar->isConst() && lhsVar->isReference() && lhs == lhsVar->nameToken()->next())
return false;
}
}
const Token* jumpBackToken = nullptr;
const Token *lastVarTok = tok1;
const Token *end = tok1;
for (;;) {
if (Token::Match(end->next(), ". %name%")) {
end = end->tokAt(2);
if (end->varId())
lastVarTok = end;
} else if (end->strAt(1) == "[") {
if (end->varId()) {
const Variable *var = end->variable();
if (var && var->isStlType(stl_containers_not_const))
return false;
const Token* assignTok = end->next()->astParent();
if (var && assignTok && assignTok->isAssignmentOp() && assignTok->astOperand1() && assignTok->astOperand1()->variable()) {
// cppcheck-suppress shadowFunction - TODO: fix this
const Variable* assignVar = assignTok->astOperand1()->variable();
if (assignVar->isPointer() && !assignVar->isConst() && var->typeScope()) {
const auto& funcMap = var->typeScope()->functionMap;
// if there is no operator that is const and returns a non-const pointer, func cannot be const
if (std::none_of(funcMap.cbegin(), funcMap.cend(), [](const std::pair<std::string, const Function*>& fm) {
return fm.second->isConst() && fm.first == "operator[]" && !Function::returnsConst(fm.second);
}))
return false;
}
}
}
if (!jumpBackToken)
jumpBackToken = end->next(); // Check inside the [] brackets
end = end->linkAt(1);
} else if (end->strAt(1) == ")")
end = end->next();
else
break;
}
auto hasOverloadedMemberAccess = [](const Token* end, const Scope* scope) -> bool {
if (!end || !scope || !Token::simpleMatch(end->astParent(), "."))
return false;
const std::string op = "operator" + end->astParent()->originalName();
auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [&op](const Function& f) {
return f.isConst() && f.name() == op;
});
if (it == scope->functionList.end() || !it->retType || !it->retType->classScope)
return false;
const Function* func = it->retType->classScope->findFunction(end, /*requireConst*/ true);
return func && func->isConst();
};
auto isConstContainerUsage = [&](const ValueType* vt) -> bool {
if (!vt || !vt->container)
return false;
const auto yield = vt->container->getYield(end->str());
if (yield == Library::Container::Yield::START_ITERATOR || yield == Library::Container::Yield::END_ITERATOR) {
const Token* parent = tok1->astParent();
while (Token::Match(parent, "(|.|::"))
parent = parent->astParent();
if (parent && parent->isComparisonOp())
return true;
// TODO: use AST
if (parent && parent->isAssignmentOp() && tok1->tokAt(-2)->variable() && Token::Match(tok1->tokAt(-2)->variable()->typeEndToken(), "const_iterator|const_reverse_iterator"))
return true;
}
if ((yield == Library::Container::Yield::ITEM || yield == Library::Container::Yield::AT_INDEX) &&
(lhs->isComparisonOp() || lhs->isAssignmentOp() || (lhs->str() == "(" && Token::Match(lhs->astParent(), "%cop%"))))
return true; // assume that these functions have const overloads
return false;
};
if (end->strAt(1) == "(") {
const Variable *var = lastVarTok->variable();
if (!var)
return false;
if (var->isStlType() // assume all std::*::size() and std::*::empty() are const
&& (Token::Match(end, "size|empty|cend|crend|cbegin|crbegin|max_size|length|count|capacity|get_allocator|c_str|str ( )") || Token::Match(end, "rfind|copy"))) {
// empty body
}
else if (isConstContainerUsage(lastVarTok->valueType())) {
// empty body
}
else if (var->smartPointerType() && var->smartPointerType()->classScope && isConstMemberFunc(var->smartPointerType()->classScope, end)) {
// empty body
} else if (var->isSmartPointer() && Token::simpleMatch(tok1->next(), ".") && tok1->next()->originalName().empty() && mSettings->library.isFunctionConst(end)) {
// empty body
} else if (hasOverloadedMemberAccess(end, var->typeScope())) {
// empty body
} else if (!var->typeScope() || (end->function() != func && !isConstMemberFunc(var->typeScope(), end))) {
if (!mSettings->library.isFunctionConst(end))
return false;
}
}
// Assignment
else if (end->next()->isAssignmentOp())
return false;
// Streaming
else if (end->strAt(1) == "<<" && tok1->strAt(-1) != "<<")
return false;
else if (isLikelyStreamRead(tok1->previous()))
return false;
// ++/--
else if (end->next()->tokType() == Token::eIncDecOp || tok1->previous()->tokType() == Token::eIncDecOp)
return false;
const Token* start = tok1;
while (tok1->strAt(-1) == ")")
tok1 = tok1->linkAt(-1);
if (start->strAt(-1) == "delete")
return false;
tok1 = jumpBackToken?jumpBackToken:end; // Jump back to first [ to check inside, or jump to end of expression
if (tok1 == end && Token::Match(end->previous(), ". %name% ( !!)") && !checkFuncCall(tok1, scope, func)) // function call on member
return false;
}
// streaming: <<
else if (Token::simpleMatch(tok1->previous(), ") <<") &&
isMemberVar(scope, tok1->tokAt(-2))) {
const Variable* var = tok1->tokAt(-2)->variable();
if (!var || !var->isMutable())
return false;
}
// streaming: >> *this
else if (Token::simpleMatch(tok1, ">> * this") && isLikelyStreamRead(tok1)) {
return false;
}
// function/constructor call, return init list
else if (const Token* funcTok = getFuncTok(tok1)) {
if (!checkFuncCall(funcTok, scope, func))
return false;
} else if (Token::simpleMatch(tok1, "> (") && (!tok1->link() || !Token::Match(tok1->link()->previous(), "static_cast|const_cast|dynamic_cast|reinterpret_cast"))) {
return false;
}
}
return true;
}
void CheckClass::checkConstError(const Token *tok, const std::string &classname, const std::string &funcname, bool suggestStatic, bool foundAllBaseClasses)
{
checkConstError2(tok, nullptr, classname, funcname, suggestStatic, foundAllBaseClasses);
}
void CheckClass::checkConstError2(const Token *tok1, const Token *tok2, const std::string &classname, const std::string &funcname, bool suggestStatic, bool foundAllBaseClasses)
{
std::list<const Token *> toks{ tok1 };
if (tok2)
toks.push_back(tok2);
if (!suggestStatic) {
const std::string msg = foundAllBaseClasses ?
"Technically the member function '$symbol' can be const.\nThe member function '$symbol' can be made a const " :
"Either there is a missing 'override', or the member function '$symbol' can be const.\nUnless it overrides a base class member, the member function '$symbol' can be made a const ";
reportError(toks, Severity::style, "functionConst",
"$symbol:" + classname + "::" + funcname +"\n"
+ msg +
"function. Making this function 'const' should not cause compiler errors. "
"Even though the function can be made const function technically it may not make "
"sense conceptually. Think about your design and the task of the function first - is "
"it a function that must not change object internal state?", CWE398, Certainty::inconclusive);
}
else {
const std::string msg = foundAllBaseClasses ?
"Technically the member function '$symbol' can be static (but you may consider moving to unnamed namespace).\nThe member function '$symbol' can be made a static " :
"Either there is a missing 'override', or the member function '$symbol' can be static.\nUnless it overrides a base class member, the member function '$symbol' can be made a static ";
reportError(toks, Severity::performance, "functionStatic",
"$symbol:" + classname + "::" + funcname +"\n"
+ msg +
"function. Making a function static can bring a performance benefit since no 'this' instance is "
"passed to the function. This change should not cause compiler errors but it does not "
"necessarily make sense conceptually. Think about your design and the task of the function first - "
"is it a function that must not access members of class instances? And maybe it is more appropriate "
"to move this function to an unnamed namespace.", CWE398, Certainty::inconclusive);
}
}
//---------------------------------------------------------------------------
// ClassCheck: Check that initializer list is in declared order.
//---------------------------------------------------------------------------
namespace { // avoid one-definition-rule violation
struct VarInfo {
VarInfo(const Variable *_var, const Token *_tok)
: var(_var), tok(_tok) {}
const Variable *var;
const Token *tok;
std::vector<const Variable*> initArgs;
};
}
void CheckClass::initializerListOrder()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("initializerList"))
return;
// This check is not inconclusive. However it only determines if the initialization
// order is incorrect. It does not determine if being out of order causes
// a real error. Out of order is not necessarily an error but you can never
// have an error if the list is in order so this enforces defensive programming.
if (!mSettings->certainty.isEnabled(Certainty::inconclusive))
return;
logChecker("CheckClass::initializerListOrder"); // style,inconclusive
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
// iterate through all member functions looking for constructors
for (std::list<Function>::const_iterator func = scope->functionList.cbegin(); func != scope->functionList.cend(); ++func) {
if (func->isConstructor() && func->hasBody()) {
// check for initializer list
const Token *tok = func->arg->link()->next();
if (tok->str() == ":") {
std::vector<VarInfo> vars;
tok = tok->next();
// find all variable initializations in list
for (; tok && tok != func->functionScope->bodyStart; tok = tok->next()) {
if (Token::Match(tok, "%name% (|{")) {
const Token* const end = tok->linkAt(1);
const Variable *var = scope->getVariable(tok->str());
if (var)
vars.emplace_back(var, tok);
else
tok = end;
for (; tok != end; tok = tok->next()) {
if (Token::Match(tok->astParent(), ".|::"))
continue;
if (const Variable* argVar = scope->getVariable(tok->str())) {
if (scope != argVar->scope())
continue;
if (argVar->isStatic())
continue;
if (tok->variable() && tok->variable()->isArgument())
continue;
if (var->isPointer() && (argVar->isArray() || Token::simpleMatch(tok->astParent(), "&")))
continue;
if (var->isReference())
continue;
if (Token::simpleMatch(tok->astParent(), "="))
continue;
vars.back().initArgs.emplace_back(argVar);
}
}
}
}
for (std::size_t j = 0; j < vars.size(); j++) {
// check for use of uninitialized arguments
for (const auto& arg : vars[j].initArgs)
if (vars[j].var->index() < arg->index())
initializerListError(vars[j].tok, vars[j].var->nameToken(), scope->className, vars[j].var->name(), arg->name());
// need at least 2 members to have out of order initialization
if (j == 0)
continue;
// check for out of order initialization
if (vars[j].var->index() < vars[j - 1].var->index())
initializerListError(vars[j].tok,vars[j].var->nameToken(), scope->className, vars[j].var->name());
}
}
}
}
}
}
void CheckClass::initializerListError(const Token *tok1, const Token *tok2, const std::string &classname, const std::string &varname, const std::string& argname)
{
std::list<const Token *> toks = { tok1, tok2 };
const std::string msg = argname.empty() ?
"Member variable '$symbol' is in the wrong place in the initializer list." :
"Member variable '$symbol' uses an uninitialized argument '" + argname + "' due to the order of declarations.";
reportError(toks, Severity::style, "initializerList",
"$symbol:" + classname + "::" + varname + '\n' +
msg + '\n' +
msg + ' ' +
"Members are initialized in the order they are declared, not in the "
"order they are in the initializer list. Keeping the initializer list "
"in the same order that the members were declared prevents order dependent "
"initialization errors.", CWE398, Certainty::inconclusive);
}
//---------------------------------------------------------------------------
// Check for self initialization in initialization list
//---------------------------------------------------------------------------
void CheckClass::checkSelfInitialization()
{
logChecker("CheckClass::checkSelfInitialization");
for (const Scope *scope : mSymbolDatabase->functionScopes) {
const Function* function = scope->function;
if (!function || !function->isConstructor())
continue;
const Token* tok = function->arg->link()->next();
if (tok->str() != ":")
continue;
for (; tok != scope->bodyStart; tok = tok->next()) {
if (Token::Match(tok, "[:,] %var% (|{")) {
const Token* varTok = tok->next();
if (Token::Match(varTok->astParent(), "(|{")) {
if (const Token* initTok = varTok->astParent()->astOperand2()) {
if (initTok->varId() == varTok->varId())
selfInitializationError(tok, varTok->str());
else if (initTok->isCast() && ((initTok->astOperand1() && initTok->astOperand1()->varId() == varTok->varId()) || (initTok->astOperand2() && initTok->astOperand2()->varId() == varTok->varId())))
selfInitializationError(tok, varTok->str());
}
}
}
}
}
}
void CheckClass::selfInitializationError(const Token* tok, const std::string& varname)
{
reportError(tok, Severity::error, "selfInitialization", "$symbol:" + varname + "\nMember variable '$symbol' is initialized by itself.", CWE665, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for virtual function calls in constructor/destructor
//---------------------------------------------------------------------------
void CheckClass::checkVirtualFunctionCallInConstructor()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckClass::checkVirtualFunctionCallInConstructor"); // warning
std::map<const Function *, std::list<const Token *>> virtualFunctionCallsMap;
for (const Scope *scope : mSymbolDatabase->functionScopes) {
if (scope->function == nullptr || !scope->function->hasBody() ||
!(scope->function->isConstructor() ||
scope->function->isDestructor()))
continue;
const std::list<const Token *> & virtualFunctionCalls = getVirtualFunctionCalls(*scope->function, virtualFunctionCallsMap);
for (const Token *callToken : virtualFunctionCalls) {
std::list<const Token *> callstack(1, callToken);
getFirstVirtualFunctionCallStack(virtualFunctionCallsMap, callToken, callstack);
if (callstack.empty())
continue;
const Function* const func = callstack.back()->function();
if (!(func->hasVirtualSpecifier() || func->hasOverrideSpecifier()))
continue;
if (func->isPure())
pureVirtualFunctionCallInConstructorError(scope->function, callstack, callstack.back()->str());
else if (!func->hasFinalSpecifier() &&
!(func->nestedIn && func->nestedIn->classDef && func->nestedIn->classDef->isFinalType()))
virtualFunctionCallInConstructorError(scope->function, callstack, callstack.back()->str());
}
}
}
const std::list<const Token *> & CheckClass::getVirtualFunctionCalls(const Function & function,
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap)
{
const std::map<const Function *, std::list<const Token *>>::const_iterator found = virtualFunctionCallsMap.find(&function);
if (found != virtualFunctionCallsMap.end())
return found->second;
virtualFunctionCallsMap[&function] = std::list<const Token *>();
std::list<const Token *> & virtualFunctionCalls = virtualFunctionCallsMap.find(&function)->second;
if (!function.hasBody() || !function.functionScope)
return virtualFunctionCalls;
for (const Token *tok = function.arg->link(); tok != function.functionScope->bodyEnd; tok = tok->next()) {
if (function.type != Function::eConstructor &&
function.type != Function::eCopyConstructor &&
function.type != Function::eMoveConstructor &&
function.type != Function::eDestructor) {
if ((Token::simpleMatch(tok, ") {") && tok->link() && Token::Match(tok->link()->previous(), "if|switch")) ||
Token::simpleMatch(tok, "else {")) {
// Assume pure virtual function call is prevented by "if|else|switch" condition
tok = tok->linkAt(1);
continue;
}
}
if (tok->scope()->type == Scope::eLambda)
tok = tok->scope()->bodyEnd->next();
const Function * callFunction = tok->function();
if (!callFunction ||
function.nestedIn != callFunction->nestedIn ||
Token::simpleMatch(tok->previous(), ".") ||
!(tok->astParent() && (tok->astParent()->str() == "(" || (tok->astParent()->str() == "::" && Token::simpleMatch(tok->astParent()->astParent(), "(")))))
continue;
if (tok->previous() &&
tok->strAt(-1) == "(") {
const Token * prev = tok->previous();
if (prev->previous() &&
(mSettings->library.ignorefunction(tok->str())
|| mSettings->library.ignorefunction(prev->strAt(-1))))
continue;
}
if (callFunction->isImplicitlyVirtual()) {
if (!callFunction->isPure() && Token::simpleMatch(tok->previous(), "::"))
continue;
virtualFunctionCalls.push_back(tok);
continue;
}
const std::list<const Token *> & virtualFunctionCallsOfTok = getVirtualFunctionCalls(*callFunction, virtualFunctionCallsMap);
if (!virtualFunctionCallsOfTok.empty())
virtualFunctionCalls.push_back(tok);
}
return virtualFunctionCalls;
}
void CheckClass::getFirstVirtualFunctionCallStack(
std::map<const Function *, std::list<const Token *>> & virtualFunctionCallsMap,
const Token * callToken,
std::list<const Token *> & pureFuncStack)
{
const Function *callFunction = callToken->function();
if (callFunction->isImplicitlyVirtual() && (!callFunction->isPure() || !callFunction->hasBody())) {
pureFuncStack.push_back(callFunction->tokenDef);
return;
}
std::map<const Function *, std::list<const Token *>>::const_iterator found = virtualFunctionCallsMap.find(callFunction);
if (found == virtualFunctionCallsMap.cend() || found->second.empty()) {
pureFuncStack.clear();
return;
}
const Token * firstCall = *found->second.cbegin();
pureFuncStack.push_back(firstCall);
getFirstVirtualFunctionCallStack(virtualFunctionCallsMap, firstCall, pureFuncStack);
}
void CheckClass::virtualFunctionCallInConstructorError(
const Function * scopeFunction,
const std::list<const Token *> & tokStack,
const std::string &funcname)
{
if (scopeFunction && !mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("virtualCallInConstructor"))
return;
const char * scopeFunctionTypeName = scopeFunction ? getFunctionTypeName(scopeFunction->type) : "constructor";
ErrorPath errorPath;
std::transform(tokStack.cbegin(), tokStack.cend(), std::back_inserter(errorPath), [](const Token* tok) {
return ErrorPathItem(tok, "Calling " + tok->str());
});
int lineNumber = 1;
if (!errorPath.empty()) {
lineNumber = errorPath.front().first->linenr();
errorPath.back().second = funcname + " is a virtual function";
}
std::string constructorName;
if (scopeFunction) {
const Token *endToken = scopeFunction->argDef->link()->next();
if (scopeFunction->type == Function::Type::eDestructor)
constructorName = "~";
for (const Token *tok = scopeFunction->tokenDef; tok != endToken; tok = tok->next()) {
if (!constructorName.empty() && Token::Match(tok->previous(), "%name%|%num% %name%|%num%"))
constructorName += ' ';
constructorName += tok->str();
if (tok->str() == ")")
break;
}
}
reportError(errorPath, Severity::style, "virtualCallInConstructor",
"Virtual function '" + funcname + "' is called from " + scopeFunctionTypeName + " '" + constructorName + "' at line " + std::to_string(lineNumber) + ". Dynamic binding is not used.", CWE(0U), Certainty::normal);
}
void CheckClass::pureVirtualFunctionCallInConstructorError(
const Function * scopeFunction,
const std::list<const Token *> & tokStack,
const std::string &purefuncname)
{
const char * scopeFunctionTypeName = scopeFunction ? getFunctionTypeName(scopeFunction->type) : "constructor";
ErrorPath errorPath;
std::transform(tokStack.cbegin(), tokStack.cend(), std::back_inserter(errorPath), [](const Token* tok) {
return ErrorPathItem(tok, "Calling " + tok->str());
});
if (!errorPath.empty())
errorPath.back().second = purefuncname + " is a pure virtual function without body";
reportError(errorPath, Severity::warning, "pureVirtualCall",
"$symbol:" + purefuncname +"\n"
"Call of pure virtual function '$symbol' in " + scopeFunctionTypeName + ".\n"
"Call of pure virtual function '$symbol' in " + scopeFunctionTypeName + ". The call will fail during runtime.", CWE(0U), Certainty::normal);
}
//---------------------------------------------------------------------------
// Check for members hiding inherited members with the same name
//---------------------------------------------------------------------------
void CheckClass::checkDuplInheritedMembers()
{
if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("duplInheritedMember"))
return;
logChecker("CheckClass::checkDuplInheritedMembers"); // warning
// Iterate over all classes
for (const Type &classIt : mSymbolDatabase->typeList) {
// Iterate over the parent classes
checkDuplInheritedMembersRecursive(&classIt, &classIt);
}
}
namespace {
struct DuplMemberInfo {
DuplMemberInfo(const Variable* cv, const Variable* pcv, const Type::BaseInfo* pc) : classVar(cv), parentClassVar(pcv), parentClass(pc) {}
const Variable* classVar;
const Variable* parentClassVar;
const Type::BaseInfo* parentClass;
};
struct DuplMemberFuncInfo {
DuplMemberFuncInfo(const Function* cf, const Function* pcf, const Type::BaseInfo* pc) : classFunc(cf), parentClassFunc(pcf), parentClass(pc) {}
const Function* classFunc;
const Function* parentClassFunc;
const Type::BaseInfo* parentClass;
};
}
static std::vector<DuplMemberInfo> getDuplInheritedMembersRecursive(const Type* typeCurrent, const Type* typeBase, bool skipPrivate = true)
{
std::vector<DuplMemberInfo> results;
for (const Type::BaseInfo &parentClassIt : typeBase->derivedFrom) {
// Check if there is info about the 'Base' class
if (!parentClassIt.type || !parentClassIt.type->classScope)
continue;
// Don't crash on recursive templates
if (parentClassIt.type == typeBase)
continue;
// Check if they have a member variable in common
for (const Variable &classVarIt : typeCurrent->classScope->varlist) {
for (const Variable &parentClassVarIt : parentClassIt.type->classScope->varlist) {
if (classVarIt.name() == parentClassVarIt.name() && (!parentClassVarIt.isPrivate() || !skipPrivate)) // Check if the class and its parent have a common variable
results.emplace_back(&classVarIt, &parentClassVarIt, &parentClassIt);
}
}
if (typeCurrent != parentClassIt.type) {
const auto recursive = getDuplInheritedMembersRecursive(typeCurrent, parentClassIt.type, skipPrivate);
results.insert(results.end(), recursive.begin(), recursive.end());
}
}
return results;
}
static std::vector<DuplMemberFuncInfo> getDuplInheritedMemberFunctionsRecursive(const Type* typeCurrent, const Type* typeBase, bool skipPrivate = true)
{
std::vector<DuplMemberFuncInfo> results;
for (const Type::BaseInfo &parentClassIt : typeBase->derivedFrom) {
// Check if there is info about the 'Base' class
if (!parentClassIt.type || !parentClassIt.type->classScope)
continue;
// Don't crash on recursive templates
if (parentClassIt.type == typeBase)
continue;
for (const Function& classFuncIt : typeCurrent->classScope->functionList) {
if (classFuncIt.isImplicitlyVirtual())
continue;
if (classFuncIt.tokenDef->isExpandedMacro())
continue;
for (const Function& parentClassFuncIt : parentClassIt.type->classScope->functionList) {
if (classFuncIt.name() == parentClassFuncIt.name() &&
(parentClassFuncIt.access != AccessControl::Private || !skipPrivate) &&
!classFuncIt.isConstructor() && !classFuncIt.isDestructor() &&
classFuncIt.argsMatch(parentClassIt.type->classScope, parentClassFuncIt.argDef, classFuncIt.argDef, emptyString, 0) &&
(classFuncIt.isConst() == parentClassFuncIt.isConst() || Function::returnsConst(&classFuncIt) == Function::returnsConst(&parentClassFuncIt)) &&
!(classFuncIt.isDelete() || parentClassFuncIt.isDelete()))
results.emplace_back(&classFuncIt, &parentClassFuncIt, &parentClassIt);
}
}
if (typeCurrent != parentClassIt.type) {
const auto recursive = getDuplInheritedMemberFunctionsRecursive(typeCurrent, parentClassIt.type);
results.insert(results.end(), recursive.begin(), recursive.end());
}
}
return results;
}
void CheckClass::checkDuplInheritedMembersRecursive(const Type* typeCurrent, const Type* typeBase)
{
const auto resultsVar = getDuplInheritedMembersRecursive(typeCurrent, typeBase);
for (const auto& r : resultsVar) {
duplInheritedMembersError(r.classVar->nameToken(), r.parentClassVar->nameToken(),
typeCurrent->name(), r.parentClass->type->name(), r.classVar->name(),
typeCurrent->classScope->type == Scope::eStruct,
r.parentClass->type->classScope->type == Scope::eStruct);
}
const auto resultsFunc = getDuplInheritedMemberFunctionsRecursive(typeCurrent, typeBase);
for (const auto& r : resultsFunc) {
duplInheritedMembersError(r.classFunc->token, r.parentClassFunc->token,
typeCurrent->name(), r.parentClass->type->name(), r.classFunc->name(),
typeCurrent->classScope->type == Scope::eStruct,
r.parentClass->type->classScope->type == Scope::eStruct, /*isFunction*/ true);
}
}
void CheckClass::duplInheritedMembersError(const Token *tok1, const Token* tok2,
const std::string &derivedName, const std::string &baseName,
const std::string &memberName, bool derivedIsStruct, bool baseIsStruct, bool isFunction)
{
ErrorPath errorPath;
const std::string member = isFunction ? "function" : "variable";
errorPath.emplace_back(tok2, "Parent " + member + " '" + baseName + "::" + memberName + "'");
errorPath.emplace_back(tok1, "Derived " + member + " '" + derivedName + "::" + memberName + "'");
const std::string symbols = "$symbol:" + derivedName + "\n$symbol:" + memberName + "\n$symbol:" + baseName;
const std::string message = "The " + std::string(derivedIsStruct ? "struct" : "class") + " '" + derivedName +
"' defines member " + member + " with name '" + memberName + "' also defined in its parent " +
std::string(baseIsStruct ? "struct" : "class") + " '" + baseName + "'.";
reportError(errorPath, Severity::warning, "duplInheritedMember", symbols + '\n' + message, CWE398, Certainty::normal);
}
//---------------------------------------------------------------------------
// Check that copy constructor and operator defined together
//---------------------------------------------------------------------------
enum class CtorType : std::uint8_t {
NO,
WITHOUT_BODY,
WITH_BODY
};
void CheckClass::checkCopyCtorAndEqOperator()
{
// This is disabled because of #8388
// The message must be clarified. How is the behaviour different?
// cppcheck-suppress unreachableCode - remove when code is enabled again
if ((true) || !mSettings->severity.isEnabled(Severity::warning)) // NOLINT(readability-simplify-boolean-expr)
return;
// logChecker
for (const Scope * scope : mSymbolDatabase->classAndStructScopes) {
const bool hasNonStaticVars = std::any_of(scope->varlist.begin(), scope->varlist.end(), [](const Variable& var) {
return !var.isStatic();
});
if (!hasNonStaticVars)
continue;
CtorType copyCtors = CtorType::NO;
bool moveCtor = false;
CtorType assignmentOperators = CtorType::NO;
for (const Function &func : scope->functionList) {
if (copyCtors == CtorType::NO && func.type == Function::eCopyConstructor) {
copyCtors = func.hasBody() ? CtorType::WITH_BODY : CtorType::WITHOUT_BODY;
}
if (assignmentOperators == CtorType::NO && func.type == Function::eOperatorEqual) {
const Variable * variable = func.getArgumentVar(0);
if (variable && variable->type() && variable->type()->classScope == scope) {
assignmentOperators = func.hasBody() ? CtorType::WITH_BODY : CtorType::WITHOUT_BODY;
}
}
if (func.type == Function::eMoveConstructor) {
moveCtor = true;
break;
}
}
if (moveCtor)
continue;
// No method defined
if (copyCtors != CtorType::WITH_BODY && assignmentOperators != CtorType::WITH_BODY)
continue;
// both methods are defined
if (copyCtors != CtorType::NO && assignmentOperators != CtorType::NO)
continue;
copyCtorAndEqOperatorError(scope->classDef, scope->className, scope->type == Scope::eStruct, copyCtors == CtorType::WITH_BODY);
}
}
void CheckClass::copyCtorAndEqOperatorError(const Token *tok, const std::string &classname, bool isStruct, bool hasCopyCtor)
{
const std::string message = "$symbol:" + classname + "\n"
"The " + std::string(isStruct ? "struct" : "class") + " '$symbol' has '" +
getFunctionTypeName(hasCopyCtor ? Function::eCopyConstructor : Function::eOperatorEqual) +
"' but lack of '" + getFunctionTypeName(hasCopyCtor ? Function::eOperatorEqual : Function::eCopyConstructor) +
"'.";
reportError(tok, Severity::warning, "copyCtorAndEqOperator", message);
}
void CheckClass::checkOverride()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("missingOverride"))
return;
if (mSettings->standards.cpp < Standards::CPP11)
return;
logChecker("CheckClass::checkMissingOverride"); // style,c++03
for (const Scope * classScope : mSymbolDatabase->classAndStructScopes) {
if (!classScope->definedType || classScope->definedType->derivedFrom.empty())
continue;
for (const Function &func : classScope->functionList) {
if (func.hasOverrideSpecifier() || func.hasFinalSpecifier())
continue;
if (func.tokenDef->isExpandedMacro())
continue;
const Function *baseFunc = func.getOverriddenFunction();
if (baseFunc)
overrideError(baseFunc, &func);
}
}
}
void CheckClass::overrideError(const Function *funcInBase, const Function *funcInDerived)
{
const std::string functionName = funcInDerived ? ((funcInDerived->isDestructor() ? "~" : "") + funcInDerived->name()) : "";
const std::string funcType = (funcInDerived && funcInDerived->isDestructor()) ? "destructor" : "function";
ErrorPath errorPath;
if (funcInBase && funcInDerived) {
errorPath.emplace_back(funcInBase->tokenDef, "Virtual " + funcType + " in base class");
errorPath.emplace_back(funcInDerived->tokenDef, char(std::toupper(funcType[0])) + funcType.substr(1) + " in derived class");
}
reportError(errorPath, Severity::style, "missingOverride",
"$symbol:" + functionName + "\n"
"The " + funcType + " '$symbol' overrides a " + funcType + " in a base class but is not marked with a 'override' specifier.",
CWE(0U) /* Unknown CWE! */,
Certainty::normal);
}
void CheckClass::uselessOverrideError(const Function *funcInBase, const Function *funcInDerived, bool isSameCode)
{
const std::string functionName = funcInDerived ? ((funcInDerived->isDestructor() ? "~" : "") + funcInDerived->name()) : "";
const std::string funcType = (funcInDerived && funcInDerived->isDestructor()) ? "destructor" : "function";
ErrorPath errorPath;
if (funcInBase && funcInDerived) {
errorPath.emplace_back(funcInBase->tokenDef, "Virtual " + funcType + " in base class");
errorPath.emplace_back(funcInDerived->tokenDef, char(std::toupper(funcType[0])) + funcType.substr(1) + " in derived class");
}
std::string errStr = "\nThe " + funcType + " '$symbol' overrides a " + funcType + " in a base class but ";
if (isSameCode) {
errStr += "is identical to the overridden function";
}
else
errStr += "just delegates back to the base class.";
reportError(errorPath, Severity::style, "uselessOverride",
"$symbol:" + functionName +
errStr,
CWE(0U) /* Unknown CWE! */,
Certainty::normal);
}
static const Token* getSingleFunctionCall(const Scope* scope) {
const Token* const start = scope->bodyStart->next();
const Token* const end = Token::findsimplematch(start, ";", 1, scope->bodyEnd);
if (!end || end->next() != scope->bodyEnd)
return nullptr;
const Token* ftok = start;
if (ftok->str() == "return")
ftok = ftok->astOperand1();
else {
while (Token::Match(ftok, "%name%|::"))
ftok = ftok->next();
}
if (Token::simpleMatch(ftok, "(") && ftok->previous()->function())
return ftok->previous();
return nullptr;
}
static bool compareTokenRanges(const Token* start1, const Token* end1, const Token* start2, const Token* end2) {
const Token* tok1 = start1;
const Token* tok2 = start2;
bool isEqual = false;
while (tok1 && tok2) {
if (tok1->function() != tok2->function())
break;
if (tok1->str() != tok2->str())
break;
if (tok1->str() == "this")
break;
if (tok1->isExpandedMacro() || tok2->isExpandedMacro())
break;
if (tok1 == end1 && tok2 == end2) {
isEqual = true;
break;
}
tok1 = tok1->next();
tok2 = tok2->next();
}
return isEqual;
}
void CheckClass::checkUselessOverride()
{
if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("uselessOverride"))
return;
logChecker("CheckClass::checkUselessOverride"); // style
for (const Scope* classScope : mSymbolDatabase->classAndStructScopes) {
if (!classScope->definedType || classScope->definedType->derivedFrom.size() != 1)
continue;
for (const Function& func : classScope->functionList) {
if (!func.functionScope)
continue;
if (func.hasFinalSpecifier())
continue;
const Function* baseFunc = func.getOverriddenFunction();
if (!baseFunc || baseFunc->isPure() || baseFunc->access != func.access)
continue;
if (std::any_of(classScope->functionList.begin(), classScope->functionList.end(), [&func](const Function& f) { // check for overloads
if (&f == &func)
return false;
return f.name() == func.name();
}))
continue;
if (func.token->isExpandedMacro() || baseFunc->token->isExpandedMacro())
continue;
if (baseFunc->functionScope) {
bool isSameCode = compareTokenRanges(baseFunc->argDef, baseFunc->argDef->link(), func.argDef, func.argDef->link()); // function arguments
if (isSameCode) {
isSameCode = compareTokenRanges(baseFunc->functionScope->bodyStart, baseFunc->functionScope->bodyEnd, // function body
func.functionScope->bodyStart, func.functionScope->bodyEnd);
if (isSameCode) {
// bailout for shadowed members
if (!classScope->definedType ||
!getDuplInheritedMembersRecursive(classScope->definedType, classScope->definedType, /*skipPrivate*/ false).empty() ||
!getDuplInheritedMemberFunctionsRecursive(classScope->definedType, classScope->definedType, /*skipPrivate*/ false).empty())
continue;
uselessOverrideError(baseFunc, &func, true);
continue;
}
}
}
if (const Token* const call = getSingleFunctionCall(func.functionScope)) {
if (call->function() != baseFunc)
continue;
if (Token::simpleMatch(call->astParent(), "."))
continue;
std::vector<const Token*> funcArgs = getArguments(func.tokenDef);
std::vector<const Token*> callArgs = getArguments(call);
if (funcArgs.size() != callArgs.size() ||
!std::equal(funcArgs.begin(), funcArgs.end(), callArgs.begin(), [](const Token* t1, const Token* t2) {
return t1->str() == t2->str();
}))
continue;
uselessOverrideError(baseFunc, &func);
}
}
}
}
static const Variable* getSingleReturnVar(const Scope* scope) {
if (!scope || !scope->bodyStart)
return nullptr;
const Token* const start = scope->bodyStart->next();
const Token* const end = Token::findsimplematch(start, ";", 1, scope->bodyEnd);
if (!end || end->next() != scope->bodyEnd)
return nullptr;
if (!start->astOperand1() || start->str() != "return")
return nullptr;
const Token* tok = start->astOperand1();
if (tok->str() == ".") {
const Token* top = tok->astOperand1();
while (Token::Match(top, "[[.]"))
top = top->astOperand1();
if (!Token::Match(top, "%var%"))
return nullptr;
tok = tok->astOperand2();
}
return tok->variable();
}
void CheckClass::checkReturnByReference()
{
if (!mSettings->severity.isEnabled(Severity::performance) && !mSettings->isPremiumEnabled("returnByReference"))
return;
logChecker("CheckClass::checkReturnByReference"); // performance
for (const Scope* classScope : mSymbolDatabase->classAndStructScopes) {
for (const Function& func : classScope->functionList) {
if (Function::returnsPointer(&func) || Function::returnsReference(&func) || Function::returnsStandardType(&func))
continue;
if (func.isImplicitlyVirtual())
continue;
if (func.isOperator())
continue;
if (const Library::Container* container = mSettings->library.detectContainer(func.retDef))
if (container->view)
continue;
if (!func.isConst() && func.hasRvalRefQualifier())
// this method could be used by temporary objects, return by value can be dangerous
continue;
if (const Variable* var = getSingleReturnVar(func.functionScope)) {
if (!var->valueType())
continue;
if (var->isArgument())
continue;
const bool isContainer = var->valueType()->type == ValueType::Type::CONTAINER && var->valueType()->container;
const bool isView = isContainer && var->valueType()->container->view;
bool warn = isContainer && !isView;
if (!warn && !isView) {
const std::size_t size = ValueFlow::getSizeOf(*var->valueType(), *mSettings);
if (size > 2 * mSettings->platform.sizeof_pointer)
warn = true;
}
if (warn)
returnByReferenceError(&func, var);
}
}
}
}
void CheckClass::returnByReferenceError(const Function* func, const Variable* var)
{
const Token* tok = func ? func->tokenDef : nullptr;
const std::string message = "Function '" + (func ? func->name() : "func") + "()' should return member '" + (var ? var->name() : "var") + "' by const reference.";
reportError(tok, Severity::performance, "returnByReference", message);
}
void CheckClass::checkThisUseAfterFree()
{
if (!mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckClass::checkThisUseAfterFree"); // warning
for (const Scope * classScope : mSymbolDatabase->classAndStructScopes) {
for (const Variable &var : classScope->varlist) {
// Find possible "self pointer".. pointer/smartpointer member variable of "self" type.
if (var.valueType() && var.valueType()->smartPointerType != classScope->definedType && var.valueType()->typeScope != classScope) {
const ValueType valueType = ValueType::parseDecl(var.typeStartToken(), *mSettings);
if (valueType.smartPointerType != classScope->definedType)
continue;
}
// If variable is not static, check that "this" is assigned
if (!var.isStatic()) {
bool hasAssign = false;
for (const Function &func : classScope->functionList) {
if (func.type != Function::Type::eFunction || !func.hasBody())
continue;
for (const Token *tok = func.functionScope->bodyStart; tok != func.functionScope->bodyEnd; tok = tok->next()) {
if (Token::Match(tok, "%varid% = this|shared_from_this", var.declarationId())) {
hasAssign = true;
break;
}
}
if (hasAssign)
break;
}
if (!hasAssign)
continue;
}
// Check usage of self pointer..
for (const Function &func : classScope->functionList) {
if (func.type != Function::Type::eFunction || !func.hasBody())
continue;
const Token * freeToken = nullptr;
std::set<const Function *> callstack;
checkThisUseAfterFreeRecursive(classScope, &func, &var, std::move(callstack), freeToken);
}
}
}
}
bool CheckClass::checkThisUseAfterFreeRecursive(const Scope *classScope, const Function *func, const Variable *selfPointer, std::set<const Function *> callstack, const Token *&freeToken)
{
if (!func || !func->functionScope)
return false;
// avoid recursion
if (callstack.count(func))
return false;
callstack.insert(func);
const Token * const bodyStart = func->functionScope->bodyStart;
const Token * const bodyEnd = func->functionScope->bodyEnd;
for (const Token *tok = bodyStart; tok != bodyEnd; tok = tok->next()) {
const bool isDestroyed = freeToken != nullptr && !func->isStatic();
if (Token::Match(tok, "delete %var% ;") && selfPointer == tok->next()->variable()) {
freeToken = tok;
tok = tok->tokAt(2);
} else if (Token::Match(tok, "%var% . reset ( )") && selfPointer == tok->variable())
freeToken = tok;
else if (Token::Match(tok->previous(), "!!. %name% (") && tok->function() && tok->function()->nestedIn == classScope && tok->function()->type == Function::eFunction) {
if (isDestroyed) {
thisUseAfterFree(selfPointer->nameToken(), freeToken, tok);
return true;
}
if (checkThisUseAfterFreeRecursive(classScope, tok->function(), selfPointer, callstack, freeToken))
return true;
} else if (isDestroyed && Token::Match(tok->previous(), "!!. %name%") && tok->variable() && tok->variable()->scope() == classScope && !tok->variable()->isStatic() && !tok->variable()->isArgument()) {
thisUseAfterFree(selfPointer->nameToken(), freeToken, tok);
return true;
} else if (freeToken && Token::Match(tok, "return|throw")) {
// TODO
return tok->str() == "throw";
} else if (tok->str() == "{" && tok->scope()->type == Scope::ScopeType::eLambda) {
tok = tok->link();
}
}
return false;
}
void CheckClass::thisUseAfterFree(const Token *self, const Token *free, const Token *use)
{
std::string selfPointer = self ? self->str() : "ptr";
const ErrorPath errorPath = { ErrorPathItem(self, "Assuming '" + selfPointer + "' is used as 'this'"), ErrorPathItem(free, "Delete '" + selfPointer + "', invalidating 'this'"), ErrorPathItem(use, "Call method when 'this' is invalid") };
const std::string usestr = use ? use->str() : "x";
const std::string usemsg = use && use->function() ? ("Calling method '" + usestr + "()'") : ("Using member '" + usestr + "'");
reportError(errorPath, Severity::warning, "thisUseAfterFree",
"$symbol:" + selfPointer + "\n" +
usemsg + " when 'this' might be invalid",
CWE(0), Certainty::normal);
}
void CheckClass::checkUnsafeClassRefMember()
{
if (!mSettings->safeChecks.classes || !mSettings->severity.isEnabled(Severity::warning))
return;
logChecker("CheckClass::checkUnsafeClassRefMember"); // warning,safeChecks
for (const Scope * classScope : mSymbolDatabase->classAndStructScopes) {
for (const Function &func : classScope->functionList) {
if (!func.hasBody() || !func.isConstructor())
continue;
const Token *initList = func.constructorMemberInitialization();
while (Token::Match(initList, "[:,] %name% (")) {
if (Token::Match(initList->tokAt(2), "( %var% )")) {
const Variable * const memberVar = initList->next()->variable();
const Variable * const argVar = initList->tokAt(3)->variable();
if (memberVar && argVar && memberVar->isConst() && memberVar->isReference() && argVar->isArgument() && argVar->isConst() && argVar->isReference())
unsafeClassRefMemberError(initList->next(), classScope->className + "::" + memberVar->name());
}
initList = initList->linkAt(2)->next();
}
}
}
}
void CheckClass::unsafeClassRefMemberError(const Token *tok, const std::string &varname)
{
reportError(tok, Severity::warning, "unsafeClassRefMember",
"$symbol:" + varname + "\n"
"Unsafe class: The const reference member '$symbol' is initialized by a const reference constructor argument. You need to be careful about lifetime issues.\n"
"Unsafe class checking: The const reference member '$symbol' is initialized by a const reference constructor argument. You need to be careful about lifetime issues. If you pass a local variable or temporary value in this constructor argument, be extra careful. If the argument is always some global object that is never destroyed then this is safe usage. However it would be defensive to make the member '$symbol' a non-reference variable or a smart pointer.",
CWE(0), Certainty::normal);
}
// a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now
// see https://trac.cppcheck.net/ticket/12108 for more details
#ifdef __clang__
inline namespace CheckClass_internal
#else
namespace
#endif
{
/* multifile checking; one definition rule violations */
class MyFileInfo : public Check::FileInfo {
public:
struct NameLoc {
std::string className;
std::string fileName;
int lineNumber;
int column;
std::size_t hash;
bool isSameLocation(const NameLoc& other) const {
return fileName == other.fileName &&
lineNumber == other.lineNumber &&
column == other.column;
}
};
std::vector<NameLoc> classDefinitions;
/** Convert data into xml string */
std::string toString() const override
{
std::string ret;
for (const NameLoc &nameLoc: classDefinitions) {
ret += "<class name=\"" + ErrorLogger::toxml(nameLoc.className) +
"\" file=\"" + ErrorLogger::toxml(nameLoc.fileName) +
"\" line=\"" + std::to_string(nameLoc.lineNumber) +
"\" col=\"" + std::to_string(nameLoc.column) +
"\" hash=\"" + std::to_string(nameLoc.hash) +
"\"/>\n";
}
return ret;
}
};
}
Check::FileInfo *CheckClass::getFileInfo(const Tokenizer &tokenizer, const Settings& /*settings*/) const
{
if (!tokenizer.isCPP())
return nullptr;
// One definition rule
std::vector<MyFileInfo::NameLoc> classDefinitions;
for (const Scope * classScope : tokenizer.getSymbolDatabase()->classAndStructScopes) {
if (classScope->isAnonymous())
continue;
if (classScope->classDef && Token::simpleMatch(classScope->classDef->previous(), ">"))
continue;
// the full definition must be compared
const bool fullDefinition = std::all_of(classScope->functionList.cbegin(),
classScope->functionList.cend(),
[](const Function& f) {
return f.hasBody();
});
if (!fullDefinition)
continue;
std::string name;
const Scope *scope = classScope;
while (scope->isClassOrStruct() && !classScope->className.empty()) {
if (Token::Match(scope->classDef, "struct|class %name% :: %name%")) {
// TODO handle such classnames
name.clear();
break;
}
name = scope->className + "::" + name;
scope = scope->nestedIn;
}
if (name.empty())
continue;
name.erase(name.size() - 2);
if (scope->type != Scope::ScopeType::eGlobal)
continue;
MyFileInfo::NameLoc nameLoc;
nameLoc.className = std::move(name);
nameLoc.fileName = tokenizer.list.file(classScope->classDef);
nameLoc.lineNumber = classScope->classDef->linenr();
nameLoc.column = classScope->classDef->column();
// Calculate hash from the full class/struct definition
std::string def;
for (const Token *tok = classScope->classDef; tok != classScope->bodyEnd; tok = tok->next())
def += tok->str();
for (const Function &f: classScope->functionList) {
if (f.functionScope && f.functionScope->nestedIn != classScope) {
for (const Token *tok = f.functionScope->bodyStart; tok != f.functionScope->bodyEnd; tok = tok->next())
def += tok->str();
}
}
nameLoc.hash = std::hash<std::string> {}(def);
classDefinitions.push_back(std::move(nameLoc));
}
if (classDefinitions.empty())
return nullptr;
auto *fileInfo = new MyFileInfo;
fileInfo->classDefinitions.swap(classDefinitions);
return fileInfo;
}
Check::FileInfo * CheckClass::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const
{
auto *fileInfo = new MyFileInfo;
for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) {
if (std::strcmp(e->Name(), "class") != 0)
continue;
const char *name = e->Attribute("name");
const char *file = e->Attribute("file");
const char *line = e->Attribute("line");
const char *col = e->Attribute("col");
const char *hash = e->Attribute("hash");
if (name && file && line && col && hash) {
MyFileInfo::NameLoc nameLoc;
nameLoc.className = name;
nameLoc.fileName = file;
nameLoc.lineNumber = strToInt<int>(line);
nameLoc.column = strToInt<int>(col);
nameLoc.hash = strToInt<std::size_t>(hash);
fileInfo->classDefinitions.push_back(std::move(nameLoc));
}
}
if (fileInfo->classDefinitions.empty()) {
delete fileInfo;
fileInfo = nullptr;
}
return fileInfo;
}
bool CheckClass::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger)
{
bool foundErrors = false;
(void)ctu; // This argument is unused
(void)settings; // This argument is unused
std::unordered_map<std::string, MyFileInfo::NameLoc> all;
CheckClass dummy(nullptr, &settings, &errorLogger);
dummy.
logChecker("CheckClass::analyseWholeProgram");
for (const Check::FileInfo* fi1 : fileInfo) {
const auto *fi = dynamic_cast<const MyFileInfo*>(fi1);
if (!fi)
continue;
for (const MyFileInfo::NameLoc &nameLoc : fi->classDefinitions) {
auto it = all.find(nameLoc.className);
if (it == all.end()) {
all[nameLoc.className] = nameLoc;
continue;
}
if (it->second.hash == nameLoc.hash)
continue;
// Same location, sometimes the hash is different wrongly (possibly because of different token simplifications).
if (it->second.isSameLocation(nameLoc))
continue;
std::list<ErrorMessage::FileLocation> locationList;
locationList.emplace_back(nameLoc.fileName, nameLoc.lineNumber, nameLoc.column);
locationList.emplace_back(it->second.fileName, it->second.lineNumber, it->second.column);
const ErrorMessage errmsg(std::move(locationList),
emptyString,
Severity::error,
"$symbol:" + nameLoc.className +
"\nThe one definition rule is violated, different classes/structs have the same name '$symbol'",
"ctuOneDefinitionRuleViolation",
CWE_ONE_DEFINITION_RULE,
Certainty::normal);
errorLogger.reportErr(errmsg);
foundErrors = true;
}
}
return foundErrors;
}
| null |
899 | cpp | cppcheck | check.h | lib/check.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkH
#define checkH
//---------------------------------------------------------------------------
#include "config.h"
#include "errortypes.h"
#include <list>
#include <string>
#include <utility>
namespace tinyxml2 {
class XMLElement;
}
namespace CTU {
class FileInfo;
}
namespace ValueFlow {
class Value;
}
class Settings;
class Token;
class ErrorLogger;
class ErrorMessage;
class Tokenizer;
/** Use WRONG_DATA in checkers to mark conditions that check that data is correct */
#define WRONG_DATA(COND, TOK) ((COND) && wrongData((TOK), #COND))
/// @addtogroup Core
/// @{
/**
* @brief Interface class that cppcheck uses to communicate with the checks.
* All checking classes must inherit from this class
*/
class CPPCHECKLIB Check {
public:
/** This constructor is used when registering the CheckClass */
explicit Check(const std::string &aname);
protected:
/** This constructor is used when running checks. */
Check(std::string aname, const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger), mName(std::move(aname)) {}
public:
virtual ~Check() {
if (!mTokenizer)
instances().remove(this);
}
Check(const Check &) = delete;
Check& operator=(const Check &) = delete;
/** List of registered check classes. This is used by Cppcheck to run checks and generate documentation */
static std::list<Check *> &instances();
/** run checks, the token list is not simplified */
virtual void runChecks(const Tokenizer &, ErrorLogger *) = 0;
/** get error messages */
virtual void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const = 0;
/** class name, used to generate documentation */
const std::string& name() const {
return mName;
}
/** get information about this class, used to generate documentation */
virtual std::string classInfo() const = 0;
/**
* Write given error to stdout in xml format.
* This is for for printout out the error list with --errorlist
* @param errmsg Error message to write
*/
static void writeToErrorList(const ErrorMessage &errmsg);
/** Base class used for whole-program analysis */
class CPPCHECKLIB FileInfo {
public:
FileInfo() = default;
virtual ~FileInfo() = default;
virtual std::string toString() const {
return std::string();
}
};
virtual FileInfo * getFileInfo(const Tokenizer& /*tokenizer*/, const Settings& /*settings*/) const {
return nullptr;
}
virtual FileInfo * loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const {
(void)xmlElement;
return nullptr;
}
// Return true if an error is reported.
virtual bool analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<FileInfo*> &fileInfo, const Settings& /*settings*/, ErrorLogger & /*errorLogger*/) {
(void)ctu;
(void)fileInfo;
//(void)settings;
//(void)errorLogger;
return false;
}
protected:
static std::string getMessageId(const ValueFlow::Value &value, const char id[]);
const Tokenizer* const mTokenizer{};
const Settings* const mSettings{};
ErrorLogger* const mErrorLogger{};
/** report an error */
void reportError(const Token *tok, const Severity severity, const std::string &id, const std::string &msg) {
reportError(tok, severity, id, msg, CWE(0U), Certainty::normal);
}
/** report an error */
void reportError(const Token *tok, const Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty) {
const std::list<const Token *> callstack(1, tok);
reportError(callstack, severity, id, msg, cwe, certainty);
}
/** report an error */
void reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg) {
reportError(callstack, severity, id, msg, CWE(0U), Certainty::normal);
}
/** report an error */
void reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty);
void reportError(const ErrorPath &errorPath, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty);
/** log checker */
void logChecker(const char id[]);
ErrorPath getErrorPath(const Token* errtok, const ValueFlow::Value* value, std::string bug) const;
/**
* Use WRONG_DATA in checkers when you check for wrong data. That
* will call this method
*/
bool wrongData(const Token *tok, const char *str);
private:
const std::string mName;
};
/// @}
//---------------------------------------------------------------------------
#endif // checkH
| null |
900 | cpp | cppcheck | checkother.h | lib/checkother.h | null | /* -*- C++ -*-
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2024 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
//---------------------------------------------------------------------------
#ifndef checkotherH
#define checkotherH
//---------------------------------------------------------------------------
#include "check.h"
#include "config.h"
#include "errortypes.h"
#include "tokenize.h"
#include <set>
#include <string>
#include <vector>
namespace ValueFlow {
class Value;
}
class Settings;
class Token;
class Function;
class Variable;
class ErrorLogger;
/// @addtogroup Checks
/// @{
/** @brief Various small checks */
class CPPCHECKLIB CheckOther : public Check {
friend class TestCharVar;
friend class TestIncompleteStatement;
friend class TestOther;
public:
/** @brief This constructor is used when registering the CheckClass */
CheckOther() : Check(myName()) {}
/** Is expression a comparison that checks if a nonzero (unsigned/pointer) expression is less than zero? */
static bool comparisonNonZeroExpressionLessThanZero(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr, bool suppress = false);
/** Is expression a comparison that checks if a nonzero (unsigned/pointer) expression is positive? */
static bool testIfNonZeroExpressionIsPositive(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr);
private:
/** @brief This constructor is used when running checks. */
CheckOther(const Tokenizer *tokenizer, const Settings *settings, ErrorLogger *errorLogger)
: Check(myName(), tokenizer, settings, errorLogger) {}
/** @brief Run checks against the normal token list */
void runChecks(const Tokenizer &tokenizer, ErrorLogger *errorLogger) override {
CheckOther checkOther(&tokenizer, &tokenizer.getSettings(), errorLogger);
// Checks
checkOther.warningOldStylePointerCast();
checkOther.suspiciousFloatingPointCast();
checkOther.invalidPointerCast();
checkOther.checkCharVariable();
checkOther.redundantBitwiseOperationInSwitchError();
checkOther.checkSuspiciousCaseInSwitch();
checkOther.checkDuplicateBranch();
checkOther.checkDuplicateExpression();
checkOther.checkRedundantAssignment();
checkOther.checkUnreachableCode();
checkOther.checkSuspiciousSemicolon();
checkOther.checkVariableScope();
checkOther.checkSignOfUnsignedVariable(); // don't ignore casts (#3574)
checkOther.checkIncompleteArrayFill();
checkOther.checkVarFuncNullUB();
checkOther.checkNanInArithmeticExpression();
checkOther.checkCommaSeparatedReturn();
checkOther.checkRedundantPointerOp();
checkOther.checkZeroDivision();
checkOther.checkNegativeBitwiseShift();
checkOther.checkInterlockedDecrement();
checkOther.checkUnusedLabel();
checkOther.checkEvaluationOrder();
checkOther.checkFuncArgNamesDifferent();
checkOther.checkShadowVariables();
checkOther.checkKnownArgument();
checkOther.checkKnownPointerToBool();
checkOther.checkComparePointers();
checkOther.checkIncompleteStatement();
checkOther.checkRedundantCopy();
checkOther.clarifyCalculation();
checkOther.checkPassByReference();
checkOther.checkConstVariable();
checkOther.checkConstPointer();
checkOther.checkComparisonFunctionIsAlwaysTrueOrFalse();
checkOther.checkInvalidFree();
checkOther.clarifyStatement();
checkOther.checkCastIntToCharAndBack();
checkOther.checkMisusedScopedObject();
checkOther.checkAccessOfMovedVariable();
checkOther.checkModuloOfOne();
checkOther.checkOverlappingWrite();
}
/** @brief Clarify calculation for ".. a * b ? .." */
void clarifyCalculation();
/** @brief Suspicious statement like '*A++;' */
void clarifyStatement();
/** @brief Are there C-style pointer casts in a c++ file? */
void warningOldStylePointerCast();
void suspiciousFloatingPointCast();
/** @brief Check for pointer casts to a type with an incompatible binary data representation */
void invalidPointerCast();
/** @brief %Check scope of variables */
void checkVariableScope();
bool checkInnerScope(const Token *tok, const Variable* var, bool& used) const;
/** @brief %Check for comma separated statements in return */
void checkCommaSeparatedReturn();
/** @brief %Check for function parameters that should be passed by reference */
void checkPassByReference();
void checkConstVariable();
void checkConstPointer();
/** @brief Using char variable as array index / as operand in bit operation */
void checkCharVariable();
/** @brief Incomplete statement. A statement that only contains a constant or variable */
void checkIncompleteStatement();
/** @brief %Check zero division*/
void checkZeroDivision();
/** @brief Check for NaN (not-a-number) in an arithmetic expression */
void checkNanInArithmeticExpression();
/** @brief copying to memory or assigning to a variable twice */
void checkRedundantAssignment();
/** @brief %Check for redundant bitwise operation in switch statement*/
void redundantBitwiseOperationInSwitchError();
/** @brief %Check for code like 'case A||B:'*/
void checkSuspiciousCaseInSwitch();
/** @brief %Check for objects that are destroyed immediately */
void checkMisusedScopedObject();
/** @brief %Check for suspicious code where if and else branch are the same (e.g "if (a) b = true; else b = true;") */
void checkDuplicateBranch();
/** @brief %Check for suspicious code with the same expression on both sides of operator (e.g "if (a && a)") */
void checkDuplicateExpression();
/** @brief %Check for code that gets never executed, such as duplicate break statements */
void checkUnreachableCode();
/** @brief %Check for testing sign of unsigned variable */
void checkSignOfUnsignedVariable();
/** @brief %Check for suspicious use of semicolon */
void checkSuspiciousSemicolon();
/** @brief %Check for free() operations on invalid memory locations */
void checkInvalidFree();
void invalidFreeError(const Token *tok, const std::string &allocation, bool inconclusive);
/** @brief %Check for code creating redundant copies */
void checkRedundantCopy();
/** @brief %Check for bitwise shift with negative right operand */
void checkNegativeBitwiseShift();
/** @brief %Check for buffers that are filled incompletely with memset and similar functions */
void checkIncompleteArrayFill();
/** @brief %Check that variadic function calls don't use NULL. If NULL is \#defined as 0 and the function expects a pointer, the behaviour is undefined. */
void checkVarFuncNullUB();
/** @brief %Check to avoid casting a return value to unsigned char and then back to integer type. */
void checkCastIntToCharAndBack();
/** @brief %Check for using of comparison functions evaluating always to true or false. */
void checkComparisonFunctionIsAlwaysTrueOrFalse();
/** @brief %Check for redundant pointer operations */
void checkRedundantPointerOp();
/** @brief %Check for race condition with non-interlocked access after InterlockedDecrement() */
void checkInterlockedDecrement();
/** @brief %Check for unused labels */
void checkUnusedLabel();
/** @brief %Check for expression that depends on order of evaluation of side effects */
void checkEvaluationOrder();
/** @brief %Check for access of moved or forwarded variable */
void checkAccessOfMovedVariable();
/** @brief %Check if function declaration and definition argument names different */
void checkFuncArgNamesDifferent();
/** @brief %Check for shadow variables. Less noisy than gcc/clang -Wshadow. */
void checkShadowVariables();
void checkKnownArgument();
void checkKnownPointerToBool();
void checkComparePointers();
void checkModuloOfOne();
void checkOverlappingWrite();
void overlappingWriteUnion(const Token *tok);
void overlappingWriteFunction(const Token *tok);
// Error messages..
void checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, bool result);
void checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName);
void clarifyCalculationError(const Token *tok, const std::string &op);
void clarifyStatementError(const Token* tok);
void cstyleCastError(const Token *tok, bool isPtr = true);
void suspiciousFloatingPointCastError(const Token *tok);
void invalidPointerCastError(const Token* tok, const std::string& from, const std::string& to, bool inconclusive, bool toIsInt);
void passedByValueError(const Variable* var, bool inconclusive, bool isRangeBasedFor = false);
void constVariableError(const Variable *var, const Function *function);
void constStatementError(const Token *tok, const std::string &type, bool inconclusive);
void signedCharArrayIndexError(const Token *tok);
void unknownSignCharArrayIndexError(const Token *tok);
void charBitOpError(const Token *tok);
void variableScopeError(const Token *tok, const std::string &varname);
void zerodivError(const Token *tok, const ValueFlow::Value *value);
void nanInArithmeticExpressionError(const Token *tok);
void redundantAssignmentError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive);
void redundantInitializationError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive);
void redundantAssignmentInSwitchError(const Token *tok1, const Token *tok2, const std::string &var);
void redundantAssignmentSameValueError(const Token* tok, const ValueFlow::Value* val, const std::string& var);
void redundantCopyError(const Token *tok1, const Token* tok2, const std::string& var);
void redundantBitwiseOperationInSwitchError(const Token *tok, const std::string &varname);
void suspiciousCaseInSwitchError(const Token* tok, const std::string& operatorString);
void selfAssignmentError(const Token *tok, const std::string &varname);
void misusedScopeObjectError(const Token *tok, const std::string &varname, bool isAssignment = false);
void duplicateBranchError(const Token *tok1, const Token *tok2, ErrorPath errors);
void duplicateAssignExpressionError(const Token *tok1, const Token *tok2, bool inconclusive);
void oppositeExpressionError(const Token *opTok, ErrorPath errors);
void duplicateExpressionError(const Token *tok1, const Token *tok2, const Token *opTok, ErrorPath errors, bool hasMultipleExpr = false);
void duplicateValueTernaryError(const Token *tok);
void duplicateExpressionTernaryError(const Token *tok, ErrorPath errors);
void duplicateBreakError(const Token *tok, bool inconclusive);
void unreachableCodeError(const Token* tok, const Token* noreturn, bool inconclusive);
void redundantContinueError(const Token* tok);
void unsignedLessThanZeroError(const Token *tok, const ValueFlow::Value *v, const std::string &varname);
void pointerLessThanZeroError(const Token *tok, const ValueFlow::Value *v);
void unsignedPositiveError(const Token *tok, const ValueFlow::Value *v, const std::string &varname);
void pointerPositiveError(const Token *tok, const ValueFlow::Value *v);
void suspiciousSemicolonError(const Token *tok);
void negativeBitwiseShiftError(const Token *tok, int op);
void redundantCopyError(const Token *tok, const std::string &varname);
void incompleteArrayFillError(const Token* tok, const std::string& buffer, const std::string& function, bool boolean);
void varFuncNullUBError(const Token *tok);
void commaSeparatedReturnError(const Token *tok);
void redundantPointerOpError(const Token* tok, const std::string& varname, bool inconclusive, bool addressOfDeref);
void raceAfterInterlockedDecrementError(const Token* tok);
void unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef);
void unknownEvaluationOrder(const Token* tok, bool isUnspecifiedBehavior = false);
void accessMovedError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive);
void funcArgNamesDifferent(const std::string & functionName, nonneg int index, const Token* declaration, const Token* definition);
void funcArgOrderDifferent(const std::string & functionName, const Token * declaration, const Token * definition, const std::vector<const Token*> & declarations, const std::vector<const Token*> & definitions);
void shadowError(const Token *var, const Token *shadowed, const std::string& type);
void knownArgumentError(const Token *tok, const Token *ftok, const ValueFlow::Value *value, const std::string &varexpr, bool isVariableExpressionHidden);
void knownPointerToBoolError(const Token* tok, const ValueFlow::Value* value);
void comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2);
void checkModuloOfOneError(const Token *tok);
void getErrorMessages(ErrorLogger *errorLogger, const Settings *settings) const override {
CheckOther c(nullptr, settings, errorLogger);
// error
c.zerodivError(nullptr, nullptr);
c.misusedScopeObjectError(nullptr, "varname");
c.invalidPointerCastError(nullptr, "float *", "double *", false, false);
c.negativeBitwiseShiftError(nullptr, 1);
c.negativeBitwiseShiftError(nullptr, 2);
c.raceAfterInterlockedDecrementError(nullptr);
c.invalidFreeError(nullptr, "malloc", false);
c.overlappingWriteUnion(nullptr);
c.overlappingWriteFunction(nullptr);
//performance
c.redundantCopyError(nullptr, "varname");
c.redundantCopyError(nullptr, nullptr, "var");
// style/warning
c.checkComparisonFunctionIsAlwaysTrueOrFalseError(nullptr, "isless","varName",false);
c.checkCastIntToCharAndBackError(nullptr, "func_name");
c.cstyleCastError(nullptr);
c.suspiciousFloatingPointCastError(nullptr);
c.passedByValueError(nullptr, false);
c.constVariableError(nullptr, nullptr);
c.constStatementError(nullptr, "type", false);
c.signedCharArrayIndexError(nullptr);
c.unknownSignCharArrayIndexError(nullptr);
c.charBitOpError(nullptr);
c.variableScopeError(nullptr, "varname");
c.redundantAssignmentInSwitchError(nullptr, nullptr, "var");
c.suspiciousCaseInSwitchError(nullptr, "||");
c.selfAssignmentError(nullptr, "varname");
c.clarifyCalculationError(nullptr, "+");
c.clarifyStatementError(nullptr);
c.duplicateBranchError(nullptr, nullptr, ErrorPath{});
c.duplicateAssignExpressionError(nullptr, nullptr, true);
c.oppositeExpressionError(nullptr, ErrorPath{});
c.duplicateExpressionError(nullptr, nullptr, nullptr, ErrorPath{});
c.duplicateValueTernaryError(nullptr);
c.duplicateExpressionTernaryError(nullptr, ErrorPath{});
c.duplicateBreakError(nullptr, false);
c.unreachableCodeError(nullptr, nullptr, false);
c.unsignedLessThanZeroError(nullptr, nullptr, "varname");
c.unsignedPositiveError(nullptr, nullptr, "varname");
c.pointerLessThanZeroError(nullptr, nullptr);
c.pointerPositiveError(nullptr, nullptr);
c.suspiciousSemicolonError(nullptr);
c.incompleteArrayFillError(nullptr, "buffer", "memset", false);
c.varFuncNullUBError(nullptr);
c.nanInArithmeticExpressionError(nullptr);
c.commaSeparatedReturnError(nullptr);
c.redundantPointerOpError(nullptr, "varname", false, /*addressOfDeref*/ true);
c.unusedLabelError(nullptr, false, false);
c.unusedLabelError(nullptr, false, true);
c.unusedLabelError(nullptr, true, false);
c.unusedLabelError(nullptr, true, true);
c.unknownEvaluationOrder(nullptr);
c.accessMovedError(nullptr, "v", nullptr, false);
c.funcArgNamesDifferent("function", 1, nullptr, nullptr);
c.redundantBitwiseOperationInSwitchError(nullptr, "varname");
c.shadowError(nullptr, nullptr, "variable");
c.shadowError(nullptr, nullptr, "function");
c.shadowError(nullptr, nullptr, "argument");
c.knownArgumentError(nullptr, nullptr, nullptr, "x", false);
c.knownPointerToBoolError(nullptr, nullptr);
c.comparePointersError(nullptr, nullptr, nullptr);
c.redundantAssignmentError(nullptr, nullptr, "var", false);
c.redundantInitializationError(nullptr, nullptr, "var", false);
const std::vector<const Token *> nullvec;
c.funcArgOrderDifferent("function", nullptr, nullptr, nullvec, nullvec);
c.checkModuloOfOneError(nullptr);
}
static std::string myName() {
return "Other";
}
std::string classInfo() const override {
return "Other checks\n"
// error
"- division with zero\n"
"- scoped object destroyed immediately after construction\n"
"- assignment in an assert statement\n"
"- free() or delete of an invalid memory location\n"
"- bitwise operation with negative right operand\n"
"- cast the return values of getc(),fgetc() and getchar() to character and compare it to EOF\n"
"- race condition with non-interlocked access after InterlockedDecrement() call\n"
"- expression 'x = x++;' depends on order of evaluation of side effects\n"
"- overlapping write of union\n"
// warning
"- either division by zero or useless condition\n"
"- access of moved or forwarded variable.\n"
// performance
"- redundant data copying for const variable\n"
"- subsequent assignment or copying to a variable or buffer\n"
"- passing parameter by value\n"
// portability
"- Passing NULL pointer to function with variable number of arguments leads to UB.\n"
// style
"- C-style pointer cast in C++ code\n"
"- casting between incompatible pointer types\n"
"- [Incomplete statement](IncompleteStatement)\n"
"- [check how signed char variables are used](CharVar)\n"
"- variable scope can be limited\n"
"- unusual pointer arithmetic. For example: \"abc\" + 'd'\n"
"- redundant assignment, increment, or bitwise operation in a switch statement\n"
"- redundant strcpy in a switch statement\n"
"- Suspicious case labels in switch()\n"
"- assignment of a variable to itself\n"
"- Comparison of values leading always to true or false\n"
"- Clarify calculation with parentheses\n"
"- suspicious comparison of '\\0' with a char\\* variable\n"
"- duplicate break statement\n"
"- unreachable code\n"
"- testing if unsigned variable is negative/positive\n"
"- Suspicious use of ; at the end of 'if/for/while' statement.\n"
"- Array filled incompletely using memset/memcpy/memmove.\n"
"- NaN (not a number) value used in arithmetic expression.\n"
"- comma in return statement (the comma can easily be misread as a semicolon).\n"
"- prefer erfc, expm1 or log1p to avoid loss of precision.\n"
"- identical code in both branches of if/else or ternary operator.\n"
"- redundant pointer operation on pointer like &\\*some_ptr.\n"
"- find unused 'goto' labels.\n"
"- function declaration and definition argument names different.\n"
"- function declaration and definition argument order different.\n"
"- shadow variable.\n"
"- variable can be declared const.\n"
"- calculating modulo of one.\n"
"- known function argument, suspicious calculation.\n";
}
bool diag(const Token* tok) {
return !mRedundantAssignmentDiag.emplace(tok).second;
}
std::set<const Token*> mRedundantAssignmentDiag;
};
/// @}
//---------------------------------------------------------------------------
#endif // checkotherH
| null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.