2014-08-29 17:06:46 +02:00
/*
* Cppcheck - A tool for static C / C + + code analysis
2020-05-10 11:16:32 +02:00
* Copyright ( C ) 2007 - 2020 Cppcheck team .
2014-08-29 17:06:46 +02:00
*
* 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"
2017-05-27 04:33:47 +02:00
2015-08-02 21:57:32 +02:00
# include "astutils.h"
2017-05-27 04:33:47 +02:00
# include "settings.h"
2014-08-29 17:06:46 +02:00
# include "symboldatabase.h"
2017-05-27 04:33:47 +02:00
# include "token.h"
# include "tokenize.h"
# include "valueflow.h"
2014-08-29 17:06:46 +02:00
2017-05-27 04:33:47 +02:00
# include <algorithm>
# include <cstddef>
2015-06-18 19:07:51 +02:00
# include <limits>
2017-05-27 04:33:47 +02:00
# include <list>
# include <ostream>
# include <set>
2015-07-30 13:30:16 +02:00
# include <stack>
2017-05-27 04:33:47 +02:00
# include <utility>
2015-06-18 19:07:51 +02:00
2016-02-27 16:03:50 +01:00
// CWE ids used
2021-01-05 11:38:19 +01:00
static const struct CWE uncheckedErrorConditionCWE ( 391U ) ;
2016-08-24 12:43:45 +02:00
static const struct CWE CWE398 ( 398U ) ; // Indicator of Poor Code Quality
static const struct CWE CWE570 ( 570U ) ; // Expression is Always False
static const struct CWE CWE571 ( 571U ) ; // Expression is Always True
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
2014-08-29 17:06:46 +02:00
//---------------------------------------------------------------------------
// Register this check class (by creating a static instance of it)
namespace {
CheckCondition instance ;
}
2018-11-07 06:49:07 +01:00
bool CheckCondition : : diag ( const Token * tok , bool insert )
{
2018-11-10 21:30:01 +01:00
if ( ! tok )
2018-11-07 06:49:07 +01:00
return false ;
2020-08-31 08:46:56 +02:00
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 ) {
2018-11-10 21:30:01 +01:00
if ( insert )
2018-11-07 06:49:07 +01:00
mCondDiags . insert ( tok ) ;
return false ;
}
return true ;
}
2019-07-16 08:21:06 +02:00
bool CheckCondition : : isAliased ( const std : : set < int > & vars ) const
2017-09-04 14:52:10 +02:00
{
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
2017-09-04 14:52:10 +02:00
if ( Token : : Match ( tok , " = & %var% ; " ) & & vars . find ( tok - > tokAt ( 2 ) - > varId ( ) ) ! = vars . end ( ) )
return true ;
}
return false ;
2017-09-04 09:34:03 +02:00
}
2014-08-29 17:06:46 +02:00
void CheckCondition : : assignIf ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
2014-08-29 17:06:46 +02:00
if ( tok - > str ( ) ! = " = " )
continue ;
if ( Token : : Match ( tok - > tokAt ( - 2 ) , " [;{}] %var% = " ) ) {
const Variable * var = tok - > previous ( ) - > variable ( ) ;
2017-08-09 20:00:26 +02:00
if ( var = = nullptr )
2014-08-29 17:06:46 +02:00
continue ;
char bitop = ' \0 ' ;
MathLib : : bigint num = 0 ;
if ( Token : : Match ( tok - > next ( ) , " %num% [&|] " ) ) {
bitop = tok - > strAt ( 2 ) . at ( 0 ) ;
num = MathLib : : toLongNumber ( tok - > next ( ) - > str ( ) ) ;
} 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 : : toLongNumber ( endToken - > previous ( ) - > str ( ) ) ;
}
}
if ( bitop = = ' \0 ' )
continue ;
if ( num < 0 & & bitop = = ' | ' )
continue ;
assignIfParseScope ( tok , tok - > tokAt ( 4 ) , var - > declarationId ( ) , var - > isLocal ( ) , bitop , num ) ;
}
}
}
2015-07-23 12:06:33 +02:00
static bool isParameterChanged ( const Token * partok )
{
bool addressOf = Token : : Match ( partok , " [(,] & " ) ;
2019-07-16 08:21:06 +02:00
int argumentNumber = 0 ;
2015-07-23 12:06:33 +02:00
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 ;
}
2014-08-29 17:06:46 +02:00
/** parse scopes recursively */
bool CheckCondition : : assignIfParseScope ( const Token * const assignTok ,
const Token * const startTok ,
2019-07-16 08:21:06 +02:00
const nonneg int varid ,
2014-08-29 17:06:46 +02:00
const bool islocal ,
const char bitop ,
const MathLib : : bigint num )
{
bool ret = false ;
for ( const Token * tok2 = startTok ; tok2 ; tok2 = tok2 - > next ( ) ) {
2014-09-01 10:52:27 +02:00
if ( ( bitop = = ' & ' ) & & Token : : Match ( tok2 - > tokAt ( 2 ) , " %varid% %cop% %num% ; " , varid ) & & tok2 - > strAt ( 3 ) = = std : : string ( 1U , bitop ) ) {
2014-08-29 17:06:46 +02:00
const MathLib : : bigint num2 = MathLib : : toLongNumber ( tok2 - > strAt ( 4 ) ) ;
2014-09-01 10:52:27 +02:00
if ( 0 = = ( num & num2 ) )
2014-08-29 17:06:46 +02:00
mismatchingBitAndError ( assignTok , num , tok2 , num2 ) ;
}
if ( Token : : Match ( tok2 , " %varid% = " , varid ) ) {
return true ;
}
2019-03-09 22:00:59 +01:00
if ( bitop = = ' & ' & & Token : : Match ( tok2 , " %varid% &= %num% ; " , varid ) ) {
const MathLib : : bigint num2 = MathLib : : toLongNumber ( tok2 - > strAt ( 2 ) ) ;
if ( 0 = = ( num & num2 ) )
mismatchingBitAndError ( assignTok , num , tok2 , num2 ) ;
}
2014-08-29 17:06:46 +02:00
if ( Token : : Match ( tok2 , " ++|-- %varid% " , varid ) | | Token : : Match ( tok2 , " %varid% ++|-- " , varid ) )
return true ;
2015-07-23 12:06:33 +02:00
if ( Token : : Match ( tok2 , " [(,] &| %varid% [,)] " , varid ) & & isParameterChanged ( tok2 ) )
return true ;
2014-08-29 17:06:46 +02:00
if ( tok2 - > str ( ) = = " } " )
return false ;
if ( Token : : Match ( tok2 , " break|continue|return " ) )
ret = true ;
if ( ret & & tok2 - > str ( ) = = " ; " )
return false ;
2015-01-31 10:50:39 +01:00
if ( ! islocal & & Token : : Match ( tok2 , " %name% ( " ) & & ! Token : : simpleMatch ( tok2 - > next ( ) - > link ( ) , " ) { " ) )
2014-08-29 17:06:46 +02:00
return true ;
if ( Token : : Match ( tok2 , " if|while ( " ) ) {
if ( ! islocal & & tok2 - > str ( ) = = " while " )
continue ;
2015-11-11 13:45:28 +01:00
if ( tok2 - > str ( ) = = " while " ) {
// is variable changed in loop?
const Token * bodyStart = tok2 - > linkAt ( 1 ) - > next ( ) ;
const Token * bodyEnd = bodyStart ? bodyStart - > link ( ) : nullptr ;
2018-06-16 16:10:28 +02:00
if ( ! bodyEnd | | bodyEnd - > str ( ) ! = " } " | | isVariableChanged ( bodyStart , bodyEnd , varid , ! islocal , mSettings , mTokenizer - > isCPP ( ) ) )
2015-11-11 13:45:28 +01:00
continue ;
}
2014-08-29 17:06:46 +02:00
// parse condition
const Token * const end = tok2 - > next ( ) - > link ( ) ;
for ( ; tok2 ! = end ; tok2 = tok2 - > next ( ) ) {
if ( Token : : Match ( tok2 , " [(,] &| %varid% [,)] " , varid ) ) {
return true ;
}
2017-09-18 01:45:02 +02:00
if ( Token : : Match ( tok2 , " &&|%oror%|( %varid% ==|!= %num% &&|%oror%|) " , varid ) ) {
2014-08-29 17:06:46 +02:00
const Token * vartok = tok2 - > next ( ) ;
const MathLib : : bigint num2 = MathLib : : toLongNumber ( vartok - > strAt ( 2 ) ) ;
2017-09-18 02:06:35 +02:00
if ( ( num & num2 ) ! = ( ( bitop = = ' & ' ) ? num2 : num ) ) {
2017-12-26 00:07:24 +01:00
const std : : string & op ( vartok - > strAt ( 1 ) ) ;
2017-09-18 02:06:35 +02:00
const bool alwaysTrue = op = = " != " ;
const std : : string condition ( vartok - > str ( ) + op + vartok - > strAt ( 2 ) ) ;
assignIfError ( assignTok , tok2 , condition , alwaysTrue ) ;
}
2014-08-29 17:06:46 +02:00
}
2015-06-20 16:23:16 +02:00
if ( Token : : Match ( tok2 , " %varid% %op% " , varid ) & & tok2 - > next ( ) - > isAssignmentOp ( ) ) {
return true ;
}
2014-08-29 17:06:46 +02:00
}
2018-04-05 15:53:49 +02:00
const bool ret1 = assignIfParseScope ( assignTok , end - > tokAt ( 2 ) , varid , islocal , bitop , num ) ;
2014-08-29 17:06:46 +02:00
bool ret2 = false ;
if ( Token : : simpleMatch ( end - > next ( ) - > link ( ) , " } else { " ) )
ret2 = assignIfParseScope ( assignTok , end - > next ( ) - > link ( ) - > 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 )
{
2019-09-20 15:06:37 +02:00
if ( tok2 & & diag ( tok2 - > tokAt ( 2 ) ) )
return ;
2018-04-09 09:54:39 +02:00
std : : list < const Token * > locations = { tok1 , tok2 } ;
2014-08-29 17:06:46 +02:00
reportError ( locations ,
Severity : : style ,
" assignIfError " ,
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
" Mismatching assignment and comparison, comparison ' " + condition + " ' is always " + std : : string ( result ? " true " : " false " ) + " . " , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
void CheckCondition : : mismatchingBitAndError ( const Token * tok1 , const MathLib : : bigint num1 , const Token * tok2 , const MathLib : : bigint num2 )
{
2018-04-09 09:54:39 +02:00
std : : list < const Token * > locations = { tok1 , tok2 } ;
2014-08-29 17:06:46 +02:00
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 " ,
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
msg . str ( ) , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
static void getnumchildren ( const Token * tok , std : : list < MathLib : : bigint > & numchildren )
{
if ( tok - > astOperand1 ( ) & & tok - > astOperand1 ( ) - > isNumber ( ) )
numchildren . push_back ( MathLib : : toLongNumber ( 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 : : toLongNumber ( tok - > astOperand2 ( ) - > str ( ) ) ) ;
else if ( tok - > astOperand2 ( ) & & tok - > str ( ) = = tok - > astOperand2 ( ) - > str ( ) )
getnumchildren ( tok - > astOperand2 ( ) , numchildren ) ;
}
2015-09-02 23:00:29 +02:00
/* Return whether tok is in the body for a function returning a boolean. */
static bool inBooleanFunction ( const Token * tok )
{
2017-08-09 20:00:26 +02:00
const Scope * scope = tok ? tok - > scope ( ) : nullptr ;
2015-09-02 23:00:29 +02:00
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 ;
2017-02-06 15:37:12 +01:00
while ( Token : : Match ( ret , " static|const " ) )
2015-09-02 23:00:29 +02:00
ret = ret - > next ( ) ;
2017-03-04 11:13:28 +01:00
return Token : : Match ( ret , " bool|_Bool " ) ;
2015-09-02 23:00:29 +02:00
}
}
return false ;
}
2015-02-22 13:09:39 +01:00
void CheckCondition : : checkBadBitmaskCheck ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2015-02-22 13:09:39 +01:00
return ;
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
2015-02-22 13:09:39 +01:00
if ( tok - > str ( ) = = " | " & & tok - > astOperand1 ( ) & & tok - > astOperand2 ( ) & & tok - > astParent ( ) ) {
2015-02-26 12:34:18 +01:00
const Token * parent = tok - > astParent ( ) ;
const bool isBoolean = Token : : Match ( parent , " &&|%oror% " ) | |
( parent - > str ( ) = = " ? " & & parent - > astOperand1 ( ) = = tok ) | |
2017-03-04 11:13:28 +01:00
( parent - > str ( ) = = " = " & & parent - > astOperand2 ( ) = = tok & & parent - > astOperand1 ( ) & & parent - > astOperand1 ( ) - > variable ( ) & & Token : : Match ( parent - > astOperand1 ( ) - > variable ( ) - > typeStartToken ( ) , " bool|_Bool " ) ) | |
2015-09-02 23:00:29 +02:00
( parent - > str ( ) = = " ( " & & Token : : Match ( parent - > astOperand1 ( ) , " if|while " ) ) | |
( parent - > str ( ) = = " return " & & parent - > astOperand1 ( ) = = tok & & inBooleanFunction ( tok ) ) ;
2015-02-22 13:09:39 +01:00
2018-11-14 06:59:25 +01:00
const bool isTrue = ( tok - > astOperand1 ( ) - > hasKnownIntValue ( ) & & tok - > astOperand1 ( ) - > values ( ) . front ( ) . intvalue ! = 0 ) | |
( tok - > astOperand2 ( ) - > hasKnownIntValue ( ) & & tok - > astOperand2 ( ) - > values ( ) . front ( ) . intvalue ! = 0 ) ;
2015-02-22 13:09:39 +01:00
if ( isBoolean & & isTrue )
badBitmaskCheckError ( tok ) ;
}
}
}
void CheckCondition : : badBitmaskCheckError ( const Token * tok )
{
2016-08-23 17:48:36 +02:00
reportError ( tok , Severity : : warning , " badBitmaskCheck " , " Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'? " , CWE571 , false ) ;
2015-02-22 13:09:39 +01:00
}
2014-08-29 17:06:46 +02:00
void CheckCondition : : comparison ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
2016-07-31 22:09:47 +02:00
if ( ! tok - > isComparisonOp ( ) )
continue ;
const Token * expr1 = tok - > astOperand1 ( ) ;
const Token * expr2 = tok - > astOperand2 ( ) ;
if ( ! expr1 | | ! expr2 )
continue ;
if ( expr1 - > isNumber ( ) )
std : : swap ( expr1 , expr2 ) ;
if ( ! expr2 - > isNumber ( ) )
continue ;
const MathLib : : bigint num2 = MathLib : : toLongNumber ( expr2 - > str ( ) ) ;
if ( num2 < 0 )
continue ;
if ( ! Token : : Match ( expr1 , " [&|] " ) )
continue ;
std : : list < MathLib : : bigint > numbers ;
getnumchildren ( expr1 , numbers ) ;
2018-07-14 08:18:10 +02:00
for ( const MathLib : : bigint num1 : numbers ) {
2016-07-31 22:09:47 +02:00
if ( num1 < 0 )
2014-08-29 17:06:46 +02:00
continue ;
2016-07-31 22:09:47 +02:00
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 = = " == " ? false : true ) ;
}
} 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 ? false : true ) ;
} else if ( ( Token : : Match ( tok , " <=|> " ) ) & & ( num1 < = num2 ) ) {
comparisonError ( expr1 , expr1 - > str ( ) , num1 , op , num2 , or_equal ? true : false ) ;
}
} 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 ? true : false ) ;
} 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 ? false : true ) ;
2016-04-13 15:21:31 +02:00
}
2014-08-29 17:06:46 +02:00
}
}
}
}
}
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 " + ( result ? " true " : " false " ) + " . \n "
" The expression ' " + expression . str ( ) + " ' is always " + ( result ? " true " : " false " ) +
" . 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. " ) ;
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
reportError ( tok , Severity : : style , " comparisonError " , errmsg , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
2016-12-06 12:31:16 +01:00
bool CheckCondition : : isOverlappingCond ( const Token * const cond1 , const Token * const cond2 , bool pure ) const
2014-08-29 17:06:46 +02:00
{
if ( ! cond1 | | ! cond2 )
return false ;
// same expressions
2018-09-28 08:38:24 +02:00
if ( isSameExpression ( mTokenizer - > isCPP ( ) , true , cond1 , cond2 , mSettings - > library , pure , false ) )
2014-08-29 17:06:46 +02:00
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 ;
2018-09-28 08:38:24 +02:00
if ( ! isSameExpression ( mTokenizer - > isCPP ( ) , true , expr1 , expr2 , mSettings - > library , pure , false ) )
2014-08-29 17:06:46 +02:00
return false ;
const MathLib : : bigint value1 = MathLib : : toLongNumber ( num1 - > str ( ) ) ;
const MathLib : : bigint value2 = MathLib : : toLongNumber ( num2 - > str ( ) ) ;
2017-03-15 19:37:14 +01:00
if ( cond2 - > str ( ) = = " & " )
return ( ( value1 & value2 ) = = value2 ) ;
2015-02-01 13:03:38 +01:00
return ( ( value1 & value2 ) > 0 ) ;
2014-08-29 17:06:46 +02:00
}
return false ;
}
2019-01-09 20:41:01 +01:00
void CheckCondition : : duplicateCondition ( )
{
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
return ;
const SymbolDatabase * const symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
for ( const Scope & scope : symbolDatabase - > scopeList ) {
if ( scope . type ! = Scope : : eIf )
continue ;
const Token * cond1 = scope . classDef - > next ( ) - > astOperand2 ( ) ;
if ( ! cond1 )
continue ;
if ( cond1 - > hasKnownIntValue ( ) )
continue ;
const Token * tok2 = scope . classDef - > next ( ) ;
if ( ! tok2 )
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 ;
2020-12-03 07:15:31 +01:00
if ( ! isExpressionChanged ( cond1 , scope . classDef - > next ( ) , cond2 , mSettings , mTokenizer - > isCPP ( ) ) & &
2019-01-09 20:41:01 +01:00
isSameExpression ( mTokenizer - > isCPP ( ) , true , cond1 , cond2 , mSettings - > library , true , true , & errorPath ) )
duplicateConditionError ( cond1 , cond2 , 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 , false ) ;
}
2014-08-29 17:06:46 +02:00
void CheckCondition : : multiCondition ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
const SymbolDatabase * const symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2014-08-29 17:06:46 +02:00
2018-07-14 08:18:10 +02:00
for ( const Scope & scope : symbolDatabase - > scopeList ) {
if ( scope . type ! = Scope : : eIf )
2014-08-29 17:06:46 +02:00
continue ;
2018-07-14 08:18:10 +02:00
const Token * const cond1 = scope . classDef - > next ( ) - > astOperand2 ( ) ;
2019-06-30 23:26:49 +02:00
if ( ! cond1 )
continue ;
2014-08-29 17:06:46 +02:00
2018-07-14 08:18:10 +02:00
const Token * tok2 = scope . classDef - > next ( ) ;
2019-06-30 23:26:49 +02:00
// Check each 'else if'
2015-03-15 10:06:56 +01:00
for ( ; ; ) {
2014-08-29 17:06:46 +02:00
tok2 = tok2 - > link ( ) ;
if ( ! Token : : simpleMatch ( tok2 , " ) { " ) )
break ;
tok2 = tok2 - > linkAt ( 1 ) ;
if ( ! Token : : simpleMatch ( tok2 , " } else { if ( " ) )
break ;
tok2 = tok2 - > tokAt ( 4 ) ;
2019-06-30 23:26:49 +02:00
if ( tok2 - > astOperand2 ( ) & &
2018-11-14 06:59:25 +01:00
! cond1 - > hasKnownIntValue ( ) & &
2019-06-30 23:26:49 +02:00
! tok2 - > astOperand2 ( ) - > hasKnownIntValue ( ) ) {
ErrorPath errorPath ;
if ( isOverlappingCond ( cond1 , tok2 - > astOperand2 ( ) , true ) )
overlappingElseIfConditionError ( tok2 , cond1 - > linenr ( ) ) ;
else if ( isOppositeCond ( true , mTokenizer - > isCPP ( ) , cond1 , tok2 - > astOperand2 ( ) , mSettings - > library , true , true , & errorPath ) )
oppositeElseIfConditionError ( cond1 , tok2 , errorPath ) ;
}
2014-08-29 17:06:46 +02:00
}
}
}
2019-07-16 08:21:06 +02:00
void CheckCondition : : overlappingElseIfConditionError ( const Token * tok , nonneg int line1 )
2014-08-29 17:06:46 +02:00
{
2019-09-20 15:06:37 +02:00
if ( diag ( tok ) )
return ;
2014-08-29 17:06:46 +02:00
std : : ostringstream errmsg ;
errmsg < < " Expression is always false because 'else if' condition matches previous condition at line "
< < line1 < < " . " ;
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
reportError ( tok , Severity : : style , " multiCondition " , errmsg . str ( ) , CWE398 , false ) ;
2019-06-30 23:26:49 +02:00
}
void CheckCondition : : oppositeElseIfConditionError ( const Token * ifCond , const Token * elseIfCond , ErrorPath errorPath )
{
2019-09-20 15:06:37 +02:00
if ( diag ( ifCond ) & diag ( elseIfCond ) )
return ;
2019-06-30 23:26:49 +02:00
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 , false ) ;
2014-08-29 17:06:46 +02:00
}
//---------------------------------------------------------------------------
2017-09-03 10:34:34 +02:00
// - Opposite inner conditions => always false
// - (TODO) Same/Overlapping inner condition => always true
// - same condition after early exit => always false
2014-08-29 17:06:46 +02:00
//---------------------------------------------------------------------------
2017-09-08 18:08:32 +02:00
static bool isNonConstFunctionCall ( const Token * ftok , const Library & library )
2017-09-06 22:51:21 +02:00
{
2017-09-08 18:08:32 +02:00
if ( library . isFunctionConst ( ftok ) )
return false ;
2017-09-06 22:51:21 +02:00
const Token * obj = ftok - > next ( ) - > astOperand1 ( ) ;
while ( obj & & obj - > str ( ) = = " . " )
obj = obj - > astOperand1 ( ) ;
if ( ! obj )
return true ;
else if ( obj - > variable ( ) & & obj - > variable ( ) - > isConst ( ) )
return false ;
else if ( ftok - > function ( ) & & ftok - > function ( ) - > isConst ( ) )
return false ;
return true ;
}
2017-09-03 10:34:34 +02:00
void CheckCondition : : multiCondition2 ( )
2014-08-29 17:06:46 +02:00
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2014-08-29 17:06:46 +02:00
2018-07-14 08:18:10 +02:00
for ( const Scope & scope : symbolDatabase - > scopeList ) {
2017-08-31 16:00:12 +02:00
const Token * condTok = nullptr ;
2018-07-14 08:18:10 +02:00
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 ( ) ;
2017-08-31 16:00:12 +02:00
if ( ! condTok | | condTok - > str ( ) ! = " ; " )
continue ;
condTok = condTok - > astOperand2 ( ) ;
if ( ! condTok | | condTok - > str ( ) ! = " ; " )
continue ;
condTok = condTok - > astOperand1 ( ) ;
}
if ( ! condTok )
2014-08-29 17:06:46 +02:00
continue ;
2017-08-31 16:00:12 +02:00
const Token * const cond1 = condTok ;
2014-08-29 17:06:46 +02:00
2018-07-14 08:18:10 +02:00
if ( ! Token : : simpleMatch ( scope . classDef - > linkAt ( 1 ) , " ) { " ) )
2014-08-29 17:06:46 +02:00
continue ;
2021-01-15 20:48:07 +01:00
bool functionCall = false ;
2017-09-06 22:26:00 +02:00
bool nonConstFunctionCall = false ;
2014-08-29 17:06:46 +02:00
bool nonlocal = false ; // nonlocal variable used in condition
2019-07-16 08:21:06 +02:00
std : : set < int > vars ; // variables used in condition
2018-11-23 20:41:39 +01:00
visitAstNodes ( condTok ,
[ & ] ( const Token * cond ) {
2017-09-06 22:26:00 +02:00
if ( Token : : Match ( cond , " %name% ( " ) ) {
2021-01-15 20:48:07 +01:00
functionCall = true ;
2018-06-16 16:10:28 +02:00
nonConstFunctionCall = isNonConstFunctionCall ( cond , mSettings - > library ) ;
2017-09-06 22:26:00 +02:00
if ( nonConstFunctionCall )
2018-11-23 20:41:39 +01:00
return ChildrenToVisit : : done ;
2017-09-06 22:26:00 +02:00
}
2014-08-29 17:06:46 +02:00
if ( cond - > varId ( ) ) {
vars . insert ( cond - > varId ( ) ) ;
const Variable * var = cond - > variable ( ) ;
2017-09-04 15:58:22 +02:00
if ( ! nonlocal & & var ) {
2017-09-08 15:44:56 +02:00
if ( ! ( var - > isLocal ( ) | | var - > isArgument ( ) ) )
2017-09-04 15:58:22 +02:00
nonlocal = true ;
2017-09-04 22:25:20 +02:00
else if ( ( var - > isPointer ( ) | | var - > isReference ( ) ) & & ! Token : : Match ( cond - > astParent ( ) , " %oror%|&&|! " ) )
2017-09-04 15:58:22 +02:00
// TODO: if var is pointer check what it points at
nonlocal = true ;
}
2015-08-07 15:25:47 +02:00
} else if ( ! nonlocal & & cond - > isName ( ) ) {
2014-08-29 17:06:46 +02:00
// varid is 0. this is possibly a nonlocal variable..
2018-06-16 16:10:28 +02:00
nonlocal = Token : : Match ( cond - > astParent ( ) , " %cop%|(|[ " ) | | Token : : Match ( cond , " %name% . " ) | | ( mTokenizer - > isCPP ( ) & & cond - > str ( ) = = " this " ) ;
2017-08-31 16:00:12 +02:00
} else {
2018-11-23 20:41:39 +01:00
return ChildrenToVisit : : op1_and_op2 ;
2014-08-29 17:06:46 +02:00
}
2018-11-23 20:41:39 +01:00
return ChildrenToVisit : : none ;
} ) ;
2014-08-29 17:06:46 +02:00
2017-09-06 22:26:00 +02:00
if ( nonConstFunctionCall )
continue ;
2020-01-04 11:38:56 +01:00
std : : vector < const Variable * > varsInCond ;
visitAstNodes ( condTok ,
[ & varsInCond ] ( const Token * cond ) {
if ( cond - > variable ( ) ) {
const Variable * var = cond - > variable ( ) ;
2020-01-04 18:47:05 +01:00
if ( std : : find ( varsInCond . begin ( ) , varsInCond . end ( ) , var ) = = varsInCond . end ( ) )
2020-01-04 11:38:56 +01:00
varsInCond . push_back ( var ) ;
}
return ChildrenToVisit : : op1_and_op2 ;
} ) ;
2017-09-03 10:34:34 +02:00
// parse until second condition is reached..
2018-10-18 21:01:47 +02:00
enum MULTICONDITIONTYPE { INNER , AFTER } ;
2017-09-03 10:34:34 +02:00
const Token * tok ;
2018-10-18 21:01:47 +02:00
// 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 ) ;
2018-10-20 09:28:28 +02:00
for ( MULTICONDITIONTYPE type : types ) {
if ( type = = MULTICONDITIONTYPE : : AFTER ) {
2018-10-18 21:01:47 +02:00
tok = scope . bodyEnd - > next ( ) ;
} else {
tok = scope . bodyStart ;
}
const Token * const endToken = tok - > scope ( ) - > bodyEnd ;
for ( ; tok & & tok ! = endToken ; tok = tok - > next ( ) ) {
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 ( const Token * op = Token : : findmatch ( tok , " ++|-- " , condEndToken ) ) {
bool bailout = false ;
while ( op ) {
if ( vars . find ( op - > astOperand1 ( ) - > varId ( ) ) ! = vars . end ( ) ) {
bailout = true ;
break ;
}
if ( nonlocal & & op - > astOperand1 ( ) - > varId ( ) = = 0 ) {
bailout = true ;
break ;
}
op = Token : : findmatch ( op - > next ( ) , " ++|-- " , condEndToken ) ;
2017-09-10 22:58:05 +02:00
}
2018-10-18 21:01:47 +02:00
if ( bailout )
2017-09-10 22:58:05 +02:00
break ;
}
2018-10-18 21:01:47 +02:00
// Condition..
const Token * cond2 = tok - > str ( ) = = " if " ? condStartToken - > astOperand2 ( ) : condStartToken - > astOperand1 ( ) ;
2018-10-31 09:47:48 +01:00
const bool isReturnVar = ( tok - > str ( ) = = " return " & & ! Token : : Match ( cond2 , " %cop% " ) ) ;
2018-10-18 21:01:47 +02:00
ErrorPath errorPath ;
if ( type = = MULTICONDITIONTYPE : : INNER ) {
2020-07-10 00:50:57 +02:00
visitAstNodes ( cond1 , [ & ] ( const Token * firstCondition ) {
2018-10-18 21:01:47 +02:00
if ( ! firstCondition )
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
2018-10-18 21:01:47 +02:00
if ( firstCondition - > str ( ) = = " && " ) {
2020-09-07 07:53:41 +02:00
if ( ! isOppositeCond ( false , mTokenizer - > isCPP ( ) , firstCondition , cond2 , mSettings - > library , true , true ) )
return ChildrenToVisit : : op1_and_op2 ;
}
if ( ! firstCondition - > hasKnownIntValue ( ) ) {
2018-10-31 09:47:48 +01:00
if ( ! isReturnVar & & isOppositeCond ( false , mTokenizer - > isCPP ( ) , firstCondition , cond2 , mSettings - > library , true , true , & errorPath ) ) {
2018-10-18 21:01:47 +02:00
if ( ! isAliased ( vars ) )
oppositeInnerConditionError ( firstCondition , cond2 , errorPath ) ;
2018-10-31 09:47:48 +01:00
} else if ( ! isReturnVar & & isSameExpression ( mTokenizer - > isCPP ( ) , true , firstCondition , cond2 , mSettings - > library , true , true , & errorPath ) ) {
2018-10-18 21:01:47 +02:00
identicalInnerConditionError ( firstCondition , cond2 , errorPath ) ;
}
2018-09-06 06:55:36 +02:00
}
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
} ) ;
2018-10-18 21:01:47 +02:00
} else {
2020-07-01 07:48:32 +02:00
visitAstNodes ( cond2 , [ & ] ( const Token * secondCondition ) {
if ( secondCondition - > str ( ) = = " || " | | secondCondition - > str ( ) = = " && " )
return ChildrenToVisit : : op1_and_op2 ;
if ( ( ! cond1 - > hasKnownIntValue ( ) | | ! secondCondition - > hasKnownIntValue ( ) ) & &
isSameExpression ( mTokenizer - > isCPP ( ) , true , cond1 , secondCondition , mSettings - > library , true , true , & errorPath ) ) {
if ( ! isAliased ( vars ) & & ! mTokenizer - > hasIfdef ( cond1 , secondCondition ) ) {
2018-10-18 21:01:47 +02:00
identicalConditionAfterEarlyExitError ( cond1 , secondCondition , errorPath ) ;
2020-07-01 07:48:32 +02:00
return ChildrenToVisit : : done ;
}
2018-10-18 21:01:47 +02:00
}
2020-07-01 07:48:32 +02:00
return ChildrenToVisit : : none ;
} ) ;
2017-09-04 14:52:10 +02:00
}
2017-09-03 10:44:22 +02:00
}
2020-01-04 11:38:56 +01:00
if ( Token : : Match ( tok , " %name% ( " ) & & isVariablesChanged ( tok , tok - > linkAt ( 1 ) , true , varsInCond , mSettings , mTokenizer - > isCPP ( ) ) ) {
break ;
}
2018-10-18 21:01:47 +02:00
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
2017-09-03 11:03:01 +02:00
break ;
2018-10-18 21:01:47 +02:00
}
bool changed = false ;
2019-07-16 08:21:06 +02:00
for ( int varid : vars ) {
2018-10-18 21:01:47 +02:00
if ( isVariableChanged ( tok1 , tok2 , varid , nonlocal , mSettings , mTokenizer - > isCPP ( ) ) ) {
changed = true ;
break ;
}
}
if ( changed )
2017-09-03 11:03:01 +02:00
break ;
}
2018-10-18 21:01:47 +02:00
if ( ( tok - > varId ( ) & & vars . find ( tok - > varId ( ) ) ! = vars . end ( ) ) | |
2021-01-15 20:48:07 +01:00
( ! tok - > varId ( ) & & nonlocal ) | |
( functionCall & & tok - > variable ( ) & & ! tok - > variable ( ) - > isLocal ( ) ) ) {
2018-10-18 21:01:47 +02:00
if ( Token : : Match ( tok , " %name% %assign%|++|-- " ) )
2017-12-21 01:13:00 +01:00
break ;
2018-10-18 21:01:47 +02:00
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 ;
2017-12-21 01:13:00 +01:00
}
2018-10-18 21:01:47 +02:00
if ( mTokenizer - > isCPP ( ) & & Token : : Match ( tok , " %name% << " ) & & ( ! tok - > valueType ( ) | | ! tok - > valueType ( ) - > isIntegral ( ) ) )
2017-09-05 22:03:29 +02:00
break ;
2018-10-18 21:01:47 +02:00
if ( isLikelyStreamRead ( mTokenizer - > isCPP ( ) , tok - > next ( ) ) | | isLikelyStreamRead ( mTokenizer - > isCPP ( ) , tok - > previous ( ) ) )
2014-08-29 17:06:46 +02:00
break ;
2018-10-18 21:01:47 +02:00
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 ) )
2015-02-26 12:34:18 +01:00
break ;
}
2014-08-29 17:06:46 +02:00
}
}
}
}
2018-10-18 21:01:47 +02:00
static std : : string innerSmtString ( const Token * tok )
{
2018-10-20 09:28:28 +02:00
if ( ! tok )
2018-10-18 21:01:47 +02:00
return " if " ;
2018-10-20 09:28:28 +02:00
if ( ! tok - > astTop ( ) )
2018-10-18 21:01:47 +02:00
return " if " ;
const Token * top = tok - > astTop ( ) ;
2018-10-20 09:28:28 +02:00
if ( top - > str ( ) = = " ( " & & top - > astOperand1 ( ) )
2018-10-18 21:01:47 +02:00
return top - > astOperand1 ( ) - > str ( ) ;
return top - > str ( ) ;
}
2018-08-17 09:25:07 +02:00
void CheckCondition : : oppositeInnerConditionError ( const Token * tok1 , const Token * tok2 , ErrorPath errorPath )
2014-08-29 17:06:46 +02:00
{
2018-11-10 21:30:01 +01:00
if ( diag ( tok1 ) & diag ( tok2 ) )
2018-11-07 06:49:07 +01:00
return ;
2017-09-04 22:54:06 +02:00
const std : : string s1 ( tok1 ? tok1 - > expressionString ( ) : " x " ) ;
const std : : string s2 ( tok2 ? tok2 - > expressionString ( ) : " !x " ) ;
2018-10-18 21:01:47 +02:00
const std : : string innerSmt = innerSmtString ( tok2 ) ;
2018-08-17 09:25:07 +02:00
errorPath . emplace_back ( ErrorPathItem ( tok1 , " outer condition: " + s1 ) ) ;
errorPath . emplace_back ( ErrorPathItem ( tok2 , " opposite inner condition: " + s2 ) ) ;
2018-10-18 21:01:47 +02:00
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 + " '). " ) ;
2017-09-04 22:54:06 +02:00
reportError ( errorPath , Severity : : warning , " oppositeInnerCondition " , msg , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
2018-08-17 09:25:07 +02:00
void CheckCondition : : identicalInnerConditionError ( const Token * tok1 , const Token * tok2 , ErrorPath errorPath )
2018-04-08 08:13:44 +02:00
{
2018-11-10 21:30:01 +01:00
if ( diag ( tok1 ) & diag ( tok2 ) )
2018-11-07 06:49:07 +01:00
return ;
2018-04-08 08:13:44 +02:00
const std : : string s1 ( tok1 ? tok1 - > expressionString ( ) : " x " ) ;
const std : : string s2 ( tok2 ? tok2 - > expressionString ( ) : " x " ) ;
2018-10-18 21:01:47 +02:00
const std : : string innerSmt = innerSmtString ( tok2 ) ;
2018-08-17 09:25:07 +02:00
errorPath . emplace_back ( ErrorPathItem ( tok1 , " outer condition: " + s1 ) ) ;
errorPath . emplace_back ( ErrorPathItem ( tok2 , " identical inner condition: " + s2 ) ) ;
2018-10-18 21:01:47 +02:00
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 + " '). " ) ;
2018-04-08 08:13:44 +02:00
reportError ( errorPath , Severity : : warning , " identicalInnerCondition " , msg , CWE398 , false ) ;
}
2018-08-17 09:25:07 +02:00
void CheckCondition : : identicalConditionAfterEarlyExitError ( const Token * cond1 , const Token * cond2 , ErrorPath errorPath )
2017-09-03 10:34:34 +02:00
{
2018-11-10 21:30:01 +01:00
if ( diag ( cond1 ) & diag ( cond2 ) )
2018-11-07 06:49:07 +01:00
return ;
2018-08-17 09:25:07 +02:00
2019-11-16 17:24:54 +01:00
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 ( ErrorPathItem ( cond1 , " If condition ' " + cond + " ' is true, the function will return/exit " ) ) ;
errorPath . emplace_back ( ErrorPathItem ( 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 ,
false ) ;
2017-09-03 10:34:34 +02:00
}
2014-08-29 17:06:46 +02:00
//---------------------------------------------------------------------------
// 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 ;
}
2015-06-13 18:08:13 +02:00
template < typename T >
static bool checkIntRelation ( const std : : string & op , const T value1 , const T value2 )
2014-08-29 17:06:46 +02:00
{
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 ) ;
}
2015-06-14 20:25:52 +02:00
template < class T >
T getvalue3 ( const T value1 , const T value2 )
{
2015-06-28 19:20:16 +02:00
const T min = std : : min ( value1 , value2 ) ;
if ( min = = std : : numeric_limits < T > : : max ( ) )
return min ;
else
return min + 1 ; // see #5895
2015-06-14 20:25:52 +02:00
}
template < >
double getvalue3 ( const double value1 , const double value2 )
{
return ( value1 + value2 ) / 2.0f ;
}
2015-06-13 18:08:13 +02:00
template < class T >
static inline T getvalue ( const int test , const T value1 , const T value2 )
2014-08-29 17:06:46 +02:00
{
// 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 ) {
2016-07-19 12:14:55 +02:00
case 1 :
return std : : numeric_limits < T > : : lowest ( ) ;
2014-08-29 17:06:46 +02:00
case 2 :
return value1 ;
case 3 :
2015-06-14 20:25:52 +02:00
return getvalue3 < T > ( value1 , value2 ) ;
2014-08-29 17:06:46 +02:00
case 4 :
return value2 ;
2016-07-19 12:14:55 +02:00
case 5 :
return std : : numeric_limits < T > : : max ( ) ;
2020-04-21 17:27:51 +02:00
}
2014-08-29 17:06:46 +02:00
return 0 ;
}
2016-05-24 15:08:07 +02:00
static bool parseComparison ( const Token * comp , bool * not1 , std : : string * op , std : : string * value , const Token * * expr , bool * inconclusive )
2015-07-13 20:53:49 +02:00
{
* not1 = false ;
while ( comp & & comp - > str ( ) = = " ! " ) {
* not1 = ! ( * not1 ) ;
comp = comp - > astOperand1 ( ) ;
}
2015-07-21 22:26:22 +02:00
if ( ! comp )
2015-07-13 20:53:49 +02:00
return false ;
2017-03-23 18:57:48 +01:00
const Token * op1 = comp - > astOperand1 ( ) ;
const Token * op2 = comp - > astOperand2 ( ) ;
if ( ! comp - > isComparisonOp ( ) | | ! op1 | | ! op2 ) {
2015-07-21 22:26:22 +02:00
* op = " != " ;
* value = " 0 " ;
* expr = comp ;
2017-03-23 18:57:48 +01:00
} else if ( op1 - > isLiteral ( ) ) {
if ( op1 - > isExpandedMacro ( ) )
2015-07-21 22:26:22 +02:00
return false ;
2015-07-13 20:53:49 +02:00
* op = invertOperatorForOperandSwap ( comp - > str ( ) ) ;
2017-03-23 18:57:48 +01:00
if ( op1 - > enumerator ( ) & & op1 - > enumerator ( ) - > value_known )
* value = MathLib : : toString ( op1 - > enumerator ( ) - > value ) ;
else
* value = op1 - > str ( ) ;
* expr = op2 ;
2015-07-13 20:53:49 +02:00
} else if ( comp - > astOperand2 ( ) - > isLiteral ( ) ) {
2017-03-23 18:57:48 +01:00
if ( op2 - > isExpandedMacro ( ) )
2015-07-21 22:26:22 +02:00
return false ;
2015-07-13 20:53:49 +02:00
* op = comp - > str ( ) ;
2017-03-23 18:57:48 +01:00
if ( op2 - > enumerator ( ) & & op2 - > enumerator ( ) - > value_known )
* value = MathLib : : toString ( op2 - > enumerator ( ) - > value ) ;
else
* value = op2 - > str ( ) ;
* expr = op1 ;
2015-07-13 20:53:49 +02:00
} else {
2015-07-21 22:26:22 +02:00
* op = " != " ;
* value = " 0 " ;
* expr = comp ;
2015-07-13 20:53:49 +02:00
}
2016-05-24 15:08:07 +02:00
* inconclusive = * inconclusive | | ( ( * value ) [ 0 ] = = ' \' ' & & ! ( * op = = " != " | | * op = = " == " ) ) ;
2015-07-13 20:53:49 +02:00
// Only float and int values are currently handled
2016-05-24 15:08:07 +02:00
if ( ! MathLib : : isInt ( * value ) & & ! MathLib : : isFloat ( * value ) & & ( * value ) [ 0 ] ! = ' \' ' )
2015-07-13 20:53:49 +02:00
return false ;
return true ;
}
2015-07-21 22:26:22 +02:00
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 - > isName ( ) ? expr1 - > str ( ) : std : : string ( " EXPR " ) ) +
" " +
op +
" " +
value1 +
( not1 ? " ) " : " " ) ;
return std : : string ( not1 ? " ! " : " " ) +
( expr1 - > isName ( ) ? expr1 - > str ( ) : std : : string ( " EXPR " ) ) ;
}
2018-08-05 22:39:40 +02:00
static std : : string conditionString ( const Token * tok )
{
2018-08-05 22:40:21 +02:00
if ( ! tok )
2018-08-05 22:39:40 +02:00
return " " ;
2018-08-05 22:40:21 +02:00
if ( tok - > isComparisonOp ( ) ) {
2018-08-05 22:39:40 +02:00
bool inconclusive = false ;
bool not_ ;
std : : string op , value ;
const Token * expr ;
2018-08-05 22:40:21 +02:00
if ( parseComparison ( tok , & not_ , & op , & value , & expr , & inconclusive ) & & expr - > isName ( ) ) {
2018-08-05 22:39:40 +02:00
return conditionString ( not_ , expr , op , value ) ;
}
}
2018-08-05 22:40:21 +02:00
if ( Token : : Match ( tok , " %cop%|&&|%oror% " ) ) {
if ( tok - > astOperand2 ( ) )
2018-08-05 22:39:40 +02:00
return conditionString ( tok - > astOperand1 ( ) ) + " " + tok - > str ( ) + " " + conditionString ( tok - > astOperand2 ( ) ) ;
return tok - > str ( ) + " ( " + conditionString ( tok - > astOperand1 ( ) ) + " ) " ;
}
return tok - > expressionString ( ) ;
}
2014-08-29 17:06:46 +02:00
void CheckCondition : : checkIncorrectLogicOperator ( )
{
2018-06-16 16:10:28 +02:00
const bool printStyle = mSettings - > isEnabled ( Settings : : STYLE ) ;
const bool printWarning = mSettings - > isEnabled ( Settings : : WARNING ) ;
2015-04-10 14:18:52 +02:00
if ( ! printWarning & & ! printStyle )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
const bool printInconclusive = mSettings - > inconclusive ;
2014-08-29 17:06:46 +02:00
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-07-14 08:18:10 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2014-08-29 17:06:46 +02:00
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart - > next ( ) ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2015-07-13 20:53:49 +02:00
if ( ! Token : : Match ( tok , " %oror%|&& " ) | | ! tok - > astOperand1 ( ) | | ! tok - > astOperand2 ( ) )
continue ;
2014-08-29 17:06:46 +02:00
2016-12-05 13:17:58 +01:00
// 'A && (!A || B)' is equivalent to 'A && B'
// 'A || (!A && B)' is equivalent to 'A || B'
2020-04-07 07:15:15 +02:00
// 'A && (A || B)' is equivalent to 'A'
// 'A || (A && B)' is equivalent to 'A'
2015-11-05 19:27:10 +01:00
if ( printStyle & &
2015-08-05 11:15:54 +02:00
( ( tok - > str ( ) = = " || " & & tok - > astOperand2 ( ) - > str ( ) = = " && " ) | |
( tok - > str ( ) = = " && " & & tok - > astOperand2 ( ) - > str ( ) = = " || " ) ) ) {
2015-07-13 20:53:49 +02:00
const Token * tok2 = tok - > astOperand2 ( ) - > astOperand1 ( ) ;
2018-09-28 08:38:24 +02:00
if ( isOppositeCond ( true , mTokenizer - > isCPP ( ) , tok - > astOperand1 ( ) , tok2 , mSettings - > library , true , false ) ) {
2015-08-05 11:15:54 +02:00
std : : string expr1 ( tok - > astOperand1 ( ) - > expressionString ( ) ) ;
std : : string expr2 ( tok - > astOperand2 ( ) - > astOperand1 ( ) - > expressionString ( ) ) ;
std : : string expr3 ( tok - > astOperand2 ( ) - > astOperand2 ( ) - > expressionString ( ) ) ;
2016-12-05 13:17:58 +01:00
// 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 ;
2015-08-05 11:15:54 +02:00
if ( expr1 . length ( ) + expr2 . length ( ) + expr3 . length ( ) > 50U ) {
if ( expr1 [ 0 ] = = ' ! ' & & expr2 [ 0 ] ! = ' ! ' ) {
expr1 = " !A " ;
expr2 = " A " ;
} else {
2015-08-05 11:30:58 +02:00
expr1 = " A " ;
expr2 = " !A " ;
2015-08-05 11:15:54 +02:00
}
expr3 = " B " ;
}
const std : : string cond1 = expr1 + " " + tok - > str ( ) + " ( " + expr2 + " " + tok - > astOperand2 ( ) - > str ( ) + " " + expr3 + " ) " ;
const std : : string cond2 = expr1 + " " + tok - > str ( ) + " " + expr3 ;
2016-12-05 13:17:58 +01:00
const std : : string cond1VerboseMsg = expr1VerboseMsg + " " + tok - > str ( ) + " " + expr2VerboseMsg + " " + tok - > astOperand2 ( ) - > str ( ) + " " + expr3VerboseMsg ;
const std : : string cond2VerboseMsg = expr1VerboseMsg + " " + tok - > str ( ) + " " + expr3VerboseMsg ;
2016-12-05 17:30:06 +01:00
// for the --verbose message, transform the actual condition and print it
2016-12-05 13:17:58 +01:00
const std : : string msg = tok2 - > expressionString ( ) + " . ' " + cond1 + " ' is equivalent to ' " + cond2 + " ' \n "
" The condition ' " + cond1VerboseMsg + " ' is equivalent to ' " + cond2VerboseMsg + " '. " ;
redundantConditionError ( tok , msg , false ) ;
2014-08-29 17:06:46 +02:00
continue ;
2020-04-07 07:15:15 +02:00
} else if ( isSameExpression ( mTokenizer - > isCPP ( ) , false , tok - > astOperand1 ( ) , tok2 , mSettings - > library , 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 = expr1 ;
const std : : string cond1VerboseMsg = expr1VerboseMsg + " " + tok - > str ( ) + " " + expr2VerboseMsg + " " + tok - > astOperand2 ( ) - > str ( ) + " " + expr3VerboseMsg ;
2021-01-02 19:10:25 +01:00
const std : : string & cond2VerboseMsg = expr1VerboseMsg ;
2020-04-07 07:15:15 +02:00
// 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 ;
2014-08-29 17:06:46 +02:00
}
2015-07-13 20:53:49 +02:00
}
2014-08-29 17:06:46 +02:00
2015-07-13 20:53:49 +02:00
// Comparison #1 (LHS)
const Token * comp1 = tok - > astOperand1 ( ) ;
2020-07-21 20:20:39 +02:00
if ( comp1 - > str ( ) = = tok - > str ( ) )
2015-07-13 20:53:49 +02:00
comp1 = comp1 - > astOperand2 ( ) ;
2014-08-29 17:06:46 +02:00
2015-07-13 20:53:49 +02:00
// Comparison #2 (RHS)
const Token * comp2 = tok - > astOperand2 ( ) ;
2014-08-29 17:06:46 +02:00
2016-05-24 15:08:07 +02:00
bool inconclusive = false ;
2018-08-05 22:39:40 +02:00
bool parseable = true ;
2016-05-24 15:08:07 +02:00
2015-07-13 20:53:49 +02:00
// Parse LHS
bool not1 ;
std : : string op1 , value1 ;
2018-08-05 22:39:40 +02:00
const Token * expr1 = nullptr ;
parseable & = ( parseComparison ( comp1 , & not1 , & op1 , & value1 , & expr1 , & inconclusive ) ) ;
2014-08-29 17:06:46 +02:00
2015-07-13 20:53:49 +02:00
// Parse RHS
bool not2 ;
std : : string op2 , value2 ;
2018-08-05 22:39:40 +02:00
const Token * expr2 = nullptr ;
parseable & = ( parseComparison ( comp2 , & not2 , & op2 , & value2 , & expr2 , & inconclusive ) ) ;
2016-05-24 15:08:07 +02:00
2016-12-05 13:17:58 +01:00
if ( inconclusive & & ! printInconclusive )
2015-07-13 20:53:49 +02:00
continue ;
2018-08-05 22:40:21 +02:00
2018-08-05 22:39:40 +02:00
const bool isfloat = astIsFloat ( expr1 , true ) | | MathLib : : isFloat ( value1 ) | | astIsFloat ( expr2 , true ) | | MathLib : : isFloat ( value2 ) ;
2018-10-01 14:40:03 +02:00
ErrorPath errorPath ;
2018-08-05 22:39:40 +02:00
// Opposite comparisons around || or && => always true or always false
2018-10-01 14:40:03 +02:00
if ( ! isfloat & & isOppositeCond ( tok - > str ( ) = = " || " , mTokenizer - > isCPP ( ) , tok - > astOperand1 ( ) , tok - > astOperand2 ( ) , mSettings - > library , true , true , & errorPath ) ) {
2018-08-05 22:39:40 +02:00
const bool alwaysTrue ( tok - > str ( ) = = " || " ) ;
2018-10-01 14:40:03 +02:00
incorrectLogicOperatorError ( tok , conditionString ( tok ) , alwaysTrue , inconclusive , errorPath ) ;
2018-08-05 22:39:40 +02:00
continue ;
}
2018-08-05 22:40:21 +02:00
if ( ! parseable )
2018-08-05 22:39:40 +02:00
continue ;
2014-08-29 17:06:46 +02:00
2018-10-01 14:40:03 +02:00
if ( isSameExpression ( mTokenizer - > isCPP ( ) , true , comp1 , comp2 , mSettings - > library , true , true ) )
2015-07-13 20:53:49 +02:00
continue ; // same expressions => only report that there are same expressions
2018-10-01 14:40:03 +02:00
if ( ! isSameExpression ( mTokenizer - > isCPP ( ) , true , expr1 , expr2 , mSettings - > library , true , true ) )
2015-07-13 20:53:49 +02:00
continue ;
2014-08-29 17:06:46 +02:00
2015-07-13 20:53:49 +02:00
// don't check floating point equality comparisons. that is bad
// and deserves different warnings.
if ( isfloat & & ( op1 = = " == " | | op1 = = " != " | | op2 = = " == " | | op2 = = " != " ) )
continue ;
2014-08-29 17:06:46 +02:00
2018-08-05 22:39:40 +02:00
2015-07-13 20:53:49 +02:00
const double d1 = ( isfloat ) ? MathLib : : toDoubleNumber ( value1 ) : 0 ;
const double d2 = ( isfloat ) ? MathLib : : toDoubleNumber ( value2 ) : 0 ;
const MathLib : : bigint i1 = ( isfloat ) ? 0 : MathLib : : toLongNumber ( value1 ) ;
const MathLib : : bigint i2 = ( isfloat ) ? 0 : MathLib : : toLongNumber ( value2 ) ;
const bool useUnsignedInt = ( std : : numeric_limits < MathLib : : bigint > : : max ( ) = = i1 ) | | ( std : : numeric_limits < MathLib : : bigint > : : max ( ) = = i2 ) ;
const MathLib : : biguint u1 = ( useUnsignedInt ) ? MathLib : : toLongNumber ( value1 ) : 0 ;
const MathLib : : biguint u2 = ( useUnsignedInt ) ? MathLib : : toLongNumber ( value2 ) : 0 ;
// evaluate if expression is always true/false
bool alwaysTrue = true , alwaysFalse = true ;
bool firstTrue = true , secondTrue = true ;
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 double testvalue = getvalue < double > ( test , d1 , d2 ) ;
result1 = checkFloatRelation ( op1 , testvalue , d1 ) ;
result2 = checkFloatRelation ( op2 , testvalue , d2 ) ;
} else if ( useUnsignedInt ) {
const MathLib : : biguint testvalue = getvalue < MathLib : : biguint > ( test , u1 , u2 ) ;
result1 = checkIntRelation ( op1 , testvalue , u1 ) ;
result2 = checkIntRelation ( op2 , testvalue , u2 ) ;
} else {
const MathLib : : bigint 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 ( tok - > str ( ) = = " && " ) {
alwaysTrue & = ( result1 & & result2 ) ;
alwaysFalse & = ! ( result1 & & result2 ) ;
} else {
alwaysTrue & = ( result1 | | result2 ) ;
alwaysFalse & = ! ( result1 | | result2 ) ;
2014-08-29 17:06:46 +02:00
}
2015-07-13 20:53:49 +02:00
firstTrue & = ! ( ! result1 & & result2 ) ;
secondTrue & = ! ( result1 & & ! result2 ) ;
}
2015-07-21 22:26:22 +02:00
const std : : string cond1str = conditionString ( not1 , expr1 , op1 , value1 ) ;
const std : : string cond2str = conditionString ( not2 , expr2 , op2 , value2 ) ;
2015-07-13 20:53:49 +02:00
if ( printWarning & & ( alwaysTrue | | alwaysFalse ) ) {
const std : : string text = cond1str + " " + tok - > str ( ) + " " + cond2str ;
2018-10-01 14:40:03 +02:00
incorrectLogicOperatorError ( tok , text , alwaysTrue , inconclusive , errorPath ) ;
2015-07-13 20:53:49 +02:00
} else if ( printStyle & & secondTrue ) {
2015-07-30 16:24:56 +02:00
const std : : string text = " If ' " + cond1str + " ', the comparison ' " + cond2str +
2017-11-03 10:39:57 +01:00
" ' is always true. " ;
2016-05-24 15:08:07 +02:00
redundantConditionError ( tok , text , inconclusive ) ;
2015-07-13 20:53:49 +02:00
} else if ( printStyle & & firstTrue ) {
//const std::string text = "The comparison " + cond1str + " is always " +
// (firstTrue ? "true" : "false") + " when " +
// cond2str + ".";
2015-07-30 16:24:56 +02:00
const std : : string text = " If ' " + cond2str + " ', the comparison ' " + cond1str +
2017-11-03 10:39:57 +01:00
" ' is always true. " ;
2016-05-24 15:08:07 +02:00
redundantConditionError ( tok , text , inconclusive ) ;
2014-08-29 17:06:46 +02:00
}
}
}
}
2018-10-01 14:40:03 +02:00
void CheckCondition : : incorrectLogicOperatorError ( const Token * tok , const std : : string & condition , bool always , bool inconclusive , ErrorPath errors )
2014-08-29 17:06:46 +02:00
{
2020-08-31 08:46:56 +02:00
if ( diag ( tok ) )
return ;
2018-10-01 14:40:03 +02:00
errors . emplace_back ( tok , " " ) ;
2014-08-29 17:06:46 +02:00
if ( always )
2018-10-01 14:40:03 +02:00
reportError ( errors , Severity : : warning , " incorrectLogicOperator " ,
2014-08-29 17:06:46 +02:00
" Logical disjunction always evaluates to true: " + condition + " . \n "
" Logical disjunction always evaluates to true: " + condition + " . "
2016-05-24 15:08:07 +02:00
" Are these conditions necessary? Did you intend to use && instead? Are the numbers correct? Are you comparing the correct variables? " , CWE571 , inconclusive ) ;
2014-08-29 17:06:46 +02:00
else
2018-10-01 14:40:03 +02:00
reportError ( errors , Severity : : warning , " incorrectLogicOperator " ,
2014-08-29 17:06:46 +02:00
" Logical conjunction always evaluates to false: " + condition + " . \n "
" Logical conjunction always evaluates to false: " + condition + " . "
2016-05-24 15:08:07 +02:00
" Are these conditions necessary? Did you intend to use || instead? Are the numbers correct? Are you comparing the correct variables? " , CWE570 , inconclusive ) ;
2014-08-29 17:06:46 +02:00
}
2016-05-24 15:08:07 +02:00
void CheckCondition : : redundantConditionError ( const Token * tok , const std : : string & text , bool inconclusive )
2014-08-29 17:06:46 +02:00
{
2020-08-31 08:46:56 +02:00
if ( diag ( tok ) )
return ;
2016-05-24 15:08:07 +02:00
reportError ( tok , Severity : : style , " redundantCondition " , " Redundant condition: " + text , CWE398 , inconclusive ) ;
2014-08-29 17:06:46 +02:00
}
//-----------------------------------------------------------------------------
// Detect "(var % val1) > val2" where val2 is >= val1.
//-----------------------------------------------------------------------------
void CheckCondition : : checkModuloAlwaysTrueFalse ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-07-14 08:18:10 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart - > next ( ) ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2014-08-29 17:06:46 +02:00
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 )
{
reportError ( tok , Severity : : warning , " moduloAlwaysTrueFalse " ,
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
" Comparison of modulo result is predetermined, because it is always less than " + maxVal + " . " , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
2016-07-29 18:46:43 +02:00
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 ;
}
2014-08-29 17:06:46 +02:00
//---------------------------------------------------------------------------
// 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 ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
2014-08-29 17:06:46 +02:00
return ;
2018-06-16 16:10:28 +02:00
const bool isC = mTokenizer - > isC ( ) ;
2014-08-29 17:06:46 +02:00
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-07-14 08:18:10 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart - > next ( ) ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( tok , " ( %name% [=&|^] " ) ) {
2014-08-29 17:06:46 +02:00
for ( const Token * tok2 = tok - > tokAt ( 3 ) ; tok2 ; tok2 = tok2 - > next ( ) ) {
if ( tok2 - > str ( ) = = " ( " | | tok2 - > str ( ) = = " [ " )
tok2 = tok2 - > link ( ) ;
2018-11-09 06:30:41 +01:00
else if ( tok2 - > isComparisonOp ( ) ) {
2014-08-29 17:06:46 +02:00
// This might be a template
if ( ! isC & & tok2 - > link ( ) )
break ;
2015-02-05 20:17:30 +01:00
if ( Token : : simpleMatch ( tok2 - > astParent ( ) , " ? " ) )
break ;
2014-08-29 17:06:46 +02:00
clarifyConditionError ( tok , tok - > strAt ( 2 ) = = " = " , false ) ;
break ;
} else if ( ! tok2 - > isName ( ) & & ! tok2 - > isNumber ( ) & & tok2 - > str ( ) ! = " . " )
break ;
}
2018-07-14 08:04:08 +02:00
} else if ( tok - > tokType ( ) = = Token : : eBitOp & & ! tok - > isUnaryOp ( " & " ) ) {
2016-05-06 17:39:41 +02:00
if ( tok - > astOperand2 ( ) & & tok - > astOperand2 ( ) - > variable ( ) & & tok - > astOperand2 ( ) - > variable ( ) - > nameToken ( ) = = tok - > astOperand2 ( ) )
continue ;
2016-05-06 15:22:45 +02:00
// 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 ;
2016-08-29 04:09:36 +02:00
if ( vt1 & & vt1 - > type = = ValueType : : BOOL & & ! Token : : Match ( tok - > astOperand1 ( ) , " %name%|(|[|::|. " ) & & countPar ( tok - > astOperand1 ( ) , tok ) = = 0 )
2016-05-06 15:22:45 +02:00
clarifyConditionError ( tok , false , true ) ;
2018-04-17 22:14:17 +02:00
else if ( vt2 & & vt2 - > type = = ValueType : : BOOL & & ! Token : : Match ( tok - > astOperand2 ( ) , " %name%|(|[|::|. " ) & & countPar ( tok , tok - > astOperand2 ( ) ) = = 0 )
2014-08-29 17:06:46 +02:00
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 " ,
Mapped toomanyconfigs ,AssignmentAddressToInteger
,AssignmentIntegerToAddress ,CastIntegerToAddressAtReturn
,CastAddressToIntegerAtReturn ,assertWithSideEffect ,assignmentInAssert
,uselessAssignmentArg ,uselessAssignmentPtrArg
,comparisonOfFuncReturningBoolError
,comparisonOfTwoFuncsReturningBoolError ,comparisonOfBoolWithBoolError
,incrementboolean ,comparisonOfBoolWithInt ,compareBoolExpressionWithInt
,negativeIndex ,pointerOutOfBounds ,arrayIndexThenCheck
,possibleBufferAccessOutOfBounds ,argumentSize
,arrayIndexOutOfBoundsCond ,noConstructor ,copyCtorPointerCopying
,noCopyConstructor ,uninitMemberVar ,operatorEqVarError
,unusedPrivateFunction ,memsetClassFloat ,mallocOnClassWarning
,operatorEq ,thisSubtraction ,operatorEqRetRefThis ,operatorEqToSelf
,useInitializationList ,duplInheritedMember ,assignIfError
,comparisonError ,multiCondition ,mismatchingBitAnd
,oppositeInnerCondition ,incorrectLogicOperator ,redundantCondition
,moduloAlwaysTrueFalse to their CWEs ids.
2016-02-20 23:56:36 +01:00
errmsg , CWE398 , false ) ;
2014-08-29 17:06:46 +02:00
}
2015-07-17 15:30:23 +02:00
void CheckCondition : : alwaysTrueFalse ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
2015-07-17 15:30:23 +02:00
return ;
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-07-14 08:18:10 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart - > next ( ) ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2021-01-10 13:30:00 +01:00
if ( Token : : simpleMatch ( tok , " < " ) & & tok - > link ( ) ) // don't write false positives when templates are used
2015-07-17 15:30:23 +02:00
continue ;
2017-03-03 19:53:16 +01:00
if ( ! tok - > hasKnownIntValue ( ) )
2015-07-17 15:30:23 +02:00
continue ;
2021-01-10 13:30:00 +01:00
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 ;
}
2019-10-31 08:32:39 +01:00
{
// is this a condition..
const Token * parent = tok - > astParent ( ) ;
while ( Token : : Match ( parent , " %oror%|&& " ) )
parent = parent - > astParent ( ) ;
if ( ! parent )
continue ;
const Token * condition = nullptr ;
if ( parent - > str ( ) = = " ? " & & precedes ( tok , parent ) )
condition = parent - > astOperand1 ( ) ;
else if ( Token : : Match ( parent - > previous ( ) , " if|while ( " ) )
condition = parent - > astOperand2 ( ) ;
2020-06-28 22:28:08 +02:00
else if ( Token : : simpleMatch ( parent , " return " ) )
condition = parent - > astOperand1 ( ) ;
2019-10-31 08:32:39 +01:00
else if ( parent - > str ( ) = = " ; " && parent->astParent() && parent->astParent()->astParent() && Token::simpleMatch(parent->astParent()->astParent()->previous(), " for ( " ))
condition = parent - > astOperand1 ( ) ;
else
continue ;
( void ) condition ;
}
2018-11-07 06:49:07 +01:00
// Skip already diagnosed values
2018-11-10 21:30:01 +01:00
if ( diag ( tok , false ) )
2018-11-07 06:49:07 +01:00
continue ;
2018-07-21 18:40:06 +02:00
if ( Token : : Match ( tok , " %num%|%bool%|%char% " ) )
2018-07-12 23:06:47 +02:00
continue ;
2018-07-21 18:40:06 +02:00
if ( Token : : Match ( tok , " ! %num%|%bool%|%char% " ) )
continue ;
2018-10-18 21:01:47 +02:00
if ( Token : : Match ( tok , " %oror%|&&|: " ) )
2017-03-08 18:39:19 +01:00
continue ;
2018-09-28 08:38:24 +02:00
if ( Token : : Match ( tok , " %comp% " ) & & isSameExpression ( mTokenizer - > isCPP ( ) , true , tok - > astOperand1 ( ) , tok - > astOperand2 ( ) , mSettings - > library , true , true ) )
2018-09-02 08:43:17 +02:00
continue ;
2020-01-03 19:35:28 +01:00
if ( isConstVarExpression ( tok , " [|(|&|+|-|*|/|%|^|>>|<< " ) )
continue ;
2015-07-17 15:30:23 +02:00
2017-09-08 14:30:42 +02:00
const bool constIfWhileExpression =
2019-08-16 07:56:39 +02:00
tok - > astParent ( ) & & Token : : Match ( tok - > astTop ( ) - > astOperand1 ( ) , " if|while " ) & & ! tok - > astTop ( ) - > astOperand1 ( ) - > isConstexpr ( ) & &
2018-07-23 08:51:59 +02:00
( Token : : Match ( tok - > astParent ( ) , " %oror%|&& " ) | | Token : : Match ( tok - > astParent ( ) - > astOperand1 ( ) , " if|while " ) ) ;
2018-07-21 18:40:06 +02:00
const bool constValExpr = tok - > isNumber ( ) & & Token : : Match ( tok - > astParent ( ) , " %oror%|&&|? " ) ; // just one number in boolean expression
2017-09-08 14:30:42 +02:00
const bool compExpr = Token : : Match ( tok , " %comp%|! " ) ; // a compare expression
2019-09-23 08:49:04 +02:00
const bool ternaryExpression = Token : : simpleMatch ( tok - > astParent ( ) , " ? " ) ;
2020-06-28 22:28:08 +02:00
const bool returnExpression = Token : : simpleMatch ( tok - > astTop ( ) , " return " ) & & ( tok - > isComparisonOp ( ) | | Token : : Match ( tok , " &&|%oror% " ) ) ;
2018-10-18 21:01:47 +02:00
2020-06-28 22:28:08 +02:00
if ( ! ( constIfWhileExpression | | constValExpr | | compExpr | | ternaryExpression | | returnExpression ) )
2016-02-06 14:37:44 +01:00
continue ;
2015-07-30 13:30:16 +02:00
// Don't warn when there are expanded macros..
bool isExpandedMacro = false ;
2020-07-10 00:50:57 +02:00
visitAstNodes ( tok , [ & ] ( const Token * tok2 ) {
2015-07-30 13:30:16 +02:00
if ( ! tok2 )
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
2015-07-30 13:30:16 +02:00
if ( tok2 - > isExpandedMacro ( ) ) {
isExpandedMacro = true ;
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : done ;
2015-07-30 13:30:16 +02:00
}
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : op1_and_op2 ;
} ) ;
2017-08-28 17:10:49 +02:00
if ( isExpandedMacro )
continue ;
2017-03-03 19:53:16 +01:00
for ( const Token * parent = tok ; parent ; parent = parent - > astParent ( ) ) {
2017-08-28 17:10:49 +02:00
if ( parent - > isExpandedMacro ( ) ) {
isExpandedMacro = true ;
break ;
}
2017-03-03 19:53:16 +01:00
}
2015-07-30 13:30:16 +02:00
if ( isExpandedMacro )
continue ;
2017-05-13 19:07:24 +02:00
// don't warn when condition checks sizeof result
bool hasSizeof = false ;
2020-07-10 00:50:57 +02:00
visitAstNodes ( tok , [ & ] ( const Token * tok2 ) {
2017-05-13 19:07:24 +02:00
if ( ! tok2 )
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
2017-05-13 19:07:24 +02:00
if ( tok2 - > isNumber ( ) )
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
2017-05-13 19:07:24 +02:00
if ( Token : : simpleMatch ( tok2 - > previous ( ) , " sizeof ( " ) ) {
hasSizeof = true ;
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
2017-05-13 19:07:24 +02:00
}
if ( tok2 - > isComparisonOp ( ) | | tok2 - > isArithmeticalOp ( ) ) {
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : op1_and_op2 ;
2020-11-11 08:01:11 +01:00
}
2020-07-10 00:50:57 +02:00
return ChildrenToVisit : : none ;
} ) ;
2020-11-11 08:01:11 +01:00
if ( hasSizeof )
2017-05-13 19:07:24 +02:00
continue ;
2017-10-16 22:05:00 +02:00
alwaysTrueFalseError ( tok , & tok - > values ( ) . front ( ) ) ;
2015-07-17 15:30:23 +02:00
}
}
}
2017-10-16 22:05:00 +02:00
void CheckCondition : : alwaysTrueFalseError ( const Token * tok , const ValueFlow : : Value * value )
2015-07-17 15:30:23 +02:00
{
2019-10-31 08:32:39 +01:00
const bool alwaysTrue = value & & ( value - > intvalue ! = 0 ) ;
2015-07-17 15:30:23 +02:00
const std : : string expr = tok ? tok - > expressionString ( ) : std : : string ( " x " ) ;
2019-10-31 08:32:39 +01:00
const std : : string errmsg = " Condition ' " + expr + " ' is always " + ( alwaysTrue ? " true " : " false " ) ;
2017-10-16 22:05:00 +02:00
const ErrorPath errorPath = getErrorPath ( tok , value , errmsg ) ;
reportError ( errorPath ,
2015-07-17 15:30:23 +02:00
Severity : : style ,
" knownConditionTrueFalse " ,
2017-10-16 22:05:00 +02:00
errmsg ,
2019-10-31 08:32:39 +01:00
( alwaysTrue ? CWE571 : CWE570 ) , false ) ;
2015-07-17 15:30:23 +02:00
}
2015-11-30 08:51:15 +01:00
void CheckCondition : : checkInvalidTestForOverflow ( )
{
2021-01-05 11:38:19 +01:00
// 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
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2015-11-30 08:51:15 +01:00
return ;
2021-01-05 11:38:19 +01:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
if ( ! Token : : Match ( tok , " <|<=|>=|> " ) | | ! tok - > isBinaryOp ( ) )
continue ;
2015-11-30 08:51:15 +01:00
2021-01-05 11:38:19 +01:00
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 ] = = ' < ' ) ? ' > ' : ' < ' ;
2015-11-30 08:51:15 +01:00
2021-01-05 11:38:19 +01:00
if ( ! Token : : Match ( lhs , " [+-] " ) | | ! lhs - > isBinaryOp ( ) )
2015-11-30 08:51:15 +01:00
continue ;
2021-01-05 11:38:19 +01:00
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 )
2015-11-30 08:51:15 +01:00
continue ;
2021-01-05 11:38:19 +01:00
const Token * exprTokens [ 2 ] = { lhs - > astOperand1 ( ) , lhs - > astOperand2 ( ) } ;
for ( const Token * expr : exprTokens ) {
if ( lhs - > str ( ) = = " - " & & expr = = lhs - > astOperand2 ( ) )
continue ; // TODO?
2015-11-30 08:51:15 +01:00
2021-01-05 11:38:19 +01:00
if ( expr - > hasKnownIntValue ( ) )
continue ;
if ( ! isSameExpression ( mTokenizer - > isCPP ( ) ,
true ,
expr ,
lhs - > astSibling ( ) ,
mSettings - > library ,
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 ( ) , result ? " true " : " false " ) ;
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 ;
}
2015-11-30 08:51:15 +01:00
2021-01-05 11:38:19 +01:00
// 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 ;
}
}
2015-11-30 08:51:15 +01:00
}
}
}
2021-01-05 11:38:19 +01:00
void CheckCondition : : invalidTestForOverflow ( const Token * tok , const ValueType * valueType , const std : : string & replace )
2015-11-30 08:51:15 +01:00
{
2021-01-05 11:38:19 +01:00
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 , false ) ;
2015-11-30 08:51:15 +01:00
}
2017-10-22 14:32:54 +02:00
void CheckCondition : : checkPointerAdditionResultNotNull ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2017-10-22 14:32:54 +02:00
return ;
2018-06-16 16:10:28 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-07-14 08:18:10 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2017-10-22 14:32:54 +02:00
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2017-10-22 14:32:54 +02:00
if ( ! tok - > isComparisonOp ( ) | | ! tok - > astOperand1 ( ) | | ! tok - > astOperand2 ( ) )
continue ;
2017-10-22 23:13:12 +02:00
// Macros might have pointless safety checks
if ( tok - > isExpandedMacro ( ) )
continue ;
2017-10-22 14:32:54 +02:00
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. " ) ;
}
2019-04-18 20:20:24 +02:00
void CheckCondition : : checkDuplicateConditionalAssign ( )
{
if ( ! mSettings - > isEnabled ( Settings : : STYLE ) )
return ;
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 - > next ( ) - > link ( ) , " ) { " ) )
continue ;
const Token * blockTok = tok - > next ( ) - > link ( ) - > next ( ) ;
const Token * condTok = tok - > next ( ) - > astOperand2 ( ) ;
if ( ! Token : : Match ( condTok , " ==|!= " ) )
continue ;
if ( condTok - > str ( ) = = " != " & & Token : : simpleMatch ( blockTok - > link ( ) , " } else { " ) )
continue ;
if ( ! blockTok - > next ( ) )
continue ;
const Token * assignTok = blockTok - > next ( ) - > astTop ( ) ;
if ( ! Token : : simpleMatch ( assignTok , " = " ) )
continue ;
2019-04-26 12:30:41 +02:00
if ( nextAfterAstRightmostLeaf ( assignTok ) ! = blockTok - > link ( ) - > previous ( ) )
continue ;
2019-04-18 20:20:24 +02:00
if ( ! isSameExpression (
mTokenizer - > isCPP ( ) , true , condTok - > astOperand1 ( ) , assignTok - > astOperand1 ( ) , mSettings - > library , true , true ) )
continue ;
if ( ! isSameExpression (
mTokenizer - > isCPP ( ) , true , condTok - > astOperand2 ( ) , assignTok - > astOperand2 ( ) , mSettings - > library , true , true ) )
continue ;
duplicateConditionalAssignError ( condTok , assignTok ) ;
}
}
}
void CheckCondition : : duplicateConditionalAssignError ( const Token * condTok , const Token * assignTok )
{
ErrorPath errors ;
2019-04-26 12:30:41 +02:00
std : : string msg = " Duplicate expression for the condition and assignment. " ;
2019-04-18 20:20:24 +02:00
if ( condTok & & assignTok ) {
if ( condTok - > str ( ) = = " == " ) {
2019-04-26 12:30:41 +02:00
msg = " Assignment ' " + assignTok - > expressionString ( ) + " ' is redundant with condition ' " + condTok - > expressionString ( ) + " '. " ;
2019-04-18 20:20:24 +02:00
errors . emplace_back ( condTok , " Condition ' " + condTok - > expressionString ( ) + " ' " ) ;
errors . emplace_back ( assignTok , " Assignment ' " + assignTok - > expressionString ( ) + " ' is redundant " ) ;
} else {
2019-04-26 12:30:41 +02:00
msg = " The statement 'if ( " + condTok - > expressionString ( ) + " ) " + assignTok - > expressionString ( ) + " ' is logically equivalent to ' " + assignTok - > expressionString ( ) + " '. " ;
2019-04-18 20:20:24 +02:00
errors . emplace_back ( assignTok , " Assignment ' " + assignTok - > expressionString ( ) + " ' " ) ;
errors . emplace_back ( condTok , " Condition ' " + condTok - > expressionString ( ) + " ' is redundant " ) ;
}
}
2019-04-26 12:30:41 +02:00
2019-04-18 20:20:24 +02:00
reportError (
2019-04-26 12:30:41 +02:00
errors , Severity : : style , " duplicateConditionalAssign " , msg , CWE398 , false ) ;
2019-04-18 20:20:24 +02:00
}