@@ -9,6 +9,7 @@ import codingstandards.cpp.Customizations
99import codingstandards.cpp.Exclusions
1010import semmle.code.cpp.dataflow.new.DataFlow
1111import semmle.code.cpp.rangeanalysis.SimpleRangeAnalysis
12+ import semmle.code.cpp.rangeanalysis.RangeAnalysisUtils
1213import codeql.util.Boolean
1314
1415abstract class DoNotUsePointerArithmeticToAddressDifferentArraysSharedQuery extends Query { }
@@ -68,11 +69,13 @@ int elementSize(Type type, Boolean deref) {
6869 * length depends on `elementSize()` of the original pointed-to type.
6970 */
7071class CastedToBytePointer extends ArrayLikeAccess , Conversion {
72+ /** The sizeof() the pointed-to type */
7173 int size ;
7274
7375 CastedToBytePointer ( ) {
7476 getType ( ) .( PointerType ) .getBaseType ( ) .getSize ( ) = 1 and
75- size = elementSize ( getExpr ( ) .getType ( ) , true )
77+ size = elementSize ( getExpr ( ) .getType ( ) , true ) and
78+ size > 1
7679 }
7780
7881 override Element getElement ( ) { result = this }
@@ -138,7 +141,7 @@ module ArrayToArrayExprFlow = DataFlow::Global<ArrayToArrayExprConfig>;
138141
139142/** Holds if the address taken expression `addressOf` takes the address of an array element at `index` of `array`. */
140143predicate pointerOperandCreation ( AddressOfExpr addressOf , ArrayLikeAccess array , int index ) {
141- exists ( ArrayExpr ae |
144+ exists ( ArrayExpr ae , Expr arrayOffset |
142145 (
143146 ArrayToArrayExprFlow:: flow ( array .getNode ( ) , DataFlow:: exprNode ( ae .getArrayBase ( ) ) ) and
144147 array instanceof ArrayVariableAccess
@@ -149,7 +152,10 @@ predicate pointerOperandCreation(AddressOfExpr addressOf, ArrayLikeAccess array,
149152 // flow() may hold for `ArrayVariableAccess` in the above, even though they aren't sources
150153 array instanceof CastedToBytePointer
151154 ) and
152- index = lowerBound ( ae .getArrayOffset ( ) .getFullyConverted ( ) ) and
155+ arrayOffset = ae .getArrayOffset ( ) .getFullyConverted ( ) and
156+ index = lowerBound ( arrayOffset ) and
157+ // This case typically indicates range analysis has gone wrong:
158+ not index = exprMaxVal ( arrayOffset ) and
153159 addressOf .getOperand ( ) = ae
154160 )
155161}
0 commit comments