2009-01-31 20:29:27 +01:00
/*
* Cppcheck - A tool for static C / C + + code analysis
2018-01-14 15:37:52 +01:00
* Copyright ( C ) 2007 - 2018 Cppcheck team .
2009-01-31 20:29:27 +01: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
2009-09-27 17:08:31 +02:00
* along with this program . If not , see < http : //www.gnu.org/licenses/>.
2009-01-31 20:29:27 +01:00
*/
//---------------------------------------------------------------------------
// Buffer overrun..
//---------------------------------------------------------------------------
# include "checkbufferoverrun.h"
2017-05-27 04:33:47 +02:00
# include "astutils.h"
# include "library.h"
2009-08-02 14:26:26 +02:00
# include "mathlib.h"
2017-05-27 04:33:47 +02:00
# include "settings.h"
2011-06-23 04:44:11 +02:00
# include "symboldatabase.h"
2017-05-27 04:33:47 +02:00
# include "token.h"
# include "tokenize.h"
# include "tokenlist.h"
2017-05-23 14:58:43 +02:00
# include "utils.h"
2017-05-27 04:33:47 +02:00
# include "valueflow.h"
2009-02-11 06:16:10 +01:00
2017-05-27 04:33:47 +02:00
# include <tinyxml2.h>
2009-01-31 20:29:27 +01:00
# include <algorithm>
2011-12-23 22:31:48 +01:00
# include <cstdlib>
2017-05-27 04:33:47 +02:00
# include <sstream>
2015-07-04 09:42:42 +02:00
# include <stack>
2017-05-27 04:33:47 +02:00
# include <utility>
2009-01-31 20:29:27 +01:00
//---------------------------------------------------------------------------
2009-03-20 18:16:21 +01:00
// Register this check class (by creating a static instance of it)
2011-10-13 20:53:06 +02:00
namespace {
CheckBufferOverrun instance ;
2009-03-20 18:16:21 +01:00
}
//---------------------------------------------------------------------------
2009-01-31 20:29:27 +01:00
2016-01-25 20:01:48 +01:00
// CWE ids used:
2016-08-15 18:04:55 +02:00
static const CWE CWE131 ( 131U ) ; // Incorrect Calculation of Buffer Size
static const CWE CWE170 ( 170U ) ; // Improper Null Termination
static const CWE CWE398 ( 398U ) ; // Indicator of Poor Code Quality
static const CWE CWE682 ( 682U ) ; // Incorrect Calculation
static const CWE CWE758 ( 758U ) ; // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior
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
2016-01-25 20:01:48 +01:00
//---------------------------------------------------------------------------
2011-12-08 21:28:34 +01:00
static void makeArrayIndexOutOfBoundsError ( std : : ostream & oss , const CheckBufferOverrun : : ArrayInfo & arrayInfo , const std : : vector < MathLib : : bigint > & index )
2010-04-18 11:08:29 +02:00
{
2018-04-09 06:43:48 +02:00
oss < < " $symbol: " < < arrayInfo . varname ( ) < < ' \n ' ;
2011-06-23 02:35:58 +02:00
oss < < " Array ' " < < arrayInfo . varname ( ) ;
2014-07-06 14:48:24 +02:00
for ( std : : size_t i = 0 ; i < arrayInfo . num ( ) . size ( ) ; + + i )
2011-06-23 02:35:58 +02:00
oss < < " [ " < < arrayInfo . num ( i ) < < " ] " ;
2010-04-23 16:26:40 +02:00
if ( index . size ( ) = = 1 )
2012-06-23 09:51:32 +02:00
oss < < " ' accessed at index " < < index [ 0 ] < < " , which is " ;
2011-10-13 20:53:06 +02:00
else {
2012-06-23 09:51:32 +02:00
oss < < " ' index " < < arrayInfo . varname ( ) ;
2014-07-06 14:48:24 +02:00
for ( std : : size_t i = 0 ; i < index . size ( ) ; + + i )
2010-04-23 16:26:40 +02:00
oss < < " [ " < < index [ i ] < < " ] " ;
}
2012-07-08 15:51:24 +02:00
oss < < " out of bounds. " ;
2011-12-08 21:28:34 +01:00
}
void CheckBufferOverrun : : arrayIndexOutOfBoundsError ( const Token * tok , const ArrayInfo & arrayInfo , const std : : vector < MathLib : : bigint > & index )
{
std : : ostringstream oss ;
makeArrayIndexOutOfBoundsError ( oss , arrayInfo , index ) ;
2016-01-25 20:01:48 +01:00
reportError ( tok , Severity : : error , " arrayIndexOutOfBounds " , oss . str ( ) , CWE788 , false ) ;
2010-04-18 11:08:29 +02:00
}
2014-01-22 21:25:37 +01:00
void CheckBufferOverrun : : arrayIndexOutOfBoundsError ( const Token * tok , const ArrayInfo & arrayInfo , const std : : vector < ValueFlow : : Value > & index )
2014-01-17 18:56:46 +01:00
{
2017-05-23 14:58:43 +02:00
bool inconclusive = false ;
2014-02-16 11:47:52 +01:00
const Token * condition = nullptr ;
2014-07-06 14:48:24 +02:00
for ( std : : size_t i = 0 ; i < index . size ( ) ; + + i ) {
2017-09-20 22:41:36 +02:00
inconclusive | = index [ i ] . isInconclusive ( ) ;
2014-02-16 10:32:10 +01:00
if ( condition = = nullptr )
2014-01-22 21:25:37 +01:00
condition = index [ i ] . condition ;
}
2014-01-17 18:56:46 +01:00
2017-05-23 14:58:43 +02:00
std : : list < ErrorPathItem > errorPath ;
2018-06-16 16:10:28 +02:00
if ( mSettings - > xml | | ! mSettings - > templateLocation . empty ( ) ) {
2017-05-23 14:58:43 +02:00
for ( std : : size_t i = 0 ; i < index . size ( ) ; + + i ) {
const ErrorPath & e = getErrorPath ( tok , & index [ i ] , " " ) ;
for ( ErrorPath : : const_iterator it = e . begin ( ) ; it ! = e . end ( ) ; + + it ) {
const std : : string & info = it - > second ;
if ( info . empty ( ) )
continue ;
std : : string nr ;
if ( index . size ( ) > 1U )
2017-09-07 13:00:46 +02:00
nr = " ( " + MathLib : : toString ( i + 1 ) + getOrdinalText ( i + 1 ) + " array index) " ;
2018-04-11 09:44:35 +02:00
errorPath . emplace_back ( it - > first , nr + info ) ;
2017-05-23 14:58:43 +02:00
}
}
2018-04-11 09:44:35 +02:00
errorPath . emplace_back ( tok , " Array index out of bounds " ) ;
2017-05-23 14:58:43 +02:00
} else {
2018-04-11 09:44:35 +02:00
errorPath . emplace_back ( tok , " Array index out of bounds " ) ;
2017-05-23 14:58:43 +02:00
if ( condition )
2018-04-11 09:44:35 +02:00
errorPath . emplace_back ( condition , " Assuming that condition ' " + condition - > expressionString ( ) + " ' is not redundant " ) ;
2017-05-23 14:58:43 +02:00
}
2014-02-16 10:32:10 +01:00
if ( condition ! = nullptr ) {
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : WARNING ) )
2015-01-06 15:14:15 +01:00
return ;
2015-07-29 19:54:57 +02:00
std : : ostringstream errmsg ;
2018-04-09 06:43:48 +02:00
errmsg < < " $symbol: " < < arrayInfo . varname ( ) < < ' \n ' ;
errmsg < < ValueFlow : : eitherTheConditionIsRedundant ( condition ) < < " or the array '$symbol " ;
2015-07-29 19:54:57 +02:00
for ( std : : size_t i = 0 ; i < arrayInfo . num ( ) . size ( ) ; + + i )
errmsg < < " [ " < < arrayInfo . num ( i ) < < " ] " ;
if ( index . size ( ) = = 1 )
errmsg < < " ' is accessed at index " < < index [ 0 ] . intvalue < < " , which is out of bounds. " ;
else {
errmsg < < " ' index " < < arrayInfo . varname ( ) ;
for ( std : : size_t i = 0 ; i < index . size ( ) ; + + i )
errmsg < < " [ " < < index [ i ] . intvalue < < " ] " ;
errmsg < < " is out of bounds. " ;
}
2017-05-23 14:58:43 +02:00
reportError ( errorPath , Severity : : warning , " arrayIndexOutOfBoundsCond " , errmsg . str ( ) , CWE119 , inconclusive ) ;
2014-01-17 19:44:45 +01:00
} else {
2015-07-29 19:54:57 +02:00
std : : ostringstream errmsg ;
2018-04-09 06:43:48 +02:00
errmsg < < " $symbol: " < < arrayInfo . varname ( ) < < ' \n ' ;
errmsg < < " Array '$symbol " ;
2015-07-29 19:54:57 +02:00
for ( std : : size_t i = 0 ; i < arrayInfo . num ( ) . size ( ) ; + + i )
errmsg < < " [ " < < arrayInfo . num ( i ) < < " ] " ;
if ( index . size ( ) = = 1 )
errmsg < < " ' accessed at index " < < index [ 0 ] . intvalue < < " , which is out of bounds. " ;
else {
errmsg < < " ' index " < < arrayInfo . varname ( ) ;
for ( std : : size_t i = 0 ; i < index . size ( ) ; + + i )
errmsg < < " [ " < < index [ i ] . intvalue < < " ] " ;
errmsg < < " out of bounds. " ;
}
2017-05-23 14:58:43 +02:00
reportError ( errorPath , Severity : : error , " arrayIndexOutOfBounds " , errmsg . str ( ) , CWE119 , inconclusive ) ;
2014-01-17 19:44:45 +01:00
}
2014-01-17 18:56:46 +01:00
}
2011-08-24 13:11:39 +02:00
void CheckBufferOverrun : : arrayIndexOutOfBoundsError ( const std : : list < const Token * > & callstack , const ArrayInfo & arrayInfo , const std : : vector < MathLib : : bigint > & index )
2010-08-05 11:01:47 +02:00
{
std : : ostringstream oss ;
2011-12-08 21:28:34 +01:00
makeArrayIndexOutOfBoundsError ( oss , arrayInfo , index ) ;
2016-01-15 17:07:14 +01:00
reportError ( callstack , Severity : : error , " arrayIndexOutOfBounds " , oss . str ( ) ) ;
2010-08-05 11:01:47 +02:00
}
2011-12-11 08:16:58 +01:00
static std : : string bufferOverrunMessage ( std : : string varnames )
2009-03-21 21:33:27 +01:00
{
2012-07-08 15:51:24 +02:00
varnames . erase ( std : : remove ( varnames . begin ( ) , varnames . end ( ) , ' ' ) , varnames . end ( ) ) ;
2010-02-21 15:23:50 +01:00
2012-07-08 15:51:24 +02:00
std : : string errmsg ( " Buffer is accessed out of bounds " ) ;
2011-12-11 08:16:58 +01:00
if ( ! varnames . empty ( ) )
2018-04-09 06:43:48 +02:00
errmsg = " $symbol: " + varnames + ' \n ' + errmsg + " : " + varnames ;
2012-07-08 15:51:24 +02:00
else
errmsg + = " . " ;
2011-12-11 08:48:55 +01:00
2011-12-11 08:16:58 +01:00
return errmsg ;
}
void CheckBufferOverrun : : bufferOverrunError ( const Token * tok , const std : : string & varnames )
{
2016-01-25 20:01:48 +01:00
reportError ( tok , Severity : : error , " bufferAccessOutOfBounds " , bufferOverrunMessage ( varnames ) , CWE788 , false ) ;
2011-12-11 08:16:58 +01:00
}
2010-02-21 15:23:50 +01:00
2011-12-11 08:16:58 +01:00
void CheckBufferOverrun : : bufferOverrunError ( const std : : list < const Token * > & callstack , const std : : string & varnames )
{
2016-01-15 17:07:14 +01:00
reportError ( callstack , Severity : : error , " bufferAccessOutOfBounds " , bufferOverrunMessage ( varnames ) ) ;
2009-03-21 21:33:27 +01:00
}
2011-08-21 21:18:41 +02:00
void CheckBufferOverrun : : possibleBufferOverrunError ( const Token * tok , const std : : string & src , const std : : string & dst , bool cat )
2011-08-21 20:44:55 +02:00
{
2011-08-21 21:18:41 +02:00
if ( cat )
reportError ( tok , Severity : : warning , " possibleBufferAccessOutOfBounds " ,
" Possible buffer overflow if strlen( " + src + " ) is larger than sizeof( " + dst + " )-strlen( " + dst + " ). \n "
2012-07-08 15:51:24 +02:00
" Possible buffer overflow if strlen( " + src + " ) is larger than sizeof( " + dst + " )-strlen( " + dst + " ). "
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
" The source buffer is larger than the destination buffer so there is the potential for overflowing the destination buffer. " , CWE398 , false ) ;
2011-08-21 21:18:41 +02:00
else
reportError ( tok , Severity : : warning , " possibleBufferAccessOutOfBounds " ,
" Possible buffer overflow if strlen( " + src + " ) is larger than or equal to sizeof( " + dst + " ). \n "
2012-07-08 15:51:24 +02:00
" Possible buffer overflow if strlen( " + src + " ) is larger than or equal to sizeof( " + dst + " ). "
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
" The source buffer is larger than the destination buffer so there is the potential for overflowing the destination buffer. " , CWE398 , false ) ;
2011-08-21 20:44:55 +02:00
}
2011-08-24 13:11:39 +02:00
void CheckBufferOverrun : : strncatUsageError ( const Token * tok )
2009-03-21 21:33:27 +01:00
{
2018-06-16 16:10:28 +02:00
if ( mSettings & & ! mSettings - > isEnabled ( Settings : : WARNING ) )
2009-10-13 22:33:41 +02:00
return ;
2011-01-03 17:33:03 +01:00
reportError ( tok , Severity : : warning , " strncatUsage " ,
" Dangerous usage of strncat - 3rd parameter is the maximum number of characters to append. \n "
2014-07-31 19:51:29 +02:00
" At most, strncat appends the 3rd parameter's amount of characters and adds a terminating null byte. \n "
" The safe way to use strncat is to subtract one from the remaining space in the buffer and use it as 3rd parameter. "
" Source: http://www.cplusplus.com/reference/cstring/strncat/ \n "
2016-08-12 15:19:27 +02:00
" Source: http://www.opensource.apple.com/source/Libc/Libc-167/gen.subproj/i386.subproj/strncat.c " , CWE119 , false ) ;
2009-03-21 21:33:27 +01:00
}
2011-10-05 20:17:57 +02:00
void CheckBufferOverrun : : outOfBoundsError ( const Token * tok , const std : : string & what , const bool show_size_info , const MathLib : : bigint & supplied_size , const MathLib : : bigint & actual_size )
2009-03-21 21:33:27 +01:00
{
2011-10-05 20:17:57 +02:00
std : : ostringstream oss ;
oss < < what < < " is out of bounds " ;
if ( show_size_info )
2012-07-08 15:51:24 +02:00
oss < < " : Supplied size " < < supplied_size < < " is larger than actual size " < < actual_size ;
oss < < ' . ' ;
2016-01-25 20:01:48 +01:00
reportError ( tok , Severity : : error , " outOfBounds " , oss . str ( ) , CWE788 , false ) ;
2009-03-21 21:33:27 +01:00
}
2014-12-25 10:05:55 +01:00
void CheckBufferOverrun : : pointerOutOfBoundsError ( const Token * tok , const Token * index , const MathLib : : bigint indexvalue )
2010-12-26 21:23:28 +01:00
{
2016-11-27 11:40:42 +01:00
// The severity is portability instead of error since this ub doesn't
2014-12-22 15:41:46 +01:00
// cause bad behaviour on most implementations. people create out
// of bounds pointers by intention.
2017-01-16 20:10:28 +01:00
const std : : string expr ( tok ? tok - > expressionString ( ) : std : : string ( ) ) ;
2014-12-25 14:31:46 +01:00
std : : string errmsg ;
if ( index & & ! index - > isNumber ( ) ) {
errmsg = " Undefined behaviour, when ' " +
index - > expressionString ( ) +
" ' is " +
MathLib : : toString ( indexvalue ) +
" the pointer arithmetic ' " + expr + " ' is out of bounds " ;
} else {
errmsg = " Undefined behaviour, pointer arithmetic ' " + expr + " ' is out of bounds " ;
}
2018-04-04 21:51:31 +02:00
const std : : string verbosemsg ( errmsg + " . From chapter 6.5.6 in the C specification: \n "
" \" When an expression that has integer type is added to or subtracted from a pointer, .. \" and then \" If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. \" " ) ;
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 : : portability , " pointerOutOfBounds " , errmsg + " . \n " + verbosemsg , CWE398 , false ) ;
2014-12-25 10:05:55 +01:00
/*
" Undefined behaviour: The result of this pointer arithmetic does not point into
or just one element past the end of the " + object + " .
Further information :
https : //www.securecoding.cert.org/confluence/display/seccode/ARR30-C.+Do+not+form+or+use+out+of+bounds+pointers+or+array+subscripts");
*/
2010-12-26 21:23:28 +01:00
}
2011-08-24 13:11:39 +02:00
void CheckBufferOverrun : : sizeArgumentAsCharError ( const Token * tok )
2009-03-25 07:25:10 +01:00
{
2018-06-16 16:10:28 +02:00
if ( mSettings & & ! mSettings - > isEnabled ( Settings : : WARNING ) )
2009-10-13 22:33:41 +02:00
return ;
2016-08-12 15:19:27 +02:00
reportError ( tok , Severity : : warning , " sizeArgumentAsChar " , " The size argument is given as a char constant. " , CWE682 , false ) ;
2009-03-25 07:25:10 +01:00
}
2009-12-18 17:26:15 +01:00
2011-09-05 21:59:41 +02:00
void CheckBufferOverrun : : terminateStrncpyError ( const Token * tok , const std : : string & varname )
2009-12-18 17:26:15 +01:00
{
2018-04-09 06:43:48 +02:00
const std : : string shortMessage = " The buffer '$symbol' may not be null-terminated after the call to strncpy(). " ;
2011-09-05 21:59:41 +02:00
reportError ( tok , Severity : : warning , " terminateStrncpy " ,
2018-04-09 06:43:48 +02:00
" $symbol: " + varname + ' \n ' +
shortMessage + ' \n ' +
shortMessage + ' ' +
2012-07-08 15:51:24 +02:00
" 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 "
2016-08-12 15:19:27 +02:00
" assumes buffer is null-terminated. " , CWE170 , true ) ;
2009-12-18 17:26:15 +01:00
}
2010-06-02 07:41:07 +02:00
void CheckBufferOverrun : : cmdLineArgsError ( const Token * tok )
{
2016-01-25 20:01:48 +01:00
reportError ( tok , Severity : : error , " insecureCmdLineArgs " , " Buffer overrun possible for long command line arguments. " , CWE119 , false ) ;
2010-06-02 07:41:07 +02:00
}
2011-09-05 21:59:41 +02:00
void CheckBufferOverrun : : bufferNotZeroTerminatedError ( const Token * tok , const std : : string & varname , const std : : string & function )
2011-09-05 21:41:37 +02:00
{
2018-04-09 06:43:48 +02:00
const std : : string errmsg = " $symbol: " + varname + ' \n ' +
" $symbol: " + function + ' \n ' +
" The buffer ' " + varname + " ' is not null-terminated after the call to " + function + " (). \n "
2012-07-09 11:11:05 +02:00
" The buffer ' " + varname + " ' is not null-terminated after the call to " + function + " (). "
" This will cause bugs later in the code if the code assumes the buffer is null-terminated. " ;
2011-10-14 19:45:51 +02:00
2016-08-12 15:19:27 +02:00
reportError ( tok , Severity : : warning , " bufferNotZeroTerminated " , errmsg , CWE170 , true ) ;
2011-09-05 21:41:37 +02:00
}
2009-12-18 17:26:15 +01:00
2012-12-22 09:23:34 +01:00
void CheckBufferOverrun : : argumentSizeError ( const Token * tok , const std : : string & functionName , const std : : string & varname )
{
2018-04-09 06:43:48 +02:00
reportError ( tok , Severity : : warning , " argumentSize " ,
" $symbol: " + functionName + ' \n ' +
" $symbol: " + varname + ' \n ' +
" The array ' " + varname + " ' is too small, the function ' " + functionName + " ' expects a bigger one. " , CWE398 , false ) ;
2012-12-22 09:23:34 +01:00
}
2014-02-01 22:38:29 +01:00
void CheckBufferOverrun : : negativeMemoryAllocationSizeError ( const Token * tok )
{
reportError ( tok , Severity : : error , " negativeMemoryAllocationSize " ,
2014-04-08 20:23:00 +02:00
" Memory allocation size is negative. \n "
" Memory allocation size is negative. "
2016-01-25 20:01:48 +01:00
" Negative allocation size has no specified behaviour. " , CWE131 , false ) ;
2014-02-01 22:38:29 +01:00
}
2009-01-31 20:29:27 +01:00
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// Check array usage..
//---------------------------------------------------------------------------
2010-12-31 17:43:38 +01:00
2015-11-09 10:30:39 +01:00
static bool isAddressOf ( const Token * tok )
{
const Token * tok2 = tok - > astParent ( ) ;
while ( Token : : Match ( tok2 , " %name%|.|::|[ " ) )
tok2 = tok2 - > astParent ( ) ;
2018-07-13 23:12:20 +02:00
return tok2 & & tok2 - > isUnaryOp ( " & " ) ;
2015-11-09 10:30:39 +01:00
}
2010-12-31 17:43:38 +01:00
/**
* bailout if variable is used inside if / else / switch block or if there is " break "
* @ param tok token for " if " or " switch "
* @ param varid variable id
* @ return is bailout recommended ?
*/
static bool bailoutIfSwitch ( const Token * tok , const unsigned int varid )
{
2012-03-17 21:55:08 +01:00
const Token * end = tok - > linkAt ( 1 ) - > linkAt ( 1 ) ;
if ( Token : : simpleMatch ( end , " } else { " ) ) // scan the else-block
end = end - > linkAt ( 2 ) ;
2013-11-30 07:40:32 +01:00
if ( Token : : simpleMatch ( end , " { " ) ) // Ticket #5203: Invalid code, bailout
return true ;
2014-07-29 11:59:45 +02:00
// Used later to check if the body belongs to a "if"
const bool is_if = tok - > str ( ) = = " if " ;
2014-03-21 13:20:44 +01:00
for ( ; tok & & tok ! = end ; tok = tok - > next ( ) ) {
2010-12-31 17:43:38 +01:00
// If scanning a "if" block then bailout for "break"
2012-07-08 14:34:47 +02:00
if ( is_if & & ( tok - > str ( ) = = " break " | | tok - > str ( ) = = " continue " ) )
2010-12-31 17:43:38 +01:00
return true ;
2010-12-31 18:07:46 +01:00
// bailout for "return"
else if ( tok - > str ( ) = = " return " )
return true ;
2010-12-31 17:43:38 +01:00
// bailout if varid is found
else if ( tok - > varId ( ) = = varid )
return true ;
}
// No bailout stuff found => return false
return false ;
}
2014-06-27 06:46:42 +02:00
//---------------------------------------------------------------------------
2010-04-21 18:33:21 +02:00
2017-03-27 17:33:26 +02:00
static bool checkMinSizes ( const std : : vector < Library : : ArgumentChecks : : MinSize > & minsizes , const Token * const ftok , const MathLib : : bigint arraySize , const Token * * charSizeToken , const Settings * const settings )
2014-07-06 08:41:39 +02:00
{
if ( charSizeToken )
* charSizeToken = nullptr ;
if ( minsizes . empty ( ) )
return false ;
// All conditions must be true
bool error = true ;
2017-03-27 17:33:26 +02:00
for ( std : : vector < Library : : ArgumentChecks : : MinSize > : : const_iterator minsize = minsizes . begin ( ) ; minsize ! = minsizes . end ( ) ; + + minsize ) {
2014-07-06 08:41:39 +02:00
if ( ! error )
return false ;
error = false ;
const Token * argtok = ftok - > tokAt ( 2 ) ;
for ( int argnum = 1 ; argtok & & argnum < minsize - > arg ; argnum + + )
argtok = argtok - > nextArgument ( ) ;
if ( ! argtok )
return false ;
switch ( minsize - > type ) {
case Library : : ArgumentChecks : : MinSize : : ARGVALUE :
if ( Token : : Match ( argtok , " %num% ,|) " ) ) {
const MathLib : : bigint sz = MathLib : : toLongNumber ( argtok - > str ( ) ) ;
2015-11-28 10:11:07 +01:00
if ( sz > arraySize )
2014-07-06 08:41:39 +02:00
error = true ;
2015-08-14 20:46:13 +02:00
} else if ( argtok - > tokType ( ) = = Token : : eChar & & Token : : Match ( argtok - > next ( ) , " ,|) " ) & & charSizeToken )
2014-07-06 08:41:39 +02:00
* charSizeToken = argtok ; //sizeArgumentAsCharError(argtok);
break ;
case Library : : ArgumentChecks : : MinSize : : MUL :
// TODO: handle arbitrary arg2
if ( minsize - > arg2 = = minsize - > arg + 1 & & Token : : Match ( argtok , " %num% , %num% ,|) " ) ) {
const MathLib : : bigint sz = MathLib : : toLongNumber ( argtok - > str ( ) ) * MathLib : : toLongNumber ( argtok - > strAt ( 2 ) ) ;
2015-11-28 10:11:07 +01:00
if ( sz > arraySize )
2014-07-06 08:41:39 +02:00
error = true ;
}
break ;
2014-08-03 20:11:22 +02:00
case Library : : ArgumentChecks : : MinSize : : STRLEN : {
2015-02-12 17:29:36 +01:00
if ( settings - > library . isargformatstr ( ftok , minsize - > arg ) ) {
std : : list < const Token * > parameters ;
const std : : string & formatstr ( argtok - > str ( ) ) ;
const Token * argtok2 = argtok ;
while ( ( argtok2 = argtok2 - > nextArgument ( ) ) ! = nullptr ) {
if ( Token : : Match ( argtok2 , " %num%|%str% [,)] " ) )
parameters . push_back ( argtok2 ) ;
else
parameters . push_back ( nullptr ) ;
}
2015-02-18 20:56:44 +01:00
const MathLib : : biguint len = CheckBufferOverrun : : countSprintfLength ( formatstr , parameters ) ;
2017-05-25 00:19:27 +02:00
if ( len > arraySize + 2 )
2015-02-12 17:29:36 +01:00
error = true ;
} else {
const Token * strtoken = argtok - > getValueTokenMaxStrLength ( ) ;
if ( strtoken & & Token : : getStrLength ( strtoken ) > = arraySize )
error = true ;
}
2014-08-03 20:11:22 +02:00
}
break ;
2014-07-06 08:41:39 +02:00
case Library : : ArgumentChecks : : MinSize : : SIZEOF :
2015-08-14 20:46:13 +02:00
if ( argtok - > tokType ( ) = = Token : : eString & & Token : : getStrLength ( argtok ) > = arraySize )
2014-07-06 08:41:39 +02:00
error = true ;
break ;
case Library : : ArgumentChecks : : MinSize : : NONE :
return false ;
} ;
}
return error ;
}
2016-01-15 15:20:40 +01:00
void CheckBufferOverrun : : checkFunctionParameter ( const Token & ftok , unsigned int paramIndex , const ArrayInfo & arrayInfo , const std : : list < const Token * > & callstack )
2010-04-21 19:27:28 +02:00
{
2018-06-16 16:10:28 +02:00
const std : : vector < Library : : ArgumentChecks : : MinSize > * const minsizes = mSettings - > library . argminsizes ( & ftok , paramIndex ) ;
2010-04-21 20:02:58 +02:00
2016-07-27 17:28:43 +02:00
if ( minsizes ) {
2014-07-05 20:31:43 +02:00
MathLib : : bigint arraySize = arrayInfo . element_size ( ) ;
2016-01-15 15:20:40 +01:00
if ( arraySize = = 0 )
return ;
2014-07-06 14:48:24 +02:00
for ( std : : size_t i = 0 ; i < arrayInfo . num ( ) . size ( ) ; + + i )
2014-07-05 20:31:43 +02:00
arraySize * = arrayInfo . num ( i ) ;
2015-06-07 14:01:20 +02:00
// dimension is 0 or unknown => bailout
if ( arraySize = = 0 )
return ;
2014-07-06 08:41:39 +02:00
const Token * charSizeToken = nullptr ;
2018-06-16 16:10:28 +02:00
if ( checkMinSizes ( * minsizes , & ftok , arraySize , & charSizeToken , mSettings ) )
2014-07-05 20:31:43 +02:00
bufferOverrunError ( callstack , arrayInfo . varname ( ) ) ;
2014-07-06 08:41:39 +02:00
if ( charSizeToken )
sizeArgumentAsCharError ( charSizeToken ) ;
2010-04-21 19:27:28 +02:00
}
2010-08-05 11:01:47 +02:00
// Calling a user function?
// only 1-dimensional arrays can be checked currently
2011-10-13 20:53:06 +02:00
else if ( arrayInfo . num ( ) . size ( ) = = 1 ) {
2014-07-05 20:31:43 +02:00
const Function * const func = ftok . function ( ) ;
2012-12-22 09:23:34 +01:00
2015-01-08 05:45:31 +01:00
if ( func & & func - > hasBody ( ) ) {
2012-09-11 18:03:47 +02:00
// Get corresponding parameter..
2016-01-15 15:20:40 +01:00
const Variable * const parameter = func - > getArgumentVar ( paramIndex - 1 ) ;
2010-08-05 11:01:47 +02:00
2012-09-11 18:03:47 +02:00
// Ensure that it has a compatible size..
2016-07-08 20:53:08 +02:00
if ( ! parameter | | sizeOfType ( parameter - > typeStartToken ( ) ) ! = arrayInfo . element_size ( ) )
2010-08-05 11:01:47 +02:00
return ;
2012-09-23 13:25:28 +02:00
// No variable id occur for instance when:
// - Variable function arguments: "void f(...)"
// - Unnamed parameter: "void f(char *)"
2013-07-20 12:31:04 +02:00
if ( parameter - > declarationId ( ) = = 0 )
2012-09-22 16:19:19 +02:00
return ;
2010-08-05 11:01:47 +02:00
// Check the parameter usage in the function scope..
2018-04-27 22:36:30 +02:00
for ( const Token * ftok2 = func - > functionScope - > bodyStart ; ftok2 ! = func - > functionScope - > bodyEnd ; ftok2 = ftok2 - > next ( ) ) {
2014-07-05 20:31:43 +02:00
if ( Token : : Match ( ftok2 , " if|for|switch|while ( " ) ) {
2010-12-31 18:07:46 +01:00
// bailout if there is buffer usage..
2014-07-05 20:31:43 +02:00
if ( bailoutIfSwitch ( ftok2 , parameter - > declarationId ( ) ) ) {
2010-12-31 18:07:46 +01:00
break ;
}
// no bailout is needed. skip the if-block
2011-10-13 20:53:06 +02:00
else {
2010-12-31 18:07:46 +01:00
// goto end of if block..
2014-07-05 20:31:43 +02:00
ftok2 = ftok2 - > linkAt ( 1 ) - > linkAt ( 1 ) ;
if ( Token : : simpleMatch ( ftok2 , " } else { " ) )
ftok2 = ftok2 - > linkAt ( 2 ) ;
if ( ! ftok2 )
2011-08-29 19:16:52 +02:00
break ;
2010-12-31 18:07:46 +01:00
continue ;
}
}
2010-08-05 11:01:47 +02:00
2014-07-05 20:31:43 +02:00
if ( ftok2 - > str ( ) = = " } " )
2010-08-05 11:01:47 +02:00
break ;
2014-07-05 20:31:43 +02:00
if ( ftok2 - > varId ( ) = = parameter - > declarationId ( ) ) {
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( ftok2 - > previous ( ) , " -- %name% " ) | |
Token : : Match ( ftok2 , " %name% -- " ) )
2010-10-14 20:00:32 +02:00
break ;
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( ftok2 - > previous ( ) , " ;|{|}|%op% %name% [ %num% ] " ) ) {
2014-07-05 20:31:43 +02:00
const MathLib : : bigint index = MathLib : : toLongNumber ( ftok2 - > strAt ( 2 ) ) ;
2011-10-13 20:53:06 +02:00
if ( index > = 0 & & arrayInfo . num ( 0 ) > 0 & & index > = arrayInfo . num ( 0 ) ) {
2011-12-11 08:16:58 +01:00
std : : list < const Token * > callstack2 ( callstack ) ;
2014-07-05 20:31:43 +02:00
callstack2 . push_back ( ftok2 ) ;
2010-08-05 11:01:47 +02:00
2018-04-04 21:51:31 +02:00
const std : : vector < MathLib : : bigint > indexes ( 1 , index ) ;
2011-12-11 08:16:58 +01:00
arrayIndexOutOfBoundsError ( callstack2 , arrayInfo , indexes ) ;
2010-08-05 11:01:47 +02:00
}
}
}
2011-12-11 08:16:58 +01:00
// Calling function..
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( ftok2 , " %name% ( " ) ) {
2011-12-11 08:16:58 +01:00
ArrayInfo ai ( arrayInfo ) ;
2013-07-20 12:31:04 +02:00
ai . declarationId ( parameter - > declarationId ( ) ) ;
2014-07-05 20:31:43 +02:00
checkFunctionCall ( ftok2 , ai , callstack ) ;
2011-12-11 08:16:58 +01:00
}
2010-08-05 11:01:47 +02:00
}
}
}
2012-12-22 09:23:34 +01:00
// Check 'float x[10]' arguments in declaration
2018-06-16 16:10:28 +02:00
if ( mSettings - > isEnabled ( Settings : : WARNING ) ) {
2014-07-05 20:31:43 +02:00
const Function * const func = ftok . function ( ) ;
2012-12-22 09:23:34 +01:00
// If argument is '%type% a[num]' then check bounds against num
if ( func ) {
2016-01-15 15:20:40 +01:00
const Variable * const argument = func - > getArgumentVar ( paramIndex - 1 ) ;
2012-12-28 11:15:18 +01:00
const Token * nameToken ;
if ( argument & & Token : : Match ( argument - > typeStartToken ( ) , " %type% %var% [ %num% ] [,)[] " )
2014-02-16 10:32:10 +01:00
& & ( nameToken = argument - > nameToken ( ) ) ! = nullptr ) {
2012-12-28 11:15:18 +01:00
const Token * tok2 = nameToken - > next ( ) ;
2012-12-22 09:23:34 +01:00
2016-07-08 20:53:08 +02:00
MathLib : : bigint argsize = sizeOfType ( argument - > typeStartToken ( ) ) ;
2012-12-22 09:23:34 +01:00
if ( argsize = = 100 ) // unknown size
argsize = 0 ;
2015-08-16 14:22:46 +02:00
do {
2012-12-22 09:23:34 +01:00
argsize * = MathLib : : toLongNumber ( tok2 - > strAt ( 1 ) ) ;
tok2 = tok2 - > tokAt ( 3 ) ;
2015-08-16 14:22:46 +02:00
} while ( Token : : Match ( tok2 , " [ %num% ] [,)[] " ) ) ;
2012-12-22 09:23:34 +01:00
MathLib : : bigint arraysize = arrayInfo . element_size ( ) ;
if ( arraysize = = 100 ) // unknown size
arraysize = 0 ;
2014-07-06 14:48:24 +02:00
for ( std : : size_t i = 0 ; i < arrayInfo . num ( ) . size ( ) ; i + + )
2012-12-22 09:23:34 +01:00
arraysize * = arrayInfo . num ( i ) ;
if ( Token : : Match ( tok2 , " [,)] " ) & & arraysize > 0 & & argsize > arraysize )
2014-07-05 20:31:43 +02:00
argumentSizeError ( & ftok , ftok . str ( ) , arrayInfo . varname ( ) ) ;
2012-12-22 09:23:34 +01:00
}
}
}
2010-04-21 19:27:28 +02:00
}
2011-12-11 08:16:58 +01:00
void CheckBufferOverrun : : checkFunctionCall ( const Token * tok , const ArrayInfo & arrayInfo , std : : list < const Token * > callstack )
2011-01-22 21:31:26 +01:00
{
2011-12-11 08:16:58 +01:00
// Don't go deeper than 2 levels, the checking can get very slow
// when there is no limit
if ( callstack . size ( ) > = 2 )
return ;
// Prevent recursion
2016-05-25 11:50:34 +02:00
for ( std : : list < const Token * > : : const_iterator it = callstack . cbegin ( ) ; it ! = callstack . cend ( ) ; + + it ) {
2011-12-11 08:16:58 +01:00
// Same function name => bail out
if ( tok - > str ( ) = = ( * it ) - > str ( ) )
return ;
}
callstack . push_back ( tok ) ;
2011-01-22 21:31:26 +01:00
2014-05-29 19:58:09 +02:00
const unsigned int declarationId = arrayInfo . declarationId ( ) ;
2015-02-11 16:24:25 +01:00
const Token * argtok = tok - > tokAt ( 2 ) ;
unsigned int argnr = 1U ;
while ( argtok ) {
if ( Token : : Match ( argtok , " %varid% ,|) " , declarationId ) )
checkFunctionParameter ( * tok , argnr , arrayInfo , callstack ) ;
else if ( Token : : Match ( argtok , " %varid% + %num% ,|) " , declarationId)) {
const ArrayInfo ai ( arrayInfo . limit ( MathLib : : toLongNumber ( argtok - > strAt ( 2 ) ) ) ) ;
checkFunctionParameter ( * tok , argnr , ai , callstack ) ;
}
// goto next parameter..
argtok = argtok - > nextArgument ( ) ;
argnr + + ;
2011-01-22 21:31:26 +01:00
}
}
2017-03-27 11:48:34 +02:00
void CheckBufferOverrun : : checkScope ( const Token * tok , const std : : vector < const std : : string * > & varname , const ArrayInfo & arrayInfo )
2009-01-31 20:29:27 +01:00
{
2011-09-12 01:21:13 +02:00
const MathLib : : bigint size = arrayInfo . num ( 0 ) ;
2015-11-28 12:30:03 +01:00
if ( size < = 0 ) // unknown size
2011-12-17 13:20:42 +01:00
return ;
2014-04-23 09:18:09 +02:00
if ( tok - > str ( ) = = " return " ) {
tok = tok - > next ( ) ;
if ( ! tok )
return ;
}
2018-06-16 16:10:28 +02:00
const bool printInconclusive = mSettings - > inconclusive ;
2014-04-24 10:24:40 +02:00
const MathLib : : bigint total_size = arrayInfo . element_size ( ) * size ;
2013-07-20 12:31:04 +02:00
const unsigned int declarationId = arrayInfo . declarationId ( ) ;
2011-09-10 17:21:52 +02:00
2009-01-31 20:29:27 +01:00
std : : string varnames ;
2014-07-07 21:25:30 +02:00
for ( std : : size_t i = 0 ; i < varname . size ( ) ; + + i )
2017-03-27 11:48:34 +02:00
varnames + = ( i = = 0 ? " " : " . " ) + * varname [ i ] ;
2009-01-31 20:29:27 +01:00
2016-01-18 07:52:35 +01:00
const int varcount = varname . empty ( ) ? 0 : static_cast < int > ( ( varname . size ( ) - 1 ) * 2U ) ;
2009-01-31 20:29:27 +01:00
2014-03-29 20:20:22 +01:00
// ValueFlow array index..
if ( ( declarationId > 0 & & Token : : Match ( tok , " %varid% [ " , declarationId ) ) | |
2015-12-03 13:04:55 +01:00
( declarationId = = 0 & & Token : : simpleMatch ( tok , ( varnames + " [ " ) . c_str ( ) ) ) ) {
2014-03-29 20:20:22 +01:00
2015-08-16 14:22:46 +02:00
const Token * tok2 = tok - > next ( ) ;
2014-03-29 20:20:22 +01:00
while ( tok2 - > str ( ) ! = " [ " )
tok2 = tok2 - > next ( ) ;
valueFlowCheckArrayIndex ( tok2 , arrayInfo ) ;
}
2011-01-01 20:56:21 +01:00
// If the result of pointer arithmetic means that the pointer is
// out of bounds then this flag will be set.
bool pointerIsOutOfBounds = false ;
2018-06-16 16:10:28 +02:00
const bool printPortability = mSettings - > isEnabled ( Settings : : PORTABILITY ) ;
2014-05-29 19:58:09 +02:00
2018-04-27 22:36:30 +02:00
for ( const Token * const end = tok - > scope ( ) - > bodyEnd ; tok & & tok ! = end ; tok = tok - > next ( ) ) {
2013-07-20 12:31:04 +02:00
if ( declarationId ! = 0 & & Token : : Match ( tok , " %varid% = new|malloc|realloc " , declarationId ) ) {
2010-02-10 22:11:08 +01:00
// Abort
break ;
}
2011-10-12 20:54:39 +02:00
// reassign buffer
2013-07-20 12:31:04 +02:00
if ( declarationId > 0 & & Token : : Match ( tok , " [;{}] %varid% = %any% " , declarationId ) ) {
2011-10-12 22:06:19 +02:00
// using varid .. bailout
2013-07-20 12:31:04 +02:00
if ( tok - > tokAt ( 3 ) - > varId ( ) ! = declarationId )
2011-10-12 22:06:19 +02:00
break ;
pointerIsOutOfBounds = false ;
}
2011-08-08 18:22:15 +02:00
2009-01-31 20:29:27 +01:00
// Array index..
2014-12-17 16:23:48 +01:00
if ( ( declarationId > 0 & & ( ( tok - > str ( ) = = " return " | | ( ! tok - > isName ( ) & & ! Token : : Match ( tok , " [.&] " ) ) ) & & Token : : Match ( tok - > next ( ) , " %varid% [ " , declarationId ) ) ) | |
2017-03-27 11:48:34 +02:00
( declarationId = = 0 & & ( ( tok - > str ( ) = = " return " | | ( ! tok - > isName ( ) & & ! Token : : Match ( tok , " [.&] " ) ) ) & & ( Token : : Match ( tok - > next ( ) , ( varnames + " [ " ) . c_str ( ) ) | | Token : : Match ( tok - > next ( ) , ( * varname [ 0 ] + " [ %num% ] . " + * varname [ 1 ] + " [ %num% ] " ) . c_str ( ) ) ) ) ) ) {
2011-09-12 02:42:57 +02:00
std : : vector < MathLib : : bigint > indexes ;
2014-04-23 09:18:09 +02:00
const Token * tok2 = tok - > tokAt ( 2 + varcount ) ;
2011-10-13 20:53:06 +02:00
for ( ; Token : : Match ( tok2 , " [ %num% ] " ) ; tok2 = tok2 - > tokAt ( 3 ) ) {
2011-09-12 02:42:57 +02:00
const MathLib : : bigint index = MathLib : : toLongNumber ( tok2 - > strAt ( 1 ) ) ;
2011-09-11 15:54:26 +02:00
indexes . push_back ( index ) ;
2009-01-31 20:29:27 +01:00
}
2013-03-14 06:34:12 +01:00
for ( ; Token : : Match ( tok2 - > tokAt ( 3 ) , " [ %num% ] " ) ; tok2 = tok2 - > tokAt ( 3 ) ) {
const MathLib : : bigint index = MathLib : : toLongNumber ( tok2 - > strAt ( 4 ) ) ;
indexes . push_back ( index ) ;
}
2014-12-17 16:23:48 +01:00
if ( indexes . empty ( ) & & arrayInfo . num ( ) . size ( ) = = 1U & & Token : : simpleMatch ( tok2 , " [ " ) & & tok2 - > astOperand2 ( ) ) {
const ValueFlow : : Value * value = tok2 - > astOperand2 ( ) - > getMaxValue ( false ) ;
if ( value ) {
indexes . push_back ( value - > intvalue ) ;
}
}
2011-09-12 02:42:57 +02:00
2011-10-13 20:53:06 +02:00
if ( indexes . size ( ) = = arrayInfo . num ( ) . size ( ) ) {
2011-09-12 02:42:57 +02:00
// Check if the indexes point outside the whole array..
// char a[10][10];
// a[0][20] <-- ok.
// a[9][20] <-- error.
// total number of elements of array..
MathLib : : bigint totalElements = 1 ;
// total index..
MathLib : : bigint totalIndex = 0 ;
// calculate the totalElements and totalIndex..
2014-07-07 21:25:30 +02:00
for ( std : : size_t i = 0 ; i < indexes . size ( ) ; + + i ) {
const std : : size_t ri = indexes . size ( ) - 1 - i ;
2011-09-12 02:42:57 +02:00
totalIndex + = indexes [ ri ] * totalElements ;
totalElements * = arrayInfo . num ( ri ) ;
2014-12-20 18:50:08 +01:00
if ( arrayInfo . num ( ri ) = = - 1 ) {
// unknown size
totalElements = 0 ;
break ;
}
2011-09-12 02:42:57 +02:00
}
// totalElements == 0 => Unknown size
if ( totalElements = = 0 )
continue ;
const Token * tok3 = tok - > previous ( ) ;
2015-01-31 10:50:39 +01:00
while ( tok3 & & Token : : Match ( tok3 - > previous ( ) , " %name% . " ) )
2011-09-12 02:42:57 +02:00
tok3 = tok3 - > tokAt ( - 2 ) ;
// taking address of 1 past end?
2014-07-29 11:59:45 +02:00
if ( totalIndex = = totalElements ) {
const bool addr = ( tok3 & & ( tok3 - > str ( ) = = " & " | |
2014-08-03 20:11:22 +02:00
Token : : simpleMatch ( tok3 - > previous ( ) , " & ( " ) ) ) ;
2014-07-29 11:59:45 +02:00
if ( addr )
continue ;
}
2011-09-12 02:42:57 +02:00
// Is totalIndex in bounds?
2011-10-13 20:53:06 +02:00
if ( totalIndex > totalElements | | totalIndex < 0 ) {
2014-04-23 09:18:09 +02:00
arrayIndexOutOfBoundsError ( tok - > tokAt ( 1 + varcount ) , arrayInfo , indexes ) ;
2011-09-12 02:42:57 +02:00
}
// Is any array index out of bounds?
2011-10-13 20:53:06 +02:00
else {
2011-09-12 02:42:57 +02:00
// check each index for overflow
2014-07-07 21:25:30 +02:00
for ( std : : size_t i = 0 ; i < indexes . size ( ) ; + + i ) {
2011-10-13 20:53:06 +02:00
if ( indexes [ i ] > = arrayInfo . num ( i ) ) {
2012-03-13 21:30:03 +01:00
if ( indexes . size ( ) = = 1U ) {
2014-04-23 09:18:09 +02:00
arrayIndexOutOfBoundsError ( tok - > tokAt ( 1 + varcount ) , arrayInfo , indexes ) ;
2012-03-13 21:30:03 +01:00
break ; // only warn about the first one
}
2011-09-12 02:42:57 +02:00
// The access is still within the memory range for the array
// so it may be intentional.
2015-04-10 14:18:52 +02:00
else if ( printInconclusive ) {
2014-04-23 09:18:09 +02:00
arrayIndexOutOfBoundsError ( tok - > tokAt ( 1 + varcount ) , arrayInfo , indexes ) ;
2011-09-12 02:42:57 +02:00
break ; // only warn about the first one
}
}
}
}
}
tok = tok2 ;
2009-01-31 20:29:27 +01:00
continue ;
}
// memset, memcmp, memcpy, strncpy, fgets..
2017-11-03 10:39:57 +01:00
if ( declarationId = = 0 & & Token : : Match ( tok , " %name% ( !!) " ) ) {
2018-04-09 09:54:39 +02:00
std : : list < const Token * > callstack ( 1 , tok ) ;
2016-05-25 11:50:34 +02:00
const Token * tok2 = tok - > tokAt ( 2 ) ;
if ( Token : : Match ( tok2 , ( varnames + " , " ) . c_str ( ) ) )
2011-12-11 08:16:58 +01:00
checkFunctionParameter ( * tok , 1 , arrayInfo , callstack ) ;
2016-05-25 11:50:34 +02:00
tok2 = tok2 - > nextArgument ( ) ;
if ( Token : : Match ( tok2 , ( varnames + " , " ) . c_str ( ) ) )
2011-12-11 08:16:58 +01:00
checkFunctionParameter ( * tok , 2 , arrayInfo , callstack ) ;
2009-01-31 20:29:27 +01:00
}
2015-01-30 20:27:48 +01:00
if ( total_size > 0 ) {
// Writing data into array..
2015-09-01 15:17:17 +02:00
if ( ( declarationId > 0 & & Token : : Match ( tok , " strcpy|strcat ( %varid% , %str%|%var% ) " , declarationId ) ) | |
( declarationId = = 0 & & Token : : Match ( tok , ( " strcpy|strcat ( " + varnames + " , %str%|%var% ) " ) . c_str ( ) ) ) ) {
const Token * lastParamTok = tok - > tokAt ( varcount + 4 ) ;
if ( lastParamTok - > tokType ( ) = = Token : : Type : : eString ) {
const std : : size_t len = Token : : getStrLength ( lastParamTok ) ;
2015-10-11 12:50:46 +02:00
if ( len > = total_size ) {
2015-09-01 15:17:17 +02:00
bufferOverrunError ( tok , declarationId > 0 ? emptyString : varnames ) ;
2015-01-30 20:27:48 +01:00
continue ;
}
2015-09-01 15:17:17 +02:00
} else {
const Variable * var = lastParamTok - > variable ( ) ;
if ( var & & var - > isArray ( ) & & var - > dimensions ( ) . size ( ) = = 1 ) {
const MathLib : : bigint len = var - > dimension ( 0 ) ;
if ( len > total_size ) {
if ( printInconclusive )
possibleBufferOverrunError ( tok , tok - > strAt ( 4 ) , tok - > strAt ( 2 ) , tok - > str ( ) = = " strcat " ) ;
continue ;
}
}
2015-01-30 20:27:48 +01:00
}
2011-08-21 20:44:55 +02:00
}
2009-02-20 22:16:07 +01:00
2015-01-30 20:27:48 +01:00
// Detect few strcat() calls
const std : : string strcatPattern = declarationId > 0 ? std : : string ( " strcat ( %varid% , %str% ) ; " ) : ( " strcat ( " + varnames + " , %str% ) ; " ) ;
if ( Token : : Match ( tok , strcatPattern . c_str ( ) , declarationId ) ) {
std : : size_t charactersAppend = 0 ;
const Token * tok2 = tok ;
2009-08-30 13:44:23 +02:00
2015-05-13 13:40:40 +02:00
do {
2015-01-30 20:27:48 +01:00
charactersAppend + = Token : : getStrLength ( tok2 - > tokAt ( 4 + varcount ) ) ;
if ( charactersAppend > = static_cast < std : : size_t > ( total_size ) ) {
bufferOverrunError ( tok2 ) ;
break ;
}
tok2 = tok2 - > tokAt ( 7 + varcount ) ;
2015-05-13 13:40:40 +02:00
} while ( Token : : Match ( tok2 , strcatPattern . c_str ( ) , declarationId ) ) ;
2009-08-30 13:44:23 +02:00
}
2009-01-31 20:29:27 +01:00
2015-01-30 20:27:48 +01:00
// Check function call..
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( tok , " %name% ( " ) ) {
2015-01-30 20:27:48 +01:00
// No varid => function calls are not handled
if ( declarationId = = 0 )
continue ;
2011-01-22 21:31:26 +01:00
2015-01-30 20:27:48 +01:00
const ArrayInfo arrayInfo1 ( declarationId , varnames , total_size / size , size ) ;
const std : : list < const Token * > callstack ;
checkFunctionCall ( tok , arrayInfo1 , callstack ) ;
}
2009-01-31 20:29:27 +01:00
}
2011-01-01 20:56:21 +01:00
// undefined behaviour: result of pointer arithmetic is out of bounds
2015-01-30 20:27:48 +01:00
if ( declarationId & & Token : : Match ( tok , " = %varid% + %num% ; " , declarationId ) ) {
2011-01-01 20:56:21 +01:00
const MathLib : : bigint index = MathLib : : toLongNumber ( tok - > strAt ( 3 ) ) ;
2015-04-10 14:18:52 +02:00
if ( printPortability & & index > size )
2014-12-25 10:05:55 +01:00
pointerOutOfBoundsError ( tok - > tokAt ( 2 ) ) ;
2013-07-20 12:31:04 +02:00
if ( index > = size & & Token : : Match ( tok - > tokAt ( - 2 ) , " [;{}] %varid% = " , declarationId ) )
2011-01-01 20:56:21 +01:00
pointerIsOutOfBounds = true ;
}
2013-07-20 12:31:04 +02:00
else if ( pointerIsOutOfBounds & & Token : : Match ( tok , " [;{}=] * %varid% [;=] " , declarationId ) ) {
2011-10-05 20:17:57 +02:00
outOfBoundsError ( tok - > tokAt ( 2 ) , tok - > strAt ( 2 ) , false , 0 , 0 ) ;
2011-01-01 20:56:21 +01:00
}
2009-01-31 20:29:27 +01:00
}
}
2015-11-28 12:30:03 +01:00
static std : : vector < ValueFlow : : Value > valueFlowGetArrayIndexes ( const Token * const tok , bool conditional , std : : size_t dimensions )
2015-11-08 12:39:08 +01:00
{
unsigned int indexvarid = 0 ;
const std : : vector < ValueFlow : : Value > empty ;
std : : vector < ValueFlow : : Value > indexes ;
2017-04-08 15:49:56 +02:00
for ( const Token * tok2 = tok ; indexes . size ( ) < dimensions & & Token : : simpleMatch ( tok2 , " [ " ) ; tok2 = tok2 - > link ( ) - > next ( ) ) {
2015-11-08 12:39:08 +01:00
if ( ! tok2 - > astOperand2 ( ) )
return empty ;
const ValueFlow : : Value * index = tok2 - > astOperand2 ( ) - > getMaxValue ( conditional ) ;
if ( ! index )
return empty ;
if ( indexvarid = = 0U )
indexvarid = index - > varId ;
if ( index - > varId > 0 & & indexvarid ! = index - > varId )
return empty ;
if ( index - > intvalue < 0 )
return empty ;
indexes . push_back ( * index ) ;
}
return indexes ;
}
2014-03-29 20:20:22 +01:00
void CheckBufferOverrun : : valueFlowCheckArrayIndex ( const Token * const tok , const ArrayInfo & arrayInfo )
{
2014-10-21 22:56:53 +02:00
// Declaration in global scope or namespace?
if ( tok - > scope ( ) - > type = = Scope : : eGlobal | | tok - > scope ( ) - > type = = Scope : : eNamespace )
2014-08-19 07:03:00 +02:00
return ;
2014-08-23 12:28:54 +02:00
/*
{
const Token * parent = tok - > astParent ( ) ;
2015-01-31 10:50:39 +01:00
while ( Token : : Match ( parent , " %name%|::|*|& " ) )
2014-08-23 12:28:54 +02:00
parent = parent - > astParent ( ) ;
if ( parent & & ! Token : : simpleMatch ( parent , " = " ) )
return ;
}
*/
2018-06-16 16:10:28 +02:00
const bool printInconclusive = mSettings - > inconclusive ;
2014-03-29 20:20:22 +01:00
// Taking address?
2015-11-09 10:30:39 +01:00
const bool addressOf = isAddressOf ( tok ) ;
2014-03-29 20:20:22 +01:00
// Look for errors first
for ( int warn = 0 ; warn = = 0 | | warn = = 1 ; + + warn ) {
// Negative index..
for ( const Token * tok2 = tok ; tok2 & & tok2 - > str ( ) = = " [ " ; tok2 = tok2 - > link ( ) - > next ( ) ) {
const Token * index = tok2 - > astOperand2 ( ) ;
if ( ! index )
continue ;
2018-06-16 16:10:28 +02:00
const ValueFlow : : Value * value = index - > getValueLE ( - 1LL , mSettings ) ;
2014-04-02 06:49:28 +02:00
if ( value )
negativeIndexError ( index , * value ) ;
2014-03-29 20:20:22 +01:00
}
// Index out of bounds..
2015-11-08 12:39:08 +01:00
const std : : vector < ValueFlow : : Value > indexes ( valueFlowGetArrayIndexes ( tok , warn = = 1 , arrayInfo . num ( ) . size ( ) ) ) ;
if ( indexes . size ( ) ! = arrayInfo . num ( ) . size ( ) )
continue ;
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// Check if the indexes point outside the whole array..
// char a[10][10];
// a[0][20] <-- ok.
// a[9][20] <-- error.
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// total number of elements of array..
const MathLib : : bigint totalElements = arrayInfo . numberOfElements ( ) ;
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// total index..
const MathLib : : bigint totalIndex = arrayInfo . totalIndex ( indexes ) ;
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// totalElements <= 0 => Unknown size
if ( totalElements < = 0 )
continue ;
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
if ( addressOf & & totalIndex = = totalElements )
continue ;
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// Is totalIndex in bounds?
if ( totalIndex > = totalElements ) {
arrayIndexOutOfBoundsError ( tok , arrayInfo , indexes ) ;
break ;
}
2014-03-29 20:20:22 +01:00
2015-11-08 12:39:08 +01:00
// Is any array index out of bounds?
if ( printInconclusive ) {
// check each index for overflow
for ( std : : size_t i = 0 ; i < indexes . size ( ) ; + + i ) {
if ( indexes [ i ] . intvalue > = arrayInfo . num ( i ) ) {
// The access is still within the memory range for the array
// so it may be intentional.
arrayIndexOutOfBoundsError ( tok , arrayInfo , indexes ) ;
break ; // only warn about the first one
2014-03-29 20:20:22 +01:00
}
}
}
}
}
2009-01-31 20:29:27 +01:00
2010-04-21 18:33:21 +02:00
void CheckBufferOverrun : : checkScope ( const Token * tok , const ArrayInfo & arrayInfo )
{
2014-12-24 14:03:52 +01:00
bool reassigned = false ;
2018-04-27 22:36:30 +02:00
for ( const Token * const end = tok - > scope ( ) - > bodyEnd ; tok ! = end ; tok = tok - > next ( ) ) {
2014-12-24 14:03:52 +01:00
if ( reassigned & & tok - > str ( ) = = " ; " )
break ;
2016-05-25 14:41:26 +02:00
if ( tok - > varId ( ) ! = arrayInfo . declarationId ( ) )
continue ;
2014-12-24 14:03:52 +01:00
2016-05-25 14:41:26 +02:00
if ( tok - > strAt ( 1 ) = = " = " ) {
reassigned = true ;
}
2011-05-07 11:34:48 +02:00
2016-05-25 14:41:26 +02:00
checkScope_inner ( tok , arrayInfo ) ;
}
}
2014-12-22 09:38:00 +01:00
2016-05-25 14:41:26 +02:00
void CheckBufferOverrun : : checkScope ( const Token * tok , std : : map < unsigned int , ArrayInfo > arrayInfos )
{
unsigned int reassigned = 0 ;
2018-04-27 22:36:30 +02:00
for ( const Token * const end = tok - > scope ( ) - > bodyEnd ; tok ! = end ; tok = tok - > next ( ) ) {
2016-05-25 14:41:26 +02:00
if ( reassigned & & tok - > str ( ) = = " ; " ) {
arrayInfos . erase ( reassigned ) ;
reassigned = 0 ;
2010-04-21 18:33:21 +02:00
}
2010-05-17 19:51:35 +02:00
2016-05-25 14:41:26 +02:00
if ( ! tok - > variable ( ) | | tok - > variable ( ) - > nameToken ( ) = = tok )
2010-04-21 18:33:21 +02:00
continue ;
2018-04-04 21:51:31 +02:00
const std : : map < unsigned int , ArrayInfo > : : const_iterator arrayInfo = arrayInfos . find ( tok - > varId ( ) ) ;
2016-05-25 14:41:26 +02:00
if ( arrayInfo = = arrayInfos . cend ( ) )
continue ;
2010-04-21 19:27:28 +02:00
2016-05-25 14:41:26 +02:00
if ( tok - > strAt ( 1 ) = = " = " ) {
reassigned = tok - > varId ( ) ;
}
checkScope_inner ( tok , arrayInfo - > second ) ;
}
}
void CheckBufferOverrun : : checkScope_inner ( const Token * tok , const ArrayInfo & arrayInfo )
{
2018-06-16 16:10:28 +02:00
const bool printPortability = mSettings - > isEnabled ( Settings : : PORTABILITY ) ;
const bool printWarning = mSettings - > isEnabled ( Settings : : WARNING ) ;
const bool printInconclusive = mSettings - > inconclusive ;
2016-05-25 14:41:26 +02:00
2018-05-31 12:17:24 +02:00
const Token * astParent = tok - > astParent ( ) ;
2016-05-25 14:41:26 +02:00
if ( tok - > strAt ( 1 ) = = " [ " ) {
valueFlowCheckArrayIndex ( tok - > next ( ) , arrayInfo ) ;
}
2018-05-31 12:17:24 +02:00
else if ( printPortability & & ! tok - > isCast ( ) & & astParent & & astParent - > str ( ) = = " + " ) {
2016-05-25 14:41:26 +02:00
// undefined behaviour: result of pointer arithmetic is out of bounds
const Token * index ;
2018-05-31 12:17:24 +02:00
if ( tok = = astParent - > astOperand1 ( ) )
index = astParent - > astOperand2 ( ) ;
2016-05-25 14:41:26 +02:00
else
2018-05-31 12:17:24 +02:00
index = astParent - > astOperand1 ( ) ;
2016-05-25 14:41:26 +02:00
if ( index ) {
2018-06-16 16:10:28 +02:00
const ValueFlow : : Value * value = index - > getValueGE ( arrayInfo . num ( 0 ) + 1U , mSettings ) ;
2016-05-25 14:41:26 +02:00
if ( ! value )
2018-06-16 16:10:28 +02:00
value = index - > getValueLE ( - 1 , mSettings ) ;
2016-05-25 14:41:26 +02:00
if ( value )
2018-05-31 12:17:24 +02:00
pointerOutOfBoundsError ( astParent , index , value - > intvalue ) ;
2016-05-25 14:41:26 +02:00
}
}
2018-05-31 12:17:24 +02:00
else if ( printPortability & & astParent & & astParent - > str ( ) = = " - " ) {
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2016-07-08 20:53:08 +02:00
const Variable * var = symbolDatabase - > getVariableFromVarId ( arrayInfo . declarationId ( ) ) ;
2016-05-25 14:41:26 +02:00
if ( var & & var - > isArray ( ) ) {
2018-05-31 12:17:24 +02:00
const Token * index = astParent - > astOperand2 ( ) ;
2018-06-16 16:10:28 +02:00
const ValueFlow : : Value * value = index ? index - > getValueGE ( 1 , mSettings ) : nullptr ;
2016-05-25 14:41:26 +02:00
if ( index & & ! value )
2018-06-16 16:10:28 +02:00
value = index - > getValueLE ( - 1 - arrayInfo . num ( 0 ) , mSettings ) ;
2016-05-25 14:41:26 +02:00
if ( value )
2018-05-31 12:17:24 +02:00
pointerOutOfBoundsError ( astParent , index , value - > intvalue ) ;
2016-05-25 14:41:26 +02:00
}
}
if ( ! tok - > scope ( ) - > isExecutable ( ) ) // No executable code outside of executable scope - continue to increase performance
return ;
2018-05-31 12:17:24 +02:00
const Token * tok2 = astParent ;
2016-05-25 14:41:26 +02:00
if ( tok2 ) {
while ( tok2 - > astParent ( ) & & ! Token : : Match ( tok2 - > astParent ( ) , " [,(] " ) )
tok2 = tok2 - > astParent ( ) ;
while ( tok2 - > astParent ( ) & & tok2 - > astParent ( ) - > str ( ) = = " , " )
tok2 = tok2 - > astParent ( ) ;
if ( tok2 - > astParent ( ) & & tok2 - > astParent ( ) - > str ( ) = = " ( " )
tok2 = tok2 - > astParent ( ) ;
if ( tok2 - > str ( ) ! = " ( " )
return ;
tok2 = tok2 - > previous ( ) ;
// Check function call..
checkFunctionCall ( tok2 , arrayInfo , std : : list < const Token * > ( ) ) ;
const MathLib : : biguint total_size = arrayInfo . num ( 0 ) * arrayInfo . element_size ( ) ;
if ( printWarning & & printInconclusive & & Token : : Match ( tok2 , " strncpy|memcpy|memmove ( %varid% , %str% , %num% ) " , arrayInfo . declarationId ( ) ) ) {
if ( Token : : getStrLength ( tok2 - > tokAt ( 4 ) ) > = total_size ) {
const MathLib : : biguint num = MathLib : : toULongNumber ( tok2 - > strAt ( 6 ) ) ;
if ( total_size = = num )
bufferNotZeroTerminatedError ( tok2 , tok2 - > strAt ( 2 ) , tok2 - > str ( ) ) ;
2011-09-05 21:19:38 +02:00
}
2016-05-25 14:41:26 +02:00
}
2011-09-05 21:19:38 +02:00
2016-05-25 14:41:26 +02:00
if ( printWarning & & Token : : Match ( tok2 , " strncpy|strncat ( %varid% , " , arrayInfo . declarationId ( ) ) & & Token : : Match ( tok2 - > linkAt ( 1 ) - > tokAt ( - 2 ) , " , %num% ) " ) ) {
const Token * param3 = tok2 - > linkAt ( 1 ) - > previous ( ) ;
// check for strncpy which is not terminated
if ( tok2 - > str ( ) = = " strncpy " ) {
// strncpy takes entire variable length as input size
const MathLib : : biguint num = MathLib : : toULongNumber ( param3 - > str ( ) ) ;
// this is currently 'inconclusive'. See TestBufferOverrun::terminateStrncpy3
if ( printInconclusive & & num > = total_size ) {
const Token * tok4 = tok2 - > next ( ) - > link ( ) - > next ( ) ;
for ( ; tok4 ; tok4 = tok4 - > next ( ) ) {
const Token * tok3 = tok2 - > tokAt ( 2 ) ;
if ( tok4 - > varId ( ) = = tok3 - > varId ( ) ) {
2016-11-24 07:04:58 +01:00
const Token * eq = nullptr ;
if ( Token : : Match ( tok4 , " %varid% [ " , tok3 - > varId ( ) ) & & Token : : simpleMatch ( tok4 - > linkAt ( 1 ) , " ] = " ) )
eq = tok4 - > linkAt ( 1 ) - > next ( ) ;
const Token * rhs = eq ? eq - > astOperand2 ( ) : nullptr ;
if ( ! ( rhs & & rhs - > hasKnownIntValue ( ) & & rhs - > getValue ( 0 ) ) )
2016-05-25 14:41:26 +02:00
terminateStrncpyError ( tok2 , tok3 - > str ( ) ) ;
break ;
2010-04-21 18:33:21 +02:00
}
}
}
2016-05-25 14:41:26 +02:00
}
2010-04-21 18:33:21 +02:00
2016-05-25 14:41:26 +02:00
// Dangerous usage of strncat..
else if ( tok2 - > str ( ) = = " strncat " ) {
const MathLib : : biguint n = MathLib : : toULongNumber ( param3 - > str ( ) ) ;
if ( n > = total_size )
strncatUsageError ( tok2 ) ;
}
2010-04-21 18:33:21 +02:00
2016-05-25 14:41:26 +02:00
// Dangerous usage of strncpy + strncat..
if ( Token : : Match ( param3 - > tokAt ( 2 ) , " ; strncat ( %varid% , " , arrayInfo . declarationId ( ) ) & & Token : : Match ( param3 - > linkAt ( 4 ) - > tokAt ( - 2 ) , " , %num% ) " ) ) {
const MathLib : : biguint n = MathLib : : toULongNumber ( param3 - > str ( ) ) + MathLib : : toULongNumber ( param3 - > linkAt ( 4 ) - > strAt ( - 1 ) ) ;
if ( n > total_size )
strncatUsageError ( param3 - > tokAt ( 3 ) ) ;
2010-04-21 18:33:21 +02:00
}
2016-05-25 14:41:26 +02:00
}
2010-04-21 18:33:21 +02:00
2016-05-25 14:41:26 +02:00
// Writing data into array..
if ( total_size > 0 ) {
if ( Token : : Match ( tok2 , " strcpy ( %varid% , %str% ) " , arrayInfo . declarationId ( ) ) ) {
const std : : size_t len = Token : : getStrLength ( tok2 - > tokAt ( 4 ) ) ;
if ( len > = total_size ) {
bufferOverrunError ( tok2 , arrayInfo . varname ( ) ) ;
return ;
2014-06-23 19:06:31 +02:00
}
2016-05-25 14:41:26 +02:00
}
2010-04-21 18:33:21 +02:00
2016-05-25 14:41:26 +02:00
// Detect few strcat() calls
MathLib : : biguint charactersAppend = 0 ;
const Token * tok3 = tok2 ;
2010-04-21 18:33:21 +02:00
2017-03-27 16:09:51 +02:00
while ( Token : : Match ( tok3 , " strcat ( %varid% , %str% ) " , arrayInfo . declarationId ( ) ) ) {
2016-05-25 14:41:26 +02:00
charactersAppend + = Token : : getStrLength ( tok3 - > tokAt ( 4 ) ) ;
if ( charactersAppend > = total_size ) {
bufferOverrunError ( tok3 , arrayInfo . varname ( ) ) ;
break ;
2010-04-21 18:33:21 +02:00
}
2016-05-25 14:41:26 +02:00
tok3 = tok3 - > tokAt ( 7 ) ;
2010-04-21 18:33:21 +02:00
}
2014-06-23 19:06:31 +02:00
}
2010-04-21 18:33:21 +02:00
}
}
2015-05-03 15:00:47 +02:00
//---------------------------------------------------------------------------
// Negative size in array declarations
//---------------------------------------------------------------------------
2015-07-04 09:42:42 +02:00
static bool isVLAIndex ( const Token * index )
{
std : : stack < const Token * > tokens ;
tokens . push ( index ) ;
while ( ! tokens . empty ( ) ) {
const Token * tok = tokens . top ( ) ;
tokens . pop ( ) ;
if ( ! tok )
continue ;
if ( tok - > varId ( ) ! = 0U )
return true ;
if ( tok - > str ( ) = = " ? " ) {
// this is a VLA index if both expressions around the ":" is VLA index
if ( tok - > astOperand2 ( ) & &
tok - > astOperand2 ( ) - > str ( ) = = " : " & &
isVLAIndex ( tok - > astOperand2 ( ) - > astOperand1 ( ) ) & &
isVLAIndex ( tok - > astOperand2 ( ) - > astOperand2 ( ) ) )
return true ;
continue ;
}
tokens . push ( tok - > astOperand1 ( ) ) ;
tokens . push ( tok - > astOperand2 ( ) ) ;
}
return false ;
}
2015-05-03 15:00:47 +02:00
void CheckBufferOverrun : : negativeArraySize ( )
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-04-28 09:38:33 +02:00
for ( const Variable * var : symbolDatabase - > variableList ( ) ) {
2015-05-03 15:00:47 +02:00
if ( ! var | | ! var - > isArray ( ) )
continue ;
const Token * const nameToken = var - > nameToken ( ) ;
if ( ! Token : : Match ( nameToken , " %var% [ " ) | | ! nameToken - > next ( ) - > astOperand2 ( ) )
continue ;
2018-06-16 16:10:28 +02:00
const ValueFlow : : Value * sz = nameToken - > next ( ) - > astOperand2 ( ) - > getValueLE ( - 1 , mSettings ) ;
2015-07-04 09:42:42 +02:00
// don't warn about constant negative index because that is a compiler error
if ( sz & & isVLAIndex ( nameToken - > next ( ) - > astOperand2 ( ) ) )
negativeArraySizeError ( nameToken ) ;
2015-05-03 15:00:47 +02:00
}
}
void CheckBufferOverrun : : negativeArraySizeError ( const Token * tok )
{
2018-04-09 06:43:48 +02:00
const std : : string arrayName = tok ? tok - > expressionString ( ) : std : : string ( ) ;
const std : : string line1 = arrayName . empty ( ) ? std : : string ( ) : ( " $symbol: " + arrayName + ' \n ' ) ;
2015-05-03 15:00:47 +02:00
reportError ( tok , Severity : : error , " negativeArraySize " ,
2018-04-09 06:43:48 +02:00
line1 +
" Declaration of array ' " + arrayName + " ' with negative size is undefined behaviour " , CWE758 , false ) ;
2015-05-03 15:00:47 +02:00
}
2013-03-14 06:34:12 +01:00
//---------------------------------------------------------------------------
2014-09-30 14:54:59 +02:00
// Checking member variables of structs.
2013-03-14 06:34:12 +01:00
//---------------------------------------------------------------------------
bool CheckBufferOverrun : : isArrayOfStruct ( const Token * tok , int & position )
{
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( tok - > next ( ) , " %name% [ %num% ] " ) ) {
2013-03-14 06:34:12 +01:00
tok = tok - > tokAt ( 4 ) ;
int i = 1 ;
2013-03-18 19:50:24 +01:00
for ( ; ; ) {
2014-12-27 11:09:54 +01:00
if ( Token : : Match ( tok - > next ( ) , " [ %num% ] " ) ) {
2013-03-14 06:34:12 +01:00
i + + ;
tok = tok - > tokAt ( 4 ) ;
} else
break ;
}
2014-03-14 16:26:37 +01:00
if ( Token : : simpleMatch ( tok - > next ( ) , " ; " ) ) {
2013-03-14 06:34:12 +01:00
position = i ;
return true ;
}
}
return false ;
}
2009-01-31 20:29:27 +01:00
//---------------------------------------------------------------------------
// Checking local variables in a scope
//---------------------------------------------------------------------------
2009-07-13 16:00:15 +02:00
void CheckBufferOverrun : : checkGlobalAndLocalVariable ( )
2009-01-31 20:29:27 +01:00
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2011-12-01 04:17:09 +01:00
// check string literals
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
2015-11-08 14:21:12 +01:00
if ( Token : : Match ( tok , " %str% [ " ) & & tok - > next ( ) - > astOperand2 ( ) ) {
2015-11-09 10:30:39 +01:00
const std : : size_t size = Token : : getStrSize ( tok ) ;
2015-11-07 15:05:56 +01:00
const ValueFlow : : Value * value = tok - > next ( ) - > astOperand2 ( ) - > getMaxValue ( false ) ;
2015-11-09 10:30:39 +01:00
if ( value & & value - > intvalue > = ( isAddressOf ( tok ) ? size + 1U : size ) )
2011-12-01 04:17:09 +01:00
bufferOverrunError ( tok , tok - > str ( ) ) ;
}
2015-11-07 18:12:01 +01:00
2015-11-07 19:59:48 +01:00
if ( Token : : Match ( tok , " %var% [ " ) & & tok - > next ( ) - > astOperand2 ( ) & & tok - > variable ( ) & & tok - > variable ( ) - > isPointer ( ) ) {
2015-11-07 18:12:01 +01:00
const ValueFlow : : Value * value = tok - > next ( ) - > astOperand2 ( ) - > getMaxValue ( false ) ;
if ( ! value )
continue ;
2017-03-27 18:48:34 +02:00
for ( std : : list < ValueFlow : : Value > : : const_iterator it = tok - > values ( ) . begin ( ) ; it ! = tok - > values ( ) . end ( ) ; + + it ) {
2016-11-13 22:33:39 +01:00
if ( ! it - > isTokValue ( ) | | ! it - > tokvalue )
2015-11-07 18:12:01 +01:00
continue ;
const Variable * var = it - > tokvalue - > variable ( ) ;
2015-11-08 12:39:08 +01:00
if ( var & & var - > isArray ( ) ) {
2015-11-08 17:21:32 +01:00
if ( astCanonicalType ( tok ) ! = astCanonicalType ( it - > tokvalue ) )
continue ;
2016-07-08 20:53:08 +02:00
const ArrayInfo arrayInfo ( var , symbolDatabase ) ;
2015-11-08 12:39:08 +01:00
const MathLib : : bigint elements = arrayInfo . numberOfElements ( ) ;
if ( elements < = 0 ) // unknown size
continue ;
const std : : vector < ValueFlow : : Value > indexes ( valueFlowGetArrayIndexes ( tok - > next ( ) , false , var - > dimensions ( ) . size ( ) ) ) ;
if ( indexes . size ( ) ! = var - > dimensions ( ) . size ( ) )
continue ;
const MathLib : : bigint index = arrayInfo . totalIndex ( indexes ) ;
2015-11-09 10:30:39 +01:00
if ( index < ( isAddressOf ( tok ) ? elements + 1U : elements ) )
2015-11-08 12:39:08 +01:00
continue ;
2018-04-09 09:54:39 +02:00
std : : list < const Token * > callstack = { it - > tokvalue , tok } ;
2015-11-07 18:12:01 +01:00
2017-03-27 16:09:51 +02:00
std : : vector < MathLib : : bigint > indexes2 ( indexes . size ( ) ) ;
2015-11-08 12:39:08 +01:00
for ( unsigned int i = 0 ; i < indexes . size ( ) ; + + i )
2017-03-27 16:09:51 +02:00
indexes2 [ i ] = indexes [ i ] . intvalue ;
2015-11-07 18:12:01 +01:00
2015-11-08 12:39:08 +01:00
arrayIndexOutOfBoundsError ( callstack , arrayInfo , indexes2 ) ;
2015-11-07 18:12:01 +01:00
}
}
}
2011-12-01 04:17:09 +01:00
}
2011-06-24 14:02:41 +02:00
// check all known fixed size arrays first by just looking them up
2018-06-17 18:37:40 +02:00
for ( const Scope & scope : symbolDatabase - > scopeList ) {
2016-05-25 14:41:26 +02:00
std : : map < unsigned int , ArrayInfo > arrayInfos ;
2018-06-17 18:37:40 +02:00
for ( const Variable & var : scope . varlist ) {
if ( ! var . isArray ( ) | | var . dimension ( 0 ) < = 0 )
2017-07-30 14:53:58 +02:00
continue ;
2018-06-16 16:10:28 +02:00
mErrorLogger - > reportProgress ( mTokenizer - > list . getSourceFilePath ( ) ,
2017-07-30 14:53:58 +02:00
" Check (BufferOverrun::checkGlobalAndLocalVariable 1) " ,
2018-06-17 18:37:40 +02:00
var . nameToken ( ) - > progressValue ( ) ) ;
2016-05-25 14:41:26 +02:00
2018-06-16 16:10:28 +02:00
if ( mTokenizer - > isMaxTime ( ) )
2017-07-30 14:53:58 +02:00
return ;
2016-05-25 14:41:26 +02:00
2018-06-17 18:37:40 +02:00
const Token * tok = var . nameToken ( ) ;
2017-07-30 14:53:58 +02:00
do {
if ( tok - > str ( ) = = " { " ) {
if ( Token : : simpleMatch ( tok - > previous ( ) , " = { " ) )
tok = tok - > link ( ) ;
else
break ;
}
tok = tok - > next ( ) ;
} while ( tok & & tok - > str ( ) ! = " ; " ) ;
if ( ! tok )
break ;
2018-06-17 18:37:40 +02:00
arrayInfos [ var . declarationId ( ) ] = ArrayInfo ( & var , symbolDatabase , var . declarationId ( ) ) ;
2011-06-24 14:02:41 +02:00
}
2016-05-25 14:41:26 +02:00
if ( ! arrayInfos . empty ( ) )
2018-06-17 18:37:40 +02:00
checkScope ( scope . bodyStart ? scope . bodyStart : mTokenizer - > tokens ( ) , arrayInfos ) ;
2011-06-24 14:02:41 +02:00
}
2017-03-27 11:48:34 +02:00
const std : : vector < const std : : string * > v ;
2012-10-13 11:16:48 +02:00
// find all dynamically allocated arrays next
2018-06-17 18:37:40 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2011-11-26 21:02:04 +01:00
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2017-12-31 14:58:26 +01:00
if ( ! Token : : Match ( tok , " [*;{}] %var% = " ) )
2012-03-17 21:55:08 +01:00
continue ;
2011-01-06 13:02:21 +01:00
2012-03-17 21:55:08 +01:00
// size : Max array index
MathLib : : bigint size = 0 ;
2011-01-06 13:02:21 +01:00
2016-07-08 20:53:08 +02:00
// nextTok : used to skip to next statement.
const Token * nextTok = tok ;
2012-03-17 21:55:08 +01:00
2018-06-16 16:10:28 +02:00
mErrorLogger - > reportProgress ( mTokenizer - > list . getSourceFilePath ( ) ,
2016-02-11 16:10:52 +01:00
" Check (BufferOverrun::checkGlobalAndLocalVariable 2) " ,
2012-03-17 21:55:08 +01:00
tok - > progressValue ( ) ) ;
2018-06-16 16:10:28 +02:00
if ( mTokenizer - > isMaxTime ( ) )
2016-02-11 16:10:52 +01:00
return ;
2017-03-27 16:09:51 +02:00
// varid : The variable id for the array
const Variable * var = tok - > next ( ) - > variable ( ) ;
2018-08-30 10:01:19 +02:00
// FIXME: This is an ugly fix for a crash. The SymbolDatabase
// should create the variable.
if ( ! var )
continue ;
2017-03-27 16:09:51 +02:00
2018-06-16 16:10:28 +02:00
if ( mTokenizer - > isCPP ( ) & & Token : : Match ( tok , " [*;{}] %var% = new %type% [ " ) ) {
2017-03-27 16:09:51 +02:00
tok = tok - > tokAt ( 5 ) ;
if ( tok - > astOperand2 ( ) = = nullptr | | tok - > astOperand2 ( ) - > getMaxValue ( false ) = = nullptr )
2016-07-08 20:53:08 +02:00
continue ;
2017-03-27 16:09:51 +02:00
size = tok - > astOperand2 ( ) - > getMaxValue ( false ) - > intvalue ;
nextTok = tok - > link ( ) - > next ( ) ;
2014-02-01 22:38:29 +01:00
if ( size < 0 ) {
2017-03-27 16:09:51 +02:00
negativeMemoryAllocationSizeError ( tok ) ;
2014-02-01 22:38:29 +01:00
}
2018-06-16 16:10:28 +02:00
} else if ( mTokenizer - > isCPP ( ) & & Token : : Match ( tok , " [* ; { } ] % var % = new % type % ( | ; " )) {
2012-03-17 21:55:08 +01:00
size = 1 ;
2017-03-27 16:09:51 +02:00
tok = tok - > tokAt ( 5 ) ;
if ( tok - > str ( ) = = " ; " )
nextTok = tok - > next ( ) ;
2016-07-08 20:53:08 +02:00
else
2017-03-27 16:09:51 +02:00
nextTok = tok - > link ( ) - > next ( ) ;
2016-07-08 20:53:08 +02:00
} else if ( Token : : Match ( tok , " [*;{}] %var% = malloc|alloca ( " ) & & Token : : simpleMatch ( tok - > linkAt ( 4 ) , " ) ; " ) ) {
2017-03-27 16:09:51 +02:00
tok = tok - > tokAt ( 4 ) ;
if ( tok - > astOperand2 ( ) = = nullptr | | tok - > astOperand2 ( ) - > getMaxValue ( false ) = = nullptr )
2016-07-08 20:53:08 +02:00
continue ;
2017-03-27 16:09:51 +02:00
size = tok - > astOperand2 ( ) - > getMaxValue ( false ) - > intvalue ;
nextTok = tok - > link ( ) - > tokAt ( 2 ) ;
2012-03-17 21:55:08 +01:00
2014-02-01 22:38:29 +01:00
if ( size < 0 ) {
2017-03-27 16:09:51 +02:00
negativeMemoryAllocationSizeError ( tok ) ;
2014-02-01 22:38:29 +01:00
}
2018-08-31 18:25:08 +02:00
/** @todo false negatives: this may be too conservative */
2018-09-01 08:41:41 +02:00
if ( ! var - > isPointer ( ) | | var - > typeStartToken ( ) - > next ( ) ! = var - > typeEndToken ( ) )
2018-08-31 18:25:08 +02:00
continue ;
2013-02-06 06:39:58 +01:00
// malloc() gets count of bytes and not count of
// elements, so we should calculate count of elements
// manually
2016-07-08 20:53:08 +02:00
const unsigned int typeSize = sizeOfType ( var - > typeStartToken ( ) ) ;
if ( typeSize > 0 ) {
size / = static_cast < int > ( typeSize ) ;
2014-02-01 22:38:29 +01:00
}
if ( size < 0 ) {
2017-03-27 16:09:51 +02:00
negativeMemoryAllocationSizeError ( tok ) ;
2014-02-01 22:38:29 +01:00
}
2012-03-17 21:55:08 +01:00
} else {
continue ;
2009-11-15 13:38:57 +01:00
}
2009-01-31 20:29:27 +01:00
2017-08-09 20:00:26 +02:00
if ( var = = nullptr )
2012-03-17 21:55:08 +01:00
continue ;
2009-11-06 23:58:33 +01:00
2016-07-08 20:53:08 +02:00
const MathLib : : bigint totalSize = size * static_cast < int > ( sizeOfType ( var - > typeStartToken ( ) ) ) ;
2014-12-01 16:22:56 +01:00
if ( totalSize = = 0 )
2012-03-17 21:55:08 +01:00
continue ;
2009-01-31 20:29:27 +01:00
2018-04-04 21:51:31 +02:00
const ArrayInfo temp ( var - > declarationId ( ) , var - > name ( ) , totalSize / size , size ) ;
2016-07-08 20:53:08 +02:00
checkScope ( nextTok , v , temp ) ;
2012-03-17 21:55:08 +01:00
}
2009-01-31 20:29:27 +01:00
}
}
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
2014-09-30 14:54:59 +02:00
// Checking member variables of structs.
2009-01-31 20:29:27 +01:00
//---------------------------------------------------------------------------
2009-07-13 16:00:15 +02:00
void CheckBufferOverrun : : checkStructVariable ( )
2009-01-31 20:29:27 +01:00
{
2011-09-05 03:39:52 +02:00
// find every class and struct
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2012-10-13 11:16:48 +02:00
const std : : size_t classes = symbolDatabase - > classAndStructScopes . size ( ) ;
for ( std : : size_t i = 0 ; i < classes ; + + i ) {
const Scope * scope = symbolDatabase - > classAndStructScopes [ i ] ;
2011-09-05 03:39:52 +02:00
2018-04-05 08:17:56 +02:00
for ( std : : list < Variable > : : const_iterator var = scope - > varlist . begin ( ) ; var ! = scope - > varlist . end ( ) ; + + var ) {
2018-04-05 08:21:43 +02:00
if ( ! var - > isArray ( ) )
continue ;
// create ArrayInfo from the array variable
ArrayInfo arrayInfo ( & * var , symbolDatabase ) ;
// find every function
2018-06-17 18:37:40 +02:00
for ( const Scope * func_scope : symbolDatabase - > functionScopes ) {
2018-04-05 08:21:43 +02:00
// If struct is declared in a function then check
// if scope_func matches
if ( scope - > nestedIn - > type = = Scope : : eFunction & &
scope - > nestedIn ! = func_scope ) {
continue ;
}
2011-12-18 16:35:51 +01:00
2018-04-05 08:21:43 +02:00
// check for member variables
if ( func_scope - > functionOf = = scope ) {
// only check non-empty function
2018-04-27 22:36:30 +02:00
if ( func_scope - > bodyStart - > next ( ) ! = func_scope - > bodyEnd ) {
2018-04-05 08:21:43 +02:00
// start checking after the {
2018-04-27 22:36:30 +02:00
const Token * tok = func_scope - > bodyStart - > next ( ) ;
2018-04-05 08:21:43 +02:00
checkScope ( tok , arrayInfo ) ;
2011-09-05 03:39:52 +02:00
}
2018-04-05 08:21:43 +02:00
}
2010-11-06 09:10:10 +01:00
2018-04-05 08:21:43 +02:00
// skip inner scopes..
/** @todo false negatives: handle inner scopes someday */
if ( scope - > nestedIn - > isClassOrStruct ( ) )
continue ;
2011-09-09 13:16:39 +02:00
2018-04-09 09:54:39 +02:00
std : : vector < const std : : string * > varname = { nullptr , & arrayInfo . varname ( ) } ;
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
// search the function and it's parameters
2018-04-27 22:36:30 +02:00
for ( const Token * tok3 = func_scope - > classDef ; tok3 & & tok3 ! = func_scope - > bodyEnd ; tok3 = tok3 - > next ( ) ) {
2018-04-05 08:21:43 +02:00
// search for the class/struct name
if ( tok3 - > str ( ) ! = scope - > className )
continue ;
2013-03-14 18:25:28 +01:00
2018-04-05 08:21:43 +02:00
// find all array variables
int posOfSemicolon = - 1 ;
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
// Declare variable: Fred fred1;
if ( Token : : Match ( tok3 - > next ( ) , " %var% ; " ) )
varname [ 0 ] = & tok3 - > strAt ( 1 ) ;
2013-03-14 06:34:12 +01:00
2018-04-05 08:21:43 +02:00
else if ( isArrayOfStruct ( tok3 , posOfSemicolon ) )
varname [ 0 ] = & tok3 - > strAt ( 1 ) ;
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
// Declare pointer or reference: Fred *fred1
else if ( Token : : Match ( tok3 - > next ( ) , " *|& %var% [,) ; = ] " ))
varname [ 0 ] = & tok3 - > strAt ( 2 ) ;
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
else
continue ;
2011-09-12 03:51:05 +02:00
2018-04-05 08:21:43 +02:00
// check for variable sized structure
if ( scope - > type = = Scope : : eStruct & & var - > isPublic ( ) ) {
// last member of a struct with array size of 0 or 1 could be a variable sized structure
if ( var - > dimensions ( ) . size ( ) = = 1 & & var - > dimension ( 0 ) < 2 & &
var - > index ( ) = = ( scope - > varlist . size ( ) - 1 ) ) {
// dynamically allocated so could be variable sized structure
if ( tok3 - > next ( ) - > str ( ) = = " * " ) {
// check for allocation
if ( ( Token : : Match ( tok3 - > tokAt ( 3 ) , " ; %name% = malloc ( %num% ) ; " ) | |
( Token : : Match ( tok3 - > tokAt ( 3 ) , " ; %name% = ( " ) & &
Token : : Match ( tok3 - > linkAt ( 6 ) , " ) malloc ( %num% ) ; " ) ) ) & &
( tok3 - > strAt ( 4 ) = = tok3 - > strAt ( 2 ) ) ) {
MathLib : : bigint size ;
// find size of allocation
if ( tok3 - > strAt ( 3 ) = = " ( " ) // has cast
size = MathLib : : toLongNumber ( tok3 - > linkAt ( 6 ) - > strAt ( 3 ) ) ;
2011-09-12 03:51:05 +02:00
else
2018-04-05 08:21:43 +02:00
size = MathLib : : toLongNumber ( tok3 - > strAt ( 8 ) ) ;
// We don't calculate the size of a structure even when we know
// the size of the members. We just assign a length of 100 for
// any struct. If the size is less than 100, we assume the
// programmer knew the size and specified it rather than using
// sizeof(struct). If the size is greater than 100, we assume
// the programmer specified the size as sizeof(struct) + number.
// Either way, this is just a guess and could be wrong. The
// information to make the right decision has been simplified
// away by the time we get here.
if ( size ! = 100 ) { // magic number for size of struct
// check if a real size was specified and give up
// malloc(10) rather than malloc(sizeof(struct))
if ( size < 100 | | arrayInfo . element_size ( ) = = 0 )
continue ;
// calculate real array size based on allocated size
const MathLib : : bigint elements = ( size - 100 ) / arrayInfo . element_size ( ) ;
arrayInfo . num ( 0 , arrayInfo . num ( 0 ) + elements ) ;
}
2011-09-09 13:46:06 +02:00
}
2018-04-05 08:21:43 +02:00
// size unknown so assume it is a variable sized structure
else
continue ;
2011-09-09 13:16:39 +02:00
}
2018-04-05 08:21:43 +02:00
}
}
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
// Goto end of statement.
const Token * checkTok = nullptr ;
2018-04-27 22:36:30 +02:00
while ( tok3 & & tok3 ! = func_scope - > bodyEnd ) {
2018-04-05 08:21:43 +02:00
// End of statement.
if ( tok3 - > str ( ) = = " ; " ) {
checkTok = tok3 ;
break ;
}
2011-09-12 03:51:05 +02:00
2018-04-05 08:21:43 +02:00
// End of function declaration..
if ( Token : : simpleMatch ( tok3 , " ) ; " ) )
break ;
2009-01-31 20:29:27 +01:00
2018-04-05 08:21:43 +02:00
// Function implementation..
if ( Token : : simpleMatch ( tok3 , " ) { " ) ) {
checkTok = tok3 - > tokAt ( 2 ) ;
break ;
2011-09-09 13:16:39 +02:00
}
2011-09-12 03:51:05 +02:00
2018-04-05 08:21:43 +02:00
tok3 = tok3 - > next ( ) ;
}
2011-09-12 03:51:05 +02:00
2018-04-05 08:21:43 +02:00
if ( ! tok3 )
break ;
if ( ! checkTok )
continue ;
2011-09-12 03:51:05 +02:00
2018-04-05 08:21:43 +02:00
// Check variable usage..
ArrayInfo temp = arrayInfo ;
temp . declarationId ( 0 ) ; // do variable lookup by variable and member names rather than varid
std : : string varnames ; // use class and member name for messages
for ( std : : size_t k = 0 ; k < varname . size ( ) ; + + k )
varnames + = ( k = = 0 ? " " : " . " ) + * varname [ k ] ;
2013-03-14 06:34:12 +01:00
2018-04-05 08:21:43 +02:00
temp . varname ( varnames ) ;
checkScope ( checkTok , varname , temp ) ;
2009-01-31 20:29:27 +01:00
}
}
}
}
}
//---------------------------------------------------------------------------
2016-07-07 19:38:15 +02:00
void CheckBufferOverrun : : bufferOverrun ( )
2014-06-26 17:36:20 +02:00
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2014-06-26 17:36:20 +02:00
// singlepass checking using ast, symboldatabase and valueflow
2018-06-16 16:10:28 +02:00
for ( const Token * tok = mTokenizer - > tokens ( ) ; tok ; tok = tok - > next ( ) ) {
if ( mSettings - > isEnabled ( Settings : : PORTABILITY ) & & tok - > str ( ) = = " + " & & tok - > valueType ( ) & & tok - > valueType ( ) - > pointer > 0 ) {
2018-01-27 15:39:27 +01:00
if ( ! tok - > astOperand1 ( ) | | ! tok - > astOperand1 ( ) - > valueType ( ) )
continue ;
if ( ! tok - > astOperand2 ( ) | | ! tok - > astOperand2 ( ) - > valueType ( ) )
continue ;
// pointer arithmetic..
const Token * pointerToken , * indexToken ;
if ( tok - > astOperand1 ( ) - > valueType ( ) - > pointer = = 0 ) {
indexToken = tok - > astOperand1 ( ) ;
pointerToken = tok - > astOperand2 ( ) ;
} else if ( tok - > astOperand2 ( ) - > valueType ( ) - > pointer = = 0 ) {
indexToken = tok - > astOperand2 ( ) ;
pointerToken = tok - > astOperand1 ( ) ;
2018-01-27 22:05:29 +01:00
} else {
continue ;
2018-01-27 15:39:27 +01:00
}
while ( pointerToken & & pointerToken - > str ( ) = = " . " )
pointerToken = pointerToken - > astOperand2 ( ) ;
if ( ! pointerToken | | ! pointerToken - > isName ( ) )
continue ;
const Variable * var = pointerToken - > variable ( ) ;
2018-01-27 22:09:43 +01:00
if ( ! var | | ! var - > isArray ( ) | | var - > dimension ( 0 ) < = 0 )
2018-01-27 15:39:27 +01:00
continue ;
2018-06-16 16:10:28 +02:00
const ValueFlow : : Value * value = indexToken - > getValueGE ( var - > dimension ( 0 ) + 1 , mSettings ) ;
2018-01-27 15:39:27 +01:00
if ( value ) {
pointerOutOfBoundsError ( tok , indexToken , value - > intvalue ) ;
}
}
2014-08-04 08:25:10 +02:00
// Array index
2015-01-31 10:50:39 +01:00
if ( ! Token : : Match ( tok , " %name% [ " ) )
2014-08-04 08:25:10 +02:00
continue ;
// TODO: what to do about negative index..
const Token * index = tok - > next ( ) - > astOperand2 ( ) ;
2018-06-16 16:10:28 +02:00
if ( index & & index - > getValueLE ( - 1LL , mSettings ) )
2014-08-04 08:25:10 +02:00
continue ;
// Set full varname..
2015-12-23 08:32:59 +01:00
std : : string varname ;
2014-08-04 08:25:10 +02:00
if ( tok - > astParent ( ) & & tok - > astParent ( ) - > str ( ) = = " . " ) {
const Token * parent = tok - > astParent ( ) ;
while ( parent - > astParent ( ) & & parent - > astParent ( ) - > str ( ) = = " . " )
parent = parent - > astParent ( ) ;
varname = parent - > expressionString ( ) ;
2015-12-23 08:32:59 +01:00
} else
varname = tok - > str ( ) ;
2014-08-04 08:25:10 +02:00
2016-06-21 22:42:46 +02:00
const Variable * const var = tok - > variable ( ) ;
if ( ! var )
continue ;
2014-08-04 08:25:10 +02:00
const Token * const strtoken = tok - > getValueTokenMinStrSize ( ) ;
2016-06-21 22:42:46 +02:00
if ( strtoken & & ! var - > isArray ( ) ) {
// TODO: check for access to symbol inside the array bounds, but outside the stored string:
// char arr[10] = "123";
// arr[7] = 'x'; // warning: arr[7] is inside the array bounds, but past the string's end
2018-10-09 06:53:26 +02:00
if ( tok - > valueType ( ) & & tok - > valueType ( ) - > type = = ValueType : : Type : : CONTAINER )
continue ;
2018-04-04 21:51:31 +02:00
const ArrayInfo arrayInfo ( tok - > varId ( ) , varname , 1U , Token : : getStrSize ( strtoken ) ) ;
2014-08-04 08:25:10 +02:00
valueFlowCheckArrayIndex ( tok - > next ( ) , arrayInfo ) ;
2016-06-21 22:42:46 +02:00
} else {
if ( var - > nameToken ( ) = = tok | | ! var - > isArray ( ) )
2014-06-26 17:36:20 +02:00
continue ;
2016-12-20 22:01:19 +01:00
// unknown array dimensions
bool known = true ;
for ( unsigned int i = 0 ; i < var - > dimensions ( ) . size ( ) ; + + i ) {
known & = ( var - > dimension ( i ) > = 1 ) ;
known & = var - > dimensionKnown ( i ) ;
}
if ( ! known )
continue ;
2014-06-26 17:36:20 +02:00
// TODO: last array in struct..
if ( var - > dimension ( 0 ) < = 1 & & Token : : simpleMatch ( var - > nameToken ( ) - > linkAt ( 1 ) , " ] ; } " ) )
continue ;
2016-12-18 22:10:30 +01:00
if ( var - > scope ( ) & & var - > scope ( ) - > type = = Scope : : eUnion )
continue ;
2016-07-08 20:53:08 +02:00
ArrayInfo arrayInfo ( var , symbolDatabase ) ;
2014-08-04 08:25:10 +02:00
arrayInfo . varname ( varname ) ;
2014-06-26 17:36:20 +02:00
valueFlowCheckArrayIndex ( tok - > next ( ) , arrayInfo ) ;
}
}
}
//---------------------------------------------------------------------------
2009-01-31 20:29:27 +01:00
2015-02-18 20:56:44 +01:00
MathLib : : biguint CheckBufferOverrun : : countSprintfLength ( const std : : string & input_string , const std : : list < const Token * > & parameters )
2009-09-25 18:23:44 +02:00
{
2009-10-18 12:58:48 +02:00
bool percentCharFound = false ;
2010-12-31 09:30:56 +01:00
std : : size_t input_string_size = 1 ;
2009-10-18 12:58:48 +02:00
bool handleNextParameter = false ;
2015-02-18 20:56:44 +01:00
std : : string digits_string ;
2009-10-18 12:58:48 +02:00
bool i_d_x_f_found = false ;
2009-10-08 15:27:46 +02:00
std : : list < const Token * > : : const_iterator paramIter = parameters . begin ( ) ;
2010-12-31 09:30:56 +01:00
std : : size_t parameterLength = 0 ;
2011-10-13 20:53:06 +02:00
for ( std : : string : : size_type i = 0 ; i < input_string . length ( ) ; + + i ) {
if ( input_string [ i ] = = ' \\ ' ) {
2014-08-12 15:44:20 +02:00
if ( i < input_string . length ( ) - 1 & & input_string [ i + 1 ] = = ' 0 ' )
2009-10-18 12:58:48 +02:00
break ;
+ + input_string_size ;
+ + i ;
continue ;
2009-09-25 18:23:44 +02:00
}
2009-10-18 12:58:48 +02:00
2011-10-13 20:53:06 +02:00
if ( percentCharFound ) {
switch ( input_string [ i ] ) {
2009-10-18 12:58:48 +02:00
case ' f ' :
case ' x ' :
case ' X ' :
case ' i ' :
i_d_x_f_found = true ;
2015-06-28 18:07:31 +02:00
handleNextParameter = true ;
break ;
2009-10-18 12:58:48 +02:00
case ' c ' :
case ' e ' :
case ' E ' :
case ' g ' :
case ' o ' :
case ' u ' :
case ' p ' :
case ' n ' :
2009-10-19 23:48:29 +02:00
handleNextParameter = true ;
break ;
case ' d ' :
i_d_x_f_found = true ;
2015-08-14 20:46:13 +02:00
if ( paramIter ! = parameters . end ( ) & & * paramIter & & ( * paramIter ) - > tokType ( ) ! = Token : : eString )
2010-03-09 11:03:45 +01:00
parameterLength = ( * paramIter ) - > str ( ) . length ( ) ;
2009-10-19 23:48:29 +02:00
2009-10-18 12:58:48 +02:00
handleNextParameter = true ;
break ;
case ' s ' :
2015-08-14 20:46:13 +02:00
if ( paramIter ! = parameters . end ( ) & & * paramIter & & ( * paramIter ) - > tokType ( ) = = Token : : eString )
2010-03-09 11:03:45 +01:00
parameterLength = Token : : getStrLength ( * paramIter ) ;
2009-10-08 15:27:46 +02:00
2009-10-18 12:58:48 +02:00
handleNextParameter = true ;
break ;
2009-10-08 15:27:46 +02:00
}
2009-10-18 12:58:48 +02:00
}
2009-10-08 15:27:46 +02:00
2010-04-02 07:30:58 +02:00
if ( input_string [ i ] = = ' % ' )
2009-10-18 12:58:48 +02:00
percentCharFound = ! percentCharFound ;
2011-10-13 20:53:06 +02:00
else if ( percentCharFound ) {
2009-10-18 12:58:48 +02:00
digits_string . append ( 1 , input_string [ i ] ) ;
2009-09-25 18:23:44 +02:00
}
2010-04-02 07:30:58 +02:00
if ( ! percentCharFound )
2009-10-18 12:58:48 +02:00
input_string_size + + ;
2009-09-25 18:23:44 +02:00
2011-10-13 20:53:06 +02:00
if ( handleNextParameter ) {
2010-08-06 21:02:43 +02:00
unsigned int tempDigits = static_cast < unsigned int > ( std : : abs ( std : : atoi ( digits_string . c_str ( ) ) ) ) ;
2010-04-02 07:30:58 +02:00
if ( i_d_x_f_found )
2010-08-06 21:02:43 +02:00
tempDigits = std : : max ( static_cast < unsigned int > ( tempDigits ) , 1U ) ;
2009-10-08 15:27:46 +02:00
2011-10-13 20:53:06 +02:00
if ( digits_string . find ( ' . ' ) ! = std : : string : : npos ) {
2009-10-11 21:07:18 +02:00
const std : : string endStr = digits_string . substr ( digits_string . find ( ' . ' ) + 1 ) ;
2014-07-07 21:25:30 +02:00
const unsigned int maxLen = std : : max ( static_cast < unsigned int > ( std : : abs ( std : : atoi ( endStr . c_str ( ) ) ) ) , 1U ) ;
2009-10-11 21:07:18 +02:00
2011-10-13 20:53:06 +02:00
if ( input_string [ i ] = = ' s ' ) {
2009-10-19 23:48:29 +02:00
// For strings, the length after the dot "%.2s" will limit
// the length of the string.
2010-04-02 07:30:58 +02:00
if ( parameterLength > maxLen )
2009-10-19 23:48:29 +02:00
parameterLength = maxLen ;
2011-10-13 20:53:06 +02:00
} else {
2009-10-19 23:48:29 +02:00
// For integers, the length after the dot "%.2d" can
// increase required length
2010-04-02 07:30:58 +02:00
if ( tempDigits < maxLen )
2009-10-19 23:48:29 +02:00
tempDigits = maxLen ;
}
2009-10-11 21:07:18 +02:00
}
2010-04-02 07:30:58 +02:00
if ( tempDigits < parameterLength )
2009-10-18 12:58:48 +02:00
input_string_size + = parameterLength ;
2009-10-08 15:27:46 +02:00
else
2009-10-19 23:48:29 +02:00
input_string_size + = tempDigits ;
2009-10-08 15:27:46 +02:00
parameterLength = 0 ;
2017-06-02 20:38:00 +02:00
digits_string . clear ( ) ;
2009-10-18 12:58:48 +02:00
i_d_x_f_found = false ;
percentCharFound = false ;
handleNextParameter = false ;
2010-04-02 07:30:58 +02:00
if ( paramIter ! = parameters . end ( ) )
2009-10-19 23:55:20 +02:00
+ + paramIter ;
2009-09-25 18:23:44 +02:00
}
}
2015-11-28 10:11:07 +01:00
return input_string_size ;
2009-09-25 18:23:44 +02:00
}
2010-04-10 21:12:00 +02:00
2010-05-26 10:56:34 +02:00
//---------------------------------------------------------------------------
// Checking for allocating insufficient memory for copying a string by
// allocating only strlen(src) bytes instead of strlen(src) + 1 bytes (one
// extra for the terminating null character).
// Example:
// char *b = malloc(strlen(a)); // Should be malloc(strlen(a) + 1);
// strcpy(b, a); // <== Buffer overrun
//---------------------------------------------------------------------------
void CheckBufferOverrun : : checkBufferAllocatedWithStrlen ( )
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-06-17 18:37:40 +02:00
for ( const Scope * scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart - > next ( ) ; tok & & tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2018-04-04 21:51:31 +02:00
const unsigned int dstVarId = tok - > varId ( ) ;
2017-03-27 11:48:34 +02:00
if ( ! dstVarId | | tok - > strAt ( 1 ) ! = " = " )
continue ;
tok = tok - > tokAt ( 2 ) ;
2017-09-05 16:50:36 +02:00
unsigned int srcVarId ;
2012-10-13 11:16:48 +02:00
// Look for allocation of a buffer based on the size of a string
2017-03-27 11:48:34 +02:00
if ( Token : : Match ( tok , " malloc|g_malloc|g_try_malloc|alloca ( strlen ( %var% ) ) " ) ) {
2017-09-05 16:50:36 +02:00
const Token * varTok = tok - > tokAt ( 4 ) ;
srcVarId = varTok - > varId ( ) ;
tok = varTok - > tokAt ( 2 ) ;
2018-06-16 16:10:28 +02:00
} else if ( mTokenizer - > isCPP ( ) & & Token : : Match ( tok , " new char [ strlen ( %var% ) ] " ) ) {
2017-09-05 16:50:36 +02:00
const Token * varTok = tok - > tokAt ( 5 ) ;
srcVarId = varTok - > varId ( ) ;
tok = varTok - > tokAt ( 2 ) ;
2017-03-27 11:48:34 +02:00
} else if ( Token : : Match ( tok , " realloc|g_realloc|g_try_realloc ( %name% , strlen ( %var% ) ) " )) {
2017-09-05 16:50:36 +02:00
const Token * varTok = tok - > tokAt ( 6 ) ;
srcVarId = varTok - > varId ( ) ;
tok = varTok - > tokAt ( 2 ) ;
2012-10-13 11:16:48 +02:00
} else
continue ;
2010-05-26 19:21:34 +02:00
2012-10-13 11:16:48 +02:00
// To avoid false positives and added complexity, we will only look for
// improper usage of the buffer within the block that it was allocated
2018-04-27 22:36:30 +02:00
for ( const Token * const end = tok - > scope ( ) - > bodyEnd ; tok & & tok - > next ( ) & & tok ! = end ; tok = tok - > next ( ) ) {
2012-10-13 11:16:48 +02:00
// If the buffers are modified, we can't be sure of their sizes
if ( tok - > varId ( ) = = srcVarId | | tok - > varId ( ) = = dstVarId )
break ;
if ( Token : : Match ( tok , " strcpy ( %varid% , %var% ) " , dstVarId ) & &
tok - > tokAt ( 4 ) - > varId ( ) = = srcVarId ) {
bufferOverrunError ( tok ) ;
}
2010-05-26 10:56:34 +02:00
}
2012-10-13 11:16:48 +02:00
if ( ! tok )
return ;
2010-05-26 10:56:34 +02:00
}
}
}
2010-06-02 07:41:07 +02:00
2014-07-06 08:41:39 +02:00
//---------------------------------------------------------------------------
// memcpy(temp, "hello world", 50);
//---------------------------------------------------------------------------
void CheckBufferOverrun : : checkStringArgument ( )
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-06-17 18:37:40 +02:00
for ( const Scope * const scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart ; tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2018-06-16 16:10:28 +02:00
if ( ! Token : : Match ( tok , " %name% ( " ) | | ! mSettings - > library . hasminsize ( tok - > str ( ) ) )
2014-07-06 08:41:39 +02:00
continue ;
unsigned int argnr = 1 ;
for ( const Token * argtok = tok - > tokAt ( 2 ) ; argtok ; argtok = argtok - > nextArgument ( ) , argnr + + ) {
2016-07-27 17:28:43 +02:00
if ( ! Token : : Match ( argtok , " %str% ,|) " ) )
2015-07-27 16:39:41 +02:00
continue ;
2014-08-04 08:25:10 +02:00
const Token * strtoken = argtok - > getValueTokenMinStrSize ( ) ;
if ( ! strtoken )
2014-07-06 08:41:39 +02:00
continue ;
2018-06-16 16:10:28 +02:00
const std : : vector < Library : : ArgumentChecks : : MinSize > * minsizes = mSettings - > library . argminsizes ( tok , argnr ) ;
2014-07-06 08:41:39 +02:00
if ( ! minsizes )
continue ;
2018-06-16 16:10:28 +02:00
if ( checkMinSizes ( * minsizes , tok , Token : : getStrSize ( strtoken ) , nullptr , mSettings ) )
2014-07-08 07:08:51 +02:00
bufferOverrunError ( argtok ) ;
2014-07-06 08:41:39 +02:00
}
}
}
}
2010-06-02 07:41:07 +02:00
//---------------------------------------------------------------------------
// Checking for buffer overflow caused by copying command line arguments
// into fixed-sized buffers without checking to make sure that the command
// line arguments will not overflow the buffer.
//
// int main(int argc, char* argv[])
// {
// char prog[10];
// strcpy(prog, argv[0]); <-- Possible buffer overrun
// }
//---------------------------------------------------------------------------
void CheckBufferOverrun : : checkInsecureCmdLineArgs ( )
{
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2015-02-18 20:56:44 +01:00
const std : : size_t functions = symbolDatabase - > functionScopes . size ( ) ;
2012-10-13 11:16:48 +02:00
for ( std : : size_t i = 0 ; i < functions ; + + i ) {
2014-09-02 16:10:51 +02:00
const Function * function = symbolDatabase - > functionScopes [ i ] - > function ;
if ( function ) {
const Token * tok = function - > token ;
2010-06-02 18:09:25 +02:00
2011-12-09 22:28:10 +01:00
// Get the name of the argv variable
2018-10-15 10:05:43 +02:00
unsigned int argvVarid = 0 ;
if ( Token : : simpleMatch ( tok , " main ( " ) )
tok = tok - > tokAt ( 2 ) ;
else
continue ;
if ( Token : : Match ( tok , " const| int %var% , " ) )
tok = tok - > nextArgument ( ) ;
else
continue ;
2010-06-02 07:41:07 +02:00
2018-10-15 10:05:43 +02:00
if ( Token : : Match ( tok , " char * %var% [ ] ,|) " ) ) {
argvVarid = tok - > tokAt ( 2 ) - > varId ( ) ;
} else if ( Token : : Match ( tok , " char * * %var% ,|) " ) | |
Token : : Match ( tok , " const char * %var% [ ] ,|) " ) ) {
argvVarid = tok - > tokAt ( 3 ) - > varId ( ) ;
} else if ( Token : : Match ( tok , " const char * * %var% ,|) " )) {
argvVarid = tok - > tokAt ( 4 ) - > varId ( ) ;
2015-01-31 10:50:39 +01:00
} else
2011-12-09 22:28:10 +01:00
continue ;
2010-06-02 07:41:07 +02:00
2011-12-09 22:28:10 +01:00
// Jump to the opening curly brace
2018-04-27 22:36:30 +02:00
tok = symbolDatabase - > functionScopes [ i ] - > bodyStart ;
2010-06-02 07:41:07 +02:00
2011-12-09 22:28:10 +01:00
// Search within main() for possible buffer overruns involving argv
2012-03-17 21:55:08 +01:00
for ( const Token * end = tok - > link ( ) ; tok ! = end ; tok = tok - > next ( ) ) {
2011-12-09 22:28:10 +01:00
// If argv is modified or tested, its size may be being limited properly
2018-10-15 10:05:43 +02:00
if ( tok - > varId ( ) = = argvVarid )
2011-12-09 22:28:10 +01:00
break ;
2010-06-02 07:41:07 +02:00
2011-12-09 22:28:10 +01:00
// Match common patterns that can result in a buffer overrun
// e.g. strcpy(buffer, argv[0])
2017-03-27 11:30:07 +02:00
if ( Token : : Match ( tok , " strcpy|strcat ( " ) ) {
2017-04-21 23:36:10 +02:00
const Token * nextArgument = tok - > tokAt ( 2 ) - > nextArgument ( ) ;
if ( nextArgument )
tok = nextArgument ;
else
continue ; // Ticket #7964
2018-10-15 10:05:43 +02:00
if ( Token : : Match ( tok , " * %varid% " , argvVarid ) | | Token : : Match ( tok , " %varid% [ " , argvVarid ) )
2017-03-27 11:30:07 +02:00
cmdLineArgsError ( tok ) ;
2011-12-09 22:28:10 +01:00
}
}
}
2010-06-02 07:41:07 +02:00
}
}
2010-05-26 10:56:34 +02:00
//---------------------------------------------------------------------------
2010-11-21 11:48:27 +01:00
void CheckBufferOverrun : : negativeIndexError ( const Token * tok , MathLib : : bigint index )
2010-04-18 20:51:39 +02:00
{
2010-04-18 21:03:03 +02:00
std : : ostringstream ostr ;
2012-07-08 15:51:24 +02:00
ostr < < " Array index " < < index < < " is out of bounds. " ;
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 : : error , " negativeIndex " , ostr . str ( ) , CWE786 , false ) ;
2010-04-18 20:51:39 +02:00
}
2014-04-02 06:49:28 +02:00
void CheckBufferOverrun : : negativeIndexError ( const Token * tok , const ValueFlow : : Value & index )
{
2017-05-19 17:29:16 +02:00
const ErrorPath errorPath = getErrorPath ( tok , & index , " Negative array index " ) ;
2017-05-16 19:08:47 +02:00
std : : ostringstream errmsg ;
2014-04-02 06:49:28 +02:00
if ( index . condition )
2017-05-16 19:08:47 +02:00
errmsg < < ValueFlow : : eitherTheConditionIsRedundant ( index . condition )
< < " , otherwise there is negative array index " < < index . intvalue < < " . " ;
else
errmsg < < " Array index " < < index . intvalue < < " is out of bounds. " ;
2017-09-20 22:41:36 +02:00
reportError ( errorPath , index . errorSeverity ( ) ? Severity : : error : Severity : : warning , " negativeIndex " , errmsg . str ( ) , CWE786 , index . isInconclusive ( ) ) ;
2014-04-02 06:49:28 +02:00
}
2010-04-18 11:08:29 +02:00
CheckBufferOverrun : : ArrayInfo : : ArrayInfo ( )
2018-06-17 17:20:16 +02:00
: mElementSize ( 0 ) , mDeclarationId ( 0 )
2010-04-10 21:12:00 +02:00
{
2010-04-18 11:08:29 +02:00
}
2017-04-01 09:31:27 +02:00
CheckBufferOverrun : : ArrayInfo : : ArrayInfo ( const Variable * var , const SymbolDatabase * symbolDatabase , const unsigned int forcedeclid )
2018-06-17 17:20:16 +02:00
: mVarName ( var - > name ( ) ) , mDeclarationId ( ( forcedeclid = = 0U ) ? var - > declarationId ( ) : forcedeclid )
2011-06-23 04:44:11 +02:00
{
2012-07-08 23:39:46 +02:00
for ( std : : size_t i = 0 ; i < var - > dimensions ( ) . size ( ) ; i + + )
2018-06-17 17:20:16 +02:00
mNum . push_back ( var - > dimension ( i ) ) ;
2011-06-23 04:44:11 +02:00
if ( var - > typeEndToken ( ) - > str ( ) = = " * " )
2018-06-17 17:20:16 +02:00
mElementSize = symbolDatabase - > sizeOfType ( var - > typeEndToken ( ) ) ;
2016-08-04 09:06:32 +02:00
else if ( var - > typeStartToken ( ) - > strAt ( - 1 ) = = " struct " )
2018-06-17 17:20:16 +02:00
mElementSize = 100 ;
2015-01-30 20:27:48 +01:00
else {
2018-06-17 17:20:16 +02:00
mElementSize = symbolDatabase - > sizeOfType ( var - > typeEndToken ( ) ) ;
2015-01-30 20:27:48 +01:00
}
2011-06-23 04:44:11 +02:00
}
2010-04-21 18:33:21 +02:00
/**
* Create array info with specified data
* The intention is that this is only a temporary solution . . all
* checking should be based on ArrayInfo from the start and then
* this will not be needed as the declare can be used instead .
*/
2010-12-31 09:30:56 +01:00
CheckBufferOverrun : : ArrayInfo : : ArrayInfo ( unsigned int id , const std : : string & name , MathLib : : bigint size1 , MathLib : : bigint n )
2018-06-17 17:20:16 +02:00
: mVarName ( name ) , mElementSize ( size1 ) , mDeclarationId ( id )
2010-04-21 18:33:21 +02:00
{
2018-06-17 17:20:16 +02:00
mNum . push_back ( n ) ;
2010-04-24 21:48:58 +02:00
}
2010-11-21 11:48:27 +01:00
CheckBufferOverrun : : ArrayInfo CheckBufferOverrun : : ArrayInfo : : limit ( MathLib : : bigint value ) const
2010-04-24 21:48:58 +02:00
{
2015-02-18 20:56:44 +01:00
const MathLib : : bigint uvalue = std : : max ( MathLib : : bigint ( 0 ) , value ) ;
2010-12-31 09:30:56 +01:00
MathLib : : bigint n = 1 ;
2018-06-17 17:20:16 +02:00
for ( std : : size_t i = 0 ; i < mNum . size ( ) ; + + i )
n * = mNum [ i ] ;
2010-08-06 22:37:48 +02:00
if ( uvalue > n )
n = uvalue ;
2018-06-17 17:20:16 +02:00
return ArrayInfo ( mDeclarationId , mVarName , mElementSize , n - uvalue ) ;
2010-04-21 18:33:21 +02:00
}
2015-11-08 12:39:08 +01:00
MathLib : : bigint CheckBufferOverrun : : ArrayInfo : : numberOfElements ( ) const
{
2018-06-17 17:20:16 +02:00
if ( mNum . empty ( ) )
2015-11-08 12:39:08 +01:00
return 0 ;
// total number of elements of array..
MathLib : : bigint ret = 1 ;
2018-06-17 17:20:16 +02:00
for ( std : : size_t i = 0 ; i < mNum . size ( ) ; + + i ) {
ret * = mNum [ i ] ;
2015-11-08 12:39:08 +01:00
}
return ret ;
}
MathLib : : bigint CheckBufferOverrun : : ArrayInfo : : totalIndex ( const std : : vector < ValueFlow : : Value > & indexes ) const
{
MathLib : : bigint index = 0 ;
MathLib : : bigint elements = 1 ;
2018-06-17 17:20:16 +02:00
for ( std : : size_t i = 0 ; i < mNum . size ( ) ; + + i ) {
const std : : size_t ri = mNum . size ( ) - 1U - i ;
2015-11-08 12:39:08 +01:00
index + = indexes [ ri ] . intvalue * elements ;
2018-06-17 17:20:16 +02:00
elements * = mNum [ ri ] ;
2015-11-08 12:39:08 +01:00
}
return index ;
}
2010-04-10 21:12:00 +02:00
2011-08-04 11:15:14 +02:00
void CheckBufferOverrun : : arrayIndexThenCheck ( )
{
2018-06-16 16:10:28 +02:00
if ( ! mSettings - > isEnabled ( Settings : : PORTABILITY ) )
2011-08-04 11:15:14 +02:00
return ;
2018-06-17 17:20:16 +02:00
const SymbolDatabase * symbolDatabase = mTokenizer - > getSymbolDatabase ( ) ;
2018-06-30 15:34:48 +02:00
for ( const Scope * const scope : symbolDatabase - > functionScopes ) {
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart ; tok & & tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2016-01-24 14:06:02 +01:00
if ( Token : : simpleMatch ( tok , " sizeof ( " ) ) {
tok = tok - > linkAt ( 1 ) ;
continue ;
}
2015-01-31 10:50:39 +01:00
if ( Token : : Match ( tok , " %name% [ %var% ] " ) ) {
2017-03-27 11:07:34 +02:00
tok = tok - > next ( ) ;
2014-05-03 09:30:30 +02:00
2017-03-27 11:07:34 +02:00
const unsigned int indexID = tok - > next ( ) - > varId ( ) ;
const std : : string & indexName ( tok - > strAt ( 1 ) ) ;
2012-10-13 11:16:48 +02:00
2017-03-27 11:07:34 +02:00
// Iterate AST upwards
const Token * tok2 = tok ;
const Token * tok3 = tok2 ;
while ( tok2 - > astParent ( ) & & tok2 - > tokType ( ) ! = Token : : eLogicalOp ) {
tok3 = tok2 ;
tok2 = tok2 - > astParent ( ) ;
}
2012-10-13 11:16:48 +02:00
2017-03-27 11:07:34 +02:00
// 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 ;
2013-08-23 17:04:01 +02:00
2012-10-13 11:16:48 +02:00
// check if array index is ok
2013-08-23 17:04:01 +02:00
// statement can be closed in parentheses, so "(| " is using
2017-03-27 11:07:34 +02:00
if ( Token : : Match ( tok2 , " && (| %varid% <|<= " , indexID ) )
2014-05-03 09:30:30 +02:00
arrayIndexThenCheckError ( tok , indexName ) ;
2017-03-27 11:07:34 +02:00
else if ( Token : : Match ( tok2 , " && (| %any% >|>= %varid% !!+ " , indexID ) )
2012-10-13 11:16:48 +02:00
arrayIndexThenCheckError ( tok , indexName ) ;
}
2011-08-04 11:15:14 +02:00
}
}
}
void CheckBufferOverrun : : arrayIndexThenCheckError ( const Token * tok , const std : : string & indexName )
{
2011-08-05 09:10:07 +02:00
reportError ( tok , Severity : : style , " arrayIndexThenCheck " ,
2018-04-09 06:43:48 +02:00
" $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 "
2013-10-23 08:03:37 +02:00
" is checked that is within limits. This can mean that the array might be accessed out of bounds. "
2012-07-09 11:11:05 +02:00
" Reorder conditions such as '(a[i] && i < 10)' to '(i < 10 && a[i])'. That way the array will "
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
" not be accessed if the index is out of limits. " , CWE398 , false ) ;
2011-08-04 11:15:14 +02:00
}
2013-03-19 08:22:48 +01:00
2016-10-29 12:18:11 +02:00
std : : string CheckBufferOverrun : : MyFileInfo : : toString ( ) const
{
std : : ostringstream ret ;
for ( std : : map < std : : string , struct CheckBufferOverrun : : MyFileInfo : : ArrayUsage > : : const_iterator it = arrayUsage . begin ( ) ; it ! = arrayUsage . end ( ) ; + + it ) {
ret < < " <ArrayUsage "
< < " array= \" " < < ErrorLogger : : toxml ( it - > first ) < < ' \" '
< < " index= \" " < < it - > second . index < < ' \" '
< < " fileName= \" " < < ErrorLogger : : toxml ( it - > second . fileName ) < < ' \" '
< < " linenr= \" " < < it - > second . linenr < < " \" /> \n " ;
}
for ( std : : map < std : : string , MathLib : : bigint > : : const_iterator it = arraySize . begin ( ) ; it ! = arraySize . end ( ) ; + + it ) {
ret < < " <ArraySize "
< < " array= \" " < < ErrorLogger : : toxml ( it - > first ) < < ' \" '
< < " size= \" " < < it - > second < < " \" /> \n " ;
}
return ret . str ( ) ;
}
2014-12-02 06:41:18 +01:00
Check : : FileInfo * CheckBufferOverrun : : getFileInfo ( const Tokenizer * tokenizer , const Settings * settings ) const
2014-11-15 10:43:49 +01:00
{
2014-12-02 06:41:18 +01:00
( void ) settings ;
2014-11-15 10:43:49 +01:00
MyFileInfo * fileInfo = new MyFileInfo ;
// Array usage..
2016-07-08 20:53:08 +02:00
const SymbolDatabase * const symbolDB = tokenizer - > getSymbolDatabase ( ) ;
const std : : size_t functions = symbolDB - > functionScopes . size ( ) ;
2014-11-15 10:43:49 +01:00
for ( std : : size_t i = 0 ; i < functions ; + + i ) {
2016-07-08 20:53:08 +02:00
const Scope * const scope = symbolDB - > functionScopes [ i ] ;
2018-04-27 22:36:30 +02:00
for ( const Token * tok = scope - > bodyStart ; tok & & tok ! = scope - > bodyEnd ; tok = tok - > next ( ) ) {
2014-11-15 10:43:49 +01:00
if ( Token : : Match ( tok , " %var% [ " ) & &
Token : : Match ( tok - > linkAt ( 1 ) , " ] !![ " ) & &
tok - > variable ( ) & &
tok - > variable ( ) - > isExtern ( ) & &
tok - > variable ( ) - > isGlobal ( ) & &
tok - > next ( ) - > astOperand2 ( ) ) {
const ValueFlow : : Value * value = tok - > next ( ) - > astOperand2 ( ) - > getMaxValue ( false ) ;
if ( value & & value - > intvalue > 0 ) {
2015-03-25 08:39:09 +01:00
const MathLib : : bigint arrayIndex = value - > intvalue ;
2018-04-04 21:51:31 +02:00
const std : : map < std : : string , struct MyFileInfo : : ArrayUsage > : : iterator it = fileInfo - > arrayUsage . find ( tok - > str ( ) ) ;
2015-03-19 13:14:07 +01:00
if ( it ! = fileInfo - > arrayUsage . end ( ) & & it - > second . index > = arrayIndex )
continue ;
2014-11-15 10:43:49 +01:00
struct MyFileInfo : : ArrayUsage arrayUsage ;
2015-03-19 13:14:07 +01:00
arrayUsage . index = arrayIndex ;
2014-11-15 10:43:49 +01:00
arrayUsage . fileName = tokenizer - > list . file ( tok ) ;
arrayUsage . linenr = tok - > linenr ( ) ;
2015-03-19 13:14:07 +01:00
fileInfo - > arrayUsage [ tok - > str ( ) ] = arrayUsage ;
2014-11-15 10:43:49 +01:00
}
}
}
}
// Arrays..
2016-07-08 20:53:08 +02:00
const std : : list < Variable > & varlist = symbolDB - > scopeList . front ( ) . varlist ;
2014-11-15 10:43:49 +01:00
for ( std : : list < Variable > : : const_iterator it = varlist . begin ( ) ; it ! = varlist . end ( ) ; + + it ) {
const Variable & var = * it ;
2015-01-08 21:01:22 +01:00
if ( ! var . isStatic ( ) & & var . isArray ( ) & & var . dimensions ( ) . size ( ) = = 1U & & var . dimension ( 0U ) > 0U )
2014-11-15 10:43:49 +01:00
fileInfo - > arraySize [ var . name ( ) ] = var . dimension ( 0U ) ;
}
return fileInfo ;
}
2017-03-30 10:14:17 +02:00
Check : : FileInfo * CheckBufferOverrun : : loadFileInfoFromXml ( const tinyxml2 : : XMLElement * xmlElement ) const
{
const std : : string ArrayUsage ( " ArrayUsage " ) ;
const std : : string ArraySize ( " ArraySize " ) ;
MyFileInfo * fileInfo = new MyFileInfo ;
for ( const tinyxml2 : : XMLElement * e = xmlElement - > FirstChildElement ( ) ; e ; e = e - > NextSiblingElement ( ) ) {
if ( e - > Name ( ) = = ArrayUsage ) {
const char * array = e - > Attribute ( " array " ) ;
const char * arrayIndex = e - > Attribute ( " index " ) ;
const char * fileName = e - > Attribute ( " fileName " ) ;
const char * linenr = e - > Attribute ( " linenr " ) ;
if ( ! array | | ! arrayIndex | | ! MathLib : : isInt ( arrayIndex ) | | ! fileName | | ! linenr | | ! MathLib : : isInt ( linenr ) )
continue ;
struct MyFileInfo : : ArrayUsage arrayUsage ;
arrayUsage . index = MathLib : : toLongNumber ( arrayIndex ) ;
arrayUsage . fileName = fileName ;
arrayUsage . linenr = MathLib : : toLongNumber ( linenr ) ;
fileInfo - > arrayUsage [ array ] = arrayUsage ;
} else if ( e - > Name ( ) = = ArraySize ) {
const char * array = e - > Attribute ( " array " ) ;
const char * size = e - > Attribute ( " size " ) ;
if ( ! array | | ! size | | ! MathLib : : isInt ( size ) )
continue ;
fileInfo - > arraySize [ array ] = MathLib : : toLongNumber ( size ) ;
}
}
return fileInfo ;
}
2018-01-12 08:24:01 +01:00
bool CheckBufferOverrun : : analyseWholeProgram ( const std : : list < Check : : FileInfo * > & fileInfo , const Settings & , ErrorLogger & errorLogger )
2014-11-15 10:43:49 +01:00
{
2018-01-12 08:24:01 +01:00
bool errors = false ;
2014-11-15 10:43:49 +01:00
// Merge all fileInfo
MyFileInfo all ;
for ( std : : list < Check : : FileInfo * > : : const_iterator it = fileInfo . begin ( ) ; it ! = fileInfo . end ( ) ; + + it ) {
const MyFileInfo * fi = dynamic_cast < MyFileInfo * > ( * it ) ;
if ( ! fi )
continue ;
// merge array usage
for ( std : : map < std : : string , struct MyFileInfo : : ArrayUsage > : : const_iterator it2 = fi - > arrayUsage . begin ( ) ; it2 ! = fi - > arrayUsage . end ( ) ; + + it2 ) {
2018-04-04 21:51:31 +02:00
const std : : map < std : : string , struct MyFileInfo : : ArrayUsage > : : const_iterator allit = all . arrayUsage . find ( it2 - > first ) ;
2014-11-15 10:43:49 +01:00
if ( allit = = all . arrayUsage . end ( ) | | it2 - > second . index > allit - > second . index )
all . arrayUsage [ it2 - > first ] = it2 - > second ;
}
// merge array info
for ( std : : map < std : : string , MathLib : : bigint > : : const_iterator it2 = fi - > arraySize . begin ( ) ; it2 ! = fi - > arraySize . end ( ) ; + + it2 ) {
2018-04-04 21:51:31 +02:00
const std : : map < std : : string , MathLib : : bigint > : : const_iterator allit = all . arraySize . find ( it2 - > first ) ;
2014-11-15 10:43:49 +01:00
if ( allit = = all . arraySize . end ( ) )
all . arraySize [ it2 - > first ] = it2 - > second ;
else
all . arraySize [ it2 - > first ] = - 1 ;
}
}
// Check buffer usage
for ( std : : map < std : : string , struct MyFileInfo : : ArrayUsage > : : const_iterator it = all . arrayUsage . begin ( ) ; it ! = all . arrayUsage . end ( ) ; + + it ) {
2018-04-04 21:51:31 +02:00
const std : : map < std : : string , MathLib : : bigint > : : const_iterator sz = all . arraySize . find ( it - > first ) ;
2014-11-15 10:43:49 +01:00
if ( sz ! = all . arraySize . end ( ) & & sz - > second > 0 & & sz - > second < it - > second . index ) {
ErrorLogger : : ErrorMessage : : FileLocation fileLoc ;
fileLoc . setfile ( it - > second . fileName ) ;
fileLoc . line = it - > second . linenr ;
2018-04-09 09:54:39 +02:00
std : : list < ErrorLogger : : ErrorMessage : : FileLocation > locationList ( 1 , fileLoc ) ;
2014-11-15 10:43:49 +01:00
std : : ostringstream ostr ;
ostr < < " Array " < < it - > first < < ' [ ' < < sz - > second < < " ] accessed at index " < < it - > second . index < < " which is out of bounds " ;
const ErrorLogger : : ErrorMessage errmsg ( locationList ,
2016-07-26 16:27:55 +02:00
emptyString ,
2014-11-15 10:43:49 +01:00
Severity : : error ,
ostr . str ( ) ,
" arrayIndexOutOfBounds " ,
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
CWE788 , false ) ;
2014-11-15 10:43:49 +01:00
errorLogger . reportErr ( errmsg ) ;
2018-01-12 08:24:01 +01:00
errors = true ;
2014-11-15 10:43:49 +01:00
}
}
2018-02-06 08:59:36 +01:00
return errors ;
2014-11-15 10:43:49 +01:00
}
2016-07-08 20:53:08 +02:00
unsigned int CheckBufferOverrun : : sizeOfType ( const Token * type ) const
{
2018-06-17 17:20:16 +02:00
return mTokenizer - > getSymbolDatabase ( ) - > sizeOfType ( type ) ;
2016-07-08 20:53:08 +02:00
}